问:
Python package imports: What's the rule for addressing submodules?
I am a little confused about how python knows about modules in a packages. For example, the python-pptx package has a submodule chart whose directory structure is

```<code>tree /usr/local/lib/python2.7/site-packages/pptx/chart
/usr/local/lib/python2.7/site-packages/pptx/chart
├── __init__.py
├── axis.py
├── category.py
├── chart.py
├── data.py
├── datalabel.py
├── legend.py
├── marker.py
├── plot.py
├── point.py
├── series.py
├── xlsx.py
└── xmlwriter.py
</code>```

Now if I

```<code>import pptx
</code>```

and address chart as

```<code>dir(pptx.chart)
</code>```

then the submodules data and xlsx are missing

```<code>['__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 '__path__',
 'axis',
 'category',
 'chart',
 'datalabel',
 'legend',
 'marker',
 'plot',
 'point',
 'series',
 'xmlwriter']
</code>```

I can directly address pptx.chart.axis using dir(pptx.chart.axis) but dir(pptx.chart.data) results in

```<code>AttributeError: 'module' object has no attribute 'data'
</code>```

The same thing happens if I import pptx.chart

But I can import pptx.chart.data with no issues.

What package importing rules are in place here?

ETA

Python dir() not displaying all modules in a package

is a related question, but doesn't quite address what I was asking.

As explained by Alex Hall, rephrased here, some packages and modules also load other packages and modules. For example, using

```<code>python modulefinder.py test.py | grep pptx
</code>```

I find that, among many other things, the following are loaded

```<code>P pptx.chart                /usr/local/lib/python2.7/site-packages/pptx/chart/__init__.py
m pptx.chart.axis           /usr/local/lib/python2.7/site-packages/pptx/chart/axis.py
m pptx.chart.category       /usr/local/lib/python2.7/site-packages/pptx/chart/category.py
m pptx.chart.chart          /usr/local/lib/python2.7/site-packages/pptx/chart/chart.py
m pptx.chart.datalabel      /usr/local/lib/python2.7/site-packages/pptx/chart/datalabel.py
m pptx.chart.legend         /usr/local/lib/python2.7/site-packages/pptx/chart/legend.py
m pptx.chart.marker         /usr/local/lib/python2.7/site-packages/pptx/chart/marker.py
m pptx.chart.plot           /usr/local/lib/python2.7/site-packages/pptx/chart/plot.py
m pptx.chart.point          /usr/local/lib/python2.7/site-packages/pptx/chart/point.py
m pptx.chart.series         /usr/local/lib/python2.7/site-packages/pptx/chart/series.py
m pptx.chart.xmlwriter      /usr/local/lib/python2.7/site-packages/pptx/chart/xmlwriter.py
</code>```

dir lists only loaded functions, and as pptx does not load pptx.data then dir does not list it. To find all potentially loadable modules, one has to use help

```<code>help(pptx.chart)
Help on package pptx.chart in pptx:

NAME
    pptx.chart

FILE
    /usr/local/lib/python2.7/site-packages/pptx/chart/__init__.py

PACKAGE CONTENTS
    axis
    category
    chart
    data
    datalabel
    legend
    marker
    plot
    point
    series
    xlsx
    xmlwriter
</code>```

And, if a submodule from a package is needed, one should load it explicitly and not rely on the assumption that it has been loaded by something else. Which is the rule I was looking for.

答:
When modules are imported, regardless from where, they are added as attributes to parent modules. If they are not imported from anywhere, they will not be available. This is because creating modules is an expensive process and you only want to create the modules you actually need.

Somewhere (possibly not by you directly, but by one of the modules you directly or indirectly imported) pptx.chart.axis was imported.

If you want to use a module, import it to guarantee it will be there. If you don't import it explicitly, it might still exist if it gets imported somewhere else, but it's not reliable.

Here is the effect in action with Django:

```<code>>>> import sys
>>> [x for x in sys.modules if x.startswith('django')]
[]
>>> import django
>>> [x for x in sys.modules if x.startswith('django')]
['django.utils.version', 'django', 'django.utils.lru_cache', 'django.utils']
>>> django
<module 'django' from '/Users/alexhall/.pyenv/versions/3.5.1/lib/python3.5/site-packages/django/__init__.py'>
>>> django.utils
<module 'django.utils' from '/Users/alexhall/.pyenv/versions/3.5.1/lib/python3.5/site-packages/django/utils/__init__.py'>
>>> django.core
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: module 'django' has no attribute 'core'
>>> django.db
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: module 'django' has no attribute 'db'
>>> import django.db
>>> [x for x in sys.modules if x.startswith('django')]
['django.dispatch', 'django.dispatch.dispatcher', 'django.utils.six.moves', 'django.utils.encoding', 'django.utils.version', 'django.utils.six.moves.urllib', 'django.utils.module_loading', 'django.db', 'django.utils.six', 'django.db.utils', 'django.core.signals', 'django', 'django.utils.functional', 'django.core', 'django.utils.deprecation', 'django.utils.six.moves.urllib.parse', 'django.utils.lru_cache', 'django.conf', 'django.utils.inspect', 'django.utils._os', 'django.core.exceptions', 'django.utils', 'django.conf.global_settings']
>>> django.core
<module 'django.core' from '/Users/alexhall/.pyenv/versions/3.5.1/lib/python3.5/site-packages/django/core/__init__.py'>
>>> django.db
<module 'django.db' from '/Users/alexhall/.pyenv/versions/3.5.1/lib/python3.5/site-packages/django/db/__init__.py'>
</code>```

Body:
I am a little confused about how python knows about modules in a packages. For example, the python-pptx package has a submodule chart whose directory structure is

tree /usr/local/lib/python2.7/site-packages/pptx/chart
/usr/local/lib/python2.7/site-packages/pptx/chart
├── __init__.py
├── axis.py
├── category.py
├── chart.py
├── data.py
├── datalabel.py
├── legend.py
├── marker.py
├── plot.py
├── point.py
├── series.py
├── xlsx.py
└── xmlwriter.py

Now if I

import pptx

and address chart as

dir(pptx.chart)

then the submodules data and xlsx are missing

['__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 '__path__',
 'axis',
 'category',
 'chart',
 'datalabel',
 'legend',
 'marker',
 'plot',
 'point',
 'series',
 'xmlwriter']

I can directly address pptx.chart.axis using dir(pptx.chart.axis) but dir(pptx.chart.data) results in

AttributeError: 'module' object has no attribute 'data'

The same thing happens if I import pptx.chart

But I can import pptx.chart.data with no issues.

What package importing rules are in place here?

ETA

Python dir() not displaying all modules in a package

is a related question, but doesn't quite address what I was asking.

As explained by Alex Hall, rephrased here, some packages and modules also load other packages and modules. For example, using

python modulefinder.py test.py | grep pptx

I find that, among many other things, the following are loaded

P pptx.chart                /usr/local/lib/python2.7/site-packages/pptx/chart/__init__.py
m pptx.chart.axis           /usr/local/lib/python2.7/site-packages/pptx/chart/axis.py
m pptx.chart.category       /usr/local/lib/python2.7/site-packages/pptx/chart/category.py
m pptx.chart.chart          /usr/local/lib/python2.7/site-packages/pptx/chart/chart.py
m pptx.chart.datalabel      /usr/local/lib/python2.7/site-packages/pptx/chart/datalabel.py
m pptx.chart.legend         /usr/local/lib/python2.7/site-packages/pptx/chart/legend.py
m pptx.chart.marker         /usr/local/lib/python2.7/site-packages/pptx/chart/marker.py
m pptx.chart.plot           /usr/local/lib/python2.7/site-packages/pptx/chart/plot.py
m pptx.chart.point          /usr/local/lib/python2.7/site-packages/pptx/chart/point.py
m pptx.chart.series         /usr/local/lib/python2.7/site-packages/pptx/chart/series.py
m pptx.chart.xmlwriter      /usr/local/lib/python2.7/site-packages/pptx/chart/xmlwriter.py

dir lists only loaded functions, and as pptx does not load pptx.data then dir does not list it. To find all potentially loadable modules, one has to use help

help(pptx.chart)
Help on package pptx.chart in pptx:

NAME
    pptx.chart

FILE
    /usr/local/lib/python2.7/site-packages/pptx/chart/__init__.py

PACKAGE CONTENTS
    axis
    category
    chart
    data
    datalabel
    legend
    marker
    plot
    point
    series
    xlsx
    xmlwriter

And, if a submodule from a package is needed, one should load it explicitly and not rely on the assumption that it has been loaded by something else. Which is the rule I was looking for.

Body:
When modules are imported, regardless from where, they are added as attributes to parent modules. If they are not imported from anywhere, they will not be available. This is because creating modules is an expensive process and you only want to create the modules you actually need.

Somewhere (possibly not by you directly, but by one of the modules you directly or indirectly imported) pptx.chart.axis was imported.

If you want to use a module, import it to guarantee it will be there. If you don't import it explicitly, it might still exist if it gets imported somewhere else, but it's not reliable.

Here is the effect in action with Django:

>>> import sys
>>> [x for x in sys.modules if x.startswith('django')]
[]
>>> import django
>>> [x for x in sys.modules if x.startswith('django')]
['django.utils.version', 'django', 'django.utils.lru_cache', 'django.utils']
>>> django
<module 'django' from '/Users/alexhall/.pyenv/versions/3.5.1/lib/python3.5/site-packages/django/__init__.py'>
>>> django.utils
<module 'django.utils' from '/Users/alexhall/.pyenv/versions/3.5.1/lib/python3.5/site-packages/django/utils/__init__.py'>
>>> django.core
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: module 'django' has no attribute 'core'
>>> django.db
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: module 'django' has no attribute 'db'
>>> import django.db
>>> [x for x in sys.modules if x.startswith('django')]
['django.dispatch', 'django.dispatch.dispatcher', 'django.utils.six.moves', 'django.utils.encoding', 'django.utils.version', 'django.utils.six.moves.urllib', 'django.utils.module_loading', 'django.db', 'django.utils.six', 'django.db.utils', 'django.core.signals', 'django', 'django.utils.functional', 'django.core', 'django.utils.deprecation', 'django.utils.six.moves.urllib.parse', 'django.utils.lru_cache', 'django.conf', 'django.utils.inspect', 'django.utils._os', 'django.core.exceptions', 'django.utils', 'django.conf.global_settings']
>>> django.core
<module 'django.core' from '/Users/alexhall/.pyenv/versions/3.5.1/lib/python3.5/site-packages/django/core/__init__.py'>
>>> django.db
<module 'django.db' from '/Users/alexhall/.pyenv/versions/3.5.1/lib/python3.5/site-packages/django/db/__init__.py'>


来源: stackexchange

问:
Linq help with SQL in() statement
I need help writing a Linq statement that does the same as the following sql query...

```<code>select col1, col2, col3
from table1
where col1 = 'foo'
and col2 = 0
and IsNull(col3, '') IN('A','')
</code>```

thanks

答:
The Contains operator is a special one, which you can say something along the lines of</p>

```<code>List<string> col3s= new List<string>() { "A", "B" };

from c in table1
where c.col1 = "foo" && && c.col2 = 0 && col3s.Contains(c.col3)
select new { c.col1, c.col2, c.col3 };
</code>```

ContentLicense: CC BY-SA 2.5

Title: Linq help with SQL in() statement

Body:
I need help writing a Linq statement that does the same as the following sql query...

select col1, col2, col3
from table1
where col1 = 'foo'
and col2 = 0
and IsNull(col3, '') IN('A','')

thanks

Body:
The Contains operator is a special one, which you can say something along the lines of

List<string> col3s= new List<string>() { "A", "B" };

from c in table1
where c.col1 = "foo" && && c.col2 = 0 && col3s.Contains(c.col3)
select new { c.col1, c.col2, c.col3 };


问:
XSLT identity transformation
I am new to XSLT and got a technical question about the identity transformation.

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
</code>```

This is a often posted example, but I never found something about the detailed program sequence. I often read that it works recursively. But I am not sure about the detailed process.
The template matches the union of all attribute-nodes and all other nodes except the root-node. Then the xsl:copy copies the current contextnode (there is no for-each?!) (which should be the first in the document) and applies the template again with the same choice of nodes. This will be done until all nodes are processed?

I would like to know how the program flow is in that identity-building.

==FOLLOW-UP==

Ok, thanks for your answers. I know the processing model of XSLT roughly. Please have a look onto the following. I define a template, which should result in a set of all nodes (except the root node). Then I want to see whats in that set of nodes. For that purpose, I use a for-each and select the name of the current context node.

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="@* | node()">
    <xsl:for-each select="node()">
        <xsl:value-of select="name()" />
    </xsl:for-each>
</xsl:template>

</xsl:transform>
</code>```

with that input xml:

```<code><Telefonliste>
    <Eintrag>
        <name>Peter</name>
        <nachname>Pan</nachname>
        <Tel>12345</Tel>
    </Eintrag>
    <Eintrag>
        <name>Max</name>
        <nachname>Mustermann</nachname>
        <Tel>98765</Tel>
    </Eintrag>
</Telefonliste>
</code>```

I would expect, that I get 9 nodes back. (Telefonliste, Eintrag, name, nachname, Tel, Eintrag, name, nachname, Tel) But I get only two nodes back: Eintrag, Eintrag.

Can someone explain that? I thought my matching template matches "all nodes"?

答:
The identity transform  template matches any node (except the / root node). It copies the matched node and applies templates to its children.

The very first node to be matched is the root element. From there, the processing moves down to its children and so on until the entire tree has been processed recursively (assuming there are no overriding templates).

Added:

I would expect, that I get 9 nodes back. (Telefonliste, Eintrag, name,
  nachname, Tel, Eintrag, name, nachname, Tel) But I get only two nodes
  back: Eintrag, Eintrag.

Your template is applied exactly once, to the root Telefonliste element. From there, your xsl:for-each instruction processes the two child Eintrag nodes. No further processing takes place, because none was specified (you have no xsL:apply-templates instruction).

I interpreted the match-rule that it matches all nodes in that
  xml-tree. My papers (from university) underline everywhere, that such
  queries return a set of nodes, so I thought it collects every node in
  the tree.

You need to distinguish between a select expression and a match pattern.

A select expression selects all nodes for which the expression
evaluates as true.

A match pattern, on the other hand, selects nothing. A match pattern is used by the XSLT processor to find the best-matching template to apply to the currently processed node.

The usual order is this: an xsl:apply-templates instruction selects a node-set to be processed. For each node in the node-set, the processor selects which template to apply from among the stylesheet's templates (or from the built-in default templates, if no matching template is found). If the template contains an xsl:apply-templates instruction, the process is repeated.

ContentLicense: CC BY-SA 3.0

Title: XSLT identity transformation

Body:
I am new to XSLT and got a technical question about the identity transformation.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

This is a often posted example, but I never found something about the detailed program sequence. I often read that it works recursively. But I am not sure about the detailed process.
The template matches the union of all attribute-nodes and all other nodes except the root-node. Then the xsl:copy copies the current contextnode (there is no for-each?!) (which should be the first in the document) and applies the template again with the same choice of nodes. This will be done until all nodes are processed?

I would like to know how the program flow is in that identity-building.

==FOLLOW-UP==

Ok, thanks for your answers. I know the processing model of XSLT roughly. Please have a look onto the following. I define a template, which should result in a set of all nodes (except the root node). Then I want to see whats in that set of nodes. For that purpose, I use a for-each and select the name of the current context node.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="@* | node()">
    <xsl:for-each select="node()">
        <xsl:value-of select="name()" />
    </xsl:for-each>
</xsl:template>

</xsl:transform>

with that input xml:

<Telefonliste>
    <Eintrag>
        <name>Peter</name>
        <nachname>Pan</nachname>
        <Tel>12345</Tel>
    </Eintrag>
    <Eintrag>
        <name>Max</name>
        <nachname>Mustermann</nachname>
        <Tel>98765</Tel>
    </Eintrag>
</Telefonliste>

I would expect, that I get 9 nodes back. (Telefonliste, Eintrag, name, nachname, Tel, Eintrag, name, nachname, Tel) But I get only two nodes back: Eintrag, Eintrag.

Can someone explain that? I thought my matching template matches "all nodes"?


问:
initialize GMM using sklearn python
I wish to create a sklearn GMM object with a predefined set of means, weights, and covariances ( on a grid ).

I managed to do it:

```<code>from sklearn.mixture import GaussianMixture
import numpy as np

def get_grid_gmm(subdivisions=[10,10,10], variance=0.05 ):
    n_gaussians = reduce(lambda x, y: x*y,subdivisions)
    step = [ 1.0/(2*subdivisions[0]),  1.0/(2*subdivisions[1]),  1.0/(2*subdivisions[2])]

    means = np.mgrid[ step[0] : 1.0-step[0]: complex(0,subdivisions[0]),
                      step[1] : 1.0-step[1]: complex(0,subdivisions[1]),
                      step[2] : 1.0-step[2]: complex(0,subdivisions[2])]
    means = np.reshape(means,[-1,3])
    covariances = variance*np.ones_like(means)
    weights = (1.0/n_gaussians)*np.ones(n_gaussians)
    gmm = GaussianMixture(n_components=n_gaussians, covariance_type='spherical' )
    gmm.weights_ = weights
    gmm.covariances_ = covariances
    gmm.means_ = means
    return gmm

def main():
    xx = np.random.rand(100,3)
    gmm = get_grid_gmm()
    y= gmm.predict_proba(xx)

if __name__ == "__main__":
    main()
</code>```

The problem is its missing the gmm.predict_proba() method that I need to use later on.
How can I overcome this?

UPDATE : I updated the code to be a complete example that shows the error

UPDATE2

I updated the code according to comments and answers

```<code>from sklearn.mixture import GaussianMixture
import numpy as np

def get_grid_gmm(subdivisions=[10,10,10], variance=0.05 ):
    n_gaussians = reduce(lambda x, y: x*y,subdivisions)
    step = [ 1.0/(2*subdivisions[0]),  1.0/(2*subdivisions[1]),  1.0/(2*subdivisions[2])]

    means = np.mgrid[ step[0] : 1.0-step[0]: complex(0,subdivisions[0]),
                      step[1] : 1.0-step[1]: complex(0,subdivisions[1]),
                      step[2] : 1.0-step[2]: complex(0,subdivisions[2])]
    means = np.reshape(means,[3,-1])
    covariances = variance*np.ones(n_gaussians)
    cov_type = 'spherical'
    weights = (1.0/n_gaussians)*np.ones(n_gaussians)
    gmm = GaussianMixture(n_components=n_gaussians, covariance_type=cov_type )
    gmm.weights_ = weights
    gmm.covariances_ = covariances
    gmm.means_ = means
    from sklearn.mixture.gaussian_mixture import _compute_precision_cholesky
    gmm.precisions_cholesky_ = _compute_precision_cholesky(covariances, cov_type)
    gmm.precisions_ = gmm.precisions_cholesky_ ** 2
    return gmm

def main():
    xx = np.random.rand(100,3)
    gmm = get_grid_gmm()
    _, y = gmm._estimate_log_prob(xx)
    y = np.exp(y)

if __name__ == "__main__":
    main()
</code>```

No more errors but _estimate_log_prob and predict_proba do not produce the same result for a fitted GMM. Why could that be?

答:
Since you don't train the model but just use the function for estimation, you don't need to use the object but you could use the same function they use under the hood. You could try _estimate_log_gaussian_prob. That is what they do internaly I think.

Have a look at the source:

in particular at the base class
https://github.com/scikit-learn/scikit-learn/blob/ab93d657eb4268ac20c4db01c48065b5a1bfe80d/sklearn/mixture/base.py#L342

that is calling the specific method, that in turn is calling a function
https://github.com/scikit-learn/scikit-learn/blob/ab93d657eb4268ac20c4db01c48065b5a1bfe80d/sklearn/mixture/gaussian_mixture.py#L671

Title: initialize GMM using sklearn python

Body:
I wish to create a sklearn GMM object with a predefined set of means, weights, and covariances ( on a grid ).

I managed to do it:

from sklearn.mixture import GaussianMixture
import numpy as np

def get_grid_gmm(subdivisions=[10,10,10], variance=0.05 ):
    n_gaussians = reduce(lambda x, y: x*y,subdivisions)
    step = [ 1.0/(2*subdivisions[0]),  1.0/(2*subdivisions[1]),  1.0/(2*subdivisions[2])]

    means = np.mgrid[ step[0] : 1.0-step[0]: complex(0,subdivisions[0]),
                      step[1] : 1.0-step[1]: complex(0,subdivisions[1]),
                      step[2] : 1.0-step[2]: complex(0,subdivisions[2])]
    means = np.reshape(means,[-1,3])
    covariances = variance*np.ones_like(means)
    weights = (1.0/n_gaussians)*np.ones(n_gaussians)
    gmm = GaussianMixture(n_components=n_gaussians, covariance_type='spherical' )
    gmm.weights_ = weights
    gmm.covariances_ = covariances
    gmm.means_ = means
    return gmm

def main():
    xx = np.random.rand(100,3)
    gmm = get_grid_gmm()
    y= gmm.predict_proba(xx)

if __name__ == "__main__":
    main()

The problem is its missing the gmm.predict_proba() method that I need to use later on.
How can I overcome this?

UPDATE : I updated the code to be a complete example that shows the error

UPDATE2

I updated the code according to comments and answers

from sklearn.mixture import GaussianMixture
import numpy as np

def get_grid_gmm(subdivisions=[10,10,10], variance=0.05 ):
    n_gaussians = reduce(lambda x, y: x*y,subdivisions)
    step = [ 1.0/(2*subdivisions[0]),  1.0/(2*subdivisions[1]),  1.0/(2*subdivisions[2])]

    means = np.mgrid[ step[0] : 1.0-step[0]: complex(0,subdivisions[0]),
                      step[1] : 1.0-step[1]: complex(0,subdivisions[1]),
                      step[2] : 1.0-step[2]: complex(0,subdivisions[2])]
    means = np.reshape(means,[3,-1])
    covariances = variance*np.ones(n_gaussians)
    cov_type = 'spherical'
    weights = (1.0/n_gaussians)*np.ones(n_gaussians)
    gmm = GaussianMixture(n_components=n_gaussians, covariance_type=cov_type )
    gmm.weights_ = weights
    gmm.covariances_ = covariances
    gmm.means_ = means
    from sklearn.mixture.gaussian_mixture import _compute_precision_cholesky
    gmm.precisions_cholesky_ = _compute_precision_cholesky(covariances, cov_type)
    gmm.precisions_ = gmm.precisions_cholesky_ ** 2
    return gmm

def main():
    xx = np.random.rand(100,3)
    gmm = get_grid_gmm()
    _, y = gmm._estimate_log_prob(xx)
    y = np.exp(y)

if __name__ == "__main__":
    main()

No more errors but _estimate_log_prob and predict_proba do not produce the same result for a fitted GMM. Why could that be?


问:
Get instance of main window controller in app delegate
I know that, for iOS, you can reference the root view controller from the app delegate like so:

var rootViewController = self.window!.rootViewController

How does one reference the main window controller from the app delegate when targeting OS X? I would like to pass a variable (the managed object context) this way, as I have read that it is a good solution for referencing the moc.

答:
You can access like this:</p>

```<code>NSApplication.shared().mainWindow?.contentViewController as! YourViewController;
</code>```

Body:
You can access like this:

NSApplication.shared().mainWindow?.contentViewController as! YourViewController;

ContentLicense: CC BY-SA 4.0


问:
ARKit session's currentFrame is always nil
I try to get the camera transform from the currentFrame.camera property of the ARSession.

Why do I keep getting the sceneView.session.currentFrame? as nil?

答:
I just ran a quick test and saw that the session.currentFrame is nil the first few passes through the render loop. That lag varies, it might be two or a dozen. But eventually currentFrame comes around.

```<code>class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate, SCNSceneRendererDelegate {

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Create a session configuration
    let configuration = ARWorldTrackingSessionConfiguration()
    configuration.worldAlignment = .gravityAndHeading
    configuration.planeDetection = .horizontal

    sceneView.session.delegate = self

    // Run the view's session
    sceneView.session.run(configuration)
    print(#function, sceneView.session.currentFrame)

}

// MARK: - SCNSceneRendererDelegate
func renderer(_ renderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: TimeInterval) {
    print(#function, sceneView.session.currentFrame)
}

// MARK: - ARSessionDelegate
func session(_ session: ARSession, didUpdate frame: ARFrame) {
    print(#function, sceneView.session.currentFrame)
}
</code>```

Gives us

```<code>renderer(_:didRenderScene:atTime:) nil
...
session(_:didUpdate:) Optional(<ARFrame: 0x1c42cff10 timestamp=6334.963644 capturedImage=0x1c0124d80 camera=0x1c41262c0 lightEstimate=0x1c4238640 | no anchors, 0 features>)
...
renderer(_:didRenderScene:atTime:) Optional(<ARFrame: 0x1c02c9c30 timestamp=6334.996948 capturedImage=0x1c0124b00 camera=0x1c0124920 lightEstimate=0x1c02251a0 | no anchors, 0 features>)
</code>```

Body:
I just ran a quick test and saw that the session.currentFrame is nil the first few passes through the render loop. That lag varies, it might be two or a dozen. But eventually currentFrame comes around.

class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate, SCNSceneRendererDelegate {

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Create a session configuration
    let configuration = ARWorldTrackingSessionConfiguration()
    configuration.worldAlignment = .gravityAndHeading
    configuration.planeDetection = .horizontal

    sceneView.session.delegate = self

    // Run the view's session
    sceneView.session.run(configuration)
    print(#function, sceneView.session.currentFrame)

}

// MARK: - SCNSceneRendererDelegate
func renderer(_ renderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: TimeInterval) {
    print(#function, sceneView.session.currentFrame)
}

// MARK: - ARSessionDelegate
func session(_ session: ARSession, didUpdate frame: ARFrame) {
    print(#function, sceneView.session.currentFrame)
}

Gives us

renderer(_:didRenderScene:atTime:) nil
...
session(_:didUpdate:) Optional(<ARFrame: 0x1c42cff10 timestamp=6334.963644 capturedImage=0x1c0124d80 camera=0x1c41262c0 lightEstimate=0x1c4238640 | no anchors, 0 features>)
...
renderer(_:didRenderScene:atTime:) Optional(<ARFrame: 0x1c02c9c30 timestamp=6334.996948 capturedImage=0x1c0124b00 camera=0x1c0124920 lightEstimate=0x1c02251a0 | no anchors, 0 features>)


问:
Devise sign up form displays first name can't be blank even after entering the first name
I have created a User migration with first_name and last_name fields. I also generated the Devise views for User. In the Devise Sign Up form I edited to have the first_name and last name fields. When I try to sign up, when I press on Sign up it shows that first_name and Last_name can't be blank even though those fields are not blank.
User Model:

```<code>class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :first_name, :last_name, :email,  presence: true
end
</code>```

User Migration:

```<code>class CreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
    end
  end
end
</code>```

Devise Sign Up form:

```<code>[![<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
    <%= f.label :first_name %><br />
    <%= f.text_field :first_name, autofocus: true %>
  </div>

  <div class="field">
    <%= f.label :last_name %><br />
    <%= f.text_field :last_name, autofocus: true %>
  </div>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>

  <div class="field">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>][1]][1]
</code>```

答:
You need to add them to the strong params for the devise controller.

You can create your own (Which extend Devise) and then:

```<code> class RegistrationsController < Devise::RegistrationsController

 private

 def sign_up_params
   params.require(:user).permit(:first_name, :last_name, :email, :password,
   :password_confirmation)
 end

 def account_update_params
   params.require(:user).permit(:first_name, :last_name, :email, :password,
   :password_confirmation, :current_password)
 end
 end
</code>```

Here's a good guide

Good luck!

Body:
I have created a User migration with first_name and last_name fields. I also generated the Devise views for User. In the Devise Sign Up form I edited to have the first_name and last name fields. When I try to sign up, when I press on Sign up it shows that first_name and Last_name can't be blank even though those fields are not blank.
User Model:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :first_name, :last_name, :email,  presence: true
end

User Migration:

class CreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
    end
  end
end

Devise Sign Up form:

[![
Sign up

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

    <%= f.label :first_name %>

    <%= f.text_field :first_name, autofocus: true %>

    <%= f.label :last_name %>

    <%= f.text_field :last_name, autofocus: true %>

    <%= f.label :email %>

    <%= f.email_field :email, autofocus: true %>

    <%= f.label :password %>
    <% if @minimum_password_length %>
    (<%= @minimum_password_length %> characters minimum)
    <% end %>

    <%= f.password_field :password, autocomplete: "off" %>

    <%= f.label :password_confirmation %>

    <%= f.password_field :password_confirmation, autocomplete: "off" %>

    <%= f.submit "Sign up" %>

<% end %>

<%= render "devise/shared/links" %>][1]][1]

Body:
You need to add them to the strong params for the devise controller.

You can create your own (Which extend Devise) and then:

 class RegistrationsController < Devise::RegistrationsController

 private

 def sign_up_params
   params.require(:user).permit(:first_name, :last_name, :email, :password,
   :password_confirmation)
 end

 def account_update_params
   params.require(:user).permit(:first_name, :last_name, :email, :password,
   :password_confirmation, :current_password)
 end
 end

Here's a good guide

Good luck!


问:
tensorflow.ones_like on a SparseTensor
In tensorflow, I want to do tf.ones_like on a SparseTensor; however, it seems it only works for normal (dense) tensors. Do you know any function or workaround?

As an example, I want to go from [['aa','ab','ac'],['ba','bb', UND],['ca',UND,UND] to [[1,1,1],[1,1,UND],[1,UND,UND]], where UND = undefined.

Thanks!

答:
You can do two things:

Convert sparse to dense and then create a ones tensor. Something like tf.ones_like(tf.sparse_tensor_to_dense(x))

Get a shape of sparse tensor and use it to create a ones tensor. It looks like dense_shape does this. Then use tf.ones with that shape.

Title: tensorflow.ones_like on a SparseTensor


问:
Screen reader i.e. JAWS doesn't read text of a button when text is changed on click of that button?
I am facing one minor difficulty while making my software ARIA accessibility enabled. Any kind of help would be appreciated!

I have a div which works as a 'Edit' button with click event using jQuery. I am changing text of that button 'Save' on click event. Screen reader like JAWS reads "Edit button" when the focus comes to that button for the first time.

But I want JAWS to recognise the change happened after click event i.e. After click JAWS should read "Save button". Any help? (Note that even after click, focus stays on the same button)

HTML code for that div/button:

```<code><div role="button" class="js-btn" aria-label="Edit">Edit</div>
</code>```

jQuery code to handle click event:

```<code>$(document).on("click",".js-btn",function(e){
    $(this).innerHTML("Save");
    $(this).attr("aria-label","Save");
});
</code>```

答:
First: props for thinking of accessibility, and testing for it! But aria and its features are really meant to extend html for interactive things it can't natively handle. And html can totally handle a button. So use button here, please, and you can skip the role and aria-label.

Having the native semantics might be enough to make JAWS notice the change in text - not sure, but worth a try. If it doesn't, you could add aria-live="polite" or aria-live="assertive" to your button and that should cue the SR to announce when its contents change. (Which one to use depends on how pushy you want to be about informing your user - polite won't interrupt whatever they're doing, assertive will.)

<button aria-live="polite" class="js-btn">Edit</button>

Body:
I am facing one minor difficulty while making my software ARIA accessibility enabled. Any kind of help would be appreciated!

I have a div which works as a 'Edit' button with click event using jQuery. I am changing text of that button 'Save' on click event. Screen reader like JAWS reads "Edit button" when the focus comes to that button for the first time.

But I want JAWS to recognise the change happened after click event i.e. After click JAWS should read "Save button". Any help? (Note that even after click, focus stays on the same button)

HTML code for that div/button:

Edit

jQuery code to handle click event:

$(document).on("click",".js-btn",function(e){
    $(this).innerHTML("Save");
    $(this).attr("aria-label","Save");
});


问:
How can I validate a copy constructor's parameter?
```<code>public class Rectangle {

  int width, height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public Rectangle(Rectangle source) {
    this(source.width, source.height);
  }
}
</code>```

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

答:
You could introduce a private static method that returns the relevant value with a null check to throw the IllegalArgumentException (in this case the width as it's the first parameter on the same object).

For example:

```<code>public class Rectangle {

    private int width, height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public Rectangle(Rectangle rectangle) {
        this(getWidth(rectangle), rectangle.height);
    }

    private static int getWidth(Rectangle rectangle) {
        if (rectangle == null) {
            throw new IllegalArgumentException("null value");
        }
        return rectangle.width;
    }

}
</code>```

Reflecting on the comment to the question above, why not NullPointerException?

This question: IllegalArgumentException or NullPointerException for a null parameter? has some good discussion points. But I'm inclined to agree with the sentiments of "Effective Java" that NullPointerException should be preferred as cited in this answer to that very question.

"Arguably, all erroneous method invocations boil down to an illegal
  argument or illegal state, but other exceptions are standardly used
  for certain kinds of illegal arguments and states. If a caller passes
  null in some parameter for which null values are prohibited,
  convention dictates that NullPointerException be thrown rather than
  IllegalArgumentException."

Body:
public class Rectangle {

  int width, height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public Rectangle(Rectangle source) {
    this(source.width, source.height);
  }
}

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

Body:
You could introduce a private static method that returns the relevant value with a null check to throw the IllegalArgumentException (in this case the width as it's the first parameter on the same object).

For example:

public class Rectangle {

    private int width, height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public Rectangle(Rectangle rectangle) {
        this(getWidth(rectangle), rectangle.height);
    }

    private static int getWidth(Rectangle rectangle) {
        if (rectangle == null) {
            throw new IllegalArgumentException("null value");
        }
        return rectangle.width;
    }

}

Reflecting on the comment to the question above, why not NullPointerException?

This question: IllegalArgumentException or NullPointerException for a null parameter? has some good discussion points. But I'm inclined to agree with the sentiments of "Effective Java" that NullPointerException should be preferred as cited in this answer to that very question.

"Arguably, all erroneous method invocations boil down to an illegal
  argument or illegal state, but other exceptions are standardly used
  for certain kinds of illegal arguments and states. If a caller passes
  null in some parameter for which null values are prohibited,
  convention dictates that NullPointerException be thrown rather than
  IllegalArgumentException."


问:
Cannot resolve method using(com.firebase.ui.storage.images.FirebaseImageLoader)
I'm trying to use the awesome Glide integration provided by FirebaseUI, but I am unable to do so.

I have followed everything described here: Downloading images with FirebaseUI

Cannot resolve method using(com.ui.firebase.storage.images.FirebaseImageLoader)

is the error that I am currently getting.

Are my settings good?

Here are the versions of the two libraries I am using:

Glide 4.0.0-RC1

FirebaseUI 2.0.1

And this is my gradle (app):

```<code>dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.firebase:geofire-android:2.1.1'
    compile 'com.google.android.gms:play-services-location:11.0.1'
    compile 'com.android.support:design:25.3.1'

    implementation 'com.google.firebase:firebase-database:11.0.1'
    implementation 'com.android.support:cardview-v7:25.3.1'
    compile 'com.firebaseui:firebase-ui-storage:2.0.1'
    compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
    compile 'com.android.support:support-v4:25.3.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC1'
    implementation 'com.google.firebase:firebase-storage:11.0.1'
    implementation 'com.google.firebase:firebase-auth:11.0.1'

}

apply plugin: 'com.google.gms.google-services'
</code>```

答:
Unfortunately, FirebaseUI doesn't yet support Glide 4.0 so you have two options:

Downgrade Glide to v3.8.0

Write your own Glide Module. You can see my response here on how you would go about upgrading the FirebaseUI storage code.

This issue is being tracked here: https://github.com/firebase/FirebaseUI-Android/issues/731

Edit: As per link above, the issue has been resolved in version 3.0

Body:
I'm trying to use the awesome Glide integration provided by FirebaseUI, but I am unable to do so.

I have followed everything described here: Downloading images with FirebaseUI

Cannot resolve method using(com.ui.firebase.storage.images.FirebaseImageLoader)

is the error that I am currently getting.

Are my settings good?

Here are the versions of the two libraries I am using:

Glide 4.0.0-RC1

FirebaseUI 2.0.1

And this is my gradle (app):

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.firebase:geofire-android:2.1.1'
    compile 'com.google.android.gms:play-services-location:11.0.1'
    compile 'com.android.support:design:25.3.1'

    implementation 'com.google.firebase:firebase-database:11.0.1'
    implementation 'com.android.support:cardview-v7:25.3.1'
    compile 'com.firebaseui:firebase-ui-storage:2.0.1'
    compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
    compile 'com.android.support:support-v4:25.3.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC1'
    implementation 'com.google.firebase:firebase-storage:11.0.1'
    implementation 'com.google.firebase:firebase-auth:11.0.1'

}

apply plugin: 'com.google.gms.google-services'


问:
How to send formatted Rich Text Box as mail signature to some one in c# winform
I have created an email signature using Rich Text Box. I want to sent this to my client through smtp protocol. I know the code to send smtp mail, but how to send this formatted text to the client as mail body?

Thanks in advance.

答:
What you want to do is sending an email in html format:

```<code>MailMessage myMail = new MailMessage();
myMail.IsBodyHtml = true;
myMail.Body = "<b>here your html text</b>";
</code>```

Use the System.Net.Mail namespace.

Body:
What you want to do is sending an email in html format:

MailMessage myMail = new MailMessage();
myMail.IsBodyHtml = true;
myMail.Body = "<b>here your html text</b>";

Use the System.Net.Mail namespace.


问:
JAVA reading XML, direct from element
I have program for reading XML file. Recently my supplier changed some part of the source XML file and I have no idea how to read the changed parts.

XML :

```<code><Product>
<Weight>5,000</Weight>
<Color>blue</Color>
<Stock Warehouse_name="London" Availability="5,00"/>
<Stock Warehouse_name="Berlin" Availability="0,00"/>
<Stock Warehouse_name="Sydney" Availability="42,00"/>
</Product>
</code>```

Maybe you see my problem already. Weight and Color are OK, but the Stock is my problem. Instead to give the information between the elements, the information is direct in the element. I'm using the standard method to retrieve the data:

```<code>color = (eElement.getElementsByTagName("Color").item(0).getTextContent());
</code>```

Any suggestion? I'm pretty new to Java, so please explain it to me as simple, as possible.

答:
You need to get the Stock nodes and convert to Element, then you can get the attribute you want.

```<code>final DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// textoXml contains your xml file
final Document doc = dBuilder.parse(new ByteArrayInputStream(textoXml.getBytes()));
// Here you gat the Stock node you want and cast to Element
final Element eStock = (Element) doc.getElementsByTagName("Stock").item(0);
final String warehouseName = eStock.getAttribute("Warehouse_name");
</code>```

You can see some other examples in https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

Title: JAVA reading XML, direct from element

Body:
I have program for reading XML file. Recently my supplier changed some part of the source XML file and I have no idea how to read the changed parts.

XML :

<Product>
<Weight>5,000</Weight>
<Color>blue</Color>
<Stock Warehouse_name="London" Availability="5,00"/>
<Stock Warehouse_name="Berlin" Availability="0,00"/>
<Stock Warehouse_name="Sydney" Availability="42,00"/>
</Product>

Maybe you see my problem already. Weight and Color are OK, but the Stock is my problem. Instead to give the information between the elements, the information is direct in the element. I'm using the standard method to retrieve the data:

color = (eElement.getElementsByTagName("Color").item(0).getTextContent());

Any suggestion? I'm pretty new to Java, so please explain it to me as simple, as possible.

Body:
You need to get the Stock nodes and convert to Element, then you can get the attribute you want.

final DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// textoXml contains your xml file
final Document doc = dBuilder.parse(new ByteArrayInputStream(textoXml.getBytes()));
// Here you gat the Stock node you want and cast to Element
final Element eStock = (Element) doc.getElementsByTagName("Stock").item(0);
final String warehouseName = eStock.getAttribute("Warehouse_name");

You can see some other examples in https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/


问:
Node js and Angular js
I am to send a user entered text through Angular js to Node js the issue is the node js server recognizes the event but does not get the data and print it I know I am doing some mistake in the code and do not know how to fix it. can some one please fix this code please.

angular.js

```<code>var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.submit= function(){
      var data = {
          id : "Angkirat"
          Password : "Sandhu"
      }

      $http.post("http://localhost:8081/meow", data)
        .success(function(req,res) {
         console.dir(req.body);
         res.send(req.body);
         alert("hogaya")
       }).error(function() {

      });
   }
});
</code>```

Server.js

```<code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cors = require('cors');
var http = require("http");
var fs = require("fs");
var url = require("url");
var display = "";

http.createServer(function(request,response){
    var pathname = url.parse(request.url).pathname;
    console.log("Request for" + pathname + "received.");
    fs.readFile(pathname.substr(1),function (err,data){
        if(err){
            console.log(err);
            response.writeHead(404, {'Content-Type': 'text/html'});
        }else{
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write(data.toString());
        }
        app.use(cors());
        app.use(bodyParser.json());
        app.post('/meow', function(req, res){
            var cope = req.body.params;
            display = cope;
            console.log(cope);
        });
        response.end();
    });
}).listen(8080);
console.log(display)
</code>```

Please can some one fix this problem for me.

答:
In server.js file console req.body instead of req.body.params</p>

```<code>    app.post('/meow', function(req, res){
    console.log(req.body);
    console.log(req.body.id) //to access the id
    console.log(req.body.Password) //to access the password
    });
    response.end();
</code>```

Title: Node js and Angular js

Body:
I am to send a user entered text through Angular js to Node js the issue is the node js server recognizes the event but does not get the data and print it I know I am doing some mistake in the code and do not know how to fix it. can some one please fix this code please.

angular.js

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.submit= function(){
      var data = {
          id : "Angkirat"
          Password : "Sandhu"
      }

      $http.post("http://localhost:8081/meow", data)
        .success(function(req,res) {
         console.dir(req.body);
         res.send(req.body);
         alert("hogaya")
       }).error(function() {

      });
   }
});

Server.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cors = require('cors');
var http = require("http");
var fs = require("fs");
var url = require("url");
var display = "";

http.createServer(function(request,response){
    var pathname = url.parse(request.url).pathname;
    console.log("Request for" + pathname + "received.");
    fs.readFile(pathname.substr(1),function (err,data){
        if(err){
            console.log(err);
            response.writeHead(404, {'Content-Type': 'text/html'});
        }else{
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write(data.toString());
        }
        app.use(cors());
        app.use(bodyParser.json());
        app.post('/meow', function(req, res){
            var cope = req.body.params;
            display = cope;
            console.log(cope);
        });
        response.end();
    });
}).listen(8080);
console.log(display)

Please can some one fix this problem for me.

Body:
In server.js file console req.body instead of req.body.params

    app.post('/meow', function(req, res){
    console.log(req.body);
    console.log(req.body.id) //to access the id
    console.log(req.body.Password) //to access the password
    });
    response.end();


问:
Can you use heredocuments to embed AWK in a bash script?
Writing a shell script that pretty much wraps around an Awk script. I'd like to have my syntax colouring on in the awk section so I feel there must be a better way to embed awk scripts to bash than just quote the script in.

Or is it the best way to develop the awk on a separate file and use awk -f in the bash script until the script's done? I'd like to keep within one file all times!

```<code>#!/bin/bash
awkscript='
BEGIN{
    print "test"
}
{print $3}'
df | awk "$awkscript"
</code>```

This is the quote way, and quite ugly if you ask me. Any chance for heredocs here?

答:
Sometimes this may be usefull:</p>

```<code>awkscript=$(cat << EOT
BEGIN{
    print "test"
}
{print $3}
EOT
)

df | awk "$awkscript"
</code>```

Body:
Writing a shell script that pretty much wraps around an Awk script. I'd like to have my syntax colouring on in the awk section so I feel there must be a better way to embed awk scripts to bash than just quote the script in.

Or is it the best way to develop the awk on a separate file and use awk -f in the bash script until the script's done? I'd like to keep within one file all times!

#!/bin/bash
awkscript='
BEGIN{
    print "test"
}
{print $3}'
df | awk "$awkscript"

This is the quote way, and quite ugly if you ask me. Any chance for heredocs here?

Body:
Sometimes this may be usefull:

awkscript=$(cat << EOT
BEGIN{
    print "test"
}
{print $3}
EOT
)

df | awk "$awkscript"


问:
iPad Pro: Detect 50/50 split
Is there any way to detect the 50/50 split when using Split View multitasking on iPad Pro? iPad Air uses the compact width and regular height size class, but iPad Pro uses regular width and regular height in all Split View variants.

More specifically I don't want to have rounded corners on my views when in 50/50 split. (http://d.pr/i/18ThG + http://d.pr/i/19OFL)
I use the readable content guide for the width adjustment of the views.

答:
What it worked for me was to get the device width and the width of the current window.

For example, using:

```<code>print("root window size \(window?.frame)")
print("screen size \(UIScreen.main.bounds)")
</code>```

I get:

```<code>root window size (0.0, 0.0, 678.0, 1024.0)
screen size (0.0, 0.0, 1366.0, 1024.0)
</code>```

Then you could divide the results 678/1366 ≈ 0.4963

Title: iPad Pro: Detect 50/50 split

Body:
What it worked for me was to get the device width and the width of the current window.

For example, using:

print("root window size \(window?.frame)")
print("screen size \(UIScreen.main.bounds)")

I get:

root window size (0.0, 0.0, 678.0, 1024.0)
screen size (0.0, 0.0, 1366.0, 1024.0)

Then you could divide the results 678/1366 ≈ 0.4963


问:
Python home directory in Windows / Problem with multiple versions
I'm using Python 3 for developing and CollabNet Subversion Edge as versioning software. Subversion Edge comes with a little program called ViewVC which is written in Python 2, which is also directly bundled with it. There is a system environment variable called PYTHONHOME.

If it is set to the Python 2 distribution from Subversion Edge, my Python 3 won't start (not even IDLE), instead giving a runtime error messagebox.

If it is set to Python 3, ViewVC doesn't work.

Is there a way to make both work at the same time?

答:
Have you considered changing the Subversion Edge services to run as a specific user account, and then move the PYTHONHOME environment variable to a user-level variable for that account only?  As opposed to a system-wide variable?  It seems like it should work.

BTW, the PYTHONHOME variable is added for mod_python to work properly (which is what serves ViewVC).  If you can find another way to get mod_python to work, then you could try that.


问:
Automatically scroll to bottom of RecyclerView
I have a fragment that has a RecyclerView inside its layout file. The RecyclerView holds messages in a chat. So naturally, I need the RecyclerView to scroll to the bottom when the chat fragment gets opened.

I tried scrolling directly on the RecyclerView:

```<code>var mRecyclerView = view.FindViewById<RecyclerView>
mRecyclerView.ScrollToPosition(mMessages.Count-1);
</code>```

Second method:

```<code>LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(Application.Context);
mRecyclerView.SetLayoutManager(mLinearLayoutManager);
mLinearLayoutManager.ScrollToPosition(mMessages.Count - 1);
</code>```

Third method:

```<code>LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(Application.Context);
mRecyclerView.SetLayoutManager(mLinearLayoutManager);
mLinearLayoutManager.ScrollToPositionWithOffset(mMessages.Count - 1, 0);
</code>```

Unfortunately, nothing happens in either case. Any suggestions would be greatly appreciated!

答:
You can set setStackFromEnd=true that will set the view to show the last element, the layout direction will remain the same.

After edit I have updated: just like this:

```<code>   LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(Application.Context);
   mLinearLayoutManager.setStackFromEnd(true);
   mRecyclerView.SetLayoutManager(mLinearLayoutManager);
   mRecyclerView.scrollToPosition(mMessages.Count-1);
</code>```

please check the documentation.

Edit: the problem is you are calling scrollToPosition without setting any layout manager to the recyclerview.

Considering to the scrollToPosition function in RecyclerView class, your case makes sense.

```<code>/**
     * Convenience method to scroll to a certain position.
     *
     * RecyclerView does not implement scrolling logic, rather forwards the call to
     * {@link android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)}
     * @param position Scroll to this adapter position
     * @see android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)
     */
    public void scrollToPosition(int position) {
        if (mLayoutFrozen) {
            return;
        }
        stopScroll();
        if (mLayout == null) {
            Log.e(TAG, "Cannot scroll to position a LayoutManager set. " +
                    "Call setLayoutManager with a non-null argument.");
            return;
        }
        mLayout.scrollToPosition(position);
        awakenScrollBars();
    }
</code>```

Cannot scroll to position a LayoutManager set. Call setLayoutManager with a non-null argument.

Body:
I have a fragment that has a RecyclerView inside its layout file. The RecyclerView holds messages in a chat. So naturally, I need the RecyclerView to scroll to the bottom when the chat fragment gets opened.

I tried scrolling directly on the RecyclerView:

var mRecyclerView = view.FindViewById<RecyclerView>
mRecyclerView.ScrollToPosition(mMessages.Count-1);

Second method:

LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(Application.Context);
mRecyclerView.SetLayoutManager(mLinearLayoutManager);
mLinearLayoutManager.ScrollToPosition(mMessages.Count - 1);

Third method:

LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(Application.Context);
mRecyclerView.SetLayoutManager(mLinearLayoutManager);
mLinearLayoutManager.ScrollToPositionWithOffset(mMessages.Count - 1, 0);

Unfortunately, nothing happens in either case. Any suggestions would be greatly appreciated!

Body:
You can set setStackFromEnd=true that will set the view to show the last element, the layout direction will remain the same.

After edit I have updated: just like this:

   LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(Application.Context);
   mLinearLayoutManager.setStackFromEnd(true);
   mRecyclerView.SetLayoutManager(mLinearLayoutManager);
   mRecyclerView.scrollToPosition(mMessages.Count-1);

please check the documentation.

Edit: the problem is you are calling scrollToPosition without setting any layout manager to the recyclerview.

Considering to the scrollToPosition function in RecyclerView class, your case makes sense.

/**
     * Convenience method to scroll to a certain position.
     *
     * RecyclerView does not implement scrolling logic, rather forwards the call to
     * {@link android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)}
     * @param position Scroll to this adapter position
     * @see android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)
     */
    public void scrollToPosition(int position) {
        if (mLayoutFrozen) {
            return;
        }
        stopScroll();
        if (mLayout == null) {
            Log.e(TAG, "Cannot scroll to position a LayoutManager set. " +
                    "Call setLayoutManager with a non-null argument.");
            return;
        }
        mLayout.scrollToPosition(position);
        awakenScrollBars();
    }

Cannot scroll to position a LayoutManager set. Call setLayoutManager with a non-null argument.


问:
Can I debug (step through) code without a main() function?
Assume I want to understand a larger project by just stepping through the code with a debugger. Is it possible to just jump in at an arbitrary point (given I define the correct variables)? How do I debug libraries that don't have a main?</p>

答:
To debug code in a library, write a little application (that has a main()) that calls the functions in the library you need to debug. Then debug that application and step into the library calls it makes.

As for just "jumping into an arbitrary location" - well, you can instruct the debugger to move the instruction pointer to wherever you please, but that's usually not what you want, because you'd be missing a lot of state that previous parts of the program will have created. Usually what you want to do is set a breakpoint in the function you are interested in and then just run the program normally until you hit the breakpoint.


问:
How can I easily access data both inside and outside a container?
I have a docker container with MinGW compiler set up inside it. I want to use it for development. That is I want to compile, test, edit, compile, test ...

The container will also be used in the CI pipeline, and eventually for producing production builds. By using the same container we ensure consistency in the build environment.

My host has my development tools for code editing etc. while the container has the compiler, so clearly the files need to be shared.

I have set up a volume. Unfortunately I cannot access it with my user account:

```<code># ls -lAFd /var/lib/docker
drwx--x--x 11 root docker 4096 Jul  4 09:11 /var/lib/docker/
# ls -lAFd /var/lib/docker/volumes/mingw_build/_data
drwxr-xr-x 6 alastair docker 4096 Jul  3 14:31 /var/lib/docker/volumes/mingw_build/_data/
</code>```

My user is in group docker but group docker does NOT have read permissions on /var/lib/docker and so cannot access the _data directory of the volume.

I have tried cheating and using sudo to tweak the folder permissions so that group docker has read permissions all the way down the path, but those permissions get rewritten on reboot - no doubt when the docker server starts.

Can anyone figure out a way around this? I have tried using symlinks, but they always inherit the most restrictive permissions of the path elements.

答:
Docker includes a user/group remapping feature - based on user namespaces - that is not enabled by default.

Enable "userne-remap" on the docker daemon by following instructions there : https://docs.docker.com/engine/security/userns-remap/

Body:
I have a docker container with MinGW compiler set up inside it. I want to use it for development. That is I want to compile, test, edit, compile, test ...

The container will also be used in the CI pipeline, and eventually for producing production builds. By using the same container we ensure consistency in the build environment.

My host has my development tools for code editing etc. while the container has the compiler, so clearly the files need to be shared.

I have set up a volume. Unfortunately I cannot access it with my user account:

# ls -lAFd /var/lib/docker
drwx--x--x 11 root docker 4096 Jul  4 09:11 /var/lib/docker/
# ls -lAFd /var/lib/docker/volumes/mingw_build/_data
drwxr-xr-x 6 alastair docker 4096 Jul  3 14:31 /var/lib/docker/volumes/mingw_build/_data/

My user is in group docker but group docker does NOT have read permissions on /var/lib/docker and so cannot access the _data directory of the volume.

I have tried cheating and using sudo to tweak the folder permissions so that group docker has read permissions all the way down the path, but those permissions get rewritten on reboot - no doubt when the docker server starts.

Can anyone figure out a way around this? I have tried using symlinks, but they always inherit the most restrictive permissions of the path elements.


问:
Unable to Save nested ForeignCollectionField after 1 level android
Hi I am trying to save nested arrayList in dataBase.

I am saving it using ForeignCollectionField and i have managed to save it in DB. but when i try to retrieve from DB. it doesn't return data as stored.

You can see in  in highlighted area. it is saving in DB.

but when i try to retrieve using below query

```<code>DatabaseManager.getInstance().
            getFirstMatching("surveyId", getIntent().getStringExtra("survey_id"), CampaignDetails.class);
</code>```

it gives the result like

Here is code that i am using to save Data in Database

CampaignDetails.java

```<code>public class CampaignDetails extends UpdateableManagedObject {

    @DatabaseField
    private String campaignTitle;

    @DatabaseField
    private String surveyTitle;

    @DatabaseField
    private int surveyId;

    @ForeignCollectionField(eager = true, maxEagerLevel = 4)
    public ForeignCollection<QuestionDetail> questionDetail;

    public static void fromJson(JSONObject json) {
        if (json == null) return;
        int id = json.optInt("surveyId", 0);
        if (id == 0) return;

        CampaignDetails result = DatabaseManager.getInstance().getFirstMatching("surveyId", id, CampaignDetails.class);
        boolean created = result == null;
        if (created) {
            result = new CampaignDetails();
            result.surveyId = id;
        }

        result.questionDetail = result.getDao().getEmptyForeignCollection("questionDetail");
        result.campaignTitle = json.optString("campaignTitle");
        result.surveyTitle = json.optString("surveyTitle");
        result.hasCreated = true;
        try {
            fromJsonArray(json.getJSONArray("questionDetail"), result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (created) result.create();
        else result.update();
    }

    private static void fromJsonArray(JSONArray questionDetail, CampaignDetails campaignDetail) {

        for (int i = 0; i < questionDetail.length(); i++) {
            try {
                JSONObject jsonObject = questionDetail.getJSONObject(i);

                QuestionDetail result = DatabaseManager.getInstance().getFirstMatching("questionId", jsonObject.optString("questionId"), QuestionDetail.class);
                boolean isCreated = result == null;
                if (isCreated) {
                    result = new QuestionDetail();
                }
                result.question = jsonObject.optString("question");
                result.questionId = jsonObject.optString("questionId");
                result.questionType = jsonObject.optString("questionType");
                if (jsonObject.has("questionChoices")) {
                    result.questionChoices = result.getDao().getEmptyForeignCollection("questionChoices");
                    result.fromJson(jsonObject.getJSONArray("questionChoices"), result);
                }
                campaignDetail.questionDetail.add(result);
                result.campaignDetail = campaignDetail;
                if (isCreated) {
                    result.create();
                } else {
                    result.update();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

}
</code>```

QuestionDetail.java

```<code>public class QuestionDetail extends ManagedObject {

    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    public CampaignDetails campaignDetail;

    @DatabaseField
    public String question;

    @DatabaseField
    public String questionId;

    @DatabaseField
    public String questionType;

    @ForeignCollectionField(eager = true,maxEagerLevel = 4)
    public Collection<QuestionChoice> questionChoices;

    public void fromJson(JSONArray choices, QuestionDetail questionDetail) {

        for (int i = 0; i < choices.length(); i++) {
            try {
                JSONObject jsonObject = choices.getJSONObject(i);

                QuestionChoice result = DatabaseManager.getInstance().getFirstMatching("choiceId", jsonObject.optString("choiceId"), QuestionChoice.class);
                boolean isCreated = result == null;
                if (isCreated) {
                    result = new QuestionChoice();
                }
                result.choiceId = jsonObject.optString("choiceId");
                result.choice = jsonObject.optString("choice");
                result.questionDetail = questionDetail;
                questionChoices.add(result);
                if (isCreated) {
                    result.create();
                } else {
                    result.update();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
</code>```

QuestionChoice.Java

```<code>public class QuestionChoice extends ManagedObject {

    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    public QuestionDetail questionDetail;

    @DatabaseField
    @SerializedName("choiceId")
    @Expose
    public String choiceId;

    @DatabaseField
    @SerializedName("choice")
    @Expose
    public String choice;

}
</code>```

Can anyone help me solve my problem? I am really stuck on it Thanks.

答:
I have solved it by changing the order of code in two files given below

CampaignDetails.java

```<code>public class CampaignDetails extends UpdateableManagedObject {

    @DatabaseField
    private String campaignTitle;

    @DatabaseField
    private String surveyTitle;

    @DatabaseField
    private int surveyId;

    @ForeignCollectionField(eager = true, maxEagerLevel = 2)
    public ForeignCollection<QuestionDetail> questionDetail;

public ArrayList<QuestionDetail> getQuestionDetail() {
    if (assessmentCache == null) {
        refresh();
        assessmentCache = new ArrayList<>();

        if (questionDetail != null) {
            for (QuestionDetail assessment : questionDetail) {
                assessmentCache.add(assessment);
            }
        }
    }

    return assessmentCache;
}

public static void fromJson(JSONObject json) {
    if (json == null) return;
    int id = json.optInt("surveyId", 0);
    if (id == 0) return;

    CampaignDetails result = DatabaseManager.getInstance().getFirstMatching("surveyId", id, CampaignDetails.class);
    boolean created = result == null;
    if (created) {
        result = new CampaignDetails();
        result.surveyId = id;
        result.create();
    } else {
        result.update();
    }

    result.questionDetail = result.getDao().getEmptyForeignCollection("questionDetail");
    result.campaignTitle = json.optString("campaignTitle");
    result.surveyTitle = json.optString("surveyTitle");
    result.hasCreated = true;
    try {
        fromJsonArray(json.getJSONArray("questionDetail"), result);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    result.update();
}

private static void fromJsonArray(JSONArray questionDetail, CampaignDetails campaignDetail) {

    for (int i = 0; i < questionDetail.length(); i++) {
        try {
            JSONObject jsonObject = questionDetail.getJSONObject(i);

            QuestionDetail result = DatabaseManager.getInstance().getFirstMatching("questionId", jsonObject.optString("questionId"), QuestionDetail.class);
            boolean isCreated = result == null;
            if (isCreated) {
                result = new QuestionDetail();
            } else {
                continue;
            }
            result.questionChoices = result.getDao().getEmptyForeignCollection("questionChoices");
            result.campaignDetail = campaignDetail;
            result.question = jsonObject.optString("question");
            result.questionId = jsonObject.optString("questionId");
            result.questionType = jsonObject.optString("questionType");
            campaignDetail.questionDetail.add(result);
            if (jsonObject.has("questionChoices")) {
                result.fromJson(jsonObject.getJSONArray("questionChoices"), result);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
</code>```

}

QuestionDetail.java

```<code>public class QuestionDetail extends ManagedObject {

    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    public CampaignDetails campaignDetail;

    @DatabaseField
    public String question;

    @DatabaseField
    public String questionId;

    @DatabaseField
    public String questionType;

    @ForeignCollectionField(eager = true, maxEagerLevel = 2)
    public Collection<QuestionChoice> questionChoices;

    public void fromJson(JSONArray choices, QuestionDetail questionDetail) {

        for (int i = 0; i < choices.length(); i++) {
            try {
                JSONObject jsonObject = choices.getJSONObject(i);

                QuestionChoice result = DatabaseManager.getInstance().getFirstMatching("choiceId", jsonObject.optString("choiceId"), QuestionChoice.class);
                boolean isCreated = result == null;
                if (isCreated) {
                    result = new QuestionChoice();
                } else {
                    continue;
                }
                result.questionDetail = questionDetail;
                result.choiceId = jsonObject.optString("choiceId");
                result.choice = jsonObject.optString("choice");
                questionDetail.questionChoices.add(result);
//                result.create();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
</code>```

Body:
Hi I am trying to save nested arrayList in dataBase.

I am saving it using ForeignCollectionField and i have managed to save it in DB. but when i try to retrieve from DB. it doesn't return data as stored.

You can see in  in highlighted area. it is saving in DB.

but when i try to retrieve using below query

DatabaseManager.getInstance().
            getFirstMatching("surveyId", getIntent().getStringExtra("survey_id"), CampaignDetails.class);

it gives the result like

Here is code that i am using to save Data in Database

CampaignDetails.java

public class CampaignDetails extends UpdateableManagedObject {

    @DatabaseField
    private String campaignTitle;

    @DatabaseField
    private String surveyTitle;

    @DatabaseField
    private int surveyId;

    @ForeignCollectionField(eager = true, maxEagerLevel = 4)
    public ForeignCollection<QuestionDetail> questionDetail;

    public static void fromJson(JSONObject json) {
        if (json == null) return;
        int id = json.optInt("surveyId", 0);
        if (id == 0) return;

        CampaignDetails result = DatabaseManager.getInstance().getFirstMatching("surveyId", id, CampaignDetails.class);
        boolean created = result == null;
        if (created) {
            result = new CampaignDetails();
            result.surveyId = id;
        }

        result.questionDetail = result.getDao().getEmptyForeignCollection("questionDetail");
        result.campaignTitle = json.optString("campaignTitle");
        result.surveyTitle = json.optString("surveyTitle");
        result.hasCreated = true;
        try {
            fromJsonArray(json.getJSONArray("questionDetail"), result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (created) result.create();
        else result.update();
    }

    private static void fromJsonArray(JSONArray questionDetail, CampaignDetails campaignDetail) {

        for (int i = 0; i < questionDetail.length(); i++) {
            try {
                JSONObject jsonObject = questionDetail.getJSONObject(i);

                QuestionDetail result = DatabaseManager.getInstance().getFirstMatching("questionId", jsonObject.optString("questionId"), QuestionDetail.class);
                boolean isCreated = result == null;
                if (isCreated) {
                    result = new QuestionDetail();
                }
                result.question = jsonObject.optString("question");
                result.questionId = jsonObject.optString("questionId");
                result.questionType = jsonObject.optString("questionType");
                if (jsonObject.has("questionChoices")) {
                    result.questionChoices = result.getDao().getEmptyForeignCollection("questionChoices");
                    result.fromJson(jsonObject.getJSONArray("questionChoices"), result);
                }
                campaignDetail.questionDetail.add(result);
                result.campaignDetail = campaignDetail;
                if (isCreated) {
                    result.create();
                } else {
                    result.update();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

}

QuestionDetail.java

public class QuestionDetail extends ManagedObject {

    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    public CampaignDetails campaignDetail;

    @DatabaseField
    public String question;

    @DatabaseField
    public String questionId;

    @DatabaseField
    public String questionType;

    @ForeignCollectionField(eager = true,maxEagerLevel = 4)
    public Collection<QuestionChoice> questionChoices;

    public void fromJson(JSONArray choices, QuestionDetail questionDetail) {

        for (int i = 0; i < choices.length(); i++) {
            try {
                JSONObject jsonObject = choices.getJSONObject(i);

                QuestionChoice result = DatabaseManager.getInstance().getFirstMatching("choiceId", jsonObject.optString("choiceId"), QuestionChoice.class);
                boolean isCreated = result == null;
                if (isCreated) {
                    result = new QuestionChoice();
                }
                result.choiceId = jsonObject.optString("choiceId");
                result.choice = jsonObject.optString("choice");
                result.questionDetail = questionDetail;
                questionChoices.add(result);
                if (isCreated) {
                    result.create();
                } else {
                    result.update();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

QuestionChoice.Java

public class QuestionChoice extends ManagedObject {

    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    public QuestionDetail questionDetail;

    @DatabaseField
    @SerializedName("choiceId")
    @Expose
    public String choiceId;

    @DatabaseField
    @SerializedName("choice")
    @Expose
    public String choice;

}

Can anyone help me solve my problem? I am really stuck on it Thanks.

Body:
I have solved it by changing the order of code in two files given below

CampaignDetails.java

public class CampaignDetails extends UpdateableManagedObject {

    @DatabaseField
    private String campaignTitle;

    @DatabaseField
    private String surveyTitle;

    @DatabaseField
    private int surveyId;

    @ForeignCollectionField(eager = true, maxEagerLevel = 2)
    public ForeignCollection<QuestionDetail> questionDetail;

public ArrayList<QuestionDetail> getQuestionDetail() {
    if (assessmentCache == null) {
        refresh();
        assessmentCache = new ArrayList<>();

        if (questionDetail != null) {
            for (QuestionDetail assessment : questionDetail) {
                assessmentCache.add(assessment);
            }
        }
    }

    return assessmentCache;
}

public static void fromJson(JSONObject json) {
    if (json == null) return;
    int id = json.optInt("surveyId", 0);
    if (id == 0) return;

    CampaignDetails result = DatabaseManager.getInstance().getFirstMatching("surveyId", id, CampaignDetails.class);
    boolean created = result == null;
    if (created) {
        result = new CampaignDetails();
        result.surveyId = id;
        result.create();
    } else {
        result.update();
    }

    result.questionDetail = result.getDao().getEmptyForeignCollection("questionDetail");
    result.campaignTitle = json.optString("campaignTitle");
    result.surveyTitle = json.optString("surveyTitle");
    result.hasCreated = true;
    try {
        fromJsonArray(json.getJSONArray("questionDetail"), result);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    result.update();
}

private static void fromJsonArray(JSONArray questionDetail, CampaignDetails campaignDetail) {

    for (int i = 0; i < questionDetail.length(); i++) {
        try {
            JSONObject jsonObject = questionDetail.getJSONObject(i);

            QuestionDetail result = DatabaseManager.getInstance().getFirstMatching("questionId", jsonObject.optString("questionId"), QuestionDetail.class);
            boolean isCreated = result == null;
            if (isCreated) {
                result = new QuestionDetail();
            } else {
                continue;
            }
            result.questionChoices = result.getDao().getEmptyForeignCollection("questionChoices");
            result.campaignDetail = campaignDetail;
            result.question = jsonObject.optString("question");
            result.questionId = jsonObject.optString("questionId");
            result.questionType = jsonObject.optString("questionType");
            campaignDetail.questionDetail.add(result);
            if (jsonObject.has("questionChoices")) {
                result.fromJson(jsonObject.getJSONArray("questionChoices"), result);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

}

QuestionDetail.java

public class QuestionDetail extends ManagedObject {

    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    public CampaignDetails campaignDetail;

    @DatabaseField
    public String question;

    @DatabaseField
    public String questionId;

    @DatabaseField
    public String questionType;

    @ForeignCollectionField(eager = true, maxEagerLevel = 2)
    public Collection<QuestionChoice> questionChoices;

    public void fromJson(JSONArray choices, QuestionDetail questionDetail) {

        for (int i = 0; i < choices.length(); i++) {
            try {
                JSONObject jsonObject = choices.getJSONObject(i);

                QuestionChoice result = DatabaseManager.getInstance().getFirstMatching("choiceId", jsonObject.optString("choiceId"), QuestionChoice.class);
                boolean isCreated = result == null;
                if (isCreated) {
                    result = new QuestionChoice();
                } else {
                    continue;
                }
                result.questionDetail = questionDetail;
                result.choiceId = jsonObject.optString("choiceId");
                result.choice = jsonObject.optString("choice");
                questionDetail.questionChoices.add(result);
//                result.create();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}


问:
CRON expression for repeat every 2 or 3 weeks and on selected day of week
I want to create cron expression for repeating on 2 or 3 weeks on seleted day like Sunday,Monday etc.

Is cron expression generation possible?
If not then any alternative to handle by java code?

Thanks

答:
Yes it's possible using CronTrigger class. It uses a particular cron expression that you can use for your special need. For example the next expressions

```<code>0 0 10 ? * 2#2
0 0 10 ? * 2#3
</code>```

will fire every second/third Monday of the month at 10 am.

Body:
Yes it's possible using CronTrigger class. It uses a particular cron expression that you can use for your special need. For example the next expressions

0 0 10 ? * 2#2
0 0 10 ? * 2#3

will fire every second/third Monday of the month at 10 am.


问:
How do I access the first key of an ‘associative’ array in JavaScript?
I have a js 'associative' array, with

```<code>array['serial_number'] = 'value'
</code>```

serial_number and value are strings.
e.g. array['20910930923'] = '20101102'

I sorted it by value, works fine.
Let's say I get back the object 'sorted';

Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with

```<code>for (var i in sorted)
</code>```

and just stop after ther first one...

thanks

edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).

答:
Just thinking off the top of my head, but could you have another array with the key value pairs swapped?

So the answer would be arrayKeyValueReversed['20101102'] = '20910930923';

When you sort the array, use the first item (array[0]) as the key to get the value in the arrayKeyValueReversed.

Body:
I have a js 'associative' array, with

array['serial_number'] = 'value'

serial_number and value are strings.
e.g. array['20910930923'] = '20101102'

I sorted it by value, works fine.
Let's say I get back the object 'sorted';

Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with

for (var i in sorted)

and just stop after ther first one...

thanks

edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).


问:
EditorGUILayout.BeginHorizontal() returns an empty Rect
So I wanted to format a custom EditorWindow I am working on and I organized everything in Horizontal Layouts so the elements fit nicely like table rows.

Unfortunately, my header-row was off, so I tried to unify everything by getting the base Rect from the EditorGUILayout.BeginHorizontal() method.

Unfortunately, it returns a Rect with default values (everything is 0). So I can't work with it properly. Am I missing something or why does it return an empty Rect? In the EditorWindow itself, space is filled.

Example Code:

```<code>Rect boundary = EditorGUILayout.BeginHorizontal();
float largeWidth = boundary.width * 0.4f;
float smallWidth = boundary.width * 0.2f;
EditorGUILayout.LabelField("stuff1", GUILayout.Width(largeWidth));
EditorGUILayout.LabelField("stuff2", GUILayout.Width(largeWidth));
EditorGUILayout.LabelField("stuff3", GUILayout.Width(smallwidth));
EditorGUILayout.EndHorizontal();
</code>```

答:
Okay, so I found a blog article online, stating the obvious:

The Rect won't be filled, when the Object does not no how large it will be. The Information will be available when an event is fired that does not consist of informationgathering.

So what I ended up doing was:

I saved the window width (which is available at all time) in a field at the beginning of OnGUI()

I created some constants to mess with so everything can be aligned

These constants were just assumptions about the spacings between elements and the padding to the left and right (I know these informations are available, but it did fit, so I didn't care)

After all this is a dirty solution, but it did work.

Here is some example code for those who are interested:

```<code>public class CustomWindow : EditorWindow
{
    #region Private Fields

    private Vector2 scrollLocation;
    private float elementsWidth;
    private float textBoxWidth;
    private float buttonWidth;
    private const int WINDOW_MIN_SIZE = 400;
    private const int BORDER_SPACING = 10;
    private const int ELEMENT_SPACING = 8;

    #endregion Private Fields

    #region Public Methods

    [MenuItem("Window/CustomWindow")]
    public static void ShowWindow()
    {
        CustomWindow window = GetWindow(typeof(CustomWindow), false, "CustomWindow") as CustomWindow;
        window.Show();
        window.minSize = new Vector2(WINDOW_MIN_SIZE, WINDOW_MIN_SIZE);
        window.Load();
    }

    #endregion Public Methods

    #region Private Methods

    private void OnGUI()
    {
        elementsWidth = EditorGUIUtility.currentViewWidth - BORDER_SPACING * 2;
        textBoxWidth = elementsWidth * 0.4f;
        buttonWidth = elementsWidth * 0.2f;
        scrollLocation = EditorGUILayout.BeginScrollView(scrollLocation);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("stuff1", GUILayout.Width(largeWidth));
        EditorGUILayout.LabelField("stuff2", GUILayout.Width(largeWidth));
        EditorGUILayout.LabelField("stuff3", GUILayout.Width(smallwidth));
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.EndScrollView();
    }

    #endregion Private Methods
}
</code>```

Body:
So I wanted to format a custom EditorWindow I am working on and I organized everything in Horizontal Layouts so the elements fit nicely like table rows.

Unfortunately, my header-row was off, so I tried to unify everything by getting the base Rect from the EditorGUILayout.BeginHorizontal() method.

Unfortunately, it returns a Rect with default values (everything is 0). So I can't work with it properly. Am I missing something or why does it return an empty Rect? In the EditorWindow itself, space is filled.

Example Code:

Rect boundary = EditorGUILayout.BeginHorizontal();
float largeWidth = boundary.width * 0.4f;
float smallWidth = boundary.width * 0.2f;
EditorGUILayout.LabelField("stuff1", GUILayout.Width(largeWidth));
EditorGUILayout.LabelField("stuff2", GUILayout.Width(largeWidth));
EditorGUILayout.LabelField("stuff3", GUILayout.Width(smallwidth));
EditorGUILayout.EndHorizontal();

Body:
Okay, so I found a blog article online, stating the obvious:

The Rect won't be filled, when the Object does not no how large it will be. The Information will be available when an event is fired that does not consist of informationgathering.

So what I ended up doing was:

I saved the window width (which is available at all time) in a field at the beginning of OnGUI()

I created some constants to mess with so everything can be aligned

These constants were just assumptions about the spacings between elements and the padding to the left and right (I know these informations are available, but it did fit, so I didn't care)

After all this is a dirty solution, but it did work.

Here is some example code for those who are interested:

public class CustomWindow : EditorWindow
{
    #region Private Fields

    private Vector2 scrollLocation;
    private float elementsWidth;
    private float textBoxWidth;
    private float buttonWidth;
    private const int WINDOW_MIN_SIZE = 400;
    private const int BORDER_SPACING = 10;
    private const int ELEMENT_SPACING = 8;

    #endregion Private Fields

    #region Public Methods

    [MenuItem("Window/CustomWindow")]
    public static void ShowWindow()
    {
        CustomWindow window = GetWindow(typeof(CustomWindow), false, "CustomWindow") as CustomWindow;
        window.Show();
        window.minSize = new Vector2(WINDOW_MIN_SIZE, WINDOW_MIN_SIZE);
        window.Load();
    }

    #endregion Public Methods

    #region Private Methods

    private void OnGUI()
    {
        elementsWidth = EditorGUIUtility.currentViewWidth - BORDER_SPACING * 2;
        textBoxWidth = elementsWidth * 0.4f;
        buttonWidth = elementsWidth * 0.2f;
        scrollLocation = EditorGUILayout.BeginScrollView(scrollLocation);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("stuff1", GUILayout.Width(largeWidth));
        EditorGUILayout.LabelField("stuff2", GUILayout.Width(largeWidth));
        EditorGUILayout.LabelField("stuff3", GUILayout.Width(smallwidth));
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.EndScrollView();
    }

    #endregion Private Methods
}


问:
angular 2 parsing an empty array
Let me get this straight...

I have an array frequentClients that, on its first use, is empty, so there's going to be nothing to iterate through.

but I can't build it like this because ... client.Name doesn't exist??

```<code><div ng-if="frequentClients.items.length>0">
    <button
        (click)="switchClient(client)"
        *ngFor="let client of frequentClients">
            {{client.Name}}
    </button>
</div>
</code>```

So, even though I've told it not to iterate at all if there's nothing to iterate through, it does it anyway, then throws an error: Cannot read property 'Name' of null

What on Earth am I doing wrong here??

答:
Angular 2+ has a very good feature called safe navigation operator to handle null and undefined . It will not throw an error if the client is null or undefined

use {{client?.Name}} instead of {{client.Name}}

```<code><div ng-if="frequentClients.items.length>0">
    <button
        (click)="switchClient(client)"
        *ngFor="let client of frequentClients">
            {{client?.Name}}
    </button>
</div>
</code>```

Title: angular 2 parsing an empty array

Body:
Let me get this straight...

I have an array frequentClients that, on its first use, is empty, so there's going to be nothing to iterate through.

but I can't build it like this because ... client.Name doesn't exist??

0">
    <button
        (click)="switchClient(client)"
        *ngFor="let client of frequentClients">
            {{client.Name}}
    </button>

So, even though I've told it not to iterate at all if there's nothing to iterate through, it does it anyway, then throws an error: Cannot read property 'Name' of null

What on Earth am I doing wrong here??

Body:
Angular 2+ has a very good feature called safe navigation operator to handle null and undefined . It will not throw an error if the client is null or undefined

use {{client?.Name}} instead of {{client.Name}}

<div ng-if="frequentClients.items.length>0">
    <button
        (click)="switchClient(client)"
        *ngFor="let client of frequentClients">
            {{client?.Name}}
    </button>
</div>


问:
neovim + deoplete: how to enable 'timers'
I want to make deoplete autocompletion suggestions pop up faster, that calls for setting

```<code>g:deoplete#auto_complete_delay
</code>```

help says this requires +timers support. How do I enable this timers in config?

Thanks!

答:
+timers is a compile-time feature of Vim that is available in Neovim from v0.1.5 onwards.

Compile-time features cannot be dynamically toggled, they are either there or not. +timers is an optional feature in Vim but non-optional in Neovim. So if you are using Neovim 0.1.5+, you already have the feature active. In fact, deoplete would not work properly without it.

You can verify that the feature is enabled: :echo has('timers'). If the result is 1, it's there, 0 mean it is not.

Body:
I want to make deoplete autocompletion suggestions pop up faster, that calls for setting

g:deoplete#auto_complete_delay

help says this requires +timers support. How do I enable this timers in config?

Thanks!