text:
Q: Using javascript and jquery, to populate related select boxes with array structure Using answers to this question, I have been able to populate a select box based on the selection of another select box. ( I posted my answer here) Pulling the data from an array structure built server-side, stored in a .js file and referenced in the html page.
Now I would like to add a third select box. If I had 3 sets of data (model, make, options) something like this (pseudo code):
cars : [Honda[Accord[Lx, Dx]], [Civic[2dr, Hatchback]],
   [Toyota[Camry[Blk, Red]], [Prius[2dr,4dr]]

Ex: If Honda were selected, the next select box would have [Accord Civic] and if Accord were selected the next select box would have [Lx Dx]
How can I
1) create an array structure to hold the data? such that
2) I can use the value from one select box to reference the needed values for the next select box
Thanks
EDIT
I can create the following, but can't figure out the references in a way that would help populate a select box
var cars = [
 {"makes"  : "Honda",
  "models"  : [
    {'Accord' : ["2dr","4dr"]} ,
    {'CRV'  : ["2dr","Hatchback"]} ,
    {'Pilot': ["base","superDuper"] } ]
 },
 {"makes"   :"Toyota",
  "models"  : [
    {'Prius'   : ["green","reallyGreen"]} ,
    {'Camry'   : ["sporty","square"]} ,
    {'Corolla' : ["cheap","superFly"] } ]
 } ] ;

 alert(cars[0].models[0].Accord[0]); ---> 2dr

A: I prefer data structure like this:
var carMakers = [
    { name: 'Honda', models: [
            { name: 'Accord', features: ['2dr', '4dr'] },
            { name: 'CRV', features: ['2dr', 'Hatchback'] },
            { name: 'Pilot', features: ['base', 'superDuper'] }
        ]},

    { name: 'Toyota', models: [
            { name: 'Prius', features: ['green', 'superGreen'] },
            { name: 'Camry', features: ['sporty', 'square'] },
            { name: 'Corolla', features: ['cheap', 'superFly'] }
        ]}
];

Given the three select lists with id's: 'maker', 'model' and 'features' you can manipulate them with this (I believe this is pretty self explanatory):
// returns array of elements whose 'prop' property is 'value'
function filterByProperty(arr, prop, value) {
    return $.grep(arr, function (item) { return item[prop] == value });
}

// populates select list from array of items given as objects: { name: 'text', value: 'value' }
function populateSelect(el, items) {
    el.options.length = 0;
    if (items.length > 0)
        el.options[0] = new Option('please select', '');

    $.each(items, function () {
        el.options[el.options.length] = new Option(this.name, this.value);
    });
}

// initialization
$(document).ready(function () {
    // populating 1st select list
    populateSelect($('#maker').get(0), $.map(carMakers, function(maker) { return { name: maker.name, value: maker.name} }));

    // populating 2nd select list
    $('#maker').bind('change', function() {
        var makerName = this.value,
            carMaker = filterByProperty(carMakers, 'name', makerName),
            models = [];

        if (carMaker.length > 0)
            models = $.map(carMaker[0].models, function(model) { return { name: model.name, value: makerName + '.' + model.name} });

        populateSelect($('#model').get(0), models);
        $('#model').trigger('change');
    });

    // populating 3rd select list
    $('#model').bind('change', function () {
        var nameAndModel = this.value.split('.'),
            features = [];

        if (2 == nameAndModel.length) {
            var makerName = nameAndModel[0],
                carModel = nameAndModel[1],
                carMaker = filterByProperty(carMakers, 'name', makerName);

            if (carMaker.length > 0) {
                var model = filterByProperty(carMaker[0].models, 'name', carModel)

                if (model.length > 0)
                    features = $.map(model[0].features, function(feature) { return { name: feature, value: makerName + '.' + carModel + '.' + feature} })
            }
        }

        populateSelect($('#feature').get(0), features);
    })

    // alerting value on 3rd select list change
    $('#feature').bind('change', function () {
        if (this.value.length > 0)
            alert(this.value);
    })
});

A: Thanks to the answer from @Marko Dunic, I was able to build an array (data) structure that can be referenced to populate 3 select boxes. I didn't use the implementation code only because I didn't completely understand it...it works as posted. I will come back to this code later as I learn jQuery.
My code is posted below (obviously, your reference to jQuery may be different)

<select id="maker"size="10" style="{width=75px}"></select>
<select id="model" size="10" style="{width=75px}"></select>
<select id="feature" size="10"style="{width=75px}"></select>

A: I really liked the solution by @Marko Dunic, but it didn't meet my needs for attaching IDs to the options.  Once I attached the IDs, I realized that I could make the JS code even smaller and simpler.  My solution is designed for when the data comes from a relational database, and the JSON input data retains the relational structure with Primary/Foreign Keys.  Here is the JSON data:

    <title>Populate a select dropdown list with jQuery - WebDev Ingredients</title>

    Enter values, click submit, and look at the post parameters
    <form method="get" action="index.php">

                <select id="sType" name="type_id" style="{width=75px}"></select>
                <select id="sMake"  name="make_id" style="{width=75px}"></select>
                <select id="sModel"  name="model_id" style="{width=75px}"></select>

            <input type="submit">
    </form>

Notice that my solution shifts the functionality so that Make-Model are the 2nd and 3rd text boxes, and Type ( domestic, import, boat, etc. ) are the 1st level.  I got the boilerplate JS down to 23 lines (less comments) while retaining good formatting.
The JSON data is very easy to render from SQL queries, which are cached in java Lists on init because the Type-Make-Model rarely change.  I don't use any dynamic AJAX because that complicates the architecture, and I have a relatively small list of available values, so I just send it at the page request.
"Solutions should be a simple as possible, but no simpler" - A. Einstein

A: You should take a look here for select box manipulation.
For what you want, i think JSON will do the right job for you.
Anyhow, if i were you, i will do this way:
When I change first select, i do an ajax request. With ajax response, i will populate the second box. Same for second box and there you have the third box populated with right data.


text:
Q: When does $F(x)=\ln x -1$ cut through the $x$ axis? If you differentiate this $F(x)=\ln x -1$  you will get $(1/x)$ right?
And how am I supposed to get $(e,0)$?

A: Consider x = 0, at this point ln(o) is undefined, but you are really solving for ln(x) = 1, and the only thing that fits the bill is taking x to be e, which gives your solution as the coordinate (e,0)

A: What you have to do is to solve the following equation:
$$F(x) = \ln(x) - 1 = 0.$$
When you do, you'll find out that $x = e$.
This is where the function crosses the $x$-axis. Thus, the point is $(e,0)$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to convert function-based countdown clock program to JS class format What I did earlier. This is the countdown code I have wrote using functions. The purpose is to make a countdown clock using Vanilla JS.
const refs = {
  day: document.querySelector("span[data-value='days']"),
  hour: document.querySelector("span[data-value='hours']"),
  min: document.querySelector("span[data-value='mins']"),
  sec: document.querySelector("span[data-value='secs']"),
};

const targetDate = new Date("Jul 17, 2021");

function updateClockface(time) {
  const days = pad(Math.floor(time / (1000 * 60 * 60 * 24)));
  const hours = pad(
    Math.floor((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  );
  const mins = pad(Math.floor((time % (1000 * 60 * 60)) / (1000 * 60)));
  const secs = pad(Math.floor((time % (1000 * 60)) / 1000));

  refs.day.textContent = `${days}`;
  refs.hour.textContent = `${hours}`;
  refs.min.textContent = `${mins}`;
  refs.sec.textContent = `${secs}`;
}

function pad(value) {
  return String(value).padStart(2, "0");
}

let intervalId = setInterval(() => {
  const startTime = Date.now();
  let diff = targetDate - startTime;
  updateClockface(diff);
}, refs.sec);

But, right now, I am trying to rewrite it using js-classes. Attaching what I've tried, even though I know I did a lot of mistakes in it. Total newbie in classes.
const refs = {
  day: document.querySelector("span[data-value='days']"),
  hour: document.querySelector("span[data-value='hours']"),
  min: document.querySelector("span[data-value='mins']"),
  sec: document.querySelector("span[data-value='secs']"),
};

class Countdown {
  constructor(selector, targetDate) {
    this.$el = document.querySelector(selector);
    this.targetDate = targetDate;
  }
  getClockItems(time) {
    const days = pad(Math.floor(time / (1000 * 60 * 60 * 24)));
    const hours = pad(
      Math.floor((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    );
    const mins = pad(Math.floor((time % (1000 * 60 * 60)) / (1000 * 60)));
    const secs = pad(Math.floor((time % (1000 * 60)) / 1000));

    updateClock = () => {
      refs.day.textContent = `${days}`;
      refs.hour.textContent = `${hours}`;
      refs.min.textContent = `${mins}`;
      refs.sec.textContent = `${secs}`;
    };
  }

  pad(value) {
    return String(value).padStart(2, "0");
  }
  loadingTimer = setInterval(() => {
    const startTime = Date.now();
    let diff = targetDate - startTime;
    updateClockface(diff);
  }, refs.sec);
}

new CountdownTimer({
  selector: "#timer-1",
  targetDate: new Date("Jul 17, 2021"),
});

Attaching HTML
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        00
        Days

        00
        Hours

        00
        Minutes

        00
        Seconds

A: I've fixed the code, so that it runs.  Mostly just a lot of issues with not using this for variables attached to the class, and a few other problems.  But it seems like you're still in the middle of getting the hang of using classes.
I'm not sure why you are trying to return a function updateClock, but that looks like a pattern you would use if you weren't trying to wrap it in a class.  You tried to pass an object to the constructor, but it's currently set up to take two parameters.
If you are looking for tips on how to "properly" make use of class syntax to clean up this code, I would recommend you go to the Code Review SE.

const refs = {
  day: document.querySelector("span[data-value='days']"),
  hour: document.querySelector("span[data-value='hours']"),
  min: document.querySelector("span[data-value='mins']"),
  sec: document.querySelector("span[data-value='secs']"),
};

class Countdown {
  constructor(selector, targetDate) {
    this.$el = document.querySelector(selector);
    this.targetDate = targetDate;
  }
  updateClockItems(time) {
    const pad = this.pad;

    const days = pad(Math.floor(time / (1000 * 60 * 60 * 24)));
    const hours = pad(
      Math.floor((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    );
    const mins = pad(Math.floor((time % (1000 * 60 * 60)) / (1000 * 60)));
    const secs = pad(Math.floor((time % (1000 * 60)) / 1000));

      refs.day.textContent = `${days}`;
      refs.hour.textContent = `${hours}`;
      refs.min.textContent = `${mins}`;
      refs.sec.textContent = `${secs}`;

  }

  pad(value) {
    return String(value).padStart(2, "0");
  }
  loadingTimer = setInterval(() => {
    const startTime = Date.now();
    let diff = this.targetDate - startTime;
    this.updateClockItems(diff);
  }, refs.sec);
}

new Countdown(...Object.values({
  selector: "#timer-1",
  targetDate: new Date("Jul 17, 2021"),
}));
Attaching HTML

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>11th HW</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css" />

        00
        Days

        00
        Hours

        00
        Minutes

        00
        Seconds


text:
Q: Space between "function" and parenthesis in VS JS editor Why does Visual Studio JavaScript editor put a space between the "function" keyword and its following parenthesis ?
function foo () {
}
Is that some kind of cool convention ?

A: It is a stylistic convention in Visual Studio. In the past you could not change it, but you might find now you can: "Options -> Text Editor -> JScript -> Formatting"
Most refer the lack of space to Douglas Crockford's javascript style guide


text:
Q: Python:Numpy Function not yielding correct results I had a question concerning the results of a polynomial equation while using python/numpy.
I have defined a function using a polynomial having a rather small leading coefficient.
The following is my code and the equation:
import matplotlib.pyplot as plt
import numpy as np

def myfunction(X):
    return 9.06043895*10**(-9)*X**6-1.67073053*10**(-6)*X**5 + \
          7.49688511*10**(-5)*X**4 + 7.97984114*10**(-4)*X**3 - \
          6.07927087*10**(-2)*X**2 - 0.415861627*X + 80.62563

Input = np.arange(0, 100, 1)
Output = myfunction(Input)

plt.plot(Input, Output)

This yields the following plot:

The error seems to be in the way that the resultant Y is calculated as the array itself is off. (The values match the plot, but are in correct)
Sample of the exact same equation plotted using WolframAlpha:
(literal copy/paste from above minus the \'s and returns)

Can anyone help shed some light on this problem?
I have a feeling there may be some truncations possibly while handling the function, but I feel that this equation is not that bad...
Thank you all for your time and hopefully assistance.

A: This is an int vs. float issue.  You're getting integer overflow:
>>> np.int32(100)**6
-727379968
>>> np.float32(100)**6
1000000000000.0

because np.arange(0, 100, 1) is giving you integers.
You can make them floats however you like-- I usually use np.arange(0, 100, 1.0), but to be honest I prefer np.linspace.
With floats, I get:


text:
Q: Are there any ways to improve this python code to count even numbers in a pascal triangle? This is a piece of code I wrote to count how many even numbers there are in the first 1023 rows of the pascal triangle. However, I feel like it may need to be improved, especially the function next_row.
def next_row(r):
    i = 0
    s = []
    while i < len(r) -1:
        s.append(r[i] + r[i+1])
        i += 1
    s.insert(0, 1)
    s.append(1)
    return s

def count_even(r):
    counter = 0
    for item in r:
        if item % 2 == 0:
            counter += 1
    return counter

def results(i, t, e):
    print('In the first ' + str(i) + ' lines of the pascal triangle, there are ' + str(t) + ' entries. ' +
        str(e) + ' of them are even.')

r = [1]
even = 0
total = 0
for i in range (0, 1023):
    even += count_even(r)
    total += len(r)
    r = next_row(r)
    results(i+1, total, even)

A: IMHO your code is OK, I would propose just using
for i in range(len(r) -1):
    s.append(r[i] + r[i+1])

instead of
while i < len(r) -1:
    s.append(r[i] + r[i+1])
    i += 1

PS
If you instead use
for i in range(len(r) -1):
    s.append(r[i] ^ r[i+1])

You'll see that the results do not change, as suggested by @John Coleman, it works. But the Pascal triangle degenerates into a collection of 0s and 1s, if you print it out.
In this case, you can simplify count_even:
def count_even(r):
    return len(r)-sum(r)

A: Just making your code (first two functions) slightly less verbose using list comprehensions. By doing so, you avoid the need of initializing i=0 and an empty list s=[] and the while loop to keep track of the i. In your count_even function, you can also use the following counter = len(r[r%2==0]) provided r is an array (In your code it's a list).
def next_row(r):
    s = [r[i] + r[i+1] for i in range(len(r)-1)]
    s.insert(0, 1)
    s.append(1)
    return s

def count_even(r):
    counter =  len([i for i in r if i%2 == 0])
#   counter = len(r[r%2==0]) #  If 'r' is an array
    return counter

Rest I kept the same.

A: To make the code more readable and also more compact, I suggest you the following solution with comments, f-strings and comprehensions (instead of classic for loops). The main idea is to store the content of each line, the total count of element in each line and the count of even elements in each line inside 3 lists. This way you keep all values of the Pascal triangle in a list, if needed later:
# Initialize first line
lines  = [[1]]  # list of contents of each line (lists)
evens  = [0]    # list of counts of even elements in each line (integers)
totals = [1]    # list of total counts of elements in each line (integers)

# Build next lines
for i in range(1023):
    print(f'In the first {i+1} lines of the pascal triangle, there are {sum(totals)} entries. {sum(evens)} of them are even.')
    lines.append([1] + [lines[i][j] + lines[i][j+1] for j in range(len(lines[i])-1)] + [1])
    totals.append(len(lines[-1]))
    evens.append(len([v for v in lines[-1] if v%2 == 0]))

A: For starter you should avoid both a while loop and an iteration over indices while reading the content of an array. Watch the loop like a native talk to get more insight. In your case, since you are interested in interating over consecutive values at once, you may have a look into the pairwise recipe.
Second, instead of patching your row after the computation of all central elements, you can provide a bigger row to start your computation from by adding 0 to both sides. And to avoid resizing lists in doing so, you can use itertools.chain for that.
Lastly, to get the 1023 first rows, you may want to provide a generator that gives an endless stream of rows from the pascal triangle and cut that generator short after 1023 rows using itertools.islice.
Revised code:
import itertools

def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

def next_row(row):
    larger_row = itertools.chain([0], row, [0])
    return [a + b for a, b in pairwise(larger_row)]

def pascal_triangle():
    row = [1]
    while True:
        yield row
        row = next_row(row)

def count_even(iterable):
    return sum(item % 2 == 0 for item in iterable)

def main(limit):
    even = total = 0
    for index, row in enumerate(itertools.islice(pascal_triangle(), limit), 1):
        even += count_even(row)
        total += len(row)
        print('In the first', index, 'lines of the pascal triangle, '
              'there are', total, 'entries.', even, 'of them are even.')

if __name__ == '__main__':
    main(limit=1023)


text:
Q: Calling a function from viewDidAppear() causes memory leak but from viewWillLayoutSubiews() not I am trying to understand why the same function causes a memory leak if I call it from viewDidAppear rather than viewWillLayoutSubiews.
I have two extensions that fits the sublayers of a view to its bounds:
extension CALayer {
    func fit(rect: CGRect) {
      frame = rect

      sublayers?.forEach { $0.fit(rect: rect) }
    }
}

extension UIView {
  func fitLayers() {
    layer.fit(rect: bounds)
  }
}

And the same call priorityButton.fitLayers() from viewDidAppear doesn't deallocate the Layer objects. Both do the job as expected and works well but I'd like to understand why is it.
Thanks!


text:
Q: Epsilon-Delta definition The defintion give me a confusion. It states that
for all $\epsilon>0$ there exists a $\delta>0$ such that, whenever $|x−a|<\delta$ then $|f(x)−L|<ϵ$.
So when I think about $|x−2|<\delta$ $\to$ $|x^2 -1| < \epsilon$. It is also true for every $\epsilon >0$ since I just need to choose large $\delta$ such that $f(x)=x^2$ on $|x−2|<\delta$ contain $|x^2-1|<\epsilon$

A: The limit in the example is
$$\lim_{x \to 2} x^2 = 1.$$
The definition of the limit is:
$$\forall \epsilon> 0, \exists \delta > 0, |x-2|<\delta \Rightarrow |x^2-1|<\epsilon.$$
First of all, when we see $0<|x-2|<\delta$, we talk about $x$-coordinate. But when we see $|x^2-1|<\epsilon$, we talk about $y$-coordinate.
But, I will follow your thought.
Look at the quantifier $\forall \epsilon$. If you choose large $\delta$, for instance $\delta = 10$. So that $|x-2|<10 \Longleftrightarrow -8<x<12$. We may choose $x = 8$ so,
$$|x^2-1| = |8^2-1|=63.$$
Because the quantifier of $\epsilon$ is $\forall$ positive epsilon, we may choose $\epsilon = 1$. It is clear that
$$|x^2-1| = 63 > \epsilon.$$
So the definition of limit is not true. In fact, the limit is not equal to 1.


text:
Q: Dockerize Java Web App: Maven + Tomcat + Docker Tenho visto frequentemente diversos tutoriais do docker parar subir serviços "prontos", porém vejo poucas instruções relacionadas em como utilizá-lo dentro do fluxo de desenvolvimento. Principalmente em linguagens compiladas como exemplo o Java que exige um passo adicional de compilação que ao contrário das linguagens dinâmicas não exigem esse passo.
Como eu poderia organizar o meu workflow de desenvolvimento utilizando o Docker em todo ciclo de vida? Tanto na utilização de um container para compilar meu código, rodando o "mvn clean install", quanto no deploy no servidor de aplicação (aqui no caso o tomcat). Eu deveria montar 2 containers um para cada passo? Como ficaria as dependências entre esses dois containers já que o segundo responsável pelo deploy só poderá entrar em ação após o container de compilação ter feito seu trabalho e gerado o artefato (.war)?
Um próximo passo (e não menos importante) seria criar uma integração da execução desses passos com uma IDE (Netbeans ou Eclipse por exemplo) para que este fluxo de desenvolvimento com Docker ficasse transparente durante o processo.
Resumindo:

*

*Como ficaria o fluxo?

*Como ficariam os Dockerfile?

*Como organizar a ordem de execução? (Utilizando shellscript, talvez ou caberiam em um docker-compose?)

A: A ideia é que eu possa usar esta solução em qualquer projeto que utilize "Maven + Tomcat" colocando os seguintes arquivos na raiz do projeto seguindo os passos abaixo.
No exemplo utilizei o projeto que segue disponível no github:
https://github.com/rogeriofonseca/docker-java-tomcat-maven
1 - Estrutura de arquivos para configuração do Docker
docker-compose.yml
dockerfiles/
├── Dockerfile-apache
├── Dockerfile-maven
├── Dockerfile-mysql
└── tomcat-users.xml
scripts/
└── entrypointscript.sh

2 - docker-compose.yml
version: '2'
services:
  db:
    image: mysql:5.7
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_DATABASE=projeto_jpa
    ports:
      - "3306:3306"
  maven:
      build:
        context: dockerfiles
        dockerfile: Dockerfile-maven
      volumes:
        - ~/.m2:/root/.m2
        - $PWD:/usr/src/mymaven
      volumes_from:
        - tomcat
  tomcat:
    build:
      context: dockerfiles
      dockerfile: Dockerfile-apache
    ports:
      - "8888:8080"

2.1 Dockerfile-apache
FROM tomcat:8.0

ADD . /code
WORKDIR /code
COPY tomcat-users.xml  $CATALINA_HOME/conf/
VOLUME $CATALINA_HOME/webapps

2.2 Dockerfile-maven
FROM openjdk:7-jdk

ARG MAVEN_VERSION=3.3.9
ARG USER_HOME_DIR="/root"

RUN mkdir -p /usr/share/maven /usr/share/maven/ref \
  && curl -fsSL http://apache.osuosl.org/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz \
    | tar -xzC /usr/share/maven --strip-components=1 \
  && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn

ENV MAVEN_HOME /usr/share/maven
ENV MAVEN_CONFIG "$USER_HOME_DIR/.m2"

VOLUME "$USER_HOME_DIR/.m2"
WORKDIR /usr/src/mymaven
ENTRYPOINT ["/usr/src/mymaven/scripts/entrypointscript.sh"]

2.3 Dockerfile-mysql
FROM mysql:5.7

ENV MYSQL_ROOT_PASSWORD=root
ENV MYSQL_DATABASE=projeto_jpa

expose 3306:3306

2.4 Um ponto de atenção para este aqui. Ele é responsável por compilar e copiar todos artefatos para o tomcat.
No meu caso tenho um projeto que tem vários módulos, então o resultado final terá mais de um .war, por este motivo o "find" buscando em todo diretório e sub-diretórios.
Arquivo: scripts/entrypoint.sh
#!/bin/bash
mvn clean install -e -f  /usr/src/mymaven  &&
find /usr/src/mymaven/target -name "*.war" -exec cp '{}' /usr/local/tomcat/webapps \;

2.5 tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="tomcat" password="tomcat" roles="admin,manager, manager-gui"/>
</tomcat-users>

# Comandos úteis:
1 - Para subir os containers basta executar na raiz do projeto o comando:
$ docker-compose build --no-cache && docker-compose up -d

2 - Para recompilar após efetuar alguma alteração no código Java basta executar apenas o container específico do maven. Ele fará o papel de recompilar o código e copiar os artefatos para o volume compartilhado entre os dois containers.
$ docker-compose run maven

Ps.: O próximo passo será adequar este fluxo no meu ambiente de desenvolvimento integrando o fluxo com a minha IDE. Mas isto é pauta para outro tópico.

A: Eu fiz algo semelhante para demostrar, modestamente, compotências técnicas [GitHub Pssilva: 2017] (trabalho em progresso). Mas adaptei para contribuir com a comunidade e assim tentar responder as dúvidas acima.
Como ficaria o fluxo?
Fluxo de trabalho geralmente é uma coisa subjetiva, logo descreverei um fluxo genérico que usei no meu ambiente:
1. Ambiente Docker no VirtualBox:
Assumindo que já tenha um VM com o Ubuntu 16.04.2 LTS (Xenial Xerus)16.04.2 LTS (Xenial Xeru) com o GIT, e o servidor SSH instalados e apropriadamente configurados. Então, podemos instalar o docker.
$ssh [SEU_USER]@[IP_HOST] -p 22
$sudo su
#echo "deb [arch=amd64] https://apt.dockerproject.org/repo ubuntu-$(lsb_release -cs) main" > /etc/apt/sources.list.d/docker.list
#apt-cache policy docker-engine
#apt-get update
#apt-get install linux-image-generic-lts-$(lsb_release -cs)
#reboot
$ssh [SEU_USER]@[IP_HOST] -p 22
$sudo apt-get update
$sudo apt-get install docker-engine
$sudo service docker start
$sudo service docker status
$sudo gpasswd -a $(whoami) docker
$exit
$ssh [SEU_USER]@[IP_HOST] -p 22

2. Testar o Docker: Helo Word.

$ssh [SEU_USER]@[IP_HOST] -p 22
$docker run oskarhane/hello echo "Hello, let me out of here"
$docker ps -a

Pronto, após testar podemos limpar os conteiners e as imagens.
$docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q)
$docker rmi $(docker images -a -q)

3. Criar o projeto Spring Boot

3.1 Instalar os plugins na IDE
No meu caso eu uso a IDE Eclipse Luna Service Release 2 (4.4.2), Eclipse Java EE IDE for Web Developers.
E os principais plugins que uso são:
  - The Spring Tool Suite™ (STS)
  - m2e - Maven integration for Eclipse
  - Gradle IDE & Enide Gradle for Eclipse in one operation.
3.2 Criar o projeto:
Para este teste aqui, usando o plugin STS, crie um projeto como este da imagem:

Importante, veja o Location: /Users/[SEU_USER]/projects/microservicesSpringProject
Será onde clonaremos o repositório.

3.3 Edite o arquivo: /microservicesSpringProject/src/main/java/br/com/microservicesSpringProject/MicroservicesSpringProjectApplication.java
Deixando conforme abaxo:
package br.com.microservicesSpringProject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class MicroservicesSpringProjectApplication {

    @RequestMapping("/")
    public String home() {
        return "My Microserver: Stackoverflow";
    }
    public static void main(String[] args) {
        SpringApplication.run(MicroservicesSpringProjectApplication.class, args);
    }
}

3.4 Build Aplicação:
$cd /Users/[SEU_USER]/projects/microservicesSpringProject
$mvn package && java -jar target/microservicesSpringProject-0.0.1-SNAPSHOT.jar

Apenas para testar a aplicação, acesso o link: localhost:8080.
IMPORTANTE: o arquivo: /Users/[SEU_USER]/projects/microservicesSpringProject/target/microservicesSpringProject-0.0.1-SNAPSHOT.jar

4. Criar o repositório do projeto

4.1 Na Virtual Machine, assumindo que você já tenha configurado seu servidor git [Git: 2017 - b]
$ssh [SEU_USER]@[IP_HOST] -p 22
$mkdir -p /opt/microservicesSpringProject.git
$cd /opt/microservicesSpringProject.git
$git --bare init  --shared=[DEV_GROUP_PERMISSION]
$chmod 0777 -Rf /opt/microservicesSpringProject.git
$chown [SEU_USER] -Rf /opt/microservicesSpringProject.git

4.2 Na máquina Host, máquina física.
$cd /Users/[SEU_USER]/projects/microservicesSpringProject
$chmod 0777 /Users/[SEU_USER]/projects/microservicesSpringProject
$git init
$echo "#[NOME_PROJETO]" > README.md
$git add .
$git commit -m 'initial commit'
$git remote add origin ssh://[SEU_USER]@[IP_SERVER]:22/opt/microservicesSpringProject.git
$git push origin master

5. Criar a sua própria imagem docker: Criar o arquivo Dockerfile

Aqui podemos responder: Como ficariam os Dockerfile?.
O mesmo arquivo Dockerfile pode ser reutilizado para gerar multiplas images.
O arquivo dockerfile [Docker: 2017 - a] pode ser feito de várias maneiras, a o formato a seguir me atendeu [Docker: 2017 - b]:
# escape=\ (backslash)
# My Microservices
#
# VERSION               0.0.1
# AUTHOR                Paulo Sergio da Silva
# EMAIL                 pss1suporte@gmail.com

FROM    ubuntu
VOLUME /tmp

LABEL Description="This image is used to build a application whith Architecture Microservices." Vendor="PSSILVA Products" Version="1.0"
RUN apt-get update && apt-get install -y inotify-tools apache2 openssh-server git
RUN apt-get clean all
RUN apt-get install -y default-jre
RUN apt-get install -y default-jdk
RUN apt-get install -y openjdk-8-jre
RUN apt-get install -y openjdk-8-jdk
RUN apt-get install -y software-properties-common && add-apt-repository ppa:maxmind/ppa && apt-get update && apt-get -y install libmaxminddb0 libmaxminddb-dev mmdb-bin
RUN apt-get clean all
RUN apt-get update

CMD ["mkdir","-p","/opt/spring-1.5.1.RELEASE"]
#COPY spring-1.5.1.RELEASE/* /opt/spring-1.5.1.RELEASE/

#CMD ["ln","-s","./opt/spring-1.5.1.RELEASE/bash/spring","/etc/bash_completion.d/spring"]
#CMD ["ln","-s","./opt/spring-1.5.1.RELEASE/zsh/_spring","/usr/local/share/zsh/site-functions/_spring"]

ADD microservicesSpringProject-0.0.1-SNAPSHOT.jar /root/microservicesSpringProject-0.0.1-SNAPSHOT.jar
RUN sh -c 'touch /root/microservicesSpringProject-0.0.1-SNAPSHOT.jar'

ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /root/microservicesSpringProject-0.0.1-SNAPSHOT.jar" ]

#CMD ["java","-jar","/root/microservicesSpringProject-0.0.1-SNAPSHOT.jar"]

Apenas para versionamento, crie o arquivo Dockerfile na pasta /Users/[SEU_USER]/projects/microservicesSpringProject/docker-image
$mkdir -p /Users/[SEU_USER]/projects/microservicesSpringProject/docker-image/spring-1.5.1.RELEASE
$cd /Users/[SEU_USER]/projects/microservicesSpringProject/docker-image
$vim Dockerfile

Na Virtual Machine, crie o arquivo e construa (build) a imagem docker.
$ssh [SEU_USER]@[IP_HOST] -p 22
$mkdir -p ~/projects/microservicesSpringProject/docker-image/spring-1.5.1.RELEASE
$cd ~/projects/microservicesSpringProject/docker-image

//O comando abaixo envia a aplicação Spring Boot (.jar) da Máquina Física - MF para a Máquina Virtual.
$scp  -P22 -v -r -C  /Users/[SEU_USER]/projects/microservicesSpringProject/target/microservicesSpringProject-0.0.1-SNAPSHOT.jar [SEU_USER]@[IP_HOST]:/home/[SEU_USER]/projects/microservicesSpringProject/docker-image

$vim Dockerfile
$docker build -t ubuntu:MicroservicesSpringBoot .

Após o processamento acima, podemos verificar as imagens docker instaladas:
$docker images

Agora, ainda na Virtual Machine, podemos executar a aplicação Spring Boot:
$docker run -e "JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,address=5005,server=y,suspend=n" -p 8080:8080 -p 5005:5005 -t -i ubuntu:MicroservicesSpringBoot java -jar /root/microservicesSpringProject-0.0.1-SNAPSHOT.jar

Após o comando acima, podemos acessar a aplicação Spring Boot rodando no container Docker de dentro da VM acessando o link: [IP_HOST]:8080.
Podemos entrar no container e trabalhar no servidor da seguinte forma:
 $docker run -t -i ubuntu:MicroservicesSpringBoot /bin/bash

6. Enviar a imgem Docker: hub.docker.com

Considerando que você já tenha uma conta no hub.docker.com [hub.docker: 2017]. E tendo em mente que reutilização aumenta a produtividade, é indicado fortemente como boa prática temos que enviar o container docker para o meu repositório.
$docker login
$docker tag [IMAGE_ID] [LOGIN_HUB_DOCKER]/[NOME_REPO]:latest
$docker push LOGIN_HUB_DOCKER]/[NOME_REPO]

7. Automação do Processo.

Aqui, procuro responder as eguintes perguntas: Como organizar a ordem de execução? (Utilizando shellscript, talvez ou caberiam em um docker-compose?)
Mas infelizmente tratarei de foma mais conceitual do que empírica abordando o assunto Integração Contínua - IC [Stackoverflow - CI: 2017]. Por não ter muita confiança no pouco que sei, estou buscando implementas as orientações e boas práticas [Alan Mark Berg: 2015] usados no ambiente Jenkins.

Acredito que seja isso. Obrigado pela pergunta e por isso, pela oportunidade em aprender e contribuir.

Referência:
[Sébastien Goasguen: 2016], Docker Cookbook: SOLUTIONS AND EXAMPLES FOR BUILDING DISTRIBUTED APPLICATIONS.
[Alan Mark Berg: 2015], Jenkins Continuous Integration Cookbook: Second Edition
[Docker: 2017 - a], Disponível em: Dockerfile Best Practices. Acesso: 01 Abr 2017
[Docker: 2017 - b], Disponível em: Dockerfile Examples. Acesso: 01 Abr 2017
[Docker: 2017 - c], Disponível em: PaaS Docker: Image Docker criada com a intensão de implementar um Plataforma as a Service - PaaS. Acesso: 02 Abr 2017
[Git: 2017 - a], Disponível em: Git Essencial Obtendo um Repositório Git. Acesso: 01 Abr 2017
[Git: 2017 - b], Disponível em: Git no Servidor - Configurando o Servidor. Acesso: 01 Abr 2017
[Christian Posta: 2016], Disponível em: Microservices for Java Developers: A Hands-on Introduction to Frameworks and Containers. Acesso: 01 Abr 2017
[Markus Eisele: 2016], Disponível em: Modern Java EE Design Patterns: Building Scalable Architecture for Sustainable Enterprise Development.
[Spring: 2017], Disponível em: Spring Boot with Docker: Site com tutorial. Acesso: 02 Abr 2017
[GitHub Pssilva: 2017], Disponível em: GitHub Pssilva: Meu modesto repositório GitHub. Acesso: 02 Abr 2017
[hub.docker: 2017], Disponível em: Hub Docker: repositório Docker. Acesso: 02 Abr 2017
[Stackoverflow - CI: 2017], Disponível em: Continuous Integration - CI: repositório Docker. Acesso: 02 Abr 2017

A: No atual projeto do qual participo estou usando a seguinte estrutura:

raiz-projeto/
  frontend/
    ...
    package.json
  backend/
    ...
    pom.xml
  infra/
    dockerfiles/
      db.Dockerfile
      app-server.Dockerfile
      web-server.Dockerfile
      ...
    helpers.sh
  docker-compose.yml
  dev.docker-compose.yml
  test.docker-compose.yaml
  .alias

Como os nomes sugerem:

1 o código da api rest reside em 'backend';

2. o código da spa reside em 'frontend';

3. boa parte do código adicional relacionado a configuração do ambiente onde a solução roda reside em 'infra';

4. em 'docker-compose.yml', encontra-se a configuração dos containeres mais próxima possível de como estará na produção, em se fazendo necessário poderá haver um arquivo de extensão Dockerfile para montagem da imagem daquele container/serviço específico.

5. 'dev.docker-compose.yml' contem a configuração necessária para rodar um ambiente mínimo para desenvolvimento nas tecnologias envolvidas, por exemplo:
  5a. ambiente nodejs para desenvolvimento de frontend;
  5b. ambiente maven para desenvolvimento do backend;

6. 'test.docker-compose.yml' contem a configuração necesária para execução de testes automatizado, seja mocando serviços inteiros para prover dependências aos módulos sob teste (um backend para um frontend, um banco de testes para um backend, um ldap para um backend, etc)

7. por fim, nao menos importante, '.alias' é um compêndio de linux aliases a serem usado dentro daquele projeto e facilmente configurável através de 'source ./.alias'. Dentre outras coisas pode conter um apelido para a linha de comando quase sempre necessário quando se trabalha com docker, exemplo:
  7a. alias draf='docker rm `docker ps -aq` -f'
  7b. alias dcr='docker-compose run'
  7c. alias dev-backend='dcr -f dev.docker-compose.yml backend /bin/bash'

É uma estrutura em processo de otimização, de forma que está sempre sofrendo adaptações.

A: Eu vou partir do pressuposto que você possui uma IDE e o mínimo de recursos para compilar seu projeto Java nela.
Uma das mudanças que eu proponho é usar o Spring Boot e utilizar o Tomcat embarcado, o que vai simplificar o seu deploy, podendo rodar sua aplicação com um simples java -jar app.jar.
Dockerizar a aplicação
Dentro do seu projeto Spring Boot, criamos o Dockerfile (src/main/docker/Dockerfile):
FROM openjdk:8-jre-alpine
VOLUME /tmp

ADD *.jar app.jar

ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]

Para construir a imagem docker é necessário adicionar um plugin ao Maven.
Construir uma imagem Docker com Maven
No pom.xml você deve adicionar o seguinte:
<properties>
   <docker.image.prefix>myorganization</docker.image.prefix>
</properties>
<build>
    <plugins>
        <plugin>
            <groupId>com.spotify</groupId>
            <artifactId>docker-maven-plugin</artifactId>
            <version>0.4.10</version>
            <configuration>
                <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                <dockerDirectory>src/main/docker</dockerDirectory>
                <resources>
                    <resource>
                        <targetPath>/</targetPath>
                        <directory>${project.build.directory}</directory>
                        <include>${project.build.finalName}.jar</include>
                    </resource>
                </resources>
                <forceTags>true</forceTags>
                <imageTags>
                    <imageTag>${project.version}</imageTag>
                    <imageTag>latest</imageTag>
                </imageTags>
            </configuration>
        </plugin>
    </plugins>
</build>

Este trecho possui 3 configurações:

*

*O nome da imagem, que resultará em myorganization/myproject

*O diretório onde deve ser encontrado Dockerfile

*Os arquivos (resources) a copiar do diretório de compilação para construir a imagem docker (neste caso somente o arquivo .jar é necessário)

Para fazer o build da imagem docker, você deve executar o seguinte comando:
mvn package docker:build -DpushImage

Você não precisa fazer o push para rodar a imagem criada localmente. Mas ele vai te permitir disponibilizar a imagem no Dockerhub, facilitando o deploy automatizado em provedores de cloud. Para tanto, você deve alterar a configuração docker.image.prefix para o seu próprio docker ID.
Executando a aplicação com docker
docker run -p 8080:8080 -t myorganization/myproject


text:
Q: angularjs ReferenceError: google is not defined Here am trying to use google map's api in my app for location picker. By accesing this url
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=places&language=en-US"></script>

Though this is working in local solution its not working in my main app.It is giving an error
ReferenceError: google is not defined angular.js:13294
at HTMLDocument.<anonymous> (VM6558 locator.js:87)
at fire (jquery.js:3187)
at Object.self.add [as done] (jquery.js:3246)
at jQuery.fn.ready (jquery.js:3496)
at Object.<anonymous> (VM6558 locator.js:86)
at Object.invoke (angular.js:4625)
at Object.enforcedReturnValue [as $get] (angular.js:4464)
at Object.invoke (angular.js:4625)
at angular.js:4424

Order of the Scripts
<link rel="stylesheet" href="libs/bootstrap/dist/css/bootstrap.min.css"/>
<script type="text/javascript" src="libs/jquery/dist/jquery.min.js">  </script>
<script type="text/javascript" src="libs/jquery-ui/jquery-ui.min.js"></script>
<link rel="stylesheet" href="/public/libs/jquery-ui/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=places&language=en-US"></script>
<script src="libs/angular/angular.js"></script>
<script src="libs/angular-route/angular-route.js"></script>
<script src="libs/angular-animate/angular-animate.js"></script>

A:

vm.initialize = function(){
        var mapOptions = {
          zoom: 14,
          center: new google.maps.LatLng(10.772573, 106.698000)
        }

        map = new google.maps.Map(document.getElementById('order-detail-map'), mapOptions);
        latlng = new google.maps.LatLng(vm.order.customer.address.position.lat, vm.order.customer.address.position.long);
        setTimeout(function(){
          google.maps.event.trigger(map, 'resize');
          map.setCenter(latlng);
        }, 50);

        myMarker = new google.maps.Marker({
          draggable: false,
          animation: google.maps.Animation.DROP,
          icon: "i/marker.png",
          position:latlng
        });
        myMarker.setMap(map);
      }
      google.maps.event.addDomListener(window, 'load', vm.initialize());


text:
Q: Relation between representations of boson operators? I have a simple (I think !) question about the representations of boson operators and how they are related. First of all let's define two conjugate observables $Q$ and $P$ (i.e. $\left[Q,P\right]=i$ and $Q^\dagger=Q$, $P^\dagger=P$).  If we further define:
\begin{equation}
a=\sqrt{\frac{\alpha}{2}}\left(Q+\frac{i}{\alpha}P\right)~~~~~~~~~~~~
a^\dagger=\sqrt{\frac{\alpha}{2}}\left(Q-\frac{i}{\alpha}P\right)~~~~~~~\alpha\in \mathbb{C},
\end{equation}
(as in the harmonic oscillator problem) we have that $\left[a,a^{\dagger}\right]=1$. We can there identify $a^{(\dagger)}$ as boson annihilation (creation) operators. However we can also define:
\begin{equation}
b=\sqrt{Q}e^{iP}~~~~~~~~~~~~~~~~b^\dagger=e^{-iP}\sqrt{Q}
\end{equation}
which will verify $\left[b,b^{\dagger}\right]=1$ (this requires a bit more algebra though).
Question : Is there a relation between these two representations ? These are specific examples, but one could probably think of other representations. Since these representations implement the same commutation relations, does it mean that there are related by some transformation (a unitary transformation in particular) ?
(I give here specific examples for bosonic operators, but I guess one may extend the discussion to any type of operator satisfying some commutation relation).

A: Your non standard representation does not produce a well-behaved canonical theory.
The most evident and direct way to face it, barring theoretical remarks based on the absence of rigorous hypotheses sufficient to apply some theorem (Stone von Neumann, Nelson, FS^3, Dixmier...), is the following.
To construct a representation of your bosonic theory (a) you have to build up the orthonormal set  of occupation numbers states $\{|n\rangle\}_{n=0,1,2,\ldots}$ and (b) you have to prove that this set is complete (i.e., maximal)($^*$).
By definition, where $C_n \neq 0$ is a normalization coefficient:
$$|n\rangle := C_n(b^\dagger)^n|0\rangle \qquad (1)$$
with:
$$b|0\rangle =0\quad\mbox{and}\quad \langle 0|0\rangle =1\:.\qquad (2)$$
The former equation in (2), making explicit the form of the operator $b$ in the Hilbert space of the theory, $L^2(\mathbb R)$, and writing down the equation using the wavefunction $\psi_0$ of $|0\rangle$ in position representation, reads:
$$\sqrt{x}\psi_0(x+1)=0  \quad \mbox{(almost everywhere)}\:,\qquad (3)$$
where I have exploited the fact that $\{e^{-i\lambda P}\}_{\lambda \in \mathbb R}$ is the unitary representation of the group of $x$-translations.
The only $L^2$ solution of (3) is trivially: $$\psi_0(x) = 0 \quad \mbox{almost everywhere.}$$ Consequently the latter condition in (2) is untenable and all  the construction aborts here.

footnotes
$(^*)$ Technically speaking, these vectors are consequently analytic vectors for all the involved operators and this a guarantee for the validity of several crucial properties like essentially self-adjointness of the new canonical variables.

A: There is only one unitary representation for the algebra of bosonic operators. Given a set of creation and annihilation operators,
$$
[b,b^\dagger] = 1,
$$
you can define a set of canonical position and momentum operators,
$$
[Q,P] = iC,\quad [C,P] = [C,Q] = 0.
$$
which is known as Heisenberg algebra. $C$ is the center of this algebra. There is only one unitary representation for Heisenberg algebra (Stone-von Neumann theorem).
As for the "new representation" you mentioned, those ($P'$ and $Q'$) are just action-angle variables. $Q'$ in the "new representation" is the amplitude of oscillation, whereas $P'$ is roughly the phase angle. More specifically (set $\alpha=1$),
$$
Q = \sqrt{2Q'}\cos(P');\quad P = \sqrt{2Q'}\sin(P').
$$
$P'$ and $Q'$ are the "new" variables. They also form canonical conjugate pair. You can check this for both classical and quantum oscillators.

A: Yes, your b excitations are known: they are tweaked coherent states, based on the Displacement operator of optical phase space.
For simplicity, take α=2, so that
$$
Q=\frac{a+a^\dagger}{2}, \qquad iP=a-a^\dagger,
$$
and hence
$$
b=\sqrt{\frac{a+a^\dagger}{2}} e^{a- a^\dagger}= \sqrt{\frac{a+a^\dagger}{2}} D^\dagger(1),\\
b^\dagger= e^{a^\dagger -a}   \sqrt{\frac{a+a^\dagger}{2}} =D(1)\sqrt{\frac{a+a^\dagger}{2}} ~,
$$
where the displacement operator is defined as $D(1)= e^{a^\dagger -a}$.
Then, evidently,
$$[b,b^\dagger]=\frac{a+a^\dagger}{2}   - D(1)\frac{a+a^\dagger}{2}D^\dagger(1)=1  ~. $$
Acting on the Fock vacuum annihilated by a, different α than the above!, the displacement operators
define the coherent state $D(\alpha=1)|0\rangle=|\alpha=1\rangle$, the eigenstate of the annihilation operator, but I am not sure of the drift of the rest of your question.
Slight modifications of these maps are popular in deformed oscillator algebras, section 4.g).


text:
Q: What is the best tool to inspect the state and size of a user's session state in a ASP.Net 2.0 application We'd like to inspect the state of a user's session state and predefined points during the flow of a legacy web application. We'd like to see which objects are currently present and what the total size is.

A: You can monitor some of the asp.net session performance counters


text:
Q: python - how to use a generator to create another generator without defining a new function? Suppose I have a for loop that iterates over a generator and in this loop i'm building a list for later use:
q = []
for index, val in enumerate(['a', 'b', 'c']):
    q.append(index+val)

I want to hold onto the generator without creating a function such as this:
def foo(gen):
    for index, val in gen:
        yield index+val

is it at all possible or is there some inherent problem I don't see here?
I suppose it should look something like this:
iter_q = something()
for index, val in enumerate(['a', 'b', 'c']):
    q.add_iteration(index+val)

OK, now that I've written this, it does seem quite impossible (or useless), since this for loop will have to iterate through the whole list before the "generator" is ready, which makes it just an iterator over a premade list, and not a generator in the useful sense of the object.
Posting anyway because I couldn't find such a question myself. (plus, maybe someone still has something interesting to say about it)

A: If I'm understanding your question correctly, I think you might be wanting a generator expression:
q = (index + val for index, val in enumerate(someOtherGenerator))

That statement creates a new generator q, which will work just like the generator returned by your foo function. You don't need to assign it to a variable either, you can create generator expressions just about anywhere, such as in a function call:
doSomethingWithAGenerator(i+v for i,v in enumerate(someOtherGenerator))

There are some kinds of generators that can't be made in generator expressions, but the most common kinds can be.

A: I look at it this way: itertools.cycle is probably the best-in-class example of a function looping over an iterator while pretending not to exhaust it. It ultimately creates a complete copy of the entire thing. If itertools can't do it any better than that, there probably is no other (general) solution.


text:
Q: Flask: How do I pass an uploaded file as input to a method? AttributeError: '_io.BytesIO' object has no attribute 'lower' I'm completely new to flask (in fact I've just started this morning) and so far I've only managed to implement a basic upload function (taken from the flask doc). The file upload works but I just can't seem to figure out how to pass the file into another method (mining). When I do, I always get the error message: AttributeError: '_io.BytesIO' object has no attribute 'lower'. It would mean the world to me to receive any kind of help! Thank you all in advance.
def mining(xes):
    log = xes_importer.apply(xes)
    tracefilter_log_pos = attributes_filter.apply_events(log, ["complete"], parameters={attributes_filter.Parameters.ATTRIBUTE_KEY: "lifecycle:transition", attributes_filter.Parameters.POSITIVE: True})
    variants = pm4py.get_variants_as_tuples(tracefilter_log_pos)
    Alpha(variants.keys())
    Heuristic(variants.keys(), 1, 0.5)

UPLOAD_FOLDER = '/Users/jenny/processmining_lab/uploads'
ALLOWED_EXTENSIONS = set(['xes'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # If the user does not select a file, the browser submits an
        # empty file without a filename.
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return mining(file)
    return '''
    <!doctype html>
    <title>Upload new File</title>

Upload new File

    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

Here is the traceback

A: This depends on what you're mining function looks like.
file is a werkzeug.FileStorage object which has it's own various methods.
So (without seeing) your mining function it should probably be something like:
def mining(file_obj):

    lower_fname = file_obj.filename.lower()
    data = file_obj.read()

    # Do something

The AttributeError you mention sounds like you're trying to run the lower method of something which doesn't return a string.
As a side-note: it's difficult to know where in your code this exception hasn't occured as you never posted the full traceback.

EDIT

My mining function is actually at the top of the code I've inserted.  I've also now included the traceback.

Looks like you're using PM4Py for which this document states:

from pm4py.objects.log.importer.xes import importer as xes_importer
log = xes_importer.apply('<path_to_xes_file.xes>')

So you need to actually pass a file path to the mining function.
I suggest changing your main code to do:
        if file and allowed_file(file.filename):
            sfilename = secure_filename(file.filename)
            output_path = os.path.join(app.config['UPLOAD_FOLDER'], sfilename)

            # Now save to this `output_path` and pass that same var to your mining function
            file.save(output_path)
            return mining(output_path)


text:
Q: Is using Answerer is correct? If there is a position in a company that answers questions related to for example physics, what is the best word that describes this position?
"Answerer of Questions related to Physics"  ?

A: As well as the straight expert answers already provided, you also have the common corporate concept of a subject matter expert or SME (also domain expert in certain contexts). Wikiref:

A subject-matter expert (SME) or domain expert is a person who is an authority in a particular area or topic.

I know Wikipedia isn't the best of dictionary-style resources, but it's probably too jargon-ish to have made it to the real world just yet.

A: I think the best word in that case is expert. This suggests that the person is the company's authority on the subject of physics. If the position is more public-oriented and the person is not necessarily the expert, but just the one who answers questions, consider guide or resource.

A: In court, the term is "expert" witness when any technical consultation is necessary.
If the trial is about computer programming, say, than an "expert" witness is called to testify. The same term is used in any profession or practice.
In order to be an "expert," local jurisprudence suggests the level of expertise required, such as published work, professional involvement, or academic achievement in the field.


text:
Q: If $f(x)$ is continuously decreasing and $\lim_{x \to \infty} f(x) = 0$, is $xf(x)$ uniformly continuous?
Suppose $f:[0, \infty) \to [0, \infty)$ is decreasing and continuous with $\lim_{x \to \infty} f(x) = 0$. Let $g(x) = xf(x)$. Is $g(x)$ uniformly continuous on $[0, \infty)$?

My work: I've been able to come up with a counterexample where $g(x)$ is not Lipschitz. Since Lipschitz is stronger than uniform continuity, this isn't a full solution, but nevertheless the ideas may be useful. That said, there might be a very simple counterexample that's eluding me.
First, recall that there are continuous functions $h:[0, \infty) \to [0, \infty)$ such that $$\limsup_{x \to +\infty} \ h(x) = +\infty$$ but $\int_0^{+\infty} h(x) \ dx < +\infty$
Here is a brief construction: for integer $n \geq 1$, in each interval $[n, n+\frac{2^{1-n}}{n}]$ the graph of $h$ looks like an isosceles triangle of area $2^{-n}$ and height $n$. Elsewhere $h(x) = 0$. It's easy to see the integral of $h$ over $\mathbb{R}_+$ is $1$, but its $\lim \sup$ is $+\infty$.
Now consider that $$f(x) = 1 - \int_0^{x} h(t) \ dt$$
is continuous (actually differentiable), decreasing and vanishing at $+\infty$.
If we consider $g(x) = xf(x)$, note that $g'(x) = xf'(x) + f(x) = f(x) - xh(x)$. $f(x)$ is bounded and $|xh(x)|$ can be made arbitrarily large, and hence $|g'|$ can be made arbitrarily large, so there is no uniform bound on $\left|\frac{g(x) - g(y)}{x-y}\right|$. This implies $g$ is not Lipschitz. This example may or may not be uniformly continuous, but I can't prove it.

A: Choose a strictly increasing sequence of integers $0=a_0<a_1<\cdots$. Now define $f$ as follows. If $a_k\leq x\leq a_{k+1}-1$ for some $k$ then $f(x)=2^{-k}$; on the interval $[a_{k+1}-1,a_{k+1}]$ the function is linear.
Now on the interval $(a_{k+1}-1,a_{k+1})$ we have $g(x)$ is differentiable with derivative at most $2^{-k}-2^{-k-1}(a_{k+1}-1)$; call this bound $b_k$. If we choose $a_k$ increasing sufficiently quickly, $b_k\to-\infty$. Thus for $x_k$ in the middle of this interval and any given $\varepsilon>0$ we need $\delta\leq\varepsilon/|b_k|$, so no fixed $\delta>0$ works.

A: Let $a_n=\frac{\ln(1)}{n^{1/2}}$ and $b_n=\sum_{k=2}^n (\ln(k))^{-1}$ for $n>3$. Let $f(b_n)=a_n$ and $f$ have a straight line graph between $b_n$ and $b_{n+1}$. Then f is defined on $[c,\infty)$ for some $c>0$ and $f(x+c)$ has the desired properties.


text:
Q: how to parse this in Android with the help of DTO How do I parse this JSON in android, I tried using this DTO
private Map<String , Map<String, String>> airlines;
private Map<String , Map<String, String>> airports;
private Map<String , Map<String, String>> providers;

but it gives an exception :-  , Cannot construct instance of java.util.LinkedHashMap (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('Spicejet')
    "airlines": {
      "SG": "Spicejet",
      "AI": "Air India",
      "G8": "Go Air",
      "9W": "Jet Airways",
      "6E": "Indigo"
    },
    "airports": {
      "DEL": "New Delhi",
      "BOM": "Mumbai"
    },
    "providers": {
      "1": "MakeMyTrip",
      "2": "Cleartrip",
      "3": "Yatra",
      "4": "Musafir"
    }

A: Map holds key/pair values and values in your json fields (airlines, airports, providers). can be parsed to Map<String, String> directly. So simply change types of your fields to Map<String, String> :
private Map<String, String> airlines;
private Map<String, String> airports;
private Map<String, String> providers;


text:
Q: View numbers with two decimals in UILabel Im a total newbie to Swift and pretty poor in English. However, I'm trying to build a priceless we use in our company.
I want the user to type in some figures, and let them know the price. It contains a lot of variables but i think everyone is configured the same.
Lets say i want the user to type in an amount in at UiTextField, and a label shall display  1000 / amount with two decimals.
My code at this point is this;
import UIKit
import Foundation

class ViewController: UIViewController {
    @IBOutlet weak var svar: UILabel!
    @IBOutlet weak var inpu2: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
         svar.text = ""
    }

    @IBAction func input(_ sender: Any) {
        if let treStørrelse = Float(inpu2.text!) {
            svar.text = "\(1000 / treStørrelse)"
        }
    }
}

My output at this point is shown as xx.xxxxxxxxxx
I want it to be shown xx.xx
I also need to use the answer in further calculation.

A: In your case the easiest and more safe way is to use the NumberFormatter object:
lazy var numberFormatter: NumberFormatter = {
  let nf = NumberFormatter()
  nf.minimumFractionDigits = 2
  nf.maximumFractionDigits = 2

  return nf
}()

@IBAction func input(_ sender: Any) {
    if let text = inpu2.text, let treStørrelse = Float(text) {
        svar.text = numberFormatter.string(for: 1000 / treStørrelse)
    }
}

Here the expected output will be rounded to the second decimal, and it'll always display 2 decimals. For instance:

*

*4 is interpolated as 4.00

*4.6 is interpolated as 4.60

*4.4374 is interpolated as 4.44

*4.4324 is interpolated as 4.43


text:
Q: PostGIS Measure multiple linestrings I'm new in postgis and i'm trying to mesasure linestrings giving two initial points, start and end point in the same layer (geometry type is linestring). This linestrings represents roads, rivers, underground pipes..etc.
Using postgis function named 'length3d' i can measure ONE line (one record of table), but i need measue multiple and contiguous line; something like this example (using the next annotations for the explanation example)

*

*|S| -->  Line Start point

*|E| -->  Line End point

*@ --> Point in line

*(s)  --> user start point

*(e)  --> user end point

Example:
|S|===@===@===(s)==|E-S|===@==@===@==|E-S|===@===@===(e)==@==|E|

Linestring format:
LINESTRING(-6.366424 38.93301,-6.3625 38.938,-6.361 38.9572,-6.36158230284898 38.9397667955807,-6.36131118520776)

User points could be between two existing points that composed the line.
|S| to |E-S| is one record on DB
|E-S| to |E-S| is other record and |E-S| to |E| is other record.
How i can measure distance from (s) to (e)?
Thanks in advance!

A: Using PL/pgSQL you can create a function that measures each of the components of your path (from (s) to [E-S], from [E-S] to [E-S] and so on).
You can pre-process, and create an temporary linestring(or multilinestring) that represents the line between (s) and (e) and then use ST_Length3D directly on that.


text:
Q: Create a docker image of a postgres database? I am a beginner to Docker, and I would like to know how can I create a Docker image of my existing postgresql database?

A: Your best bet is to pull the standard, preconfigured Postgres image (of the appropriate version) from Docker Hub. Set it up with a volume for storing the database. Use pg_dump to export your existing database, and pg_restore to the new one.


text:
Q: How to marshal C# List with X++ List in MS Dynamics AX 2012 I have an MS Dynamics AX 2012 project and I am using .Net interop.
There is a C# method inside a static class called Database:
 public static List<String> GetAllDatabases(string dataSource)

After referencing this assembly, I can execute in X++:
ADOMD.ADOMD.Model.Database::GetAllDatabases();

But I can't read the string list that it's returning.
I would like to use something like:
List databaNameCollection = new List( Types::String );
;

databaNameCollection =  ADOMD.ADOMD.Model.Database::GetAllDatabases();

But it trows an error:
Error executing code:  (object) has no valid runable code in method 'GetSID'.

How could I do it?
-------EDITED------
I found this post:
http://blogs.msdn.com/b/x/archive/2010/01/19/traversing-elements-in-an-ienumerable-from-x.aspx
But it was in 2010, probably for AX 2009, I tried to assign:
ClrObject enumerator;
str theValue;
;

enumerator = ADOMD.ADOMD.Model.Database::GetAllDatabases();
while (enumerator.MoveNext())
    {
        theValue = enumerator.get_Current();
        print theValue;
    }

The GetallDatabases method is working with another .Net project, it is returning 10 objects, but at the X++ code, is returning nothing.
Thanks

A: To answer your question about .NET types in X++ and get_{x} and set_{x}:
.NET properties are shown in X++ as methods. For example, the get & set property below in C#
string Name {get;set;}

will show in X++ as
string get_Name();
void set_Name(str value);

Basically C# properties are just syntactic sugar. The C# compiler will create a get_{x} method for each get property and a set_{x} for each set property.
In your case, if you want to access the Name property in the cubeDef object you would have to write something like this in X++:
info(cubeDef.get_Name());

A: I made it using the example at: http://blogs.msdn.com/b/x/archive/2010/01/19/traversing-elements-in-an-ienumerable-from-x.aspx
But without the enumerator.MoveNext(), since it is not an X++ Object, changing it to a for loop worked, the final code is:
ClrObject enumerator;
str theValue;
int i;
int length = 0;
List databaNameCollection = new List( Types::String );
;

try
  {
    permission = new InteropPermission(InteropKind::CLRInterop);
    if (permission == null)
    {
            return;
    }
    permission.assert();
    enumerator = ADOMD.ADOMD.Model.Database::GetAllDatabases();
    length = enumerator.get_Count();

    for (i = 0; i < length; i++)
    {
        stringElement = enumerator.get_Item(i);
        databaNameCollection.addStart(stringElement);
    }
     CodeAccessPermission::revertAssert();
 }
 catch (Exception::CLRError)
 {
     CodeAccessPermission::revertAssert();
     info(CLRInterop::getLastException().ToString());
 }

But some questions still remain:
1) I can't assign databaNameCollection.addStart(enumerator.get_Item(i)); directly.
2) I can't access the complex objects attributes, like:
cubeDef  = enumerator.get_Item(i);
info(cubeDef.Name);

where cubeDef is of type: Microsoft.AnalysisServices.AdomdClient.CubeDef.
3) I can't find the documentation of the CLRObject that describes these get_{propertyName} methods.
EX: get_Item
Best Regards


text:
Q: @Input com Observable no angular Não tenho um erro ainda, mas não sei como fazer...
Tenho uma toolbar no meu AppComponent, que exibe um menu dropdown com uma lista. Essa lista vem do back-end. Preciso de um Observable que recebe um boolean, pois se for true recebo uma lista e false outra lista.

<mat-toolbar>

    <button class="buttonMenu" mat-button [matMenuTriggerFor]="menuIntegradores">Integradores</button>
    <mat-menu #menuIntegradores="matMenu">
        <button mat-menu-item *ngFor="let integrador of integradores"
            (click)="moreInformations(integradores.indexOf(integrador))">{{integrador.tecnologia}}</button>
    </mat-menu>
</mat-toolbar>

A váriavel boolean foi declarada em outro component components/integrador.ts,que é onde é feita a requisição da lista ao back-end

A: Ficou a dúvida se o problema é na chamada da api ou no tratamento da resposta.
Pela forma que escreveu parece que uma condicional ngif já resolve.

 Lista true

<ng-template #elseBlock>lista false.</ng-template>


text:
Q: Why does CSP script-src unsafe-inline induce styling issues on my Angular webapp? The issue:
When I try to remove unsafe-inline source for script-src CSP my Angular webapp does not work anymore.
What is the root cause of this issue ?
When using SCSS in Angular@12+, Angular add a property onload on the index.html
<link rel="stylesheet" href="styles.672c1ac3d6da8cc311a2.css" media="print" onload="this.media='all'">
This results in a violation of the CSP unsafe-inline source for script-src header.
How to fix this issue and remove this "security breach" on my Angular web app ?

A: The solution:
Adding "inlineCritical": false to the angular.json solved the issue because it disable Critical CSS inlining.
    "configurations": {
        "production": {
          "optimization": {
            "styles": {
              "inlineCritical": false
            }
          }
        }
      }

Why Angular does that?
When the browser renders a page, it has to wait for the CSS resources to be downloaded and parsed. It can give the (false) impression that the loading of your application is slow, and impacts the First Contentful Paint (FCP) time.
A common technique to avoid that is to inline the CSS directly in the HTML, to avoid an extra request (this is what Lighthouse recommends). But you don't want to inline all your CSS, otherwise the time to download the HTML increases. You just want to inline critical CSS resources, the ones that blocks the rendering, and that your user will see (you can defer the rest of CSS).
The Angular CLI introduces a new option in v11.1 to help us with this: inlineCSS
The CLI will then use critters under the hood to extract the critical CSS of your application, and inline them directly in the HTML.
Running ng build --prod with the above configuration produces an index.html file with a style element containing the critical CSS extracted, and the usual styles.xxxxx.css is loaded asynchronously using:
<link rel="stylesheet" href="styles.3d6bb69e3d075769b349.css" media="print" onload="this.media='all'">
For more informations about the unsafe-inline CSP keyword: https://content-security-policy.com/unsafe-inline/


text:
Q: Error when using Quantized Conv2D with tf.qint8 inputs I am new to quantization and I was learning usage of QuantizedConv2D operation in tensorflow. The code is as below
import tensorflow as tf
a = tf.constant([1.5,1.2],shape = [1,1,1,2], name ='a')
a1 = tf.constant([[2.0],[1.0]],shape = [1,1,2,1], name ='b')
min_a= tf.reduce_min(a)
max_a= tf.reduce_max(a)
x = tf.quantize(a,min_a,max_a,tf.qint8)
min_a1= tf.reduce_min(a1)
max_a1= tf.reduce_max(a1)
x1 = tf.quantize(a1,min_a1,max_a1,tf.qint8)
y1 = t  f.nn.quantized_conv2d(x.output,x1.output,x.output_min,x.output_max,x1.output_min,x1.output_max,[1,1,1,1],"SAME")
with tf.Session() as sess:
  print (sess.run(y1))

I get the following error:

InvalidArgumentError (see above for traceback): No OpKernel was
  registered to support Op 'QuantizedConv2D' with these attrs.
  Registered devices: [CPU], Registered kernels:   device='CPU'; Tinput
  in [DT_QUINT8]; Tfilter in [DT_QUINT8]; out_type in [DT_QINT32]
           [[Node: QuantizedConv2D = QuantizedConv2D[Tfilter=DT_QINT8, Tinput=DT_QINT8, dilations=[1, 1, 1, 1], out_type=DT_QINT32,
  padding="SAME", strides=[1, 1, 1, 1]](QuantizeV2, QuantizeV2_1,
  QuantizeV2:1, QuantizeV2:2, QuantizeV2_1:1, QuantizeV2_1:2)]]

I am not sure if my code is right or this is a bug.
Any help will be appreciated.
Thanks and Regards,
Abhinav

A: I believe the documentation for tf.nn.quantized_conv2d is confusing, because this operation is only registered for the input datatype tf.quint8. You could do the following:
x = tf.quantize(a, min_a, max_a, tf.quint8)
x1 = tf.quantize(a1, min_a1, max_a1, tf.quint8)

I opened an issue on GitHub.


text:
Q: PHP query string hi  i am facing a strang problem that a part of querystring are showing in title on page i have used following function
         function tabVideo(){
global $db,$bll;
          ?>

              <?
            $page_vi=$_GET['page_vi'];
              $rec_per_page=3;
              if (empty($page_vi)) $page_vi = 1;
                $sql = "SELECT COUNT(*) as total_rec FROM think_video";
                     $rs = $db->sql_fetchrow($db->sql_query($sql));
                         $total_rec = $rs['total_rec'];
                 // find out how many pages
                    $total_pages = ceil($total_rec / $rec_per_page);
              // find out where to start at
                  $start = ($page_vi*$rec_per_page)-$rec_per_page;

                       $sql="select id,videotitle,videodescription,videofile,DATE_FORMAT(FROM_UNIXTIME(videodate),'%d/%m/%Y') as videodate, videodate as vd from think_video order by vd DESC limit $start,$rec_per_page";
                $result = $db->sql_query($sql);
             while($row=$db->sql_fetchrow($result)){
                   ?>

<?=$row['videodate']." ".trim($row['videotitle'])?>

<?=trim($row['videodescription'])?>

             <? }
        if($page_vi>1)
               $paging .= '<< terug naar vorige video’s ';
                  if($page_vi<$total_pages)
                  $paging .= 'klik hier voor oudere video’s >>     ';
    $NavigationButton = $paging;
    // paging end

    if($total_rec==0){
        $NavigationButton="
Binnenkort
";
    }

       ?>

            <?=$NavigationButton; ?>

thi d letter #fragment-1 are come in title this problem come on IE

A: This is the old Flash and IE URL problem. Hope that fixes it for you.

A: All strange problems are object to investigation.
This investigation called debugging in programming science
IBM has a nice article to start from: http://www.ibm.com/developerworks/library/os-debug/


text:
Q: How to configure load balancing with 2 master node in Jenkins? I need to configure High Availability for our big project which has actually 70-80 spring-boot applications.
We have a jenkins master with slaves and I need one more master (I have enough VM for slaves and a master) and I need to configure them with load balancer.
Do you have any idea, how can I do that?


text:
Q: TestScheduler does not unsubscribe on completion I have stumbled upon a strange behavior of the Microsoft.Reactive.Testing.TestScheduler that I cannot explain.
Conside the simple test below: A testable hot observable is created, the test scheduler is run to exhaustion and then the messages and subscriptions are validated.
Can someone explain to me why with variant 1 the tests fails, while with variant 2 it works? The failure being that the does not terminate when xs completes at 300, but instead runs until the scheduler disposes it at 550.
Do you recon that this behavior is intentional, and if so, why?
To my understanding both xs and xs.AsObservable() are both just IObservable<int>. The difference being, that the former could be cast back to ITestableObservable<int> while the later cannot. I would expected this to not make any difference in this context.
In addition to xs.AsObservable() it will apparently also work for any other operator. Like for example xs.Select(x => x).
[Fact]
public void SanityCheck()
{
    var scheduler = new TestScheduler();

    var xs = scheduler.CreateHotObservable(
        OnNext(200, 0),
        OnCompleted<int>(300)
    );

    var res = scheduler.Start(
        () => xs,                     // variant 1
        //() => xs.AsObservable(),    // variant 2
        0, 50, 550);

    res.Messages.AssertEqual(
        OnNext(200, 0),
        OnCompleted<int>(300)
    );

    xs.Subscriptions.AssertEqual(
        Subscribe(50, 300) // variant 1 fails here by producing Subscribe(50, 550) instead
    );
}


text:
Q: Overhead associated with DBCC CHECKTABLE? Have a logshipped VLDB and don't run DBCC CHECKDB on primary due to the long running periods of high CPU and tempdb usage.   Have read about DBCC CHECKTABLE as a possibility for a more granular data integrity checking option.  Does DBCC CHECKTABLE have overhead levels similar to DBCC CHECKDB?  Can it be run during business hours without adversely affecting server CPU and TempDB performance?

A: The code behind CHECKTABLE is indeed likely the vast amount of time spent by CHECDB, as mentioned by @Mo64. I.e., the "sum of CHECKTABLE" should roughly be the same as a CHECKDB, one can imagine.
However, by default CHECKTABLE uses a database snapshot. Not a "table snapshot", since there is no such concept. I.e., you can check one table and if modification occurs on some other table at the same time, the original for that data need to be saved in the snapshot file first. Here is one aspect where the "sum of CHECKTABLE" can exceed one CHECKDB.
Anyhow, your question is about overhead. Yes, pretty much the same (or rather, it won't be (much) less for CHECKTABLE. You have the database snapshot and copy-on-write for the whole database (although the snapshot would live for a shorted time when you check only one table). And SQL server should need space in tempdb as well.
Above is from theoretical reasoning, I should add.


text:
Q: Make nav underline animate based on class I have a .nav-link
When .active is added to it, it gets text-decoration: underline. How do i make this text decoration animate by sliding in from the left?

A: You can create and animate custom underline like this. As you cannot animate the text-decordation: underline;
.nav-link:after{
      content: '';
      position: absolute;
      width: 0; height: 3px;
      display: block;
      margin-top: 5px;
      right: 0;
      background: #fff;
      transition: width .2s ease; // this will add animation from left to right.
      -webkit-transition: width .2s ease;
    }

.nav-link:active:after{
  width: 100%;
  left: 0;
  background: #fff;
}


text:
Q: AttributeError: 'MongoAlchemy' object has no attribute 'insert' MongoDB Flask MongoAlchemy I am newbie to Flask restplus API's with mongoAlchemy , i am writing the curd opetaion for Flask restplus API's with mongoalchemy but getting the error while saving data to mongoalchemy
**
**Traceback (most recent call last):
  File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask_restplus\api.py", line 313, in
wrapper
    resp = resource(*args, **kwargs)
  File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\views.py", line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask_restplus\resource.py", line 44, in dispatch_request
    resp = meth(*args, **kwargs)
  File "c:\app\api\controller\essential_controller.py", line 24, in post
    return essential_service.create_essential_service(data=data)
  File "c:\app\api\service\essential_service.py", line 10, in create_essential_service
    essentialData.save()
  File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask_mongoalchemy\__init__.py", line 275, in save
    self._session.insert(self, safe=safe)
AttributeError: 'MongoAlchemy' object has no attribute 'insert'

**
MY code looks like below
database file
from flask.ext.mongoalchemy import MongoAlchemy
from flask import Flask

mongododb = MongoAlchemy()

def init_app():
    app = Flask(__name__)
    app.config['DEBUG'] = True
    app.config['MONGOALCHEMY_SERVER'] = 'localhost'
    app.config['MONGOALCHEMY_PORT'] = '27017'
    app.config['MONGOALCHEMY_DATABASE'] = 'publicvoicedb'
    mongododb.init_app(app)
    return app

class Location(mongododb.Document):
     type= mongododb.StringField()
     cooridantes =mongododb.StringField()

class Essential(mongododb.Document):
        subscriberName = mongododb.StringField()
        mobileNumber = mongododb.IntField()
        address = mongododb.StringField()
        pincode = mongododb.IntField()
        location = mongododb.DocumentField(Location)
        category = mongododb.StringField()
        request_date =mongododb.StringField()
        serviceType = mongododb.StringField()
        issueDescription = mongododb.StringField()

controller
from flask import request
from flask_restplus import Resource

from service import essential_service
from models.dto import dto as EssentialDto

api = EssentialDto.EssentialDto.api
essential = EssentialDto.EssentialDto.essential

@api.route('/')
class EssentialController(Resource):
    @api.doc('Get all essential services')
    @api.marshal_list_with(essential, envelope='data')
    def get(self):
        """List all essential service"""
        return essential_service.get_all_service()

    @api.response(201, 'essential services successfully created.')
    @api.doc('create a new essential service')
    @api.expect(essential, validate=True)
    def post(self):
        """Creates a Essential service """
        data = request.json
        return essential_service.create_essential_service(data=data)

service layer
from database.db import mongododb
from database.db import Location
from database.db import Essential

def create_essential_service(data):
    print('data =', data)
    essentialData = Essential(subscriberName=data['subscriberName'],
    mobileNumber=data['mobileNumber'])

    essentialData.save()

def get_all_service():
    return Essential.query.filter(Essential.serviceType == 'PoliceService').first()

def get_by_service_type(serviceType):
    return Essential.query.filter_by(serviceType=serviceType).first()

Blue print
from flask_restplus import Api
from flask import Blueprint

from controller.essential_controller import api as essential_ns
'''from controller.author_controller import app as authors_ns'''

blueprint = Blueprint('api', __name__)

api = Api(blueprint,
          title='PublicVoice Backend service',
          version='0.0.1',
          description='PublicVoice Backend service'
          )

api.add_namespace(essential_ns, path='/essentials')

mange.py (this my main runner class)
import os
import unittest

from flask_script import Manager

from api import blueprint
from api.database import  db
from api.database.db import Location, Essential

app = db.init_app()
app.register_blueprint(blueprint)

app.app_context().push()

manager = Manager(app)

@manager.command
def run():
    app.run()

if __name__ == '__main__':
    manager.run()

requiremnet.txt
Flask==0.10.1
Flask-Bcrypt==0.7.1
Flask-Migrate==2.1.1
Flask-MongoAlchemy==0.7.2
flask-mongoengine==0.9.5
flask-restplus==0.10.1
Flask-Script==2.0.6
Flask-SQLAlchemy==2.4.1
Flask-Testing==0.8.0
Flask-WTF==0.14.3


text:
Q: Why does pdflatex produce bigger output files than latex+dvipdfm? Consider this sample code:
\documentclass{article}
\usepackage{lipsum}

\begin{document}
\lipsum[1-4]
\end{document}

When I compile this with latex and then use dvipdfm, the output file is 7893 bytes. When I use pdflatex, the output PDF is a whopping 20696 bytes. Naturally, the outputs are visually indistinguishable one from another.
Why does this happen? What does pdflatex put in there that takes so much space?
For reference, I have used the latest MikTeX 2.9 on Windows 7, and ran the commands without any extra switches.

A: Martin Heller has stated the correct answer: dvipdfm uses a different font format than pdftex. You can look into the PDF file by loading it into a text editor. Sometimes (well, often), the objects are compressed and you only see some data. So you either need a decompression algorithm built into your head, or use a tool like qpdf to uncompress the objects (that is what I do):
qpdf --qdf --object-streams=disable test-pdflatex.pdf test-pdflatex-long.pdf

Now the output file is much more readable and you can now compare the output of dvipdfm and pdftex. I don't know if this applies to all cases, but in this example you can take a look at the font object:
% dvipdfm:
9 0 obj
<<
  /FontFile3 11 0 R
  /Ascent 694
  /CapHeight 683
  /Descent -194
  /Flags 6
  /FontBBox [-40 -250 1009 750 ]
  /FontName /DJLCQW+CMR10
  /ItalicAngle 0
  /StemV 69
  /Type /FontDescriptor
>>
endobj

and
% pfdtex
9 0 obj
<<
  /FontFile 11 0 R
  /Ascent 694
  /CapHeight 683
  /CharSet (/A/C/D/E/I/L/M/N/P/Q/S/U/V/a/b/c/comma/d/e/f/g/h/hyphen/i/j/l/m/n/o/one/p/period/q/r/s/t/u/v/w/y)
  /Descent -194
  /Flags 4
  /FontBBox [ -40 -250 1009 750 ]
  /FontName /QJZLYL+CMR10
  /ItalicAngle 0
  /StemV 69
  /Type /FontDescriptor
  /XHeight 431
>>
endobj

Both have different entries referring to the font file (/FontFile3 and /FontFile). According to the table 126 "Embedded font organization for various font types" in the PDF specification, the entry /FontFile refers to a Type1 font program and /FontFile3 to whatever the subtype in the referred stream is. So we need to take a look at object #11 in the dvipdfm file:
11 0 obj
<<
  /Subtype /Type1C
  /Length 12 0 R
>>
stream
....
endstream
endobj

So it is Type1C, which is according to the same table in the PDF spec: "Type 1–equivalent font program represented in the Compact Font Format (CFF), as described in Adobe Technical Note #5176, The Compact Font Format Specification."
To find out what the secret of CFF is, a look at the introduction of "The Compact Font Format Specification" suffices:

Principal space savings are a result of using a compact binary representation for most of the information, sharing of common data between fonts, and defaulting frequently occurring data.


text:
Q: Comparing timestamp from database to last 6 months I'm using laravel and for some reason my logic here isn't applying correctly.
The if statement here should take the results from the database and see if the created_at timestamp is within the last 6 months. If so, I have a css class for 'newCust' below. If the created_at timestamp is past 6 months, it should not be applied.
I'm using subMonth to get the last 6 months but it seems like it's not applying because now it's applying the CSS class to all rows so I'm wondering if my date comparison is off here.
$d->createdAt = new \DateTime($d->created_at);  // created_at is full timestamp (2011-01-01 00:00:00)
$deadline = Carbon::now()->subMonths(6)->format('Y-m-d H:i:s');
if($d->createdAt > $deadline){  // I'm trying to say here that if the created_at timestamp is within the last 6 months, then apply following logic
$d->call_status = 'newCust';
}

A: You can use Carbon to compare:
if $d is an instance of a model, created_at should be already a carbon object
$deadline = Carbon::now()->subMonths(6);

if($d->created_at.gt($deadline)){
    // Do something
    // Set the format here
}

Carbon has multiple comparison functions:

*

*eq() equals

*ne() not equals

*gt() greater than

*gte() greater than or equals

*lt() less than

*lte() less than or equals

A: Using just plain old DateTime this will do what you want
$createdAt = new \DateTime('2017-11-17 00:00:00');
echo $createdAt->format('d/m/Y H:i:s') . PHP_EOL;

$deadline = new \DateTime();
$deadline->sub( new DateInterval('P6M') );
echo $deadline->format('d/m/Y H:i:s') . PHP_EOL;

if ($createdAt > $deadline) {
    echo 'YES';
}else{
    echo 'NO';
}

Adjust the date used by $createdAt to test it.


text:
Q: Duda para crear un ModelFactory Laravel 5.3 Sabiendo que tengo 3 tablas:
personas (id, nombre, apellido)
$factory->define(SIMante\Personas::class, function ($faker) {
    return [
        'nombres' => $faker->firstName,
        'apellidos' => $faker->lastName,
    ];
});

perfiles (id, nombre)
$factory->define(SIMante\Perfiles::class, function ($faker) {
    return [
        'nombre' => $faker->unique()->randomElement($array = array ('Administrador','Usuario','Operario')),
    ];
});

users (id, id_personas (unique), nombre, correo, clave, id_perfiles)
No entiendo como crear el factory para la tabla  puesto que la columna id_personas debe ser unica para cada usuario.
aca lo que llevo:
$factory->define(SIMante\User::class, function (Faker\Generator $faker) {
    return [
        'id_personas' => $faker->unique()->randomElement(SIMante\Perfiles::all()->id),
        'nombre' => $faker->unique()->userName,
        'correo' => $faker->unique()->safeEmail,
        'clave' => bcrypt('123456'),
        'id_perfiles' => SIMante\Perfiles::all()->random()->id,
    ];
});

pero eso me arroja el siguiente error

undefined property: illuminate\database\eloquent\collection::$id

He intentado de varias maneras, pero todas me dan error, aunque esa es la que mas veo lógica de usar.

A: Podrías intentar con el método pluck para obtener solo el valor del id, como lo estás haciendo no es posible, pues tienes una colección (que es una especie de array) y estás llamando una propiedad en el arreglo, la cual no existe.
'id_personas' => $faker->unique()->randomElement(SIMante\Personas::all()->pluck('id')->toArray())


text:
Q: Splunk Python SDK API job.results limited to 50k results. Trying to set an offset to pull multiple chunks of 50k but don't know how to get it to work I have a job who's job['resultCount'] is 367k, but no matter what I do, I can't seem to pull more than the first 50,000 chunk.
I read this chunk of code off of an answer here for someone who had a similar end goal and setup: https://answers.splunk.com/answers/114045/python-sdk-results-resultsreader-extremely-slow.html
rs = job.results(count=maxRecords, offset=self._offset)
results.ResultsReader(io.BufferedReader(ResponseReaderWrapper(rs)))

I wrote the below code around that and I've fiddled around a bit with it, but I can't get offset=self._offset to do anything and I have no idea what it's supposed to be doing.
class SplunkConnector(object):
def __init__(self, username, password, customerGuid):
    self.username = username
    self.password = password
    self.customerGuid = customerGuid
    flag = True
    while flag:
        try:
            self.service = client.connect(host=*****, port=8089, username=self.username, password=self.password, scheme='https')
            flag = False
        except binding.HTTPError as e:
            json_log.debug(str(e))

def search(self, query_dict):
    query = query_dict['search']
    label = query_dict['label']
    search_headers = query_dict['headers']
    customer = query_dict['customer']
    customerGuid = query_dict['customerGuid']
    try:
        earliest_time = query_dict['earliest_time']
        latest_time = query_dict['latest_time']
    except KeyError:
        earliest_time = '-1d@d'
        latest_time = '@d'
    json_log.debug('Starting %s customerGuid=%s' % (label, self.customerGuid))
    kwargs_normalsearch = {'exec_mode': 'normal', 'earliest_time': earliest_time, 'latest_time': latest_time, 'output_mode': 'csv'}
    job = self.service.jobs.create(query + ' | fillnull value="---"', **kwargs_normalsearch)
    while True:
        try:
            while not job.is_ready():
                pass
            stats = {"isDone": job["isDone"],
                     "label": label,
                     "customer": customer,
                     "customerGuid": customerGuid,
                     "doneProgress": float(job["doneProgress"]) * 100,
                     "scanCount": int(job["scanCount"]),
                     "eventCount": int(job["eventCount"]),
                     "resultCount": int(job["resultCount"])}

            json_log.debug(stats)

            if stats["isDone"] == "1":
                json_log.debug("\n\nDone!\n\n")
                break
            sleep(2)
            stats = {"isDone": job["isDone"],
                     "label": label,
                     "customer": customer,
                     "customerGuid": customerGuid,
                     "doneProgress": float(job["doneProgress"]) * 100}

            json_log.debug(stats)

            if stats["isDone"] == "1":
                json_log.debug('Search %s finished for customerGuid=%s'
                               % (label, customerGuid))
                break
            sleep(2)

        except binding.HTTPError as e:
            json_log.debug(str(e))
            pass
        except AttributeError:
            stats = {"isDone": job["isDone"],
                     "label": label,
                     "customer": customer,
                     "customerGuid": customerGuid,
                     "doneProgress": float(job["doneProgress"]) * 100}

            json_log.debug(stats)

            if stats["isDone"] == "1":
                json_log.debug('Search %s finished for customerGuid=%s'
                               % (label, customerGuid))
                break
            sleep(2)

    # Get the results and display them
    result_count = job['resultCount']
    rs = job.results(count=0)
    rr = results.ResultsReader(io.BufferedReader(rs))
    results_list = []
    for result in rr:
        if isinstance(result, results.Message):
            # Diagnostic messages may be returned in the results
            json_log.debug('%s: %s label=%s customerGuid=%s'
                           % (result.type, result.message, label, customerGuid))
        elif isinstance(result, dict):
            # Normal events are returned as dicts
            keys, values = [], []

            for header in search_headers:
                if header not in result.keys():
                    print(header)
                    result[header] = ''

            for key, value in result.items():
                if key in search_headers:
                    keys.append(str(key))
                    values.append(str(value))
            if not results_list == []:
                results_list.append(values)
            else:
                results_list.append(keys)
                results_list.append(values)

    output = io.BytesIO()
    writer = csv.writer(output, delimiter=',')
    writer.writerows(results_list)
    output_string = output.getvalue()
    assert rr.is_preview is False

    job.cancel()
    return [label, output_string.replace('\r\n', '\n').replace('---', '')]

    def searches(self, query_list):
        print(query_list)
        if type(query_list) == dict:
            query_list = [value for value in query_list.values()]
        with closing(ThreadPool(processes=len(query_list))) as pool:
            results = pool.map(self.search, query_list)
            pool.terminate()

        print(results)
        search_results = {item[0]: item[1] for item in results}
        print(search_results)
        return search_results

A: I was able to get this working successfully. My code below should demonstrate how this is accomplished.
import io
import csv
from time import sleep
import splunklib.results as results
import splunklib.client as client
import splunklib.binding as binding
from multiprocessing.pool import ThreadPool
from contextlib import closing

class SplunkConnector(object):
    def __init__(self, username, password, customerGuid):
        self.username = username
        self.password = password
        self.customerGuid = customerGuid
        flag = True
        while flag:
            try:
                self.service = client.connect(host=*****, port=8089, username=self.username, password=self.password, scheme='https')
                flag = False
            except binding.HTTPError as e:
                json_log.debug(str(e))

    def search(self, query_dict):
        query = query_dict['search']
        label = query_dict['label']
        search_headers = query_dict['headers']
        customer = query_dict['customer']
        customerGuid = query_dict['customerGuid']
        try:
            earliest_time = query_dict['earliest_time']
            latest_time = query_dict['latest_time']
        except KeyError:
            earliest_time = '-1d@d'
            latest_time = '@d'
        kwargs_normalsearch = {'exec_mode': 'normal', 'earliest_time': earliest_time, 'latest_time': latest_time, 'output_mode': 'csv'}
        flag = True
        while flag:
            try:
                job = self.service.jobs.create(query + ' | fillnull value="---"', **kwargs_normalsearch)
                flag = False
            except binding.HTTPError as e:
                pass
            pass
        while True:
            try:
                while not job.is_ready():
                    pass
                stats = {"isDone": job["isDone"],
                         "label": label,
                         "customer": customer,
                         "customerGuid": customerGuid,
                         "doneProgress": float(job["doneProgress"]) * 100,
                         "scanCount": int(job["scanCount"]),
                         "eventCount": int(job["eventCount"]),
                         "resultCount": int(job["resultCount"])}

                if stats["isDone"] == "1":
                    break
                sleep(2)
                stats = {"isDone": job["isDone"],
                         "label": label,
                         "customer": customer,
                         "customerGuid": customerGuid,
                         "doneProgress": float(job["doneProgress"]) * 100}

                if stats["isDone"] == "1":
                    break
                sleep(2)

            except binding.HTTPError as e:
                pass
            except AttributeError:

                stats = {"isDone": job["isDone"],
                         "label": label,
                         "customer": customer,
                         "customerGuid": customerGuid,
                         "doneProgress": float(job["doneProgress"]) * 100}

                if stats["isDone"] == "1":
                    break
                sleep(2)

        result_count = job['resultCount']
        offset = 0
        count = 50000
        results_list = self.results_getter(job, label, customerGuid, search_headers, True, count, offset, result_count)

        while len(results_list) < int(result_count) + 1:
            offset += count
            placeholder = self.results_getter(job, label, customerGuid, search_headers, False, count, offset, result_count)
            results_list.extend(placeholder)

        output = io.BytesIO()
        writer = csv.writer(output, delimiter=',')
        writer.writerows(results_list)
        output_string = output.getvalue()
        job.cancel()
        return [label, output_string.replace('\r\n', '\n').replace('---', '')]

    def results_getter(self, job, label, customerGuid, search_headers, first, count, offset, result_count):
        # Get the results and display them
        kwargs_paginate = {"count": count,
                           "offset": offset}
        blocksearch_results = job.results(**kwargs_paginate)
        results_list = []

        reader = results.ResultsReader(blocksearch_results)

        for result in reader:
            if isinstance(result, results.Message):
                # Diagnostic messages may be returned in the results
            elif isinstance(result, dict):
                # Normal events are returned as dicts
                keys, values = [], []

                for header in search_headers:
                    if header not in result.keys():
                        result[header] = ''

                for key, value in result.items():
                    if key in search_headers:
                        keys.append(str(key))
                        values.append(str(value))
                if not results_list == []:
                    results_list.append(values)
                elif first:
                    results_list.append(keys)
                    results_list.append(values)
                else:
                    results_list.append(values)

        assert not reader.is_preview
        return results_list

    def searches(self, query_list):
        if type(query_list) == dict:
            query_list = [value for value in query_list.values()]
        with closing(ThreadPool(processes=len(query_list))) as pool:
            results = pool.map(self.search, query_list)
            pool.terminate()

        search_results = {item[0]: item[1] for item in results}
        return search_results


text:
Q: How to use my hover function on with ajax load content function? How to use my hover function on with ajax load content function ?
.....................................................................................................................................................................
first when i load page content.php , mouse over on cat image, it's will show hover text.
but when i call content using index.php, hover not work , How can i do ?
index.php

<title>ThaiCreate.Com Ajax Tutorial</title>

content.php

    hover cat images.

    <div class="love" id="love-trigger_16" style=" border-radius: 3px;
                                                   padding: 8px;
                                                   border: 1px solid #ccc;
                                                   right: -107px;
                                                   background: #fff;
                                                   top: 13px;
                                                   width: auto;
                                                   height: auto;">

A: The jQuery handlers don't dynamically attach to content loaded after they were defined.
You need to delegate your event handlers. As such:
$(document).on("hover", "#16", function
...

instead of
$("#16").hover(


text:
Q: How separate release from subsequent branches in git? I am a gitiot and have checked in a tagged git release. Problem is now branching off this when I integrate this I am not keeping nice separate release point. I want to not integrate back into this point so would prefer to branch off from a point ahead. How is this done in git?  thanks
Update: lots of feedback this question was not clear.  What happened is I branched off of a commit which I tagged as a release.  I want future branches to be off a commit beyond the tagged release.

A:
I want to not integrate back into this point so would prefer to branch
  off from a point ahead.

It sounds like you want to perform a rebase.
Let's say on your master branch you have:
A <- B <- C <- D

Then you created a branch off of A called mybranch. You did some work, but now want mybranch to be based off of C.
To accomplish this, you could do:
git checkout mybranch
git rebase C

This will re-write the history of mybranch so if you had previously pushed mybranch you will need to force-push:
git push -f origin mybranch