Inversions of diminished 7th chords

Question: I have the following passage in D minor which features two diminished 7th chords:

I have labelled most of the chords, but I am at a loss of how to label these two diminished 7th chords.
If I could distil these two 7th chords into triads it would be easier to label them. I would label the first as vii°6 since that would imply a dominant function leading to tonic (vii°6 - i6). The second I would label as ii°6 since that would imply subdominant function moving to dominant where ii°6 leads to i6/4.
As for the 7th chords, I would prefer if the two chords were labelled as "vii ?" and "ii ?" since I think that would preserve their dominant and subdominant functions. However, because of the symmetry within a diminished 7th chord, I am unsure whether or not it is possible to label different inversions.
How can I best label these two chords?
Answer: Remember that figured-bass inversions (the Arabic numerals next to the Roman numeral) just measure the intervals above the bass. So if you're ever at a loss, just count the intervals above the lowest note and list them from largest number to smallest.
But this process only gives us the full version of the figured bass:

Root position: 7 5 3
First inversion: 6 5 3
Second inversion: 6 4 3
Third inversion: 6 4 2

We can simplify this just as we simplify the figured bass for triads:

Root position: 7
First inversion: 6 5
Second inversion: 4 3
Third inversion: 4 2 (and some only teach/use 2)

The C♯ is the root for the viio7 chord in your example, meaning that the first one, with E in the bass, is in first inversion. This chord should thus be labeled viio65.
The second chord, with G in the bass (the chordal fifth), is in second inversion. It should be labeled viio43.
That second chord would be a ii half-diminished 65 if the tenor were a D instead of a C♯; I think this is a big reason why you're hearing it as a type of iio6 moving to the cadential six-four. But since it has a C♯, the viio43 is really the correct label.
If you want to show this chord's function as a predominant, you'll need another type of analysis other than Roman numerals to do so.

Inversions of diminished 7th chords


How to display zero in place of error in filter formula in google spreadsheet

Question: I am new to Google spreadsheet functions and trying to apply a formula in following way:
I have sheet1 & sheet2 in one workbook (name-formula4). I am doing sumproduct of filtered range from sheet1 to sheet2 with the following formula:
=SUMPRODUCT(filter(Sheet1!$A$1:$A$401, (Sheet1!$B$1:$B$401>= E1) * (Sheet1!$B$1:$B$401<= E2)))

Formula is perfectly ok when the range selected
(Sheet1!$B$1:$B$401>= E1) * (Sheet1!$B$1:$B$401<= E2)
has some value & is not empty. However if I leave the cells of said range empty (sheet1!b1:b3) -which are required to meet criteria- then this gives the error No Matches are found in filter evaluation. In a nut shell, I want to display 0 rather than displaying the error or NA.
Note that I cannot fill entire the selected B column since this receives live data from the form and not previous decided which one.
Please look at the following link for details and help in correcting the above formula:
https://docs.google.com/spreadsheets/d/1HTXf4VG2JupiP9UqCLRyAddYjhsom1leQOI9-DwfMaY/edit#gid=0
Comment: Cant you use =IFERROR function to convert your error to 0?
Answer: =IFERROR(SUMPRODUCT(filter(Sheet1!$A$1:$A$401, (Sheet1!$B$1:$B$401>= E1) * (Sheet1!$B$1:$B$401<= E2))),0)

Comment: Please answer following question also: http://stackoverflow.com/questions/29431786/extract-two-words-from-a-cell-in-to-another-cell-in-google-spreadsheet
Comment: for the french users, the function is `SIERREUR`, very weird ! Half of the functions are translated only :O
Answer: I've had the same issue with my sheets too. I agree with the comments above hiding the error isn't best practice. However hiding the N/A response / customising it is very useful! You need to wrap the whole logic in a NA statement so it starts with it first. Here is how you can do something like this with the formula you are using.
=IFNA(SUMPRODUCT(FILTER((Sheet1!$A$1:$A$401,
     (Sheet1!$B$1:$B$401>= E1)*(Sheet1!$B$1:$B$401<= E2))),
     "input text or response you want here")

Change "input text or response you want here" to what you want to respond. If you just want it to return a numerical value, like 0, you can remove the quotes at the end and the text response and just put the number. Don't forget the comma (,) after the bracket though!
It should look like this:
=IFNA(SUMPRODUCT(FILTER((Sheet1!$A$1:$A$401,
       (Sheet1!$B$1:$B$401>= E1)*(Sheet1!$B$1:$B$401<= E2))),0)

Comment: `IFNA()` was made to get around this error, and is the correct solution.
Answer: I do NOT recommend IFERROR because it will suppress all type of errors. And that is not a good practice.
What you should be doing is...
IF the filter returns 0 items, THEN just display 0
ELSE, display sum of all the items.
=IF(COUNT(FILTER(_range_,_condition_)) = 0, 0, SUM(FILTER(_range_,_condition_)))

Comment: I tried this, and COUNT on an empty FILTER result returns 0. Presumably it is SUM on an empty FILTER result that causes problems, to me this seem wrong, the sum of no elements is 0.
So Mohsin's solution works, thanks :)


When is the binomial expansion with negative exponent valid for polynomials with complex numbers

Question: So for a normal binomial expansion with negative exponent, say
$$f(x) = (1 - 2x)^{-1},$$
we know it is valid for
$$-1/2 < x < 1/2.$$
But what is the case for complex numbers?
I was able to see how the expansion would work in the below link:
Binomial Expansion negative power with complex numbers
But I was not able to understand for which values it would be valid.
So say for example,
$$f(x) = (1 - (1+3i)x)^{-1}$$
How can I determine for which values of $x$ it will be valid?
Answer: The expansion of a :
$$\frac{1}{1-z}$$
where $z$ is a complex variable is finite when the modulus of $z$ is less than 1.
In your example you have to solve the inequality
$$|(1+3i)x|<1$$
to find the domain. Here it is valid for :
$$|x|<\frac{1}{\sqrt{10}}. $$
Comment: Thanks for the answer. Can you also tell if I'm right in assuming that for any binomial expansion involving a negative term there must be at least 3 terms that is the constant, linear and quadratic to give a good approximation.
Comment: I'm not sure to get your question. Higher is the order approximation, lower is the error. I don't understand what you mean by "good" approximation. Could you precise it ?
Comment: Certainly. So by good I mean the approximation should be atleast precise upto the first decimal place. Also please you link some resources that might contain a proof for it.


How to style a webform like a spreadsheet?

Question: I've been asked to develop a webform to look like a spreadsheet.
Unfortunately, the site is written in D6 and I've only really developed in D7.
Can anyone recommend a module / method to achieve this?
Comment: Kiamlaluno - I appreciate that this may be classified as off-topic, sorry about that.  But this place is also an awesome tool to stand on the shoulders of giants (or other drupal developers)
Is there a particular area or forum out there that you can recommend I use in future ?
Answer: It sounds like you're looking for Webform Table Element that will render your webform inside a table.

This module will add a new component to Webform module that allows you
  to render multiple components inside a table element.


How to draw multiple circles by using "LineRenderer"

Question: There is a code for a drawing circle with LineRenderer.
but I want to draw multiple circles  with different radius, I  used "for loop" but there is one circle instead of multiple
public float ThetaScale = 0.01f;
public float radius = 3f;
private int Size;
private LineRenderer LineDrawer;
private float Theta = 0f;

void Start ()
{
  LineDrawer = GetComponent<LineRenderer>();
}

void Update ()
{
 Theta = 0f;
 Size = (int)((1f / ThetaScale) + 1f);
 LineDrawer.SetVertexCount(Size);

 for (int l = 0; l < 5; l++)
 {

    for(int i = 0; i < Size; i++)
    {
      Theta += (2.0f * Mathf.PI * ThetaScale);
      float x = l * radius * Mathf.Cos(Theta);
      float y = l * radius * Mathf.Sin(Theta);
      LineDrawer.SetPosition(i, new Vector3(x, 0, y));
    }

 }
 }

Comment: define "there is no result" please, your code do not compile, the result is not the desired, if it's not, why? that kind of stuff ^^
Answer:
In every loop you always overwrite the same positions indices in the same line renderer. So you will always only have the last circle.
Note that it is also quite expensive to use SetPoisition repeatedly. As it says in the API you should rather work on an array and then use SetPoisitions to assign all positions at once.
One thing is a bit unclear though: If you use one single LineRenderer you won't get independent circles but they will always be connected at some point. Otherwise you would need 5 separated LineRenderer instances.
Option A: 5 circles but connected to each other since part of a single LineRenderer
void Start ()
{
    LineDrawer = GetComponent<LineRenderer>();
    LineDrawer.loop = false;

    Theta = 0f;
    // Use one position more to close the circle
    Size = (int)((1f / ThetaScale) + 1f) + 1;

    LineDrawer.positionCount = 5 * Size;
    var positions = new Vector3[5 * Size];

    for (int l = 0; l < 5; l++)
    {
       for(int i = 0; i < Size; i++)
       {
           Theta += (2.0f * Mathf.PI * ThetaScale);
           float x = l * radius * Mathf.Cos(Theta);
           float y = l * radius * Mathf.Sin(Theta);

           positions[5 * l + i] = new Vector3(x, 0, y);
        }
    }

    LineDrawer.SetPositions(positions);
}

Option B: 5 separated circles in 5 separated LineRenderers
// Drag 5 individual LineRenderer here via the Inspector
public LineRenderer[] lines = new LineRenderer[5];

void Start ()
{
    foreach(var line in lines)
    {
        line.loop = true;

        Theta = 0f;
        Size = (int)((1f / ThetaScale) + 1f);

        line.positionCount = Size;

        var positions = new Vector3[Size];

        for(int i = 0; i < Size; i++)
        {
            Theta += (2.0f * Mathf.PI * ThetaScale);
            float x = l * radius * Mathf.Cos(Theta);
            float y = l * radius * Mathf.Sin(Theta);

            positions[5 * l + i] = new Vector3(x, 0, y);
        }

        line.SetPositions(positions);
    }
}

Answer: You missed few details here and there. Here, this will work:
using UnityEngine;

[ExecuteAlways]
[RequireComponent( typeof(LineRenderer) )]
public class CircularBehaviour : MonoBehaviour
{
    [SerializeField][Min(3)] int _numSegments = 16;
    [SerializeField][Min(1)] int _numCircles = 5;
    [SerializeField] float _radius = 3f;
    LineRenderer _lineRenderer;
    void Awake ()
    {
        _lineRenderer = GetComponent<LineRenderer>();
        _lineRenderer.loop = false;
        _lineRenderer.useWorldSpace = false;
    }
    void Update ()
    {
        const float TAU = 2f * Mathf.PI;
        float theta = TAU / (float)_numSegments;
        int numVertices = _numSegments + 1;
        _lineRenderer.positionCount = numVertices * _numCircles;

        int vert = 0;
        for( int l=1 ; l<=_numCircles ; l++ )
        {
            float r = _radius * (float)l;
            for( int i=0 ; i<numVertices ; i++ )
            {
                float f = theta * (float)i;
                Vector3 v = new Vector3{ x=Mathf.Cos(f) , y=Mathf.Sin(f) } * r;
                _lineRenderer.SetPosition( vert++ , v );
            }
        }
    }
}

But
as @derHugo explained, this is not what you're looking for exactly as all circles will be drawn connected.


Isometries of two dimensional space

Question: I know that isometries of R^n are composed of orthogonal transformations followed by translation. My questions are:

In 2-D space, there are glide reflections, but why must the glide be according to the axis of reflection? Why can't we reflect according to some axis and then translate according to another vector altogether?
Why are there no glide rotations in 2-D space?
Answer:
The composition of a reflection in a line $l_1$ and translation along a line $l_2$ equals the composition of a reflection in some other line $l_3$ and translation along $l_3$.
The composition of a rotation and a translation equals a rotation around some other point.

Isometries of two dimensional space


Applying filters learned from convolutional neural networks

Question: I have a neural network that I trained on 32 * 32 px size images. Can I use these filters learned from the network on larger images not used in training the network such as a 600 * 800 px image? Or does it not make any sense to apply filters that were learned on smaller images on larger images and vice versa?
Here is an example of some images:
An image from training set

Here is a random image that I got online to test

Here is when I applied the filter(s)
Comment: If you give me sample images, both the 32x32 and the 600x800 then I might be able to give R-code in my answer.  I'm assuming they are grayscale.
Answer: Your question:
Can I use convolutional filters used on 32x32 px size images upon 600x800px images?
My answer:
If the features are the same sizes (aproximately) then zero pad the edges and go to town.  If not, then there are tricks you can do that will allow them to be used with slightly more noisy results.
Options include:

sub-sample the "big" pictures so they are on the scale of the
learning.  Convolutional methods work on sub-pixel resolutions.
Sub-sampling can be "pick random", "pick mean", "pick median" or
other.  Personally I like to pick about 30% of the way between the
mean and the median, but it is just personal preference.
interpolate rows and columns in the convolutional templates, so that
they operate as if they were larger.  Zero padding rows/columns can
also work

The convolutional templates are invariant on translation, not the other operations (rotation, skew, scale).
I think there are higher-dimensional analogies to the FFT, cousins and second cousins, that are invariant in those other operations, but I do not know what they are and they are higher dimensional.  From my "mathematical modeling" undergraduate course sponsored by Lockheed, I am sure that whatever they are - they are of interest for folks who perform extensive photogrammetry.  Those analogies would work seamlessly without having to account for rotation, skew or scale.


html botões menu dropdown

Question: Tenho um menu com drop down e ao passar o rato para a segunda hipótese ele desaparece.

Home

Quem Somos?

Missão e Valores

Actividades

Seguridad Suministro

Produtos petroliferos

GPL

Gás Natural

Internacional

Finanzas

Financiacion

Informações Financeiras

Normativa

Normativa Internacional

Normativa Nacional

Normativa Sectorial

Cores conecta

Miembros

sujetos obligados

Info cores

Novedades

Desde CORES

Calendario Eventos

Área corporativa

Comment: Por acaso tem como deixar o css/js do que tem para isso? Ou postar també, no jsfiddle por exemplo?
Comment: Você poderia postar na própria pergunta só os trechos do CSS relativos ao menu? Recomendo ainda a leitura deste artigo da central de ajuda: http://pt.stackoverflow.com/help/mcve
Comment: E só de ver da para perceber que você não esta fechando o `` e tem um `` onde deveria ser um ``.
Comment: http://jsfiddle.net/cgPtw/
Comment: Acho que copiei mal o codigo
Comment: Ja coloquei o trecho na pergunta
Answer: O problema é quando o rato passa por cima do elemento com class .Galeria. Baixe o z-index para forçar o rato a ver o menu.
Tentei isto e funcionou bem: http://jsfiddle.net/cgPtw/1/
.Galeria {
    position:absolute;
    top:200px;
    left:150px;
    z-index: -1;
}

html botões menu dropdown


Property [project] is marked with contradictory annotations

Question: My requirement is to read from a csv file in Google Cloud Storage and load it to Google Datastore. Below is the code snippet.

import com.google.datastore.v1.Entity;
import com.google.datastore.v1.Key;
import com.opencsv.CSVParser;

import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.io.gcp.datastore.DatastoreIO;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

import javax.annotation.Nullable;
import java.util.UUID;

import static com.google.datastore.v1.client.DatastoreHelper.makeKey;
import static
com.google.datastore.v1.client.DatastoreHelper.makeValue;

public class PipelineClass {

static class CreateEntitiesFn extends DoFn<String, Entity> {
  /**
     *
     */
    private static final Logger LOG = LoggerFactory.getLogger(PipelineClass.class);
    private static final long serialVersionUID = 1L;
    private final String namespace;
  private final String kind;
  private final Key ancestorKey;

  CreateEntitiesFn(String namespace, String kind) {
      this.namespace = namespace;
      this.kind = kind;

      ancestorKey = makeAncestorKey(namespace, kind);
  }

  Entity makeEntity(String id, String group) {

      Entity.Builder entityBuilder = Entity.newBuilder();
      Key.Builder keyBuilder = makeKey(ancestorKey, kind,
                                     UUID.randomUUID().toString());

      if (namespace != null) {

keyBuilder.getPartitionIdBuilder().setNamespaceId(namespace);
      }

      entityBuilder.setKey(keyBuilder.build());
      entityBuilder.getMutableProperties().put("id",
          makeValue(id).build());
      entityBuilder.getMutableProperties().put("group",
          makeValue(group).build());

      return entityBuilder.build();
  }

  public void processElement(ProcessContext c) throws Exception {

      CSVParser parser = new CSVParser();
      String[] parts = parser.parseLine(c.element());
      String id = parts[0];
      String group = parts[1];

      c.output(makeEntity(id, group));
  }
}

static Key makeAncestorKey(@Nullable String namespace, String kind) {
  Key.Builder keyBuilder = makeKey(kind, "root");
  if (namespace != null) {
      keyBuilder.getPartitionIdBuilder().setNamespaceId(namespace);
  }
  return keyBuilder.build();
}

public interface Options extends PipelineOptions {
  @Description("Path of the file to read from and store to Cloud Datastore")
  @Default.String("gs://myproject-263315.appspot.com/source/food.csv")
  String getInput();

  void setInput(String value);

  @Description("Dataset ID to read from Cloud Datastore")
  @Default.String("myproject-263315")
  String getProject();

  void setProject(String value);

  @Description("Cloud Datastore Entity Kind")
  @Default.String("FoodGroup")
  String getKind();

  void setKind(String value);

  @Description("Dataset namespace")
  @Default.String("nutrients")
  String getNamespace();

  void setNamespace(@Nullable String value);

  @Description("Number of output shards")
  @Default.Integer(0)
  int getNumShards();

  void setNumShards(int value);
}

public static void main(String args[]) {

 // PipelineOptionsFactory.register(Options.class);
  Options options =
        PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);

  Pipeline p = Pipeline.create(options);
  p.apply(TextIO.read().from(options.getInput()))
          .apply(ParDo.of(new
CreateEntitiesFn(options.getNamespace(), options.getKind())))

.apply(DatastoreIO.v1().write().withProjectId(options.getProject()));

  p.run();

  }
}

I am using ecplise to develop code. Below is my POM.xml
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>my.dataflow1</groupId>
  <artifactId>my.artifact1</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <packaging>jar</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <bigquery.version>v2-rev374-1.23.0</bigquery.version>
    <google-clients.version>1.23.0</google-clients.version>
    <guava.version>20.0</guava.version>
    <hamcrest.version>1.3</hamcrest.version>
    <joda.version>2.4</joda.version>
    <junit.version>4.12</junit.version>
    <maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
    <exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
    <maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
    <maven-shade-plugin.version>3.1.0</maven-shade-plugin.version>
    <mockito.version>1.9.5</mockito.version>
    <pubsub.version>v1-rev382-1.23.0</pubsub.version>
    <slf4j.version>1.7.25</slf4j.version>
    <surefire-plugin.version>2.20.1</surefire-plugin.version>
  </properties>

  <repositories>
    <repository>
      <id>ossrh.snapshots</id>
      <name>Sonatype OSS Repository Hosting</name>
      <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
      <releases>
        <enabled>false</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven-compiler-plugin.version}</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${surefire-plugin.version}</version>
        <configuration>
          <parallel>all</parallel>
          <threadCount>4</threadCount>
          <redirectTestOutputToFile>true</redirectTestOutputToFile>
        </configuration>
        <dependencies>
          <dependency>
            <groupId>org.apache.maven.surefire</groupId>
            <artifactId>surefire-junit47</artifactId>
            <version>${surefire-plugin.version}</version>
          </dependency>
        </dependencies>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>${maven-jar-plugin.version}</version>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>${maven-shade-plugin.version}</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <finalName>${project.artifactId}-bundled-${project.version}</finalName>
              <filters>
                <filter>
                  <artifact>*:*</artifact>
                  <excludes>
                    <exclude>META-INF/LICENSE</exclude>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                  </excludes>
                </filter>
              </filters>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>

    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <version>${exec-maven-plugin.version}</version>
          <configuration>
            <cleanupDaemonThreads>false</cleanupDaemonThreads>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

  <dependencies>

    <dependency>
      <groupId>com.google.cloud.dataflow</groupId>
      <artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
      <version>2.5.0</version>
    </dependency>

    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>${google-clients.version}</version>
      <exclusions>

        <exclusion>
          <groupId>com.google.guava</groupId>
          <artifactId>guava-jdk5</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-bigquery</artifactId>
      <version>${bigquery.version}</version>
      <exclusions>

        <exclusion>
          <groupId>com.google.guava</groupId>
          <artifactId>guava-jdk5</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>com.google.http-client</groupId>
      <artifactId>google-http-client</artifactId>
      <version>${google-clients.version}</version>
      <exclusions>

        <exclusion>
          <groupId>com.google.guava</groupId>
          <artifactId>guava-jdk5</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>3.7</version>
</dependency>

    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-pubsub</artifactId>
      <version>${pubsub.version}</version>
      <exclusions>

        <exclusion>
          <groupId>com.google.guava</groupId>
          <artifactId>guava-jdk5</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>${joda.version}</version>
    </dependency>

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>${guava.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-jdk14</artifactId>
      <version>${slf4j.version}</version>

      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-all</artifactId>
      <version>${hamcrest.version}</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
    </dependency>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>${mockito.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

When executing the code via maven with below command,
mvn compile exec:java -e -Dexec.mainClass=com.dataflow1.PipelineClass -Dexec.args="--project=myproject-263315 --runner=DataflowRunner" -Pdataflow-runner

I am getting the bleow error,
Exception in thread "main" java.lang.IllegalArgumentException: Property [project] is marked with contradictory annotations. Found [[Default.String(value=myproject-263315) on my.dataflow1.PipelineClass$Options#getProject()], [Default.InstanceFactory(value=class org.apache.beam.sdk.extensions.gcp.options.GcpOptions$DefaultProjectFactory) on org.apache.beam.runners.dataflow.options.DataflowPipelineOptions#getProject()], [Default.InstanceFactory(value=class org.apache.beam.sdk.extensions.gcp.options.GcpOptions$DefaultProjectFactory) on org.apache.beam.sdk.extensions.gcp.options.GcpOptions#getProject()]].

Can somebody help me in getting this corrected. Held up in this and struck up in this for long. Any help is highly appreciated.
Thanks.
Comment: I've found this [post](https://stackoverflow.com/questions/48473024/import-csv-into-google-cloud-datastore), that maybe is useful for you. It has a Java solution and also a simple Python script. Hope this helps!
Answer: The option "Project" is a reserved in the PiplineOptions. "JobName" is another.
Comment: What happen if the option is reserved? Is impossible to setup the value in the `PipelineOptionsFactory`? I'm trying to set up the option `region` (apache beam 2.21.0) and I get the same error: `Property [region] is marked with contradictory annotations. Found [[Default.String(value=europe-west1) on .options.IngestionOptions#getRegion()], [Default.InstanceFactory(value=class org.apache.beam.runners.dataflow.options.DataflowPipelineOptions$DefaultGcpRegionFactory) on org.apache.beam.runners.dataflow.options.DataflowPipelineOptions#getRegion()]]`


how was text format deleted?

Question: I migrated a drupal 6 site to drupal 8. It still needs the php module. I have a text format with the "PHP evaluator" filter enabled.
Overnight, this text format disappeared.
I was asleep. Only the adminstrator role has "administer text formats and filters" permission but I have no reason to believe an administrator deleted it manually.
How else could this have got removed?

I recovered by:

backed up the site;
drush cex
copy filter.format.php_code.yml from a backup
drush cim
flushed all caches

It is rather worrying that this could have happened. I can't immediately see anything relevant in the logs (but not sure where to look). Is there a good way to create audit logs to record administrator actions?
Comment: What is php_code text format?
Comment: People aren't going to be able to guess from here how something was deleted from your website. If you're asking more to get reassurance that Drupal core doesn't have anything in it to automatically delete arbitrary text formats, you can be reassured that it doesn't. Anything beyond that would have to come down to custom or contrib modules, your deployment workflow, the server, a rogue/bored/lazy admin, i.e. something specific that's been done on your site that only people working with it would know
Comment: @Kevin it is the [text format](https://www.drupal.org/docs/user_guide/en/structure-text-formats.html) that has the "[PHP evaluator](https://www.drupal.org/project/php)" filter enabled.
Comment: @Clive I know that running composer has messed up my markdown filter configuration in the past. I'm more interested in knowing if there is a good way to audit changes.
Comment: @Clive I believe there is a bug in core - see my answer
Comment: It's very unlikely it was a bug in core. Not impossible, but there are many, many more likely scenarios.
Comment: @Jaypan yes, it is actually a bug in the php module - see below
Comment: Yeah, as I said, very unlikely to be a bug in core. Not that they don't exist, but there is a thorough testing suite built around core that makes such bugs unlikely. They will nearly always exist in contributed or custom module or theme.
Answer: I have managed to replicate the issue on a backup.

revert to known working snapshot
visit https://example.org/admin/config/content/formats - PHP format is present
visit https://example.org/admin/modules/uninstall
select "help topics" (experimental module that comes with core)
select "uninstall"
flush all caches
visit https://example.org/admin/config/content/formats - PHP format is missing

This seems like a bug in core's module uninstall process.
Appearances are deceptive. It appears the fault actually lies with the PHP module: #3016061: Text format with system name "php_code" is deleted when you view admin/modules/uninstall
Comment: It's a bug but in the PHP module, not core: https://www.drupal.org/project/php/issues/3016061
Comment: @Clive thanks that does look exactly like my issue
Comment: What are "help topics"?

how was text format deleted?


mod_rewrite, 301 problem

Question: Currently I can access specific site in two ways:
 1. http://a.com/foo/bar
 2. http://a.com/index.php?url=foo/bar

What I'm trying to achive is to allow to do it only using first way, and make redirect 301 on the second to the first one. Here's the code which I made so far and put into .htaccess:
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

  #tricky part
  RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?url=?(.*)\ HTTP/
  RewriteRule ^index\.php$ http://a.com/$1 [R=301,L]
</IfModule>

Currently it do almost all the job, it's redirecting index.php to /, but index.php?url=foo/bar to /?url=foo/bar and I can't manage to make it right. TIA.
Comment: possible duplicate of [Everything You Ever Wanted to Know about Mod_Rewrite Rules but Were Afraid to Ask?](http://serverfault.com/questions/214512/everything-you-ever-wanted-to-know-about-mod-rewrite-rules-but-were-afraid-to-ask)
Answer: Try this
RewriteCond %{query_string} ^url=(.*)$
RewriteRule ^.*index.php$ /$1? [R=301]

Comment: Unfortunatelly it doesn't work. It redirects me back to main domain (a.com).

mod_rewrite, 301 problem


Examples of categories where morphisms are not functions

Question: Can someone give examples of categories where objects are some sort of structure based on sets and morphisms are not functions?
Comment: If you soften your "and" to "or" then that's easy: take the category of sets and _relations_. But it turns out to be isomorphic to a different category whose objects are structured sets and whose morphisms are functions. There is also a locally small category which is demonstrably _not_ equivalent to any concrete category. See also [here](http://math.stackexchange.com/questions/250592/non-concrete-categories-constructed-from-concrete-categories).
Comment: In fact, the question (taken literally) is quite boring (see the answers). It is more interesting to ask for categories which have no faithful functor to $\mathsf{Set}$ at all (i.e. are not "concretizable"). Homotopy categories provide the most prominent examples.
Comment: fyi: "I believe that algebraic topology is generally concerned with structures gotten by putting together finitely many, or countably many, finite-dimensional pieces; so their size has a bound lying within any universe, and as soon as we impose such a bound, we can concretize it within any universe. Further, given any category, if we assume the Axiom of Universes, we can pass to a larger universe where we can concretize it. So while Freyd's non-concretizability result is interesting, I think that more fundamental to one's understanding of the situation is Theorem 6.5.6" -- G.B.
Comment: G.B. = George Bergman, and he's referring to his book on universal algebra.
Answer: Consider the category with exactly two objects $a$ and $b$ (they can be anything you want!) and which has exactly one non-identity morphism —going from $a$ to $b$— which is my chair.
Comment: But, assuming you put your chair on the table at night, your chair should be invertible.
Comment: The idea is that a morphism can be anything you want as far as they satisfy the definition of a category...
Comment: How is the word "chair" a morphism? I do not get the concept on this one…
Answer: Let $G$ be a directed graph.  Then we can think of $G$ as a category whose objects are the vertices in $G$.  Given vertices $a, b \in G$ the morphisms from $a$ to $b$ are the set of paths in the graph $G$ from $a$ to $b$ with composition being concatenation of paths.  Note that we allow "trivial" paths that start at a given vertex $a$, traverse no edges, and end at the starting vertex $a$.  We have to do this for the category to have identities.
Also we can create categories whose morphisms are not exactly maps but instead equivalence classes of maps.  For example given an appropriately nice ring $R$ we can create the stable module category whose objects are $R$-modules.  Given two $R$-modules $A$ and $B$ the set of morphisms from $A$ to $B$ is the abelian group of $R$-module homomorphisms from $A$ to $B$ modulo the subgroup of homomorphisms that factor through a projective $R$-module.
Comment: In the first example, I fail to see how the set of paths from a to b isn't equivalent to a set of functions. For each path `p` that starts at `a` and ends at `b`, there is a function `f_p(a) = b`.
Comment: The question is not about equivalence.
Answer: Assuming suitable access to 'large sets', every category is isomorphic to a (possibly large) category of (possibly large) sets and (possibly large) functions.
We can replace each object $A$ with the (possibly large) set of all arrows with codomain $A$. Call this set $|A|$.
Then, we can replace each arrow $f : A \to B$ with the (possibly large) function $|A| \to |B|$ defined by $g \mapsto f \circ g$.
In many categories, we can restrict the sets $|A|$ to include only arrows coming from a particular (small) set of domains. When we can do this, we can avoid making use of large sets/functions.
Comment: this construction is Yoneda lemma-based, right? but I've never seen it explained this clearly. Can you post a reference which describes this issue the way you did?
Comment: @magma: Hrm. I know a couple very closely related notions: one is the Yoneda lemma as you described, another is in terms of category actions on a set, analogous to the Cayley representation of a group. But now that you've made me think about it, I'm not sure whether or not I've actually seen anyone give this exact construction.
Answer: I think the Fukaya category of a symplectic manifold is an example.  The objects are the Lagrangian submanifolds, while the morphisms are the intersection points of the Lagrangians.
Answer: Also natural deduction can be considered as a category with formulas as objects and proofs as morphisms.
Answer: Algebras/any structures and binary relations or partial functions between them.
$n+1$-manifolds as arrows with $2$ pieces of $n$-dim. boundaries, called cobordism (like a cylinder, between two disks). The objects are the $n$-manifolds.
The objects are points in a topological space, and the arrows are paths. Or, the objects are the paths and the arrows are homotopopies between them. Moreover, we can make higher dimensional categories about this one..
Many many more...
Comment: An example is $\mathbf{Set}^{op}$, see this [related Q](http://math.stackexchange.com/questions/140196/how-to-interpret-1-to-0-in-bf-set-mathrmop-and-bf-set-mathrmop)
Answer: Topological spaces with continuous maps defined up to homotopy.
Comment: Yes, this is what i said, isn't it.
Comment: This is a very good one because is not even concretizable, so it is, in some sense, intrinsecally non-set based
Comment: See http://en.wikipedia.org/wiki/Homotopy_category
Answer: Suppose that $X$ is a set and$\mathcal{P}(X)$ is the collection of all subsets of $X$. Let the objects objects of the category be the elements of $\mathcal{P}(X)$. Let the morphisms be ordered pairs $(A, B)$ where $A \subseteq B$. Functions are sets of ordered pairs. The composition of $(A,B)$ and $(B, C)$ is $(A, C)$.
Comment: Arguably, those are still functions, namely the inclusions $A \hookrightarrow B$. :)
Comment: No, $(A,B)$ is not a function $A \to B$. But it can be *interpreted* as a function. But the same is true for almost all the other examples mentioned in the other answers. The most categories mentioned are concretizable.
Answer: Here is another example, much simpler than the previous one I gave: the category of integer matrices of all (finite) dimensions.  (Any associative ring of coefficients could be used instead of integers.)
The morphisms of this category are matrices with the usual operation of multiplication (playing the role of composition of morphisms), and the objects are natural numbers.  A matrix $m\times n$ is a morphism from $n$ to $m$ (or from $m$ to $n$, passing to the opposite category).
Generally speaking, the true elements of a category are morphisms, and objects are just opaque labels to keep track of when two morphisms can be composed. A category is just a generalisation of a group (where not every element is invertible and not every pair of elements is composable).
However, this may be not a good example, because the question was about objects that "are some sort of structure based on sets," and natural numbers are not exactly "based on sets."
If desired, here is a version for sets as objects: let morphisms between sets $A$ and $B$ be "matrices" $B\times A$ with only finitely many non-zero entries.  That is, the objects are arbitrary sets and morphisms $A\to B$ are functions $B\times A\to\mathbf{Z}$ which take non-zero values on finitely many arguments.  Define the composition of morphisms as the multiplication of these "matrices."
Comment: Your first matrix example also fits with the objects being based on sets. The natural numbers have several set-theoretic constructions. For example Von Neumann ordinals: 0 = { }, 1 = {{ }}, 2 = {{ }, {{ }}}, 3 = {{ }, {{ }}, {{ }, {{ }}}}, **...** where each natural number is equal to the set of all natural numbers less than it; and Zermelo ordinals: 0 = { }, 1 = {{ }}, 2 = {{{ }}}, **...** where each natural number is equal to the set containing only its predecessor.


How to change the template from jade to html in angular meanstack project

Question: When I was creating project using Yo angular fullstack, I was selected jade is template engin. But I want to change it to html. And I want change all jade file to html file. It is possible and How can, if it is possible.
Answer: Once you've finished generating the project through Yeoman there's no way to automatically switch everything back to html. You'll have to either create a new project from scratch with new settings or edit your current project's config files (Grunt, Karma, etc.) to no longer process the .jade files. Of course, you'll have to redo all of the Jade templates into HTML.
Personally, I would create a new project with HTML selected and, then, copy and paste any files from my old project that I needed to keep into my new project.


How can I enable workflows for comments?

Question: I would like to create workflows for comments and moderate them, but I can't find comments under This workflow applies to: on /admin/config/workflow/workflows/manage/comment_workflow.
Does anyone know how I can enable workflows on comments?
Answer: TLDR: Without a module that implements workflows for the Comment entity, you cannot.
The Workflow module doesn't implement any workflow: It's an API module other modules can use to implement their workflows.
An example of this is the Content moderation module, the only Drupal core module that implements workflows. Its workflows only apply to Custom block types and Content types, as shown in /admin/config/workflow/workflows/manage/editorial.

Even when you create a new Content moderation workflow, Comment types isn't an option listed under This workflow applies to.


Is using bit wise makes the code unreadable

Question: I have encountered many occasions when I have to use between division operator(divide by 2) or the right shift operator(>>) but I tend to use the division operator assuming that use of bit wise operator will make my code less readable. Is my assumption true?
Is it good practice to use left shift operator and right shift operator in production code instead of multiply by 2 or divide by 2.
Comment: Write whichever is most clear. Using bitwise operators for an operation that isn't thought of as a bitwise one (I mean every operation boils down to bitwise ones anyway) seems rather unclear.
Comment: At least for unsigned variables this optimization will be done anyway by nearly every compiler. So I think it is not harder to read, but that depends on your team. By the way you could use a `#define` to make it easier to read.
Comment: @MrSmith42, If you mean `#define MULTIPLY_BY_TWO(x) ((x) << 1)`, then I would argue it's much better as `constexpr int multiply_by_two(int x) { return x << 1; }`, replacing `int` with whatever fits your needs best. Of course that's beside the point here when you're using one of nearly every compiler.
Comment: After all most of the people have their own preference on that topic, I suggest you to have a look at http://stackoverflow.com/questions/7522346/right-shift-and-signed-integer and http://stackoverflow.com/questions/4009885/arithmetic-bit-shift-on-a-signed-integer before playing with bit shifting.
Comment: A discussion about speed differences is here: http://stackoverflow.com/a/6357114/1921273
Answer: Using the bitwise operators for multiplication or division by 2 is utter madness.

The behaviour of << is undefined for negative signed types.
<< and >> have lower precedence than addition and subtraction so it messes up your expressions.
It's unnecessarily obfuscating.
Trust a modern compiler to optimise appropriately.
Comment: @MrSmith42: the undefinedness he is talking about is in the C standard; the compiler knows how the underlying hardware behaves and can usually apply these optimizations happily even on signed types (x86, for example, provides both arithmetic and logical shift opcodes). I've never seen the sign adjust code as a performance bottleneck, so use `unsigned` when it makes sense (typically just for bit fields), not in a dubious quest for microoptimizations.
Comment: @Matteo Italia: I agree profiling should always be the first step before trying to optimize.
Comment: As you said 'undefined for negative signed types', therefore a compiler will only optimize this for unsigned types. So make sure you are using unsigned types wherever possible to enable the compiler to make such optimizations.
Comment: @Matteo Italia: So you have no problem to make copilor dependent code? I would not rely on a specific compiler when I write programs. So only for unsigned types you can be sure that the optimization is likely to be done by the compiler (if it is an optimization on your architecture at all) and the result is what you expect (independent from a specific compiler).
Comment: @MrSmith42: what are you talking about? What I'm advocating is to use division or shift, signed or unsigned *according to logical, intended meaning*, not looking for optimizations. If you are worried about this kind of micro-optimization, profile the code, check the generated assembly and go down the rabbit hole as long as you like. But don't use `unsigned` just because you hope to exploit this kind of behavior. Yes, [divide by two for signed integers is more complicated](https://godbolt.org/g/tLMsrl), no, you shouldn't worry unless you measured it (it's still plenty faster than an `idiv`).
Answer: Integer division by constants is routinely optimized to bit shifts (if by powers of two), multiplication by the "integral reciprocal" and all kind of tricks, so performance should not be a concern.
What matters is to clearly express intent. If you are operating on integers "as numbers" and you divide by something that just happens to be a power of 2 use the division operator.
int mean(int a, int b) {
    return (a+b)/2; // yes overflow blah blah
}

If instead you are operating on integers as bitfields - for example, you are unpacking a nibble and you need to right shift by 4 to move it in "low" position, or you need to explicitly set some bit -, then use bitwise operators.
void hex_byte(unsigned char byte, char *out) {
    out[0]=byte>>4;
    out[1]=byte&0xf;
}

unsigned set_bit(unsigned in, unsigned n) {
    return in | (1<<n);
}

In general, most often you'll use division on signed integers, bitwise operators on unsigned ones.


Android TextView use with multiple fonts (languages)

Question: I have a textview which is preloaded with some content. what i want is to display certain part of the content in english n some in chinese. Say for example i have three paragraphs in english then each such paragraph is to be followed with chinese para. I can't use spanning of the content since the length varies. Please provide me with the solution for this or a better alternative.
Thanks :)
Answer: You can format it in the HTML way like this:
MyTypeFace.class
package my.app;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;

public class MyTypeFace extends TypefaceSpan {
private final Typeface newType;
public MyTypeFace(String family, Typeface type) {
    super(family);
    newType = type;
}
@Override
public void updateDrawState(TextPaint ds) {
    applyCustomTypeFace(ds, newType);
}
@Override
public void updateMeasureState(TextPaint paint) {
    applyCustomTypeFace(paint, newType);
}
private static void applyCustomTypeFace(Paint paint, Typeface tf) {
    int oldStyle;
    Typeface old = paint.getTypeface();
    if (old == null) {
        oldStyle = 0;
    } else {
        oldStyle = old.getStyle();
    }
    int fake = oldStyle & ~tf.getStyle();
    if ((fake & Typeface.BOLD) != 0) {
        paint.setFakeBoldText(true);
    }
    if ((fake & Typeface.ITALIC) != 0) {
        paint.setTextSkewX(-0.25f);
    }
    paint.setTypeface(tf);
}
}

Now,Just go on to fetch the stories from the String.xml, apply the typeface on them,and Display them.
String text1=findViewById(R.string.text1);
String text2=findViewById(R.string.text2);

TextView textView = (TextView) findViewById(R.id.custom_fonts);
txt.setTextSize(30);
Typeface font1 = Typeface.createFromAsset(getAssets(), "english.ttf");
Typeface font2 = Typeface.createFromAsset(getAssets(), "chinese.ttf");
text1.setSpan (new MyTypeFace("", font1), 0, 4,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
text2.setSpan (new MyTypeFace("", font2), 4, 11,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
String totalText=text1+"
"+text2;
textView.setText(Html.fromHtml(totalText));

Comment: Thanks for replying but i think this will not solve my problem...i had mentioned that each english para has to be followed by a para in chinese... if i use two String variables they'll contain the enitre data n formatting would not be easy... It's like how we do translation of content from one language to the other and so i want the solution regarding that.
Comment: Thanks for the reply but even this will not work exactly...let me give u some example that might help u out..Say i have a story in english n i would like it to be translated to chinese..now using the string.xml in resource I set the content of the textview..say i have the story in 5 paragraphs...so i display the first para in englisg followed by its chinese para..so i need to have 2 typeface fonts,one for english n one for chinese...secondly i may have 100 of such stories whose number of para may vary from 1 to any given integer so i can't intialize i=10 or any other number.
Comment: can we set different fonty type i mean diff font faces on a single piece of text in textview without spaning the test?
Answer: You can try to figured it out from this sample:
TextView text = new TextView(context);
text.setText(Html.fromHtml("" + "some text" + "" +  "
" +
            "" + "some text" + "" + "
" +
            "" + "some text" + ""));


scipy.integrate.quad gives wrong result on large ranges

Question: I am trying to integrate over the sum of two 'half' normal distributions. scipy.integrate.quad works fine when I try to integrate over a small range but returns 0 when I do it for large ranges. Here's the code:
mu1 = 0
mu2 = 0
std1 = 1
std2 = 1

def integral_fun(x):
    nor1 = 0.5 * ((1 / (np.sqrt(2 * np.pi) * std1)) * (np.e ** ((-(x-mu1) ** 2) / (2 * std1 **2))))
    nor2 = 0.5 * ((1 / (np.sqrt(2 * np.pi) * std2)) * (np.e ** ((-(x-mu2) ** 2) / (2 * std2 **2))))
    return nor1 + nor2

integrate.quad(integral_fun, -5, 5)
Out[54]: (0.9999994266968564, 8.668320228277793e-10)

integrate.quad(integral_fun, -10, 10)
Out[55]: (1.0000000000000002, 8.671029607900576e-10)

integrate.quad(integral_fun, -100000, 100000)
Out[56]: (0.0, 0.0)

Why is this happening?
Comment: @ThePredator This is because in that case scipy will transform the integral into one over the range ``(0,1]`` with the transformation ``x = (1-t)/t``. This then well samples points near the origin.
Comment: numerical integrals are approximated by a weighted sum of function values. If I had to guess I would say that the function values are all 0, because almost all points of the range have a density of (almost) 0.
Comment: it works though if the ranges are from `-inf` to `inf`
Answer: The reason here is that your function is only very strongly peaked in a very small region of your integration region and is effectively zero everywhere else, quad never finds this peak and thus only see's the integrand being zero.
Since in this case you know where the peaks are, it would be reasonable to split the limits of the integration so that you consider the regions around the peaks separately.
To do this you can use the points argument in a slightly bastardized way to force quad to consider the peaks separately.
In [3]: integrate.quad(integral_fun, -100000, 100000, points=[-10,10])
Out[3]: (1.0000000000000002, 8.671029607900576e-10)


Connecting to a database from another application

Question: What is the proper way to do a remote connection to my Drupal database from a remote application? I am trying to integrate IPB with Drupal so I would like to modify my Drupal database from IPB.
Answer: Since you asked, the "correct" way would be to implement a simple web-service in Drupal in order to perform these tasks remotely from your application.  You could build a simple RESTful API to handle all your CRUD needs, for example.
The Services module is an excellent starting-point.
The reasoning for this is that you should really avoid modifying your Drupal database directly (unless you really know what youy are doing) and even if you must, connecting to it directly from another application is not only bad practice but a security risk too!
Please reconsider and use a webservice-approach, think of the kittens! :)
Comment: Using Drupal's hooks, any module can add additional behaviors on data insert and updates. Direct access to the database means you bypass all these added behaviors.
Comment: So this correct way isn't what most people go for?


Ajax webform do submit without ajax when it is loaded via ajax

Question: I'm trying to load a node containing an ajax webform and add it to an existing div, this works fine, but when I click to next step, the form is submitted to the webform action path.
Any idea?
Thanks!
          $.ajax({
            url: '/path/to/my/node/with/webform'
            success: function (data) {
              // Add html to existing container.
              $(data).appendTo('body');
            }
          });

Answer: Short answer: you need to attach the Drupal behaviors after inserting your new content into the DOM:
$.ajax({
  url: '/path/to/my/node/with/webform'
  success: function (data) {
    // Add html to existing container.
    $(data).appendTo('body');
    // Attach the new behaviors to the DOM
    Drupal.attachBehaviors();
  }
});

Long answer: Although Drupal has jQuery included with core, it does not use jQuery functions like $.on() or $.delegate() or $.live(), which attach behaviors to elements when they are inserted into the DOM. Instead Drupal uses behaviors, which is a Drupal specific method of attaching behaviors to elements.
Behaviors have three parts:
1) Scripts add new behaviors to the Drupal.behaviors object. Example:
Drupal.behaviors.someArbitraryKey = {
  attach: function (context, settings) {
    attachHandlerToElement(context, settings);
  }
};

Generally people consider this to be an onload function, as it is called when the document has loaded and is ready to have JavaScript executed on it. However, it can also be called using Drupal.attachBehaviors(), which will be addressed in #3 below. When the DOM is loaded, or Drupal.attachBehaviors() is called, the .attach() function of the behavior is executed, in this case calling attachHandlerToElement(context, settings); whenever this is executed.
2) $.once() is used to ensure that handlers are not attached multiple times to an element. Because behaviors can be executed multiple times, event handlers can be attached to elements multiple times, if steps aren't taken to prevent that. The jQuery $.once() function, provided by core, ensures that the code it contains is only attached to the element a single time:
function attachHandlerToElement(context) {
  $(context).find(".some_selector").once("some-arbitrary-key").each(function () {
    // Note that $(this) is the current iteration
    // of .some_selector
    $(this).click(function () {
      // Do something.
    });
  });
}

By calling $.once() on elements, the contained code in the $.each() loop is only ever attached a single time. This means that the $.click() handler above is only attached a single time to elements with the class .some_selector.
3) When new content is inserted into the DOM, whether that be from an AJAX call, or even just new elements inserted using JavaScript, Drupal.attachBehaviors() is called. This in turn loops through all behaviors, and executes their attach() handler.
A final note on context. On initial page load, context is the full DOM. Drupal.attachBehaviors(context) takes an argument, context, which should be an element of the DOM (not a jQuery object containing it). In your case, you are appending your content to the body, so there is no need to pass an argument, as you will need to parse the full DOM. If you were appending your content to some element though, you could do something like this:
$(data).appendTo('#some_element');
Drupal.attachBehaviors($(#some_element").eq(0));

This would pass it the element of the DOM to which the new content was attached. This element becomes context in the attach() handler, and is more efficient than passing in the full DOM.
Comment: Thanks for your help! The problem was this: https://drupal.stackexchange.com/a/244801/57114

I need to add an ajax response in a custom controller.


Publish updatable Java software through Wordpress

Question: I have just written a Java program that I now need to publish. I want to make the software easily updatable, and I therefore need your advice. The program will be used by people with minimal technical knowledge, hence usability is absolute key. The program is not open source.
The situation is this:
First time users download a zip-file containing one .jar-file and two folders that should contain the program output files (.xml-files and .png-files). I want to make it as easy as possible for the user to update the .jar (replace it with another .jar, not necessarily at run time). To my help I have a simple web-based Wordpress site that the user will view as the source of the program.
I'll list the possible solutions I've come up with:
1 (fallback solution). The user have to manually go to the Wordpress site where I'll put a separate direct download link (from Google Drive) for the .jar-file. The user then has to manually replace the .jar in the existing folder with the new one.The drawback to this is that it requires too much work from the user, and they program probably won't get updated very often.
2. Alongside the Program.jar in the zip-file the first user downloads, I place another Program-Updater.jar. This new .jar's sole purpose is to, when the user opens it, download a new version of Program.jar from the web and replace the existing one.This is better than the previous option because it requires less work, even though it's not automatic. The drawback is that I need one more .jar which can confuse the user, and most importantly I have no way of updating the Program-Updater.jar.
3. Java Web Start.I've tried reading up on how this works, but I'm wondering if there is a way to get it to work. One possible problem is that I can't really access the host, and to be able to set up the .jnlp the correct way I think you need this. I'm also wondering how the program's file structure would be (is the .jar even placed on the user's computer?) and if this could confuse the user. Also how to make it always work offline.
4. Suggest your own solution!
Any input on this matter would be greatly appreciated, and I'll gladly give more info than I already have.
Cheers
Comment: If you use github, you can use their webhooks to send a json payload on a new git commit, and trigger a script to get the latest jarfile/compile it.
Comment: @Rogue Haven't come across Webhooks before, will definitely check it out! From what I can see webhooks is mainly used in web development, to make services like jenkins and jira listen to when a Git repo has changed. Is there actually a way to make my desktop .jar listen to the same events and start downloading a new file?
Comment: well realistically anything that listens on a port for a json payload from github can begin executing anything as a result from it
Comment: From your answer I've somehow discovered GetDown which seems very promising!
Answer: Getdown was the way to go; it is extremely easy to use.
I'll put the .zip on Google Drive with a direct download link to it on my Wordpress site.
The files used by getdown are placed in and downloaded from my public git repo.
Comment: Now I've actually created an installer and put an .exe on the site instead.


Is a topologically transitive action on a second countable space point transitive?

Question: Let $G$ be a topological group acting continuously on an Hausdorff space $X$. We say that the action is topologically transitive if for any open $U\subseteq X$, $UG$ is dense in $X$, and we say that the action is point transitive if there exist a point $x$ with dense orbit $xG$.
It's straightforward to see that point transitive implies topologically transitive, and exercise 6 in the first chapter of Auslander's "Minimal Flows and their Extensions" asks to prove that the converse also holds if $X$ is second countable.
It's easy to see that if $Y\subseteq X$ is the set of transitive points (points with a dense orbit), then $Y=\bigcap UG$, where $U$ varies over nonempty sets in a basis for the topology of $X$, and so if $X$ is second countable there is a comeager $G_\delta$ set of points with dense orbits. With some extra assumptions on $X$, such as $X$ compact, or more generally $X$ Baire, this is enough to solve the exercise I mentioned, but I don't see why this intersection must be nonempty in general.
The book so far has been very careful in stating explicitely when $X$ is assumed compact, so I'm not sure whether this is a typo in the exercise or whether I'm missing something, the same result is also found in "Topological Dynamics" by Gottschalk and Hedlund as theorem 9.20, but with even stronger assumptions, namely they ask for the phase space to be Polish (hence Baire).
So in conclusion my doubt is the question in the title: Suppose that the topological group $G$ acts continuously on the second countable, Hausdorff space $X$ with an action that is topologically transitive. Must the action be point transitive? What is a counterexample if the answer is negative?
Answer: Take the natural $\Bbb Z$-action on $\{0, 1\}^{\Bbb Z}$ by shift, and consider the subspace $X$ of periodic $2$-sided sequences of some unspecified period length. Clearly the original action is topologically transitive, and $X \subset \{0, 1\}^{\Bbb Z}$ is dense. Thus, the $\Bbb Z$-action on $X$ is in particular topologically transitive as well. Every orbit is periodic.


Expectation of convex function of a Beta random variable

Question: Suppose I have two Beta random variables
$$
X \sim \text{Beta}(a, b), \\
Y \sim \text{Beta}(ca, cb),
$$
with $c > 1$. They both have same mean $\tfrac{a}{a+b}$, but $Y$ is more "peaky" than $X$. My question is as follows. Let $t \ge 0$; does
$$
\mathbb{E}(e^{-tX}) \ge \mathbb{E}(e^{-tY}) \;\; \text{?}
$$
My intuition says yes, because $X$ "spreads" the weight more, therefore taps into the places where $e^{-tx}$ is large. The case $t = 0$ is trivial, but I would like to prove it for $t > 0$.
Here is a mathematica plot, with $t = 4$, and $(a, b) \in \{(2,4), (4,8), (8,16)\}$.
p1 = Plot[
   Evaluate@
    Table[PDF[BetaDistribution[\[Alpha], 2*\[Alpha]],
      x], {\[Alpha], {2, 4, 8}}], {x, 0, 1}, Filling -> Axis];
p2 = Plot[Exp[-4 x], {x, 0, 1}];
Show[p1, p2]

and the expectations, providing some empirical support to my claim:
Plot[Hypergeometric1F1[x, 3 x, -4], {x, 2, 8}, Frame -> True]

Note: I know that the expectation I'm trying to compute is just the moment generating function of the Beta distribution evaluated at negative values. This MGF is Kummer's confluent hypergeometric function of the first kind: $\mathbb{E}(e^{-tX}) = {}_1F_1(a, a+b, -t)$. I've spent quite a bit of time investigating this function, and nothing came out of it.
Comment: May we presume "$k$" is a synonym for "$t$"?
Comment: @whuber good catch, thank you! That's indeed a typo. $k$ should be $t$, I will update the question right away.
Answer: Use the following identity: $_1F_1(x, y, t) = e^{t} {}_1F_1(y - x, y, -t)$. Thus the inequality $$_1F_1(a, a + b, -t) \geq {}_1F_1(ca, ca + cb, -t),~c > 1$$ can be rephrased as $$\begin{aligned}&e^{-t} {}_1F_1(b, a+b, t) \geq e^{-t} {}_1F_1(cb, ca+cb, t) \implies \\ &{}_1F_1(b, a+b, t) - {}_1F_1(cb, ca+cb, t) \geq 0\end{aligned}$$
The original inequality is in terms of the mgf of random variables $X \sim \text{Beta}(a,b)$ and $Y \sim \text{Beta}(ca,cb)$; the second inequality is in terms of the mgf of random variables $X^* \sim \text{Beta}(b,a)$ and $Y^* \sim \text{Beta}(cb, ca)$. This reflects the fact that a Beta random variable is completely determined by its complement.
Now, appeal to the series representation of $\mathbb{E}[e^{tX^*}]$, that is:
$$\mathbb{E}[e^{tX^*}] - \mathbb{E}[e^{tY^*}]  = \sum_{k=0}^\infty \frac{t^k}{k!}(\mathbb{E}[(X^*)^k] - \mathbb{E}[(Y^*)^k])$$
The inequality $\mathbb{E}[e^{tX^*}] - \mathbb{E}[e^{tY^*}] \geq 0$ (and by extension $\mathbb{E}[e^{-tX}] - \mathbb{E}[e^{-tY}] \geq 0$) will clearly hold if the raw moments of $X^*$ are all greater than or equal to the corresponding moments of $Y^*$.
This is in fact the case: the raw moments of $X^* \sim \text{Beta}(b,a)$ are given by
$$\mathbb{E}[(X^*)^k] = \frac{b^{(k)}}{(a + b)^{(k)}}$$
where $x^{(n)} = \prod_{i=0}^{n-1} (x + i)$ is the rising factorial. For $c > 1$, $k \geq 0$, then $\frac{(ac + bc)^{(k)}}{(a + b)^{(k)}} \geq \frac{(bc)^{(k)}}{(b)^{(k)}}$ with equality only at $k=0$ and $k=1$. Therefore, if $X^* \sim \text{Beta}(b,a)$ and $Y^* \sim \text{Beta}(cb, ca)$, then for all integers $k \geq 0$, $\mathbb{E}[(X^*)^k] \geq \mathbb{E}[(Y^*)^k]$.
Comment: Nate, many thanks for your excellent answer! I checked it in detail, makes complete sense. I can't thank you enough!


Xcode code console printing blank when using po

Question: When I use the terminal/console to print out a value by typing po object it prints blank for all objects. This only happens for my work project which is really big and my small demo projects work fine.
Also its not happening for any of my colleagues. I was using Xcode 10.2 and upgraded to Xcode 10.3 to see if it fixes the problem.

stringValue is an extension on bool that returns "true" or "false" however this happens for all objects so I don't think the code there is relevant.
Due to the huge compile time of our app its quite time consuming to always write print(object) or debugPrint(object) in the code.
Any ideas how to fix the issue?
Answer: Can you try to press on i it does the same, but sometimes it's work for me.
Also check this out: XCode's po command has stopped working

Let me know if this help you.
Answer: Try the v command.
From the XCode release notes

The LLDB debugger has a new command alias, v, for the "frame variable"
  command to print variables in the current stack frame. Because it
  bypasses the expression evaluator, v can be a lot faster and should be
  preferred over p or po. (40066460)
Comment: useful to know for the future


threejs, adding points to scene and not seeing them

Question: Hello I have one doubt:
I have studied:
https://threejs.org/docs/#api/materials/PointsMaterial
And I have adapted the example to work with my existing code.
The aim is to render points on top of the model which we have loaded on click position.
Here we have the code, the important part is onDocumentMouseDown(), the file, logic.js:
if (!Detector.webgl) Detector.addGetWebGLMessage();

// global variables for this scripts
let OriginalImg,
    SegmentImg;

var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var mousePressed = false;
var clickCount = 0;

init();
animate();

// initilize the page
function init() {
    let filename = "models/nrrd/columna01.nrrd"; // change your nrrd file
    let idDiv = 'original';
    OriginalImg = new InitCanvas(idDiv, filename);
    OriginalImg.init();
    console.log(OriginalImg);

    filename = "models/nrrd/columnasegmentado01.nrrd"; // change your nrrd file
    idDiv = 'segment';
    SegmentImg = new InitCanvas(idDiv, filename);
    SegmentImg.init();
}

let originalCanvas = document.getElementById('original');
originalCanvas.addEventListener('mousedown', onDocumentMouseDown, false);
originalCanvas.addEventListener('mouseup', onDocumentMouseUp, false);

function onDocumentMouseDown(event) {
    mousePressed = true;

    clickCount++;

    mouse.x = ( ( event.clientX - OriginalImg.renderer.domElement.offsetLeft ) / OriginalImg.renderer.domElement.clientWidth ) * 2 - 1;
    mouse.y = -( ( event.clientY - OriginalImg.renderer.domElement.offsetTop ) / OriginalImg.renderer.domElement.clientHeight ) * 2 + 1

    console.log('Mouse x position is: ', mouse.x, 'the click number was: ', clickCount);
    console.log('Mouse Y position is: ', mouse.y);

    raycaster.setFromCamera(mouse.clone(), OriginalImg.camera);
    var objects = raycaster.intersectObjects(OriginalImg.scene.children);

    var pointGeometry = new THREE.Geometry();

    var position = new THREE.Vector3();
    position.x = objects[0].point.x;
    position.y = objects[0].point.y;
    position.z = objects[0].point.z;

    pointGeometry.vertices.push(position);

    var pointMaterial = new THREE.PointsMaterial({color: 0x888888});

    var point = new THREE.Points(pointGeometry, pointMaterial);

    OriginalImg.scene.add(point);

    console.log(objects);
}

function onDocumentMouseUp(event) {
    mousePressed = false
}

function animate() {

    requestAnimationFrame(animate);
    OriginalImg.animate();
    SegmentImg.animate();

}

And we do add the points to the scene, but in fact they do not render, they do not show, and I wonder why?:

As you could see in the image we see that the raycaster intercepts those new created points, however the do not get drawn.
I wonder if they are too small, or just the color hides them with the background.
Could you help me please?.
Additional code:
// this class handles the load and the canva for a nrrd
// Using programming based on prototype: https://javascript.info/class
// This class should be improved:
//   - Canvas Width and height

InitCanvas = function (IdDiv, Filename) {

    this.IdDiv = IdDiv;
    this.Filename = Filename
}

InitCanvas.prototype = {

    constructor: InitCanvas,

    init: function () {

        this.container = document.getElementById(this.IdDiv);

        // this should be changed.
        debugger;
        this.container.innerHeight = 600;
        this.container.innerWidth = 800;

        //These statenments should be changed to improve the image position
        this.camera = new THREE.PerspectiveCamera(60, this.container.innerWidth / this.container.innerHeight, 0.01, 1e10);
        this.camera.position.z = 300;

        let scene = new THREE.Scene();
        scene.add(this.camera);

        // light

        let dirLight = new THREE.DirectionalLight(0xffffff);
        dirLight.position.set(200, 200, 1000).normalize();

        this.camera.add(dirLight);
        this.camera.add(dirLight.target);

        // read file

        let loader = new THREE.NRRDLoader();
        loader.load(this.Filename, function (volume) {

            //z plane
            let sliceZ = volume.extractSlice('z', Math.floor(volume.RASDimensions[2] / 4));

            debugger;
            this.container.innerWidth = sliceZ.iLength;
            this.container.innerHeight = sliceZ.jLength;

            sliceZ.mesh.material.color.setRGB(0,1,1);

            console.log('Our slice is: ', sliceZ);

            scene.add(sliceZ.mesh);
        }.bind(this));

        this.scene = scene;

        // renderer

        this.renderer = new THREE.WebGLRenderer({alpha: true});
        this.renderer.setPixelRatio(this.container.devicePixelRatio);
        debugger;
        this.renderer.setSize(this.container.innerWidth, this.container.innerHeight);

        // add canvas in container
        this.container.appendChild(this.renderer.domElement);

    },

    animate: function () {

        this.renderer.render(this.scene, this.camera);
    }

}

I wonder about the point size because if we see this example they are made with 0.05 of size:
https://github.com/mrdoob/three.js/blob/master/examples/webgl_interactive_raycasting_points.html
And in the example we see the camera being quite far away from the points being generated and they are visible:
https://threejs.org/examples/webgl_interactive_raycasting_points.html
What do you think?
Answer: You can use THREE.BufferGeometry() with .setDrawRange():

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(1, 5, 5);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var mesh = new THREE.Mesh(new THREE.SphereBufferGeometry(3, 32, 24), new THREE.MeshBasicMaterial({
  wireframe: true,
  color: "red"
}));
scene.add(mesh);

var idx = 0;
var maxIdx = 10;

var points = [];
for (let i = 0; i < maxIdx; i++) {
  points.push(new THREE.Vector3());
}
var geometry = new THREE.BufferGeometry().setFromPoints(points);
geometry.setDrawRange(0, idx);

var points = new THREE.Points(geometry, new THREE.PointsMaterial({
  size: 0.125,
  color: "yellow"
}));
scene.add(points);

window.addEventListener("mousemove", onMouseMove, false);
window.addEventListener("mousedown", onMouseDown, false);

var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var intersects = [];

function onMouseMove(event) {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}

function onMouseDown(event) {
  raycaster.setFromCamera(mouse, camera);
  intersects = raycaster.intersectObject(mesh);
  if (intersects.length === 0) return;

  if (idx == maxIdx) return;

  let p = intersects[0].point;
  geometry.attributes.position.setXYZ(idx, p.x, p.y, p.z);
  geometry.attributes.position.needsUpdate = true;
  idx++;
  geometry.setDrawRange(0, idx);
}

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}


Magmi off topic?

Question: I want to know explicitly if questions that exist only within the scope of Magmi (such that they are only useful to users of Magmi) are off-topic, as a question I posted recently got put on hold as off-topic because it was within the scope of magmi (Magmi product import with image attributes processor can't find images) I already knew the rule regarding third-party extensions/applications but I know (as stated in this meta post's answer Questions about extensions) that if:
"they are an integral part of the Magento landscape, then certainly they should be on topic"
I don't quite know what this means but I assumed it meant applications that are popular enough to be considered a must-have install for magento installations and I would consider Magmi exactly that (as the most popular alternative to magento's import functionality).
I was still cautious about posting the question but I finally concluded that it must be on-topic to do so as the magmi tag does exist and includes 153 questions that are mostly within the scope of only magmi (https://magento.stackexchange.com/questions/tagged/magmi)
and none of these are off topic and have answers, comments and activity.
So what exactly is the clear rule on posting questions with the magmi tag?
The community behaviour on this seems more than a little confusing.
Answer: As far as I'm concerned, Magmi questions are on-topic because the source code is readily available.
Comment: That's what I thought but still my question was marked as off, so going forward is it generally accepted that magmi questions aren't implicitly off-topic, how do we come to a point where the community as a large part comes to a consensus on this?
Comment: http://area51.stackexchange.com/ Appearantly we can make this happen.
Comment: You'll be hard-pressed to get a Magmi-specific site. I was originally warned that a Magento-specific site wouldn't happen, given the strength of the Magento tag on StackOverflow.
Comment: Not agree with that because if we talk about source code available every `free extension` will be `on topic`.
Comment: @QaisarSatti Exactly. Ideally (and perhaps mandatorily) there is relevant source code provided in the question by OP.
Comment: [Related](https://magento.meta.stackexchange.com/questions/1219/question-put-on-hold-as-off-topic)
Answer: I think Magmi questions should be treated as off topic. If we allow one exception, soon we will have to allow all of them and this website will end up being a cemetery of un-handled extension support questions.
Each developer should support his/her own extensions.
If you have issues using an extension you should address it to the developer.
On the other hand if you ask a question like:

"I'm using insert extension name here, I have insert problem here
with it. Here is the code that is causing my issue:
insert code here
Can you help me on this?".
it should be treated as on topic.

Of course there are some users in here that answer questions about their own extensions.
But they are not too many of them. Even then, the third party extension question should be treated as "off topic", but I have no problem with reopening it if there is a valid answer to it.
Comment: but the point I'm making is that if they are off-topic then we have an issue in that the tag has over a hundred questions in that aren't flagged.

Surely that's a little misleading? What do we do about all those questions?
Comment: Then we have to close those

Magmi off topic?


How to add a circular bottom collapsible toolbar in react native app?

Question: I am looking to add a circular bottom to the toolbar in a react-native application that is as shown in the image below.

How do I achieve it in the app?
Comment: you can refer the SO answer from the URL https://stackoverflow.com/questions/35572084/how-to-realize-a-circle-image-button-with-react-native
Comment: That is for a button I suppose. I am looking for collapsible toolbar with circular bottom @Google
Comment: Do you mean parallax effect?
Comment: Yes but with the circular or curved at the bottom as in the image @JAINESHDOSHI
Answer: Here is the working example. Hope this helps
<code>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Dimensions,
  Image,
  FlatList,
  AsyncStorage
} from 'react-native';

const window = Dimensions.get('window');

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

var localizedString;

type Props = {};
export default class App extends Component<Props> {

constructor(Props){
    super(Props);
    this.state={
      collapse: false
    };
  this.collapseEnable =this.collapseEnable.bind(this);
  this.collapseDisable =this.collapseDisable.bind(this);
  }

collapseEnable(){
  this.setState({
    collapse:true
  })
}

collapseDisable(){
  this.setState({
    collapse:false
  })
}

render() {
    return (
      <View style={{ flex: 1 }}>
        {(this.state.collapse==false)?
          <TouchableOpacity style={{height:40, backgroundColor:'pink', alignItems:'center', justifyContent:'center'}} onPress={()=>{this.collapseEnable()}}>
            <Text style={{fontSize:20}}>Click here</Text>
          </TouchableOpacity>
           :
          <TouchableOpacity style={styles.container} onPress={()=>{this.collapseDisable()}}>
            <View style={styles.background} >

            </View>
          </TouchableOpacity>
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  container: {
    alignSelf: 'center',
    justifyContent:'center',
    width: '100%',
    overflow: 'hidden', // for hide the not important parts from circle
    height: 100
  },
  background: { // this shape is a circle
    borderRadius: 800, // border borderRadius same as width and height
    width: '200%',
    height: 800,
    marginLeft: -200, // reposition the circle inside parent view
    position: 'absolute',
    bottom: 0, // show the bottom part of circle
    overflow: 'hidden',
    backgroundColor:'pink' // hide not important part of image
  },
});
</code>
Comment: This is for a view. Can the same be done for Toolbar?
Comment: Yes you can
Please go to this link.
Note: You have to adjust the styling.
link: codepen.io/pramod005/pen/mKdpjd
Comment: How to fit the view to screen width?
I am using gradient colour. Unable to manage the colors


Framework not found (RoboVM Google adMob)

Question: I am trying to add google admob to my Libgdx project that uses RoboVM. I followed the guide here: https://github.com/robovm/robovm-robopods/tree/master/google-mobile-ads/ios but I am getting this error:
ERROR] ld: framework not found GoogleMobileAds
[ERROR] clang: error: linker command failed with exit code 1 (use -v to
see invocation)
[ERROR] Couldn't compile app

However I followed the instructions to put the following code in the robovm.xml file:
<config>
  <executableName>${app.executable}</executableName>
  <mainClass>${app.mainclass}</mainClass>
  <os>ios</os>
  <arch>thumbv7</arch>
  <target>ios</target>
  <iosInfoPList>Info.plist.xml</iosInfoPList>
  <resources>
    <resource>
      <directory>../android/assets</directory>
      <includes>
        <include>**</include>
      </includes>
      <skipPngCrush>true</skipPngCrush>
    </resource>
    <resource>
      <directory>data</directory>
    </resource>
  </resources>
  <forceLinkClasses>
    <pattern>com.badlogic.gdx.scenes.scene2d.ui.*</pattern>
    <pattern>com.badlogic.gdx.graphics.g3d.particles.**</pattern>
    <pattern>com.android.okhttp.HttpHandler</pattern>
    <pattern>com.android.okhttp.HttpsHandler</pattern>
    <pattern>com.android.org.conscrypt.**</pattern>
    <pattern>com.android.org.bouncycastle.jce.provider.BouncyCastleProvider</pattern>
    <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.BC$Mappings</pattern>
    <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi</pattern>
    <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi$Std</pattern>
    <pattern>com.android.org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi</pattern>
    <pattern>com.android.org.bouncycastle.crypto.digests.AndroidDigestFactoryOpenSSL</pattern>
    <pattern>org.apache.harmony.security.provider.cert.DRLCertFactory</pattern>
    <pattern>org.apache.harmony.security.provider.crypto.CryptoProvider</pattern>
  </forceLinkClasses>
  <libs>
      <lib>z</lib>
  </libs>
  <frameworkPaths>
    <path>libs</path>
  </frameworkPaths>
  <frameworks>
    <framework>UIKit</framework>
    <framework>OpenGLES</framework>
    <framework>QuartzCore</framework>
    <framework>CoreGraphics</framework>
    <framework>OpenAL</framework>
    <framework>AudioToolbox</framework>
    <framework>AVFoundation</framework>
    <framework>GoogleMobileAds</framework>
  </frameworks>
</config>

EDIT:
Here's the build.gradle for iOS module:
sourceSets.main.java.srcDirs = [ "src/" ]

sourceCompatibility = '1.7'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

ext {
    mainClassName = "com.samuel.doubledodge.IOSLauncher"
}

launchIPhoneSimulator.dependsOn build
launchIPadSimulator.dependsOn build
launchIOSDevice.dependsOn build
createIPA.dependsOn build

robovm {
    archs = "thumbv7:arm64"
}

eclipse.project {
    name = appName + "-ios"
    natures 'org.robovm.eclipse.RoboVMNature'
}

Comment: Show your `build.gradle` of ios module
Comment: Edited the `build.gradle` in. @AbhishekAryan
Comment: Is your folder structure ios/libs/GoogleMobileAds.framework ?
Comment: @TomGrillGames Thanks. That was the issue. I was putting it in the ios/builds/libs instead of ios/libs. Thanks a lot for the help :)
Comment: @SamuelM And what to do if your lib should be automatically imported by gradle?
Answer: To anyone who was having this issue, TomGrillGames' solution in the comments above was what solved my problem.I was putting it in the ios/builds/libs instead of ios/libs.
Comment: And what to do if your lib should be automatically imported by gradle?


Implementing Z Buffer Algorithm

Question: I'm trying to experiment with computer graphics and would like to implement Z Buffer algorithm for rendering in Software.
So I'm trying to use the following plane equation:
z = -(ax + by + d)/c

To compute the Z coordinate of a pixel using the plane form equation
should I compute the Face normal of the triangle ? or a normal of a vertex is enough ?
Here is how I compute it:
double zValueOfPoint(float vx, float vy, float vz, float x, float y, float nx, float ny, float nz)
{
    float A = nx;
    float B = ny;
    float C = nz;
    float D = -(nx*vx, +ny * vy + nz * vz);
    float z = -(A*x + B * y + D) / C;
    return z;
}

vx,vy,vz vertex,  x,y pixel coordinate, nx,ny,nz normal of a vertex
Now for each TOP or Bottom Triangle I check the Z Pixel to ZBuffer pixel
// Top of the triangle
    for (int y = y0; y<y2; y++)
    {

        for (int x = xl_edge; x<xr_edge; x++)
        {
            float zOfPixel = zValueOfPoint(vx, vy, vz, x, y, nx, ny, nz);
            if (zOfPixel < zbuffer[int(x + y * m_Width)]) {
                zbuffer[int(x + y*m_Width)] = zOfPixel;
                SetPixel((unsigned int)x, (unsigned int)y, color);
            }

        }//end for loop x

The same for bottom triangle
Right now I get completely broken model. The Z Buffer is initialized correctly.
Comment: `float D = -(nx*vx, +ny * vy + nz * vz)` has an extra comma in the middle. Also, once you have implemented perspective interpolation in your rasterizer, this comes for free.
Comment: `z` is interpolated from the face vertexes directly the same way as `x,y` ... while rasterizing. No need to use plane equation...
Answer: You don't need to do anything with face normals when implementing Z buffering. You only need per vertex "depths" for your projected triangles.
Further, and I apologise for only skimming through your question's code, but if you want to do a perspective projection, then make sure the "depth" you are linearly interpolating per pixel is not the world/camera depth but something that is proportional (What? No mathjax on SO?) to 1/Z_world or 1/W.
That is, you have a projected triangle where each vertex, Vi, has {Vi_screenX, Vi_screenY, Vi_projectedDepth} and
Vi_projectedDepth = linear_function_of(1 / Vi_Z_camera).
Very simple examples include:

Vi_projectedDepth = 1/Vi_Z_camera or
  Vi_projectedDepth = 1.0 - 1/Vi_Z_camera

You must then linearly interpolate the Vi_projectedDepth  values across the triangle but you don't need to take the reciprocal of these interpolated values ( at least not for Z-buffer ordering. If you want to do perspective correct texturing, OTOH, you _may_ need to eventually compute the reciprocal ).
If you don't do this, you can get very strange results whenever geometry has implicit intersection - I just remembered I made a comment on this in SE Graphics.

Implementing Z Buffer Algorithm


Why won't my calculations for this code work?

Question:     private void btnCalculate_Click(object sender, RoutedEventArgs e)
    {
        double pay;
        pay = 0.00;

        double add;
        add = 0.00;

        int age;
        age = int.Parse(txtAge.Text);

        string month;
        month = txtMonth.Text;

           if (age >= 18 && age <= 55)
           {
               pay = 350;
           }

           else if (age <= 18)
           {
               pay = 150;                   //if-else-if statements depending on age
           }

           else if (age > 55)
           {
               pay = 35;
           }

        switch (month)
        {
            case "January":
            case "january":
            case "July":
            case "july":          //switch statement, how much you pay depending on month
                add = 100;
                break;

            case "February":
            case "february":
            case "August":
            case "august":
                add = 120;
                break;

            case "March":
            case "march":
            case "September":
            case "september":
                add = 140;
                break;

            case "April":
            case "april":
            case "October":
            case "october":
                add = 160;
                break;

            case "May":
            case "may":
            case "November":
            case "november":
                add = 180;
                break;

            case "June":
            case "june":
            case "December":
            case "december":
                add = 120;
                break;
        }

           lblTotal.Content = (pay + add) * 1.13; //calculation that prints to the label

    }

So when I run the code it just outputs 0 in the label
If I put the Calculation at the bottom (seen here) it will say something about the label not being reachable. Any help would be great. Code has been solved
Comment: You have to put the `lblTotal.Content = (pay + add) * 1.13;` outside the switch statement.
Comment: Also, there is a bug: the first and second if statements will execute for if age = 18.
Comment: Not realy, Joel. Only the first one. As the second is an else-if statement, it will be discarded by the first.
Comment: @vicmota, that's correct. Disregard my previous comment. Thanks
Answer:
You can directly assign variables. Declaration and assignment need not be different statements.
18 has two different checks: >= 18 in the if, and <= 18 in the first else if. Not a code error but a semantics error.
The final assignment is inside the switch block and unreachable. Put it outside the switch.

It looks like you're using WPF? If so, you should have a look at the MVVM pattern, as well as data binding. It's a good bit to learn and not easy but very important in WPF. It will eliminate the need for querying and writing properties of elements in most cases, though – because that will be handled by the runtime.
Also consider using a ComboBox for the month. Way easier to validate the data.
Answer: As suggested your label assignment was inside the switch statement causing it not to execute unless the month was June or December.
In any case, I'd suggest though that you simplify.
Try this:
private void btnCalculate_Click(object sender, RoutedEventArgs e)
{
    int age = int.Parse(txtAge.Text);
    double pay = age <= 18 ? 150.0 : (age > 55 ? 35.0 : 350.0);

    int index = (DateTime.Parse("1 " + txtMonth.Text).Month - 1) % 6;
    double[] choices = new [] { 100.0, 120.0, 140.0, 160.0, 180.0, 120.0 };
    double add = choices[index];

    lblTotal.Content = (pay + add) * 1.13;
}

Answer: The label assignment was inside the switch statement. There's a lot of other improvements you can make to code as well.
For starters, you can also join assignment and declaration of variables and use .ToLower() in switch to save yourself the extra cases:
    private void btnCalculate_Click(object sender, RoutedEventArgs e)
    {
        var pay = 0.00;
        var add = 0.00;
        var age = int.Parse(txtAge.Text);
        var month = txtMonth.Text;

        if (age >= 18 && age <= 55)
        {
            pay = 350;
        }
        else if (age <= 18)
        {
            pay = 150;
        }
        else if (age > 55)
        {
            pay = 35;
        }

        switch (month.ToLower())
        {
            case "january":
            case "july":
                add = 100;
                break;

            case "february":
            case "august":
            case "june":
            case "december":
                add = 120;
                break;

            case "march":
            case "september":
                add = 140;
                break;

            case "april":
            case "october":
                add = 160;
                break;

            case "may":
            case "november":
                add = 180;
                break;
        }

        lblTotal.Text = Convert.ToString((pay + add) * 1.13); //calculation that prints to the label
    }


Android: TextView Not showing all letters

Question: A simple AlertDialog is giving me unexpected results: missing letters. This only happens in an AlertDialog. In my theme I have set monospace as my default font and then I replaced the monospace font with a custom typeface (.otf) that was provided to me by the client.
I get expected results on Android 25 and can reproduce the issue on 19. I haven't cared to try any version between those.
Some things I have tried:

Removing the custom font to see if it was the culprit, resulting in losing all text rather than bits. Also tried switching the custom font to sans or another typeface as my default.
Creating custom dialog theme
Changing colors to see if the text was somehow matching the background, and I don't believe that is the case.
Hardcoding text. No difference
Using android.app.AlertDialograther than android.support.v7.app.AlertDialog. No Difference.
I have styles for DatePickerDialog and TimePickerDialog. I tried removing those to see if they were interfering. Obviously not, where those styles are vs 21> and my problem is in 19. I have not specified any styles or themes for AlertDialog. My root theme is Theme.AppCompat.DayNight.NoActionBar. The rest of the theme only sets primary and secondary colors. Nothing too extravagant.

Android 25 expected results

Android 19 wtf results

This is the extent of the code:
import android.support.v7.app.AlertDialog;

public static Maybe<Boolean> showConfirmDialog(Context context, int title, int message, int positive, int negative) {
        return Maybe.create(e -> {
            final AlertDialog dialog = new AlertDialog.Builder(context)
                    .setTitle(title)
                    .setMessage(message)
                    .setPositiveButton(positive, (d, w) -> e.onSuccess(true))
                    .setNegativeButton(negative, (d, w) -> e.onSuccess(false))
                    .show();

             dialog.setOnDismissListener(d -> e.onComplete());

             e.setCancellable(() -> {
                if (dialog != null && dialog.isShowing())
                   dialog.dismiss();
             });

        });
}

I ended up creating a dialog from scratch because I couldn't figure out what was going on in the amount of time I had, but it bothered me enough that I need to get a solution.
Comment: I haven't been able to recreate your symptoms.  Can you share more information?  What is the font you are using, your styles.xml file, the code you used to set the typeface, etc.
Comment: This problem originally occurred yesterday. I am trying to recreate it myself and now I can't. I am not sure what is more frustrating: the problem itself, or the fact I can't recreate the problem.
Comment: I notice it will happen on other views. But not only missing letters, but missing _parts_ of a letter. If i scroll out of view and back it will fix itself. Maybe this is an emulator problem?
Comment: Weird.  Could be an emulator problem, or a problem with that emulator on the specific hardware you're running.  Can you change the emulator settings or perhaps try a different monitor?
Answer: I have similar problem with supprot alertdialog. I resolved it by custom theme dialog. Try this variant. Add to your builder custom theme:
new AlertDialog.Builder(getContext(), R.style.DefaultAlertDialogTheme)

And here your style.xml: