问:
Algorithm to create flow chart [A little guidance??]
OK, I know it's a vague question, but I seem to be stuck with logic here...I want to create flow charts of the input programs. I hav been thinking about it since two days and can't get a best general approach...So i look desperately at you guyz to help me here....may be there is something small I am missing....

I have an xml file which contains the info about the given java program and looks like this:

```<code><Method modifier="publicstatic" type="void" name="main" >
    <FormalParameter modifier="" type="String[]" var_name="args" />
    <Throw>NullPointerException</Throw>
    <Throw>
        IndexOutofBoundException
    </Throw>
    <Field modifier="" type="int" name="x,y,z" />
    <Field modifier="" type="int" name=" sum[] " />
    <If>
        condition><![CDATA[(x==0)]]></condition>
        <Statement>
            <![CDATA[System.out.Println("I am in true")]]></Statement>
        <If>
            <condition><![CDATA[(y==2)]]></condition>
            <Statement>
                <![CDATA[System.out.Println("I am in
    true of y==2")]]></Statement>
        </If>
        <Statement>
            <![CDATA[System.out.prnitln("I am in
    true again")]]></Statement>
    </If>
    <else>
        <If>
            <condition><![CDATA[(x==2)]]></condition>
            <Statement>
                <![CDATA[System.out.println("I am in
    x==2 true")]]></Statement>
        </If>
        <else>
            <Statement>
                <![CDATA[System.out.println("I am in
     else 2")]]></Statement>
        </else>
    </else>
    <Statement>
        <![CDATA[c=b+d]]></Statement>
    <Statement>
        <![CDATA[a=b+c]]></Statement>
</Method>
</code>```

Now this is a part of the xml file generated....fir the code snippet:

```<code>public static void main(String[] args) throws NullPointerException,IndexOutofBoundException {

    int x,y,z;
    int sum[]={1,2,3,4};
    if(x==0)
    {
        System.out.Println("I am in true");
        if(y==2)
        {
            System.out.Println("I am in true of y==2");
        }
        System.out.prnitln("I am in true again");
    }
    else if(x==2)
    {
        System.out.println("I am in x==2 true");
    }
    else
    {
        System.out.println("I am in else 2");
    }

    c=b+d;
    a=b+c;
}
</code>```

Now my way of doing it is:

I have a class reader which reades the xml file and one class createFLowChart which takes care of drawing. I start traversing the method node... If I find a statement, I call a function FundStatement which draws a retangular box and connects it with prv node. Doing this for If-else constructs without adding a lot of state boolean variables. So can any one guide me in this?

Now the prob is with if-else constructs. I can not find a simple way of traversig through the if -else trees and correctly make the edge connections among the nodes without adding a number of variables to contain the state info i.e an if has started or else started etc. Here is my approach but I am finding difficulty in the depth adjustments i.e, connecting the leaves of nested if-else statements :

```<code>public void traverse(String path,CreateFlowChart parent)
{
    xPath =  XPathFactory.newInstance().newXPath();
    XPathExpression expr;
    //ArrayList<dataObjects.Interface> parentInterfaces=new ArrayList<dataObjects.Interface>();
    //dataObjects.Class[] classes=new dataObjects.Class[90];

    try {
        expr = xPath.compile(path);
        Object result = expr.evaluate(document, XPathConstants.NODESET);
        NodeList MethodNodes = (NodeList) result;
        NodeList childNodes=MethodNodes.item(0).getChildNodes();

        JOptionPane.showMessageDialog(null, "No of children of "+path+" is "+childNodes.getLength());
        for(int i=0;i<=childNodes.getLength()-1;i++)
        {

            Node node=childNodes.item(i);
            JOptionPane.showMessageDialog(null, "Found Child "+node.getNodeName());
            traverse(node,parent);
        }

        } catch (XPathExpressionException e) {
        JOptionPane.showMessageDialog(null,"error: "+e.toString());
        e.printStackTrace();
    }

}
private void traverse(Node root ,CreateFlowChart parent)
{

    if(root.getNodeName()=="If")
    {
        String condition="";
        NodeList childNodes=root.getChildNodes();
        for(int i=0;i<childNodes.getLength();i++)
        {
            Node child=(Node)childNodes.item(i);
            if(child.getNodeName()=="condition")
            {
                Element ele=(Element)child;
                condition=ele.getTextContent();

            }
        }
        dataObjects.ControlStatements ifstmt=new dataObjects.ControlStatements(condition,null,true);
        parent.foundIf(ifstmt);
        NodeList childs=root.getChildNodes();
        for(int i=0;i<childs.getLength();i++)
        {
            Node child=(Node)childs.item(i);
            traverse(child,parent);

        }

        parent.foundEndIf();

    }
    else if(root.getNodeName()=="else")
    {
        parent.foundElse();
        NodeList childNodes=root.getChildNodes();
        for(int i=0;i<childNodes.getLength();i++)
        {
            Node child=(Node)childNodes.item(i);
            traverse(child,parent);

        }
        parent.foundEndElse();

    }

    else if(root.getNodeName()=="Statement")
    {
        parent.foundStatement(root.getTextContent());

    }
}
</code>```

Now the three function called from the reader are:

```<code>public void foundIf(dataObjects.ControlStatements Ifstatement)
{
    JOptionPane.showMessageDialog(null,"Drawing If");
    graph.getModel().beginUpdate();
    try
    {
        Object v1 = graph.insertVertex(start, null, "If "+Ifstatement.condition, 20, 20, 150,60,"Branch");
        if(isInIf==false && isInElse==false)
        {
            JOptionPane.showMessageDialog(null,"Drawing normally");
            graph.insertEdge(start, null, "", currentNode,v1);
        }
        else if(isInIf==true)
        {
            JOptionPane.showMessageDialog(null,"Drawing inside a previous If");
            graph.insertEdge(start, null, "True", currentNode,v1);
            isInIf=false;
        }
        else if(isInElse==true)
        {
            JOptionPane.showMessageDialog(null,"Drawing inside a previous else");
            graph.insertEdge(start, null, "False", currentNode,v1);
            isInElse=false;
        }
        currentNode=(mxCell)v1;
        JOptionPane.showMessageDialog(null,"Pushing if node inside stack");
        lastIfNode.push(currentNode);
        isInIf=true;
    }
    finally
    {
        graph.getModel().endUpdate();
    }
}
public void foundElse()
{
    currentNode=lastIfNode.pop();
    isInElse=true;
}
public void foundStatement(String st)
{
    JOptionPane.showMessageDialog(null,"Drawing a statement");
    graph.getModel().beginUpdate();
    try
    {
        Object v1 = graph.insertVertex(currentNode, null, st, 20, 20, 150,60,"Statement");
        if(isInIf==false && isInElse==false)
        {
            JOptionPane.showMessageDialog(null,"Drawing normally");
            graph.insertEdge(start, null, "", currentNode,v1);
        }
        else if(isInIf==true)
        {
            JOptionPane.showMessageDialog(null,"Drawing inside a prv If");
            graph.insertEdge(start, null, "True", currentNode,v1);
            isInIf=false;
        }
        else if(isInElse==true)
        {
            JOptionPane.showMessageDialog(null, "Drawing inside else");
            graph.insertEdge(start, null, "False", currentNode,v1);
            isInElse=false;
            reTraceIf=false;
        }
        if(reTraceIf==true)
        {
            JOptionPane.showMessageDialog(null, "Drawing false part");
            graph.insertEdge(start, null, "False", lastIfNode.pop(),v1);
            reTraceIf=false;
        }
        if(branchEnded==true)
        {
            JOptionPane.showMessageDialog(null, "Linking brancehs");
            graph.insertEdge(start, null, "", prvBranchNode,v1);
            branchEnded=false;
        }
        currentNode=(mxCell)v1;
    }
    finally
    {
        graph.getModel().endUpdate();
    }
}
public void foundEndIf()
{
    prvBranchNode=currentNode;
    isInIf=false;
    reTraceIf=true;
}
public void foundEndElse()
{
    branchEnded=true;
}
</code>```

This works fine for the if else statements one level deep but deteriorates after that i understand that is because the globbal variable prvNode can hld only one node at a time may be a list ll do but still some problems may arise...Can any one improve it please??

答:
You can do a recursive approach to do a A DFS traversal, for eg -

```<code>1    For each line in block
2        If it is an if statement
3            Render condition in a Diamond shape
4            Get the statement block inside the if statement and go to #1
5        else
6            Render it in a rectangle shape
</code>```

This is just an idea, you will need to keep a track of the depth as well, besides keeping in mind the layout of the elements on a 2-D plane. But you should workout the traversal algorithm first and then fit the layout later.

Body:
OK, I know it's a vague question, but I seem to be stuck with logic here...I want to create flow charts of the input programs. I hav been thinking about it since two days and can't get a best general approach...So i look desperately at you guyz to help me here....may be there is something small I am missing....

I have an xml file which contains the info about the given java program and looks like this:

<Method modifier="publicstatic" type="void" name="main" >
    <FormalParameter modifier="" type="String[]" var_name="args" />
    <Throw>NullPointerException</Throw>
    <Throw>
        IndexOutofBoundException
    </Throw>
    <Field modifier="" type="int" name="x,y,z" />
    <Field modifier="" type="int" name=" sum[] " />
    <If>
        condition><![CDATA[(x==0)]]></condition>
        <Statement>
            <![CDATA[System.out.Println("I am in true")]]></Statement>
        <If>
            <condition><![CDATA[(y==2)]]></condition>
            <Statement>
                <![CDATA[System.out.Println("I am in
    true of y==2")]]></Statement>
        </If>
        <Statement>
            <![CDATA[System.out.prnitln("I am in
    true again")]]></Statement>
    </If>
    <else>
        <If>
            <condition><![CDATA[(x==2)]]></condition>
            <Statement>
                <![CDATA[System.out.println("I am in
    x==2 true")]]></Statement>
        </If>
        <else>
            <Statement>
                <![CDATA[System.out.println("I am in
     else 2")]]></Statement>
        </else>
    </else>
    <Statement>
        <![CDATA[c=b+d]]></Statement>
    <Statement>
        <![CDATA[a=b+c]]></Statement>
</Method>

Now this is a part of the xml file generated....fir the code snippet:

public static void main(String[] args) throws NullPointerException,IndexOutofBoundException {

    int x,y,z;
    int sum[]={1,2,3,4};
    if(x==0)
    {
        System.out.Println("I am in true");
        if(y==2)
        {
            System.out.Println("I am in true of y==2");
        }
        System.out.prnitln("I am in true again");
    }
    else if(x==2)
    {
        System.out.println("I am in x==2 true");
    }
    else
    {
        System.out.println("I am in else 2");
    }

    c=b+d;
    a=b+c;
}

Now my way of doing it is:

I have a class reader which reades the xml file and one class createFLowChart which takes care of drawing. I start traversing the method node... If I find a statement, I call a function FundStatement which draws a retangular box and connects it with prv node. Doing this for If-else constructs without adding a lot of state boolean variables. So can any one guide me in this?

Now the prob is with if-else constructs. I can not find a simple way of traversig through the if -else trees and correctly make the edge connections among the nodes without adding a number of variables to contain the state info i.e an if has started or else started etc. Here is my approach but I am finding difficulty in the depth adjustments i.e, connecting the leaves of nested if-else statements :

public void traverse(String path,CreateFlowChart parent)
{
    xPath =  XPathFactory.newInstance().newXPath();
    XPathExpression expr;
    //ArrayList<dataObjects.Interface> parentInterfaces=new ArrayList<dataObjects.Interface>();
    //dataObjects.Class[] classes=new dataObjects.Class[90];

    try {
        expr = xPath.compile(path);
        Object result = expr.evaluate(document, XPathConstants.NODESET);
        NodeList MethodNodes = (NodeList) result;
        NodeList childNodes=MethodNodes.item(0).getChildNodes();

        JOptionPane.showMessageDialog(null, "No of children of "+path+" is "+childNodes.getLength());
        for(int i=0;i<=childNodes.getLength()-1;i++)
        {

            Node node=childNodes.item(i);
            JOptionPane.showMessageDialog(null, "Found Child "+node.getNodeName());
            traverse(node,parent);
        }

        } catch (XPathExpressionException e) {
        JOptionPane.showMessageDialog(null,"error: "+e.toString());
        e.printStackTrace();
    }

}
private void traverse(Node root ,CreateFlowChart parent)
{

    if(root.getNodeName()=="If")
    {
        String condition="";
        NodeList childNodes=root.getChildNodes();
        for(int i=0;i<childNodes.getLength();i++)
        {
            Node child=(Node)childNodes.item(i);
            if(child.getNodeName()=="condition")
            {
                Element ele=(Element)child;
                condition=ele.getTextContent();

            }
        }
        dataObjects.ControlStatements ifstmt=new dataObjects.ControlStatements(condition,null,true);
        parent.foundIf(ifstmt);
        NodeList childs=root.getChildNodes();
        for(int i=0;i<childs.getLength();i++)
        {
            Node child=(Node)childs.item(i);
            traverse(child,parent);

        }

        parent.foundEndIf();

    }
    else if(root.getNodeName()=="else")
    {
        parent.foundElse();
        NodeList childNodes=root.getChildNodes();
        for(int i=0;i<childNodes.getLength();i++)
        {
            Node child=(Node)childNodes.item(i);
            traverse(child,parent);

        }
        parent.foundEndElse();

    }

    else if(root.getNodeName()=="Statement")
    {
        parent.foundStatement(root.getTextContent());

    }
}

Now the three function called from the reader are:

public void foundIf(dataObjects.ControlStatements Ifstatement)
{
    JOptionPane.showMessageDialog(null,"Drawing If");
    graph.getModel().beginUpdate();
    try
    {
        Object v1 = graph.insertVertex(start, null, "If "+Ifstatement.condition, 20, 20, 150,60,"Branch");
        if(isInIf==false && isInElse==false)
        {
            JOptionPane.showMessageDialog(null,"Drawing normally");
            graph.insertEdge(start, null, "", currentNode,v1);
        }
        else if(isInIf==true)
        {
            JOptionPane.showMessageDialog(null,"Drawing inside a previous If");
            graph.insertEdge(start, null, "True", currentNode,v1);
            isInIf=false;
        }
        else if(isInElse==true)
        {
            JOptionPane.showMessageDialog(null,"Drawing inside a previous else");
            graph.insertEdge(start, null, "False", currentNode,v1);
            isInElse=false;
        }
        currentNode=(mxCell)v1;
        JOptionPane.showMessageDialog(null,"Pushing if node inside stack");
        lastIfNode.push(currentNode);
        isInIf=true;
    }
    finally
    {
        graph.getModel().endUpdate();
    }
}
public void foundElse()
{
    currentNode=lastIfNode.pop();
    isInElse=true;
}
public void foundStatement(String st)
{
    JOptionPane.showMessageDialog(null,"Drawing a statement");
    graph.getModel().beginUpdate();
    try
    {
        Object v1 = graph.insertVertex(currentNode, null, st, 20, 20, 150,60,"Statement");
        if(isInIf==false && isInElse==false)
        {
            JOptionPane.showMessageDialog(null,"Drawing normally");
            graph.insertEdge(start, null, "", currentNode,v1);
        }
        else if(isInIf==true)
        {
            JOptionPane.showMessageDialog(null,"Drawing inside a prv If");
            graph.insertEdge(start, null, "True", currentNode,v1);
            isInIf=false;
        }
        else if(isInElse==true)
        {
            JOptionPane.showMessageDialog(null, "Drawing inside else");
            graph.insertEdge(start, null, "False", currentNode,v1);
            isInElse=false;
            reTraceIf=false;
        }
        if(reTraceIf==true)
        {
            JOptionPane.showMessageDialog(null, "Drawing false part");
            graph.insertEdge(start, null, "False", lastIfNode.pop(),v1);
            reTraceIf=false;
        }
        if(branchEnded==true)
        {
            JOptionPane.showMessageDialog(null, "Linking brancehs");
            graph.insertEdge(start, null, "", prvBranchNode,v1);
            branchEnded=false;
        }
        currentNode=(mxCell)v1;
    }
    finally
    {
        graph.getModel().endUpdate();
    }
}
public void foundEndIf()
{
    prvBranchNode=currentNode;
    isInIf=false;
    reTraceIf=true;
}
public void foundEndElse()
{
    branchEnded=true;
}

This works fine for the if else statements one level deep but deteriorates after that i understand that is because the globbal variable prvNode can hld only one node at a time may be a list ll do but still some problems may arise...Can any one improve it please??

Body:
You can do a recursive approach to do a A DFS traversal, for eg -

1    For each line in block
2        If it is an if statement
3            Render condition in a Diamond shape
4            Get the statement block inside the if statement and go to #1
5        else
6            Render it in a rectangle shape

This is just an idea, you will need to keep a track of the depth as well, besides keeping in mind the layout of the elements on a 2-D plane. But you should workout the traversal algorithm first and then fit the layout later.


来源: stackexchange

问:
how to merge lists? (pandas DataFrame)
I have 3 different lists named : "pos_date_data", "neu_date_data", "neg_date_data".
(each means positive, neutral, and negative)

they contains datetime value in dataframe shape.

below is how they look like when printed list. and each of they have different lengths.

```<code> datetime
0   2018-07-04
1   2018-07-04
2   2018-07-04
3   2018-07-04
4   2018-07-04
..         ...
212 2020-02-02
213 2020-02-02
214 2020-02-03
215 2020-02-04
216 2020-02-07

[217 rows x 1 columns]
</code>```

```<code>    datetime
0    2018-07-04
1    2018-07-04
2    2018-07-04
3    2018-07-04
4    2018-07-04
...         ...
1527 2020-02-09
1528 2020-02-10
1529 2020-02-11
1530 2020-02-11
1531 2020-02-12

[1532 rows x 1 columns]
</code>```

From them I'm trying to merge them in one DataFrame using pandas, python.

for that, I have to count the months by dates in whole range(2018-07 ~ 2020.03).
for example :
if the total date number of 2019-05 is 15 in the neu_date_data, I want to display it as integer number in a table.

I tried this code:

```<code>df = pd.crosstab(neg_date_data['datetime'].dt.month.rename('m'),
                 neg_date_data['datetime'].dt.year.rename('y'))
</code>```

and printed as:
in shape of crosstable, and each items stands for the number of dates in months.

```<code>y   2018  2019  2020
m
1      0     1    17
2      0     0     2
3      0     1     0
4      0     3     0
5      0    12     0
6      0    13     0
7     25    16     0
8      0    36     0
9      0     2     0
10     1     8     0
11     1     5     0
12     2     4     0
</code>```

I want to fix the code in 3 ways:

merge 3 lists and display them once.

having entire 'year' and 'month' data as columns.

for 3 rows, heading of each lists : 'pos', 'neu', 'neg', not years.

答:
First convert datetimes to months periods by Series.dt.to_period and then use Series.value_counts, last concat together:

I think for ploting should be better use months periods in rows and types in columns:

```<code>neg = neg_date_data['datetime'].dt.to_period('m').value_counts()
neu = neu_date_data['datetime'].dt.to_period('m').value_counts()

df = pd.concat([neg, neu], axis=1, keys=('neg','neu'))
print (df)
         neg  neu
2020-02    5    5
2018-07    5    5

df.plot()
</code>```

ContentLicense: CC BY-SA 4.0

Title: how to merge lists? (pandas DataFrame)

Body:
I have 3 different lists named : "pos_date_data", "neu_date_data", "neg_date_data".
(each means positive, neutral, and negative)

they contains datetime value in dataframe shape.

below is how they look like when printed list. and each of they have different lengths.

 datetime
0   2018-07-04
1   2018-07-04
2   2018-07-04
3   2018-07-04
4   2018-07-04
..         ...
212 2020-02-02
213 2020-02-02
214 2020-02-03
215 2020-02-04
216 2020-02-07

[217 rows x 1 columns]

    datetime
0    2018-07-04
1    2018-07-04
2    2018-07-04
3    2018-07-04
4    2018-07-04
...         ...
1527 2020-02-09
1528 2020-02-10
1529 2020-02-11
1530 2020-02-11
1531 2020-02-12

[1532 rows x 1 columns]

From them I'm trying to merge them in one DataFrame using pandas, python.

for that, I have to count the months by dates in whole range(2018-07 ~ 2020.03).
for example :
if the total date number of 2019-05 is 15 in the neu_date_data, I want to display it as integer number in a table.

I tried this code:

df = pd.crosstab(neg_date_data['datetime'].dt.month.rename('m'),
                 neg_date_data['datetime'].dt.year.rename('y'))

and printed as:
in shape of crosstable, and each items stands for the number of dates in months.

y   2018  2019  2020
m
1      0     1    17
2      0     0     2
3      0     1     0
4      0     3     0
5      0    12     0
6      0    13     0
7     25    16     0
8      0    36     0
9      0     2     0
10     1     8     0
11     1     5     0
12     2     4     0

I want to fix the code in 3 ways:

merge 3 lists and display them once.

having entire 'year' and 'month' data as columns.

for 3 rows, heading of each lists : 'pos', 'neu', 'neg', not years.

Body:
First convert datetimes to months periods by Series.dt.to_period and then use Series.value_counts, last concat together:

I think for ploting should be better use months periods in rows and types in columns:

neg = neg_date_data['datetime'].dt.to_period('m').value_counts()
neu = neu_date_data['datetime'].dt.to_period('m').value_counts()

df = pd.concat([neg, neu], axis=1, keys=('neg','neu'))
print (df)
         neg  neu
2020-02    5    5
2018-07    5    5

df.plot()


问:
How to retrieve the Daily Close value of previous years?

Goal:

I'm trying to build a daily seasonality trend script..

Problem:

I normalized each day's close relative to the year's high and low so every day has a value between 0 and 1. Now I'm trying to figure out how to average the same day in previous years to get multiyear average value of the scaled daily close, can't figure this out for the life of me.

End goal is to plot a 15 year (or whatever look back) seasonality graph on the daily TF.

Here is what I have so far, this plots each completed year's trend with each day's value relative to that year's high (1) and low (0). Now I'm trying to figure out how to get the scaledClose variable to represent a multiyear average value instead of just single years.

```<code>current_year = input(2020, title="Current Year")
scaledClose = 0.0
yearHigh = security(syminfo.tickerid, "12M", high, lookahead=true)
yearLow = security(syminfo.tickerid, "12M", low, lookahead=true)
if year < current_year
    scaledClose := (close - yearLow) / (yearHigh - yearLow)

plot(scaledClose)
</code>```

答:
For example, a year ago value:

```<code>// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MichelT

//@version=4
study("Get a value some years ago")
startPointTimeIndex = 9999
max_bars_back(time, 9999)

binarySearch(seachedTime) =>
    L = startPointTimeIndex
    R = 0

    for i = 0 to 100
        if L == R or time[L] == seachedTime
            break

        m = ceil((L + R) / 2)
        if time[m] > seachedTime
            R := m - 1
        else
            L := m
    _return = L

yearsBack = input(type=input.integer, defval=1, title="Years back")

requiredTime = timestamp(year - yearsBack, month, dayofmonth, hour, minute, second)
idx = binarySearch(requiredTime)

plot(year(time[idx]), title="Year", color=color.red)
plot(month(time[idx]), title="Month", color=color.green)
plot(dayofmonth(time[idx]), title="DayOfMonth", color=color.blue)

plot(hour(time[idx]), title="Hour", color=color.navy)
plot(minute(time[idx]), title="Minute", color=color.fuchsia)
</code>```

In inputs you can set how many years ago you'd like to get a value from.

Body:
Goal:

I'm trying to build a daily seasonality trend script..

Problem:

I normalized each day's close relative to the year's high and low so every day has a value between 0 and 1. Now I'm trying to figure out how to average the same day in previous years to get multiyear average value of the scaled daily close, can't figure this out for the life of me.

End goal is to plot a 15 year (or whatever look back) seasonality graph on the daily TF.

Here is what I have so far, this plots each completed year's trend with each day's value relative to that year's high (1) and low (0). Now I'm trying to figure out how to get the scaledClose variable to represent a multiyear average value instead of just single years.

current_year = input(2020, title="Current Year")
scaledClose = 0.0
yearHigh = security(syminfo.tickerid, "12M", high, lookahead=true)
yearLow = security(syminfo.tickerid, "12M", low, lookahead=true)
if year < current_year
    scaledClose := (close - yearLow) / (yearHigh - yearLow)

plot(scaledClose)

Body:
For example, a year ago value:

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MichelT

//@version=4
study("Get a value some years ago")
startPointTimeIndex = 9999
max_bars_back(time, 9999)

binarySearch(seachedTime) =>
    L = startPointTimeIndex
    R = 0

    for i = 0 to 100
        if L == R or time[L] == seachedTime
            break

        m = ceil((L + R) / 2)
        if time[m] > seachedTime
            R := m - 1
        else
            L := m
    _return = L

yearsBack = input(type=input.integer, defval=1, title="Years back")

requiredTime = timestamp(year - yearsBack, month, dayofmonth, hour, minute, second)
idx = binarySearch(requiredTime)

plot(year(time[idx]), title="Year", color=color.red)
plot(month(time[idx]), title="Month", color=color.green)
plot(dayofmonth(time[idx]), title="DayOfMonth", color=color.blue)

plot(hour(time[idx]), title="Hour", color=color.navy)
plot(minute(time[idx]), title="Minute", color=color.fuchsia)

In inputs you can set how many years ago you'd like to get a value from.


问:
loadable bundle for plists
I have a main project and a static library project inside the main project. I want few plists in my static library project. Since there is no resource directory it is not possible to add plists directly, What is did is this.

1.Added a loadable bundle to my static library project
2.Added few plists to loadable bundle
3.This loadable bundle is made as a dependency to my static library project
4.Added this loadable bundle as a dependency to my main project as well

Am i going on the right path ? when i fired the build and used show contents to see the contents of the app i was able to see the .bundle file inside the .app file. Right now i want to know how to access this bundle . .

i used this

```<code>NSBundle *staticlink = [NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"];
[staticlink load];
NSLog(@"%@",staticlink);
</code>```

console said this . .

```<code> . . . /mainproject.app/MyBundle.bundle <not yet loaded>
</code>```

What is missing ? what should i do load MyBundle ?

答:
-pathFoResource:ofType: returns a NSString object which will have the path to the bundle.

```<code>NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
[bundle load];
</code>```

ContentLicense: CC BY-SA 3.0

Title: loadable bundle for plists

Body:
I have a main project and a static library project inside the main project. I want few plists in my static library project. Since there is no resource directory it is not possible to add plists directly, What is did is this.

1.Added a loadable bundle to my static library project
2.Added few plists to loadable bundle
3.This loadable bundle is made as a dependency to my static library project
4.Added this loadable bundle as a dependency to my main project as well

Am i going on the right path ? when i fired the build and used show contents to see the contents of the app i was able to see the .bundle file inside the .app file. Right now i want to know how to access this bundle . .

i used this

NSBundle *staticlink = [NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"];
[staticlink load];
NSLog(@"%@",staticlink);

console said this . .

 . . . /mainproject.app/MyBundle.bundle <not yet loaded>

What is missing ? what should i do load MyBundle ?

Body:
-pathFoResource:ofType: returns a NSString object which will have the path to the bundle.

NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
[bundle load];


问:
It has a DefiningQuery but no InsertFunction element... err
This thing is driving me crazy, and the error is quite meaningless to me:

Unable to update the EntitySet 'TableB' because it has a DefiningQuery and no  element exists in the  element to support the current operation.

My tables are put like this:

```
TableA
int idA (identity, primary key)
...

TableB
int idA (FK for TableA.idA)
int val
```

TableB has no defined primary key in the SQL server. The Entity Framework has imported the table and the association and set both fields as key. But it will output that error when I try to do an insert into the table!

What's wrong??

Edit:
As suggested by Alex, the solution was this:

Right click on the edmx file, select Open with, XML editor

Locate the entity in the edmx:StorageModels element

Remove the DefiningQuery entirely

Rename the store:Schema="dbo" to Schema="dbo" (otherwise, the code will generate an error saying the name is invalid)

Remove the store:Name property

I left the key as it was, since it was OK to me that both the columns are part of the key.

答:
You need to manually open the .EDMX file in notepad or notepad++ or
in any text editor of your choice.

Locate the entry in edmx:StorageModels in file opened in step1.

Find the DefiningQuery element and remove this tag entirely.

Find the store:Schema="dbo" to Schema="dbo" (if you skip this step
it will generate error of the name is invalid).

Save and close the file.

Hope it will solve the problem.

ContentLicense: CC BY-SA 2.5

Body:
This thing is driving me crazy, and the error is quite meaningless to me:

Unable to update the EntitySet 'TableB' because it has a DefiningQuery and no  element exists in the  element to support the current operation.

My tables are put like this:

TableA
int idA (identity, primary key)
...

TableB
int idA (FK for TableA.idA)
int val

TableB has no defined primary key in the SQL server. The Entity Framework has imported the table and the association and set both fields as key. But it will output that error when I try to do an insert into the table!

What's wrong??

Edit:
As suggested by Alex, the solution was this:

Right click on the edmx file, select Open with, XML editor

Locate the entity in the edmx:StorageModels element

Remove the DefiningQuery entirely

Rename the store:Schema="dbo" to Schema="dbo" (otherwise, the code will generate an error saying the name is invalid)

Remove the store:Name property

I left the key as it was, since it was OK to me that both the columns are part of the key.


问:
How to use multiple columns in Bootsrap not starting From column 1?
I have two buttons in page. According to W3Schools, the page is divided into 12 columns. I want the two buttons to be 4 columns wide but from column 2 to 5 and the second from column 8 to 11. How can I do this? I am using using bootstrap to do this.

Using empty 'p' elements doesn't seem to work as seen below.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

  <input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();" class="col-sm-3">

  <input type="button" id="registerX" class="col-sm-3" name="registerX" value="Register" onclick="submitCheck();">

```

I can notice a bigger gap after the second button that the first gap. What can I do?

Edit: To see it open the code in a full page.

答:
Use offset

```<code><div class="row container fluid">
  <p class="offset-sm-1"></p>
  <div class="col-sm-3">
     <button type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();">
  </div>
  <p class="col-sm-2"></p>
  <div class="col-sm-4">
     <button type="button" id="registerX" class="col-sm-3" name="registerX" value="Register" onclick="submitCheck();">
  </div>
</div>
</code>```

The offset-sm-1 will leave one blank area that is 1 column size so that your content starts at column 2.

Body:
I have two buttons in page. According to W3Schools, the page is divided into 12 columns. I want the two buttons to be 4 columns wide but from column 2 to 5 and the second from column 8 to 11. How can I do this? I am using using bootstrap to do this.

Using empty 'p' elements doesn't seem to work as seen below.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

  <input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();" class="col-sm-3">

  <input type="button" id="registerX" class="col-sm-3" name="registerX" value="Register" onclick="submitCheck();">

I can notice a bigger gap after the second button that the first gap. What can I do?

Edit: To see it open the code in a full page.

Body:
Use offset

<div class="row container fluid">
  <p class="offset-sm-1"></p>
  <div class="col-sm-3">
     <button type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();">
  </div>
  <p class="col-sm-2"></p>
  <div class="col-sm-4">
     <button type="button" id="registerX" class="col-sm-3" name="registerX" value="Register" onclick="submitCheck();">
  </div>
</div>

The offset-sm-1 will leave one blank area that is 1 column size so that your content starts at column 2.


问:
Angular2: Custom material theme in each lazy loaded submodule

Problem with loading custom Angular Material 2 themes in separate submodules of Angular 7 app

I have angular wrapper module (app module) and many independent lazy-loaded sub-modules. Each sub-module behaves like a totaly separate app and needs its own angular material theme.

I've created custom theme for each sub-module and tried to reference the custom theme in each of components' .scss file with relative path.

Some of the Material components apply the custom theme (button) and some (mat-form-field) just take the theme specified in styles.scss.

One way I can avoid this is including each custom theme in 'styles' array of angular.json, but I'm afraid that, by doing this, each independent sub-module (app) will have to load every themes' compiled .css and it'll be overhead.

Is there any known issue with this or any better solution?

home-app.component.scss:

```<code>@import './theme.scss';

</code>```

VS.

angular.json

```<code>...
"styles": [
    "src/styles.scss",
    "src/app/orgs/home/theme.scss" // <-- FIXED BY ADDING THIS
],
...

</code>```

Expected:
Theme declared in the home-app.component.scss will be loaded and applied to every material component used in home-app.component.html

Actual:
If I don't add "src/app/orgs/home/theme.scss" to angular.json, the custom theme declared in styles.scss will be applied to some material components used in home-app.component.html, and some material components will use the imported theme specified in home-app.component.scss

答:
Did you try to add it directly into styles array of your Components?

```<code>@Component({
  selector: 'app-home',
  template: 'your-template.html',
  styles: ['your-style.scss', 'your-theme.scss']
})
</code>```

Another thing you can do is to use ShadowDom as your ViewEncapsulation :

```<code>@Component({
  selector: 'app-home',
  template: 'your-template.html',
  styles: ['your-style.scss', 'your-theme.scss'],
  encapsulation: ViewEncapsulation.ShadowDom
})
</code>```

Body:
Problem with loading custom Angular Material 2 themes in separate submodules of Angular 7 app

I have angular wrapper module (app module) and many independent lazy-loaded sub-modules. Each sub-module behaves like a totaly separate app and needs its own angular material theme.

I've created custom theme for each sub-module and tried to reference the custom theme in each of components' .scss file with relative path.

Some of the Material components apply the custom theme (button) and some (mat-form-field) just take the theme specified in styles.scss.

One way I can avoid this is including each custom theme in 'styles' array of angular.json, but I'm afraid that, by doing this, each independent sub-module (app) will have to load every themes' compiled .css and it'll be overhead.

Is there any known issue with this or any better solution?

home-app.component.scss:

@import './theme.scss';

VS.

angular.json

...
"styles": [
    "src/styles.scss",
    "src/app/orgs/home/theme.scss" // <-- FIXED BY ADDING THIS
],
...

Expected:
Theme declared in the home-app.component.scss will be loaded and applied to every material component used in home-app.component.html

Actual:
If I don't add "src/app/orgs/home/theme.scss" to angular.json, the custom theme declared in styles.scss will be applied to some material components used in home-app.component.html, and some material components will use the imported theme specified in home-app.component.scss

Body:
Did you try to add it directly into styles array of your Components?

@Component({
  selector: 'app-home',
  template: 'your-template.html',
  styles: ['your-style.scss', 'your-theme.scss']
})

Another thing you can do is to use ShadowDom as your ViewEncapsulation :

@Component({
  selector: 'app-home',
  template: 'your-template.html',
  styles: ['your-style.scss', 'your-theme.scss'],
  encapsulation: ViewEncapsulation.ShadowDom
})


问:
(AttributeError: 'NoneType' object has no attribute 'get' ) while loading saved keras model with .h5 extension in tensorflow 2.1
I have a keras model making use of feature_column api of tensorflow , I am able to save the model in .h5 extension but gets following error in colab while loading the saved model.

```<code>---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-38-8a2d51a054f6> in <module>()
----> 1 new_model = tf.keras.models.load_model('model.h5')

13 frames

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    318       obj = _GLOBAL_CUSTOM_OBJECTS[object_name]
    319     else:
--> 320       obj = module_objects.get(object_name)
    321       if obj is None:
    322         raise ValueError('Unknown ' + printable_module_name + ':' + object_name)

AttributeError: 'NoneType' object has no attribute 'get'

</code>```

following is my code and i am using tensorlow 2.1

```<code>import pandas as pd
import tensorflow as tf
import numpy as np

</code>```

```<code>
feature_layer = tf.keras.layers.DenseFeatures(feature_columns)

</code>```

```<code>def model_builder():

      tf.keras.backend.clear_session()
      model = tf.keras.Sequential()
      model.add(feature_layer)
      model.add(tf.keras.layers.Dense(32, activation='relu'))
      model.add(tf.keras.layers.Dense(32, activation='relu'))
      model.add(tf.keras.layers.Dense(1))

      model.compile(optimizer = tf.keras.optimizers.RMSprop(0.001),
                    loss=tf.keras.losses.Huber(),
                    metrics=['mae'])

      return model
</code>```

```<code>model = model_builder()
model.fit(train_ds , epochs=5,verbose=1)

</code>```

```<code>model.save('model.h5')

</code>```

```<code>
new_model = tf.keras.models.load_model('model.h5')

</code>```

I get the following error while running code in local environment ie in conda environment using jupyter notebook. But local env is having tf 2.0

```<code>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-fbbaf2c35e78> in <module>
----> 1 new_model = tf.keras.models.load_model('model1.h5')

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/saving/save.py in load_model(filepath, custom_objects, compile)
    144   if (h5py is not None and (
    145       isinstance(filepath, h5py.File) or h5py.is_hdf5(filepath))):
--> 146     return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile)
    147
    148   if isinstance(filepath, six.string_types):

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/saving/hdf5_format.py in load_model_from_hdf5(filepath, custom_objects, compile)
    166     model_config = json.loads(model_config.decode('utf-8'))
    167     model = model_config_lib.model_from_config(model_config,
--> 168                                                custom_objects=custom_objects)
    169
    170     # set weights

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/saving/model_config.py in model_from_config(config, custom_objects)
     53                     '`Sequential.from_config(config)`?')
     54   from tensorflow.python.keras.layers import deserialize  # pylint: disable=g-import-not-at-top
---> 55   return deserialize(config, custom_objects=custom_objects)
     56
     57

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/layers/serialization.py in deserialize(config, custom_objects)
    100       module_objects=globs,
    101       custom_objects=custom_objects,
--> 102       printable_module_name='layer')

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    189             custom_objects=dict(
    190                 list(_GLOBAL_CUSTOM_OBJECTS.items()) +
--> 191                 list(custom_objects.items())))
    192       with CustomObjectScope(custom_objects):
    193         return cls.from_config(cls_config)

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/sequential.py in from_config(cls, config, custom_objects)
    367     for layer_config in layer_configs:
    368       layer = layer_module.deserialize(layer_config,
--> 369                                        custom_objects=custom_objects)
    370       model.add(layer)
    371     if not model.inputs and build_input_shape:

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/layers/serialization.py in deserialize(config, custom_objects)
    100       module_objects=globs,
    101       custom_objects=custom_objects,
--> 102       printable_module_name='layer')

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    189             custom_objects=dict(
    190                 list(_GLOBAL_CUSTOM_OBJECTS.items()) +
--> 191                 list(custom_objects.items())))
    192       with CustomObjectScope(custom_objects):
    193         return cls.from_config(cls_config)

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/feature_column/feature_column_v2.py in from_config(cls, config, custom_objects)
    450     config_cp = config.copy()
    451     config_cp['feature_columns'] = serialization.deserialize_feature_columns(
--> 452         config['feature_columns'], custom_objects=custom_objects)
    453
    454     return cls(**config_cp)

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/feature_column/serialization.py in deserialize_feature_columns(configs, custom_objects)
    188   return [
    189       deserialize_feature_column(c, custom_objects, columns_by_name)
--> 190       for c in configs
    191   ]

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/feature_column/serialization.py in <listcomp>(.0)
    188   return [
    189       deserialize_feature_column(c, custom_objects, columns_by_name)
--> 190       for c in configs
    191   ]

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/feature_column/serialization.py in deserialize_feature_column(config, custom_objects, columns_by_name)
    141       cls_config,
    142       custom_objects=custom_objects,
--> 143       columns_by_name=columns_by_name)
    144
    145   # If the name already exists, re-use the column from columns_by_name,

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/feature_column/feature_column_v2.py in _from_config(cls, config, custom_objects, columns_by_name)
   2871     kwargs = _standardize_and_copy_config(config)
   2872     kwargs['normalizer_fn'] = generic_utils.deserialize_keras_object(
-> 2873         config['normalizer_fn'], custom_objects=custom_objects)
   2874     kwargs['dtype'] = dtypes.as_dtype(config['dtype'])
   2875

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    206       obj = _GLOBAL_CUSTOM_OBJECTS[object_name]
    207     else:
--> 208       obj = module_objects.get(object_name)
    209       if obj is None:
    210         raise ValueError('Unknown ' + printable_module_name + ':' + object_name)

AttributeError: 'NoneType' object has no attribute 'get'

</code>```

答:
This is how i solve the problem .
I looked at the following url:-
https://github.com/tensorflow/tensorflow/issues/31927

I put my feature columns , model all in one cell  and did exactly as a person did in last post in the above url.
But in the above url dtype in indicator column is float but i replaced it with int32 because i was getting other error and it worked

```<code>
#**************************** our main model  *********************************

keras.backend.clear_session()

feature_columns = []
feature_layer_inputs = {}
feature_columns.append(tf.feature_column.numeric_column('col_name1'))
feature_layer_inputs['col_name1'] = tf.keras.Input(shape=(1,), name='col_name1')

feature_columns.append(tf.feature_column.numeric_column('col_name2'))
feature_layer_inputs['col_name2'] = tf.keras.Input(shape=(1,), name='col_name2')

feature_columns.append(tf.feature_column.numeric_column('col_name3'))
feature_layer_inputs['col_name3'] = tf.keras.Input(shape=(1,), name='col_name3')

feature_columns.append(tf.feature_column.numeric_column('col_name4'))
feature_layer_inputs['col_name4'] = tf.keras.Input(shape=(1,), name='col_name4')

feature_columns.append(tf.feature_column.numeric_column('col_name5'))
feature_layer_inputs['col_name5'] = tf.keras.Input(shape=(1,), name='col_name5')

feature_columns.append(tf.feature_column.numeric_column('col_name6'))
feature_layer_inputs['col_name6'] = tf.keras.Input(shape=(1,), name='col_name6')

col_name7  = tf.feature_column.categorical_column_with_identity('col_name7',10,default_value=None)
feature_columns.append(tf.feature_column.indicator_column(col_name7))
feature_layer_inputs['col_name7'] = tf.keras.Input(shape=(1,), name='col_name7', dtype= tf.int32)

col_name8  = tf.feature_column.categorical_column_with_identity('col_name8',50,default_value=None)
feature_columns.append(tf.feature_column.indicator_column(col_name8))
feature_layer_inputs['col_name8'] = tf.keras.Input(shape=(1,), name='col_name8', dtype= tf.int32)

col_name9  = tf.feature_column.categorical_column_with_identity('col_name9',12,default_value=None)
feature_columns.append(tf.feature_column.indicator_column(col_name9))
feature_layer_inputs['col_name9'] = tf.keras.Input(shape=(1,), name='col_name9', dtype= tf.int32)

feature_layer = tf.keras.layers.DenseFeatures(feature_columns)
feature_layer_outputs = feature_layer(feature_layer_inputs)

x = keras.layers.Dense(32, activation='relu')(feature_layer_outputs)
x = keras.layers.Dense(32, activation='relu')(x)
output = keras.layers.Dense(1)(x)

model = keras.Model(inputs=[v for v in feature_layer_inputs.values()], outputs=output)

model.compile(optimizer='adam',loss='mae')

model.fit(train_ds , epochs=50,verbose=1)

</code>```

Now there is not error while saving or loading model

Body:
I have a keras model making use of feature_column api of tensorflow , I am able to save the model in .h5 extension but gets following error in colab while loading the saved model.

---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-38-8a2d51a054f6> in <module>()
----> 1 new_model = tf.keras.models.load_model('model.h5')

13 frames

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    318       obj = _GLOBAL_CUSTOM_OBJECTS[object_name]
    319     else:
--> 320       obj = module_objects.get(object_name)
    321       if obj is None:
    322         raise ValueError('Unknown ' + printable_module_name + ':' + object_name)

AttributeError: 'NoneType' object has no attribute 'get'

following is my code and i am using tensorlow 2.1

import pandas as pd
import tensorflow as tf
import numpy as np

feature_layer = tf.keras.layers.DenseFeatures(feature_columns)

def model_builder():

      tf.keras.backend.clear_session()
      model = tf.keras.Sequential()
      model.add(feature_layer)
      model.add(tf.keras.layers.Dense(32, activation='relu'))
      model.add(tf.keras.layers.Dense(32, activation='relu'))
      model.add(tf.keras.layers.Dense(1))

      model.compile(optimizer = tf.keras.optimizers.RMSprop(0.001),
                    loss=tf.keras.losses.Huber(),
                    metrics=['mae'])

      return model

model = model_builder()
model.fit(train_ds , epochs=5,verbose=1)

model.save('model.h5')

new_model = tf.keras.models.load_model('model.h5')

I get the following error while running code in local environment ie in conda environment using jupyter notebook. But local env is having tf 2.0

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-fbbaf2c35e78> in <module>
----> 1 new_model = tf.keras.models.load_model('model1.h5')

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/saving/save.py in load_model(filepath, custom_objects, compile)
    144   if (h5py is not None and (
    145       isinstance(filepath, h5py.File) or h5py.is_hdf5(filepath))):
--> 146     return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile)
    147
    148   if isinstance(filepath, six.string_types):

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/saving/hdf5_format.py in load_model_from_hdf5(filepath, custom_objects, compile)
    166     model_config = json.loads(model_config.decode('utf-8'))
    167     model = model_config_lib.model_from_config(model_config,
--> 168                                                custom_objects=custom_objects)
    169
    170     # set weights

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/saving/model_config.py in model_from_config(config, custom_objects)
     53                     '`Sequential.from_config(config)`?')
     54   from tensorflow.python.keras.layers import deserialize  # pylint: disable=g-import-not-at-top
---> 55   return deserialize(config, custom_objects=custom_objects)
     56
     57

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/layers/serialization.py in deserialize(config, custom_objects)
    100       module_objects=globs,
    101       custom_objects=custom_objects,
--> 102       printable_module_name='layer')

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    189             custom_objects=dict(
    190                 list(_GLOBAL_CUSTOM_OBJECTS.items()) +
--> 191                 list(custom_objects.items())))
    192       with CustomObjectScope(custom_objects):
    193         return cls.from_config(cls_config)

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/sequential.py in from_config(cls, config, custom_objects)
    367     for layer_config in layer_configs:
    368       layer = layer_module.deserialize(layer_config,
--> 369                                        custom_objects=custom_objects)
    370       model.add(layer)
    371     if not model.inputs and build_input_shape:

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/layers/serialization.py in deserialize(config, custom_objects)
    100       module_objects=globs,
    101       custom_objects=custom_objects,
--> 102       printable_module_name='layer')

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    189             custom_objects=dict(
    190                 list(_GLOBAL_CUSTOM_OBJECTS.items()) +
--> 191                 list(custom_objects.items())))
    192       with CustomObjectScope(custom_objects):
    193         return cls.from_config(cls_config)

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/feature_column/feature_column_v2.py in from_config(cls, config, custom_objects)
    450     config_cp = config.copy()
    451     config_cp['feature_columns'] = serialization.deserialize_feature_columns(
--> 452         config['feature_columns'], custom_objects=custom_objects)
    453
    454     return cls(**config_cp)

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/feature_column/serialization.py in deserialize_feature_columns(configs, custom_objects)
    188   return [
    189       deserialize_feature_column(c, custom_objects, columns_by_name)
--> 190       for c in configs
    191   ]

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/feature_column/serialization.py in <listcomp>(.0)
    188   return [
    189       deserialize_feature_column(c, custom_objects, columns_by_name)
--> 190       for c in configs
    191   ]

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/feature_column/serialization.py in deserialize_feature_column(config, custom_objects, columns_by_name)
    141       cls_config,
    142       custom_objects=custom_objects,
--> 143       columns_by_name=columns_by_name)
    144
    145   # If the name already exists, re-use the column from columns_by_name,

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/feature_column/feature_column_v2.py in _from_config(cls, config, custom_objects, columns_by_name)
   2871     kwargs = _standardize_and_copy_config(config)
   2872     kwargs['normalizer_fn'] = generic_utils.deserialize_keras_object(
-> 2873         config['normalizer_fn'], custom_objects=custom_objects)
   2874     kwargs['dtype'] = dtypes.as_dtype(config['dtype'])
   2875

~/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow_core/python/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    206       obj = _GLOBAL_CUSTOM_OBJECTS[object_name]
    207     else:
--> 208       obj = module_objects.get(object_name)
    209       if obj is None:
    210         raise ValueError('Unknown ' + printable_module_name + ':' + object_name)

AttributeError: 'NoneType' object has no attribute 'get'

Body:
This is how i solve the problem .
I looked at the following url:-
https://github.com/tensorflow/tensorflow/issues/31927

I put my feature columns , model all in one cell  and did exactly as a person did in last post in the above url.
But in the above url dtype in indicator column is float but i replaced it with int32 because i was getting other error and it worked

#**************************** our main model  *********************************

keras.backend.clear_session()

feature_columns = []
feature_layer_inputs = {}
feature_columns.append(tf.feature_column.numeric_column('col_name1'))
feature_layer_inputs['col_name1'] = tf.keras.Input(shape=(1,), name='col_name1')

feature_columns.append(tf.feature_column.numeric_column('col_name2'))
feature_layer_inputs['col_name2'] = tf.keras.Input(shape=(1,), name='col_name2')

feature_columns.append(tf.feature_column.numeric_column('col_name3'))
feature_layer_inputs['col_name3'] = tf.keras.Input(shape=(1,), name='col_name3')

feature_columns.append(tf.feature_column.numeric_column('col_name4'))
feature_layer_inputs['col_name4'] = tf.keras.Input(shape=(1,), name='col_name4')

feature_columns.append(tf.feature_column.numeric_column('col_name5'))
feature_layer_inputs['col_name5'] = tf.keras.Input(shape=(1,), name='col_name5')

feature_columns.append(tf.feature_column.numeric_column('col_name6'))
feature_layer_inputs['col_name6'] = tf.keras.Input(shape=(1,), name='col_name6')

col_name7  = tf.feature_column.categorical_column_with_identity('col_name7',10,default_value=None)
feature_columns.append(tf.feature_column.indicator_column(col_name7))
feature_layer_inputs['col_name7'] = tf.keras.Input(shape=(1,), name='col_name7', dtype= tf.int32)

col_name8  = tf.feature_column.categorical_column_with_identity('col_name8',50,default_value=None)
feature_columns.append(tf.feature_column.indicator_column(col_name8))
feature_layer_inputs['col_name8'] = tf.keras.Input(shape=(1,), name='col_name8', dtype= tf.int32)

col_name9  = tf.feature_column.categorical_column_with_identity('col_name9',12,default_value=None)
feature_columns.append(tf.feature_column.indicator_column(col_name9))
feature_layer_inputs['col_name9'] = tf.keras.Input(shape=(1,), name='col_name9', dtype= tf.int32)

feature_layer = tf.keras.layers.DenseFeatures(feature_columns)
feature_layer_outputs = feature_layer(feature_layer_inputs)

x = keras.layers.Dense(32, activation='relu')(feature_layer_outputs)
x = keras.layers.Dense(32, activation='relu')(x)
output = keras.layers.Dense(1)(x)

model = keras.Model(inputs=[v for v in feature_layer_inputs.values()], outputs=output)

model.compile(optimizer='adam',loss='mae')

model.fit(train_ds , epochs=50,verbose=1)

Now there is not error while saving or loading model


问:
Help with Processing code run exception, incorrect classpath
I'm running processing on linux with the jvm bundle. When I type in tutorial code and run it I get the following error:

incorrect classpath: /usr/java/jdk2.6.0_06/lib

can you modify processing's java classpath?

答:
It appears that your CLASSPATH environment variable is screwed up. Not sure how, but the path should almost certainly not have the 2 in it.

Try changing your CLASSPATH enviroment variable. First verify that it's wrong though.

```<code>echo $CLASSPATH
</code>```

It should be jdk1.6.0_06 not jdk2.6.0_06. Also, you really should update your JDK version. There have been significant changes since then.

Body:
It appears that your CLASSPATH environment variable is screwed up. Not sure how, but the path should almost certainly not have the 2 in it.

Try changing your CLASSPATH enviroment variable. First verify that it's wrong though.

echo $CLASSPATH

It should be jdk1.6.0_06 not jdk2.6.0_06. Also, you really should update your JDK version. There have been significant changes since then.


问:
How to signout programmatically from Liferay custom portlet
I am creating a custom portlet.

And I need to log-out the User from the portal after he performs some operation in my custom portlet. I am extending liferay's MVCPortlet.

In one of MyPortlet's action methods I need to write the code to logout the user and then redirect it to the home page.

Update:

I tried the following which I think logs out the user but does not redirect to the home page after logging out:

```<code>actionResponse.sendRedirect(PortalUtil.getPortalURL(actionRequest) + "/c/portal/logout");
</code>```

Thanks All

答:
I also did not find a way to send a specific redirect by using liferay's default logout (/c/portal/logout). So I logged out the user programmatically with the util class AuthenticatedSessionManagerUtil and
afterwards sending a specific redirect location within the response object, e.g. response.sendRedirect(yourLocation)

Note:
With Liferay 7.2 I used AuthenticatedSessionManagerUtil.signOutSimultaneousLogins(userId) instead of AuthenticatedSessionManagerUtil.logout(userId) which did not work for me.
hth

Body:
I am creating a custom portlet.

And I need to log-out the User from the portal after he performs some operation in my custom portlet. I am extending liferay's MVCPortlet.

In one of MyPortlet's action methods I need to write the code to logout the user and then redirect it to the home page.

Update:

I tried the following which I think logs out the user but does not redirect to the home page after logging out:

actionResponse.sendRedirect(PortalUtil.getPortalURL(actionRequest) + "/c/portal/logout");

Thanks All


问:
Search bar not visible to RecyclerView in Fragment
I am using the Search bar in Recycler view on Fragment but it doesn't seem to be
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.

menu.xml

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".HomeActivity">

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="@string/search"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        app:showAsAction="always" />

</menu>
</code>```

here is the java code in fragment and used with fragment

fragment.java

```<code>package part.time.job.v2;

import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.TextView;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;

import java.util.ArrayList;
import java.util.List;

import model.Jobpost;
import ui.JournalRecyclerAdapter;
import ui.JournalRecyclerAdapterEmp;
import util.JournalApi;

/**
 * A simple {@link Fragment} subclass.
 */

    public class ListjobFragment extends Fragment {

        private FirebaseUser user;
        private FirebaseAuth firebaseAuth;
        private FirebaseAuth.AuthStateListener authStateListener;
        private FirebaseFirestore db = FirebaseFirestore.getInstance();
        private List<Jobpost> journalList;
        private RecyclerView recyclerView;
        private Parcelable savedRecyclerLayoutState;
        private JournalRecyclerAdapterEmp journalRecyclerAdapterEmp;

        private CollectionReference collectionReference=db.collection("Employer");
        private TextView noJournalEntry;
        private SearchView searchView = null;
        private SearchView.OnQueryTextListener queryTextListener;

        public ListjobFragment() {
            // Required empty public constructor
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);

            // Inflate the layout for this fragment
            View view=inflater.inflate(R.layout.fragment_listjob, container, false);

            firebaseAuth= FirebaseAuth.getInstance();
            user =firebaseAuth.getCurrentUser();

            noJournalEntry= view.findViewById(R.id.no_list);
            journalList=new ArrayList<>();

            recyclerView=view.findViewById(R.id.recyclerView);
           recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            return view;
        }

        @Override
        public void onStart() {
            super.onStart();
    //        user= firebaseAuth.getCurrentUser();
    //        firebaseAuth.addAuthStateListener(authStateListener);
            if (journalList!=null){
                journalList.clear();
            }

            collectionReference.document(JournalApi.getInstance().getUserId()).collection("Job Post").whereEqualTo("userId",JournalApi.getInstance().getUserId())
                    .get()
                    .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                        @Override
                        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                            if (!queryDocumentSnapshots.isEmpty()){
                                for (QueryDocumentSnapshot journals: queryDocumentSnapshots){
    //                                Journal journal=journals.toObject(Journal.class);
                                    Jobpost jobpost=journals.toObject(Jobpost.class);
                                    journalList.add(jobpost);

                                }

                                journalRecyclerAdapterEmp = new JournalRecyclerAdapterEmp(getActivity(),journalList);
                                recyclerView.setAdapter(journalRecyclerAdapterEmp);
                                journalRecyclerAdapterEmp.notifyDataSetChanged();

                            }else {

                                noJournalEntry.setVisibility(View.VISIBLE);

                            }
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {

                        }
                    });

        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.menu, menu);
            MenuItem searchItem = menu.findItem(R.id.action_search);
            SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);

            if (searchItem != null) {
                searchView = (SearchView) searchItem.getActionView();
            }
            if (searchView != null) {
                searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));

                queryTextListener = new SearchView.OnQueryTextListener() {
                    @Override
                    public boolean onQueryTextChange(String newText) {
                        Log.i("onQueryTextChange", newText);

                        return true;
                    }
                    @Override
                    public boolean onQueryTextSubmit(String query) {
                        Log.i("onQueryTextSubmit", query);

                        return true;
                    }
                };
                searchView.setOnQueryTextListener(queryTextListener);
            }
            super.onCreateOptionsMenu(menu, inflater);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_search:
                    // Not implemented here
                    return false;
                default:
                    break;
            }
            searchView.setOnQueryTextListener(queryTextListener);
            return super.onOptionsItemSelected(item);
        }

    }
</code>```

答:
Put this in your code and you'll get your searchBar:

```<code>@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }
</code>```

Basically in fragment, to display the menu items we've to use "setHasOptionsMenu".

Body:
I am using the Search bar in Recycler view on Fragment but it doesn't seem to be
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.
please help me.

menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".HomeActivity">

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="@string/search"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        app:showAsAction="always" />

</menu>

here is the java code in fragment and used with fragment

fragment.java

package part.time.job.v2;

import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.TextView;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;

import java.util.ArrayList;
import java.util.List;

import model.Jobpost;
import ui.JournalRecyclerAdapter;
import ui.JournalRecyclerAdapterEmp;
import util.JournalApi;

/**
 * A simple {@link Fragment} subclass.
 */

    public class ListjobFragment extends Fragment {

        private FirebaseUser user;
        private FirebaseAuth firebaseAuth;
        private FirebaseAuth.AuthStateListener authStateListener;
        private FirebaseFirestore db = FirebaseFirestore.getInstance();
        private List<Jobpost> journalList;
        private RecyclerView recyclerView;
        private Parcelable savedRecyclerLayoutState;
        private JournalRecyclerAdapterEmp journalRecyclerAdapterEmp;

        private CollectionReference collectionReference=db.collection("Employer");
        private TextView noJournalEntry;
        private SearchView searchView = null;
        private SearchView.OnQueryTextListener queryTextListener;

        public ListjobFragment() {
            // Required empty public constructor
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);

            // Inflate the layout for this fragment
            View view=inflater.inflate(R.layout.fragment_listjob, container, false);

            firebaseAuth= FirebaseAuth.getInstance();
            user =firebaseAuth.getCurrentUser();

            noJournalEntry= view.findViewById(R.id.no_list);
            journalList=new ArrayList<>();

            recyclerView=view.findViewById(R.id.recyclerView);
           recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            return view;
        }

        @Override
        public void onStart() {
            super.onStart();
    //        user= firebaseAuth.getCurrentUser();
    //        firebaseAuth.addAuthStateListener(authStateListener);
            if (journalList!=null){
                journalList.clear();
            }

            collectionReference.document(JournalApi.getInstance().getUserId()).collection("Job Post").whereEqualTo("userId",JournalApi.getInstance().getUserId())
                    .get()
                    .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                        @Override
                        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                            if (!queryDocumentSnapshots.isEmpty()){
                                for (QueryDocumentSnapshot journals: queryDocumentSnapshots){
    //                                Journal journal=journals.toObject(Journal.class);
                                    Jobpost jobpost=journals.toObject(Jobpost.class);
                                    journalList.add(jobpost);

                                }

                                journalRecyclerAdapterEmp = new JournalRecyclerAdapterEmp(getActivity(),journalList);
                                recyclerView.setAdapter(journalRecyclerAdapterEmp);
                                journalRecyclerAdapterEmp.notifyDataSetChanged();

                            }else {

                                noJournalEntry.setVisibility(View.VISIBLE);

                            }
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {

                        }
                    });

        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.menu, menu);
            MenuItem searchItem = menu.findItem(R.id.action_search);
            SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);

            if (searchItem != null) {
                searchView = (SearchView) searchItem.getActionView();
            }
            if (searchView != null) {
                searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));

                queryTextListener = new SearchView.OnQueryTextListener() {
                    @Override
                    public boolean onQueryTextChange(String newText) {
                        Log.i("onQueryTextChange", newText);

                        return true;
                    }
                    @Override
                    public boolean onQueryTextSubmit(String query) {
                        Log.i("onQueryTextSubmit", query);

                        return true;
                    }
                };
                searchView.setOnQueryTextListener(queryTextListener);
            }
            super.onCreateOptionsMenu(menu, inflater);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_search:
                    // Not implemented here
                    return false;
                default:
                    break;
            }
            searchView.setOnQueryTextListener(queryTextListener);
            return super.onOptionsItemSelected(item);
        }

    }

Body:
Put this in your code and you'll get your searchBar:

@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

Basically in fragment, to display the menu items we've to use "setHasOptionsMenu".


问:
Combine: Publisher sometimes loses value and completes
I have a simple Deferred Publisher that reads data from disk and I display the data in a SwiftUI List, the Publisher works well most of the time, but sometimes it doesn't behave well, it just loses its value (which's an array of Model objects) and completes with finished message. I've tried a workaround mentioned here to use the buffer operator to keep the value in buffer because I believe the Combine's Publisher by design won't pass the data downstream if there is no demand requested by subscribers and hence dropping this data and completes, however using buffer didn't solve the issue.

The code I have:

```<code>enum FileError: Error {
    case someError
}

class ViewModel: ObservableObject {
    @Published var modelArray = [Model]()
    private var subscriptions = Set<AnyCancellable>()
    func readData() {
        DataSource()
            .readFromBundle(resource: "Sample", type: "json")
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: { completion in
                print("Completion: \(completion)")
            }) { array in
                self.modelArray = array
        }.store(in: &subscriptions)
    }
}
struct ContentView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List(self.viewModel.modelArray) { model in
                Text("\(model.name)")
            }
        }
        .onAppear {
            self.viewModel.readData()
        }
    }
}

struct Model: Codable, Identifiable {
    var id: Int
    var name: String
}

class DataSource {
    private let readQueue = DispatchQueue(label: "ReadQueue", qos: .default, attributes: .concurrent)

    func readFromBundle (resource: String, type:String) -> AnyPublisher<[Model], FileError> {
            Deferred {
                 Future { promise in
                    guard let url = Bundle.main.url(forResource: "Sample", withExtension: "json"),
                      let data = try? Data(contentsOf: url),
                      let modelArray = try? JSONDecoder().decode([Model].self, from: data)
                      else {
                        promise(.failure(.someError))
                        return
                    }
                      promise(.success(modelArray))
                }
            }
           .receive(on: self.readQueue)
           .eraseToAnyPublisher()
        }
}
</code>```

This is a link to download a working sample project.

EDIT:

Environment: Xcode 11.3.1, iOS 13.3 iPhone 11 Pro Max simulator and device.

gif screenshot (notice the console output)

EDIT2:

if I add any downstream publishers, like combineLatest for example just before sink in the consumer function readData() then a new behavior introduced, which's chaining an async publisher (readFromBundle) with a sync publisher (combineLatest) will result in the value will not deliver at all on iOS 13.3+ devices and will sometimes deliver on devices below iOS 13.3, as stated on this link.

答:
It looks like racing-kind issue, please try the following (just by code-reading)

1) use background queue explicitly

```<code>private let readQueue = DispatchQueue(label: "ReadQueue", qos: .background,
    attributes: .concurrent)
</code>```

2) schedule Publisher on this queue instead of receiving on it

```<code>.subscribe(on: self.readQueue)
</code>```

Body:
I have a simple Deferred Publisher that reads data from disk and I display the data in a SwiftUI List, the Publisher works well most of the time, but sometimes it doesn't behave well, it just loses its value (which's an array of Model objects) and completes with finished message. I've tried a workaround mentioned here to use the buffer operator to keep the value in buffer because I believe the Combine's Publisher by design won't pass the data downstream if there is no demand requested by subscribers and hence dropping this data and completes, however using buffer didn't solve the issue.

The code I have:

enum FileError: Error {
    case someError
}

class ViewModel: ObservableObject {
    @Published var modelArray = [Model]()
    private var subscriptions = Set<AnyCancellable>()
    func readData() {
        DataSource()
            .readFromBundle(resource: "Sample", type: "json")
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: { completion in
                print("Completion: \(completion)")
            }) { array in
                self.modelArray = array
        }.store(in: &subscriptions)
    }
}
struct ContentView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List(self.viewModel.modelArray) { model in
                Text("\(model.name)")
            }
        }
        .onAppear {
            self.viewModel.readData()
        }
    }
}

struct Model: Codable, Identifiable {
    var id: Int
    var name: String
}

class DataSource {
    private let readQueue = DispatchQueue(label: "ReadQueue", qos: .default, attributes: .concurrent)

    func readFromBundle (resource: String, type:String) -> AnyPublisher<[Model], FileError> {
            Deferred {
                 Future { promise in
                    guard let url = Bundle.main.url(forResource: "Sample", withExtension: "json"),
                      let data = try? Data(contentsOf: url),
                      let modelArray = try? JSONDecoder().decode([Model].self, from: data)
                      else {
                        promise(.failure(.someError))
                        return
                    }
                      promise(.success(modelArray))
                }
            }
           .receive(on: self.readQueue)
           .eraseToAnyPublisher()
        }
}

This is a link to download a working sample project.

EDIT:

Environment: Xcode 11.3.1, iOS 13.3 iPhone 11 Pro Max simulator and device.

gif screenshot (notice the console output)

EDIT2:

if I add any downstream publishers, like combineLatest for example just before sink in the consumer function readData() then a new behavior introduced, which's chaining an async publisher (readFromBundle) with a sync publisher (combineLatest) will result in the value will not deliver at all on iOS 13.3+ devices and will sometimes deliver on devices below iOS 13.3, as stated on this link.

Body:
It looks like racing-kind issue, please try the following (just by code-reading)

1) use background queue explicitly

private let readQueue = DispatchQueue(label: "ReadQueue", qos: .background,
    attributes: .concurrent)

2) schedule Publisher on this queue instead of receiving on it

.subscribe(on: self.readQueue)


问:
How to monitor progress of ssh file transfer and output to a log file
I'm writing a bash script to periodically transfer data to a remote system.  I have a local command that generates a stream, and a remote command that consumes it, so I'm doing something like this:

```<code>generate_data | ssh remoteserver.example.com consume_data
</code>```

(Where I have ssh keys set up so I can do this non-interactively.)  This works fine.  However, since this will be an automated process (running as a cron job) and may sometimes be transferring large amounts of data on limited bandwidth, I'd like to be able place periodic progress updates in my log file.  I had thought to use pv (pipe viewer) for this, and this is the best I could come up with:

```<code>generate_data | pv -fb | ssh remoteserver.example.com consume_data
</code>```

Again, it works... but pv was really written with terminal output in mind, so I end up with a mess in the log that looks like

```<code>2.06MB^M2.19MB^M2.37MB^M 2.5MB^M2.62MB^M2.87MB^M3MB^M3.12MB^M3.37MB
</code>```

I'd prefer log messages along the lines of

```<code><timestamp> 2.04MB transferred...
<timestamp> 3.08MB transferred...
</code>```

If anybody has any clever ideas of how to do this, either with different arguments to pv or via some other mechanism, I'd be grateful.

EDIT: Thanks for the answers so far.  Of course there are a lot of possible home-brewed solutions; I was hoping to find something that would work "out of the box."  (Not that I'm ruling out home-brewed; it may be the easiest thing in the end.  Since pv already does 98% of what I need, I'd prefer not to re-invent it.)

PostScript: Here's the line I ended up using, in hopes it might help someone else at some point.

```<code>{ generate_data | pv -fbt -i 60 2>&3 | ssh remoteserver consume_data } 3>&1 | awk -vRS='\r' '{print $1 " transferred in " $2; fflush();}' >> logfile
</code>```

答:
If you want to stick with pv, you could postprocess its output a little. At a minimum, turn the CRs into LFs.

```<code>{ generate_data | pv -bft 2>&3 | consume_data >/dev/null; } 3>&1 | tr '\015' '\012'
</code>```

Use awk for fancier processing.

```<code>{ generate_data | pv -bft 2>&3 | consume_data >/dev/null; } 3>&1 |
awk -vRS='\r' '{print $2, $1 " transferred"}'
</code>```

Do however keep in mind that the standard text processing utilities only flush their output at the end of each line if they're printing to a terminal. So if you pipe pv to some other utility whose output goes to a pipe or file, there will be a non-negligible delay due to buffering. If you have GNU awk or some other implementation that has the fflush function (it's common but not standard), make it flush its output on every line:

```<code>{ generate_data | pv -bft 2>&3 | consume_data >/dev/null; } 3>&1 |
awk -vRS='\r' '{print $2, $1 " transferred"; fflush()}'
</code>```

Body:
I'm writing a bash script to periodically transfer data to a remote system.  I have a local command that generates a stream, and a remote command that consumes it, so I'm doing something like this:

generate_data | ssh remoteserver.example.com consume_data

(Where I have ssh keys set up so I can do this non-interactively.)  This works fine.  However, since this will be an automated process (running as a cron job) and may sometimes be transferring large amounts of data on limited bandwidth, I'd like to be able place periodic progress updates in my log file.  I had thought to use pv (pipe viewer) for this, and this is the best I could come up with:

generate_data | pv -fb | ssh remoteserver.example.com consume_data

Again, it works... but pv was really written with terminal output in mind, so I end up with a mess in the log that looks like

2.06MB^M2.19MB^M2.37MB^M 2.5MB^M2.62MB^M2.87MB^M3MB^M3.12MB^M3.37MB

I'd prefer log messages along the lines of

<timestamp> 2.04MB transferred...
<timestamp> 3.08MB transferred...

If anybody has any clever ideas of how to do this, either with different arguments to pv or via some other mechanism, I'd be grateful.

EDIT: Thanks for the answers so far.  Of course there are a lot of possible home-brewed solutions; I was hoping to find something that would work "out of the box."  (Not that I'm ruling out home-brewed; it may be the easiest thing in the end.  Since pv already does 98% of what I need, I'd prefer not to re-invent it.)

PostScript: Here's the line I ended up using, in hopes it might help someone else at some point.

{ generate_data | pv -fbt -i 60 2>&3 | ssh remoteserver consume_data } 3>&1 | awk -vRS='\r' '{print $1 " transferred in " $2; fflush();}' >> logfile

Body:
If you want to stick with pv, you could postprocess its output a little. At a minimum, turn the CRs into LFs.

{ generate_data | pv -bft 2>&3 | consume_data >/dev/null; } 3>&1 | tr '\015' '\012'

Use awk for fancier processing.

{ generate_data | pv -bft 2>&3 | consume_data >/dev/null; } 3>&1 |
awk -vRS='\r' '{print $2, $1 " transferred"}'

Do however keep in mind that the standard text processing utilities only flush their output at the end of each line if they're printing to a terminal. So if you pipe pv to some other utility whose output goes to a pipe or file, there will be a non-negligible delay due to buffering. If you have GNU awk or some other implementation that has the fflush function (it's common but not standard), make it flush its output on every line:

{ generate_data | pv -bft 2>&3 | consume_data >/dev/null; } 3>&1 |
awk -vRS='\r' '{print $2, $1 " transferred"; fflush()}'


问:
Change the color of bottom navigation bar item
I set the primary color as a certain type of orange and I can't understand why by default my bottom navigation bar takes white and not primary color as the color for the selected items, how to solve?

xml code for the bottom navigation bar

```<code>    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"
        android:background="@color/colorAccent"
        app:menu="@menu/bottom_navigation"/>
</code>```

colors (the primary is some kind of orange)

```<code><color name="colorPrimary">#fb8c00</color>
<color name="colorPrimaryDark">#c25e00</color>
<color name="colorPrimaryLight">#ffbd45</color>
<color name="textOnPrimary">#000000</color>
<color name="colorAccent">#D81B60</color>
</code>```

as you can see the item selected and the text are white while the primary color is orange

答:
Step-1 Create drawable file under drawable folder and and add below code.

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#82C341" android:state_checked="true" />
<item android:color="#a9a9a9" android:state_checked="false"/>
</selector>
</code>```

Step-2 Then use this drawable file like this.
       Add these two lines.
        app:itemIconTint="@drawable/your_drawable_file_name"
        app:itemTextColor="@drawable/your_drawable_file_name"

Full Code

```<code><android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:itemBackground="@color/tab_bg"
    android:layout_gravity="start"
    android:padding="0dp"
    android:focusable="false"
    app:itemIconTint="@drawable/your_drawable_file_name"
    app:itemTextColor="@drawable/bottom_navigation_color_selector"
    app:menu="@menu/menu_bottom_navigation"
    app:labelVisibilityMode="labeled" />
</code>```

Body:
I set the primary color as a certain type of orange and I can't understand why by default my bottom navigation bar takes white and not primary color as the color for the selected items, how to solve?

xml code for the bottom navigation bar

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"
        android:background="@color/colorAccent"
        app:menu="@menu/bottom_navigation"/>

colors (the primary is some kind of orange)

<color name="colorPrimary">#fb8c00</color>
<color name="colorPrimaryDark">#c25e00</color>
<color name="colorPrimaryLight">#ffbd45</color>
<color name="textOnPrimary">#000000</color>
<color name="colorAccent">#D81B60</color>

as you can see the item selected and the text are white while the primary color is orange

Body:
Step-1 Create drawable file under drawable folder and and add below code.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#82C341" android:state_checked="true" />
<item android:color="#a9a9a9" android:state_checked="false"/>
</selector>

Step-2 Then use this drawable file like this.
       Add these two lines.
        app:itemIconTint="@drawable/your_drawable_file_name"
        app:itemTextColor="@drawable/your_drawable_file_name"

Full Code

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:itemBackground="@color/tab_bg"
    android:layout_gravity="start"
    android:padding="0dp"
    android:focusable="false"
    app:itemIconTint="@drawable/your_drawable_file_name"
    app:itemTextColor="@drawable/bottom_navigation_color_selector"
    app:menu="@menu/menu_bottom_navigation"
    app:labelVisibilityMode="labeled" />