问:
with python from csv to text files
I am trying to wrtie two txtfiles ( Test_8.txt and Test_9.txt ) from the csvfile.
From row COL4 i am getting single and double quotes and '['.

how can i get rid of them?

csvfie:

```<code>NR;COL1;COL2;COL3;COL4;COL5;COL6;COL7;REMARK

Test_9;96;0;4.26;4;5.25;-0.01;1;Test_9 tested, python

Test_9;96;0;4.26;4;11.75;2.35;1;Test_9 tested, python

Test_9;96;0;4.26;4;-3;-3;0.9;Test_9 tested, python

Test_8;95;0;4.25;3;4.75;-0.11;1;Test_8 tested, python

Test_8;95;0;4.25;3;-3;-3;0.9;Test_8 tested, python

Test_8;95;0;4.25;3;16.5;4.26;1;Test_8 tested, python

Test_8;95;0;4.25;3;12.751;2.861;1;Test_8 tested, python
</code>```

Expected ouput:

```<code>TYPE    1.0
NR  Test_8

COL1    95

COL2    0
COL3    4.250

COL4    3
-3.000  -3.000  0.900
4.750   -0.110  1.000
12.751  2.861   1.000
16.500  4.260   1.000

REMARK
Test_8 tested
with python
</code>```

mycode:

```<code>import os
import pandas as pd
pd.options.mode.chained_assignment = None
df=pd.read_csv(r'C:\Users\Desktop\test_map\test\mycsv_v1.csv',sep=';',index_col='NR')

df['COL3'] = df['COL3'].map('{:,.3f}'.format)

df['COL5'] = df['COL5'].map('{:,.3f}'.format)
df['COL6'] = df['COL6'].map('{:,.3f}'.format)
df['COL7'] = df['COL7'].map('{:,.3f}'.format)

ans = [[x,pd.DataFrame(y)] for x, y in df.groupby(df.index, as_index=True)]
#print ans

for table in ans:
    line1=table[1].iloc[0]
    #print line1
    line1['TYPE']=1.0
    line1['NR']=table[0]

    col567=table[1][['COL5','COL6','COL7']].sort_values(by=['COL5'], ascending=True)
    print col567

    for row in range(len(col567)):
        #print row
        line1[str(col567.values[row])[1:-1]] = None

    line1['']=None

    col8=table[1]['REMARK'].str.split(',')[0]
    col8=table[1]['REMARK'].str.split(', ')[1]
    line1['REMARK']=str(col8.values[0])
    line1['REMARK']=str(col8.values[1])

    line1=line1[['TYPE', 'NR','','COL1','', 'COL2','', 'COL3', 'COL4',
             str(col567.values[0:]), '', 'REMARK\n', col8.values[0],col8.values[1]]]

    line1.to_csv(table[0]+'.txt',sep='\t')
</code>```

myoutput;

```<code>TYPE    1.0
NR  Test_8

COL1    95

COL2    0

COL3    4.250
COL4    3
"[['-3.000' '-3.000' '0.900']
 ['12.751' '2.861' '1.000']
 ['16.500' '4.260' '1.000']
 ['4.750' '-0.110' '1.000']]"

"REMARK
"
Test_8 tested
python
</code>```

答:
You're printing a numpy.array of numpy.arrays.
The default formatting is a list of lists.

You could add your own formatting using list comprehension and string join().

```<code>col567_fmt = '\n'.join( [ '\t'.join(x) for x in col567.values[0:] ] )
line1=line1[['TYPE', 'NR','','COL1','', 'COL2','', 'COL3', 'COL4',
         col567_fmt, '', 'REMARK\n', col8.values[0],col8.values[1]]]
</code>```

Also, if you want to print using to_csv() you'll need to disable quotation. See replies to this question

Title: with python from csv to text files

Body:
I am trying to wrtie two txtfiles ( Test_8.txt and Test_9.txt ) from the csvfile.
From row COL4 i am getting single and double quotes and '['.

how can i get rid of them?

csvfie:

NR;COL1;COL2;COL3;COL4;COL5;COL6;COL7;REMARK

Test_9;96;0;4.26;4;5.25;-0.01;1;Test_9 tested, python

Test_9;96;0;4.26;4;11.75;2.35;1;Test_9 tested, python

Test_9;96;0;4.26;4;-3;-3;0.9;Test_9 tested, python

Test_8;95;0;4.25;3;4.75;-0.11;1;Test_8 tested, python

Test_8;95;0;4.25;3;-3;-3;0.9;Test_8 tested, python

Test_8;95;0;4.25;3;16.5;4.26;1;Test_8 tested, python

Test_8;95;0;4.25;3;12.751;2.861;1;Test_8 tested, python

Expected ouput:

TYPE    1.0
NR  Test_8

COL1    95

COL2    0
COL3    4.250

COL4    3
-3.000  -3.000  0.900
4.750   -0.110  1.000
12.751  2.861   1.000
16.500  4.260   1.000

REMARK
Test_8 tested
with python

mycode:

import os
import pandas as pd
pd.options.mode.chained_assignment = None
df=pd.read_csv(r'C:\Users\Desktop\test_map\test\mycsv_v1.csv',sep=';',index_col='NR')

df['COL3'] = df['COL3'].map('{:,.3f}'.format)

df['COL5'] = df['COL5'].map('{:,.3f}'.format)
df['COL6'] = df['COL6'].map('{:,.3f}'.format)
df['COL7'] = df['COL7'].map('{:,.3f}'.format)

ans = [[x,pd.DataFrame(y)] for x, y in df.groupby(df.index, as_index=True)]
#print ans

for table in ans:
    line1=table[1].iloc[0]
    #print line1
    line1['TYPE']=1.0
    line1['NR']=table[0]

    col567=table[1][['COL5','COL6','COL7']].sort_values(by=['COL5'], ascending=True)
    print col567

    for row in range(len(col567)):
        #print row
        line1[str(col567.values[row])[1:-1]] = None

    line1['']=None

    col8=table[1]['REMARK'].str.split(',')[0]
    col8=table[1]['REMARK'].str.split(', ')[1]
    line1['REMARK']=str(col8.values[0])
    line1['REMARK']=str(col8.values[1])

    line1=line1[['TYPE', 'NR','','COL1','', 'COL2','', 'COL3', 'COL4',
             str(col567.values[0:]), '', 'REMARK\n', col8.values[0],col8.values[1]]]

    line1.to_csv(table[0]+'.txt',sep='\t')

myoutput;

TYPE    1.0
NR  Test_8

COL1    95

COL2    0

COL3    4.250
COL4    3
"[['-3.000' '-3.000' '0.900']
 ['12.751' '2.861' '1.000']
 ['16.500' '4.260' '1.000']
 ['4.750' '-0.110' '1.000']]"

"REMARK
"
Test_8 tested
python

Body:
You're printing a numpy.array of numpy.arrays.
The default formatting is a list of lists.

You could add your own formatting using list comprehension and string join().

col567_fmt = '\n'.join( [ '\t'.join(x) for x in col567.values[0:] ] )
line1=line1[['TYPE', 'NR','','COL1','', 'COL2','', 'COL3', 'COL4',
         col567_fmt, '', 'REMARK\n', col8.values[0],col8.values[1]]]

Also, if you want to print using to_csv() you'll need to disable quotation. See replies to this question


来源: stackexchange

问:
Why is this binary tree preorder traversal returning none
Hi I am attempting to solve leetcode problem 1379.

Here is the statement of the problem + link:

https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/

Here is my failed attempt at a solution:

```<code># Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
        if cloned:
            if cloned.val == target.val:
                return cloned
            self.getTargetCopy(original, cloned.left, target)
            self.getTargetCopy(original, cloned.right, target)
</code>```

I am failing to understand why this is not working.

I think my solution is doing a preorder traversal of the tree and at each stage asking if the node in the cloned tree exists and if so is it's value equal to the value we are looking for? If it is then return that node and we have found the one we are looking for.

If not then check simply carry on checking the tree. Since the values in the tree are guaranteed to be unique and the target value is guaranteed to be in the tree then and I am visiting every node then surely this must work at finding the answer.

However it is failing the automated tests, it doesn't even pass the example 1 (pictured above) and is saying it is returning null.

What am I missing?

EDIT:

I tried printing my original solution with the arguements at each function call:

```<code>__main__.Solution.getTargetCopy ( self = <__main__.Solution object at 0x000002B15CF31358>, original = 7, cloned = 7, target = 3 )
__main__.Solution.getTargetCopy ( self = <__main__.Solution object at 0x000002B15CF31358>, original = 7, cloned = 4, target = 3 )
__main__.Solution.getTargetCopy ( self = <__main__.Solution object at 0x000002B15CF31358>, original = 7, cloned = None, target = 3 )
__main__.Solution.getTargetCopy ( self = <__main__.Solution object at 0x000002B15CF31358>, original = 7, cloned = None, target = 3 )
__main__.Solution.getTargetCopy ( self = <__main__.Solution object at 0x000002B15CF31358>, original = 7, cloned = 3, target = 3 )
None
</code>```

So as well can see the cloned tree traverses from 7 down to 4 then checks 4's left and right child which are both none, then it checks 7's right child 3 and confirms that it is the same as the target, at this point in the call cloned.val=3 so the return statement should return the node whose value is 3 which should be the right answer yet it seems to be returning none which is not even the value of cloned at that time (as proven by the print statement showing the arguments) what is going on?

答:
When the if condition is not true, you don't return anything.

So change these two lines:

```<code>self.getTargetCopy(original, cloned.left, target)
self.getTargetCopy(original, cloned.right, target)
</code>```

To:

```<code>res = self.getTargetCopy(original, cloned.left, target)
if res:
    return res
return self.getTargetCopy(original, cloned.right, target)
</code>```

Or even (using short circuit):

```<code>return (self.getTargetCopy(original, cloned.left, target)
     or self.getTargetCopy(original, cloned.right, target))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi I am attempting to solve leetcode problem 1379.

Here is the statement of the problem + link:

https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/

Here is my failed attempt at a solution:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
        if cloned:
            if cloned.val == target.val:
                return cloned
            self.getTargetCopy(original, cloned.left, target)
            self.getTargetCopy(original, cloned.right, target)

I am failing to understand why this is not working.

I think my solution is doing a preorder traversal of the tree and at each stage asking if the node in the cloned tree exists and if so is it's value equal to the value we are looking for? If it is then return that node and we have found the one we are looking for.

If not then check simply carry on checking the tree. Since the values in the tree are guaranteed to be unique and the target value is guaranteed to be in the tree then and I am visiting every node then surely this must work at finding the answer.

However it is failing the automated tests, it doesn't even pass the example 1 (pictured above) and is saying it is returning null.

What am I missing?

EDIT:

I tried printing my original solution with the arguements at each function call:

__main__.Solution.getTargetCopy ( self = <__main__.Solution object at 0x000002B15CF31358>, original = 7, cloned = 7, target = 3 )
__main__.Solution.getTargetCopy ( self = <__main__.Solution object at 0x000002B15CF31358>, original = 7, cloned = 4, target = 3 )
__main__.Solution.getTargetCopy ( self = <__main__.Solution object at 0x000002B15CF31358>, original = 7, cloned = None, target = 3 )
__main__.Solution.getTargetCopy ( self = <__main__.Solution object at 0x000002B15CF31358>, original = 7, cloned = None, target = 3 )
__main__.Solution.getTargetCopy ( self = <__main__.Solution object at 0x000002B15CF31358>, original = 7, cloned = 3, target = 3 )
None

So as well can see the cloned tree traverses from 7 down to 4 then checks 4's left and right child which are both none, then it checks 7's right child 3 and confirms that it is the same as the target, at this point in the call cloned.val=3 so the return statement should return the node whose value is 3 which should be the right answer yet it seems to be returning none which is not even the value of cloned at that time (as proven by the print statement showing the arguments) what is going on?

Body:
When the if condition is not true, you don't return anything.

So change these two lines:

self.getTargetCopy(original, cloned.left, target)
self.getTargetCopy(original, cloned.right, target)

To:

res = self.getTargetCopy(original, cloned.left, target)
if res:
    return res
return self.getTargetCopy(original, cloned.right, target)

Or even (using short circuit):

return (self.getTargetCopy(original, cloned.left, target)
     or self.getTargetCopy(original, cloned.right, target))


问:
Memory Leak in C#
Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose are disposed?

Would there be cases where some variables are left out?

答:
While it is possible that something in the framework has a leak, more then likely you have something that isn't being being disposed of properly or something is blocking the GC from disposing of it, IIS would be a prime candidate for this.

Just remember that not everything in .NET is fully managed code, COM interop, file io like file streams, DB requests, images, etc.

A problem we had a while ago (.net 2.0 on IIS 6) was that we would create an image and then dispose of it but IIS wouldn't release the memory for a while.

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Memory Leak in C#

LastEditorDisplayName: strager

OwnerDisplayName: Bob The Janitor

LastEditorDisplayName: Bob The Janitor


问:
can the sorting from an order by statement be saved explicitly in a table (SQL Server Version 2017)
I have this table

```<code>AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A001       Subbarao        Bangalore
A002       Mukesh          Mumbai
A003       Alex            London
</code>```

Sorting the above table should give me the below result.

```<code>select *
from table_name
order by agent_name;

AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A003       Alex             London
A002       Mukesh           Mumbai
A001       Subbarao         Bangalore
</code>```

Now, I want to keep my table and save the sorted order on the positioned rows permanently onto the same table

Eg: when I run

```<code> select * from table_name
</code>```

the results should appear as below without ordering

```<code>AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A003       Alex             London
A002       Mukesh           Mumbai
A001       Subbarao         Bangalore
</code>```

答:
Eg: when i run select * from table_name. The results should appear as below without ordering

No, this is not possible. SQL tables represent unordered set of rows. In absence of an explicit order by clause in the query, the database is free to return the rows in any order it likes, and the sort is not guaranteed to be consistent over consequent executions of the same query.

So if you want a consistent ordering, do use an order by clause to your query.

Body:
I have this table

AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A001       Subbarao        Bangalore
A002       Mukesh          Mumbai
A003       Alex            London

Sorting the above table should give me the below result.

select *
from table_name
order by agent_name;

AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A003       Alex             London
A002       Mukesh           Mumbai
A001       Subbarao         Bangalore

Now, I want to keep my table and save the sorted order on the positioned rows permanently onto the same table

Eg: when I run

 select * from table_name

the results should appear as below without ordering

AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A003       Alex             London
A002       Mukesh           Mumbai
A001       Subbarao         Bangalore


问:
Reading property from body with req.body
In the application generating dummy data every second and when I log it with "req.body" the output as below.

```<code>[
  {
    dataType: 'Number',
    deviceName: 'device1',
    attributeName: 'value',
    min: '1',
    max: '11',
    value: '9.000438216772668',
    ESP_OPS: 'i',
    timestamp: '2020-05-28T20:08:56.544Z'
  }
]
</code>```

However I would like to get "value" in this array. When I try to log it with "req.body.value" it returns "undefined". How can I catch "value" in this array?

答: req.body returns an array. In this case the array only has 1 element (which is the json object that you want access to). In JavaScript array indices start at 0, therefore you need to writereq.body[0]

Body:
In the application generating dummy data every second and when I log it with "req.body" the output as below.

[
  {
    dataType: 'Number',
    deviceName: 'device1',
    attributeName: 'value',
    min: '1',
    max: '11',
    value: '9.000438216772668',
    ESP_OPS: 'i',
    timestamp: '2020-05-28T20:08:56.544Z'
  }
]

However I would like to get "value" in this array. When I try to log it with "req.body.value" it returns "undefined". How can I catch "value" in this array?


问:
Does holding a C++ reference prevents variable of being destroyed?
Coming from a Java/C# background I am trying to implement kinda a null safety check object. The following code tries to check if there is indeed a color on the object. If there is, I want be able to do some stuff (like drawing the color on a shape). I want to be able to set this color back to null (noneColor), preventing for coloring the object.

I didn't want to set this color has a pointer, because it would be necessary to delete it on every setter and on the deconstructor. Is this a bad thought?

Code:

```<code>static const Color& noneColor = Color();

static bool isNoneColor(const Color& color) {
    return std::addressof(noneColor) == std::addressof(color);
}

MyShape:MyShape() {
    this->color = noneColor; // this->color is an object of Color
}

void MyShape::setColor(const Color& newColor)
{
    this->color= newColor;
}

void MyShape::draw()
{
    if(!isNoneColor(this->color))
        // Color shape
}

//different scope/class
void B::setColorForShape()
{
    Color color = Color(255,255,255);
    a->setColor(color);
    // Calling isNoneColor(a->color); should return false;
    // After this function ends does variable a->color have undefined behavior?
}

void B::setNoneColorForShape()
{
    a->setColor(noneColor);
    //Calling isNoneColor(a->color); should return true;
}
</code>```

Is it safe to call isNoneColor with a->color afterwards the method ends?

Edit:

MyShape:color is declared has Color& color. I want to be able to set a noneColor state on my object MyShape. With a simple Color object I can't know if that color is "null"/empty state.

答:
The answer to your question

Does holding a C++ reference prevents variable of being destroyed?

is: not generally, but in this case, yes. The standard has this to say

There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. The first context is [..]

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:

A temporary bound to a reference member in a constructor’s ctor-initializer(12.6.2) persists until the constructor exits.

A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.

The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.

A temporary bound to a reference in a new-initializer(5.3.4) persists until the completion of the full-expression containing the new-initializer. [Example][Note]

(from 12.2 [class.temporary], emphasis added, example and note omitted)

Although this is a bad practice, and something like T const& t = T(); will look odd to many C++ programmers (I presume), it is technically legal. It's usefulness can be debated, as T const t = T(); will do the same job without looking odd. See Jeremy Friesner's answer for why your approach will not work as expected because references cannot be re-seated.

Body:
Coming from a Java/C# background I am trying to implement kinda a null safety check object. The following code tries to check if there is indeed a color on the object. If there is, I want be able to do some stuff (like drawing the color on a shape). I want to be able to set this color back to null (noneColor), preventing for coloring the object.

I didn't want to set this color has a pointer, because it would be necessary to delete it on every setter and on the deconstructor. Is this a bad thought?

Code:

static const Color& noneColor = Color();

static bool isNoneColor(const Color& color) {
    return std::addressof(noneColor) == std::addressof(color);
}

MyShape:MyShape() {
    this->color = noneColor; // this->color is an object of Color
}

void MyShape::setColor(const Color& newColor)
{
    this->color= newColor;
}

void MyShape::draw()
{
    if(!isNoneColor(this->color))
        // Color shape
}

//different scope/class
void B::setColorForShape()
{
    Color color = Color(255,255,255);
    a->setColor(color);
    // Calling isNoneColor(a->color); should return false;
    // After this function ends does variable a->color have undefined behavior?
}

void B::setNoneColorForShape()
{
    a->setColor(noneColor);
    //Calling isNoneColor(a->color); should return true;
}

Is it safe to call isNoneColor with a->color afterwards the method ends?

Edit:

MyShape:color is declared has Color& color. I want to be able to set a noneColor state on my object MyShape. With a simple Color object I can't know if that color is "null"/empty state.


问:
What is the point of Node.js
Ok this is probably a little blunt and to the point, but what is the point/need for Node.js

I've noticed it mainly through CloudFoundry but just not too sure what its supposed to be doing. However I am guessing its probably something pretty big as why else would VMWare be supporting it.

Thanks in advance.

答:
Node.js does IO right. It's asynchronous and non-blocking and the beauty of using js is that it does not have a standard blocking IO.

It's fast (v8 is a beast), it scales well, It's got a vibrant community and it's popular.

There are lots of wonderful libraries that run on node like now and socket.io.

It excels at real time communication and highly concurrent websites.

It also has the added bonus of less code duplication. You can write the same MVC code on the client as the server and easily support non-js users.

Further reads:

Usages of Node.js - What obstacles is it aiming to provide a ramp for?

Why and when to use Node.js?

What so different about Node.js's event-driven? Can't we do that in ASP.Net's HttpAsyncHandler?

What is Node.js?

ContentLicense: CC BY-SA 3.0

Title: What is the point of Node.js


问:
Create Dynamic route and render component in reactjs
I am new in ReactJs.
I need a route like localhost:3000/directory/category/region/brandName and for the same route, I need to render a component

Sample of URL be like

localhost:3000/directory/photography/france/testA

localhost:3000/directory/Catering/germany/testB

for both above URLs, a component called name.js should render

答:
As far as I understand from the question, you can handle this through using "Redirect" component. Let there be a "Navigation" component where the "Router" is defined as you did

Navigation.js

```<code>import Name from './name';
import From from './from';

<Router>
  <Switch>
    <Route path="/from">
       <From />
    </Route>
    <Route path="/directory/:profession/:country/:value">
       <Name />
   </Route>
  </Switch>
</Router>
</code>```

and a "From" component where paths and redirections are defined. If "redirectionPath" is not null you can return "Redirect" component in render. Thus, you can redirect to and render the Name component.

From.js

```<code>import React, {Component} from 'react';
import {
    Redirect
} from "react-router-dom";

class From extends Component {
    state={
        redirectionPath: "/directory/photography/france/testA" // or setState anywhere you need.
    }

    ...

    render(){
        if(this.state.path){
            return (<Redirect to={this.state.redirectionPath} />)
        }
        return (
            <SomeComponent/>
        );
    }
}
</code>```

This can be one of the solutions. Hope it works for you as well.

Body:
As far as I understand from the question, you can handle this through using "Redirect" component. Let there be a "Navigation" component where the "Router" is defined as you did

Navigation.js

import Name from './name';
import From from './from';

<Router>
  <Switch>
    <Route path="/from">
       <From />
    </Route>
    <Route path="/directory/:profession/:country/:value">
       <Name />
   </Route>
  </Switch>
</Router>

and a "From" component where paths and redirections are defined. If "redirectionPath" is not null you can return "Redirect" component in render. Thus, you can redirect to and render the Name component.

From.js

import React, {Component} from 'react';
import {
    Redirect
} from "react-router-dom";

class From extends Component {
    state={
        redirectionPath: "/directory/photography/france/testA" // or setState anywhere you need.
    }

    ...

    render(){
        if(this.state.path){
            return (<Redirect to={this.state.redirectionPath} />)
        }
        return (
            <SomeComponent/>
        );
    }
}

This can be one of the solutions. Hope it works for you as well.


问:
python - is there a way to use list comprehension to create a list based on the extracted common indexes of sublists?
I am trying to figure out a clean way to get the elements at the same index of each sublist and create a new list based on those extracted elements, so first I would like a sublist containing element 0 of each earlier sublist, then same the same for element 1, 2 etc. At the moment I am using the following code to get the results I want:

```<code>lst = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [True, True, False, True], [14.5, 15.6, 12.5, 12.3]]
approach_1 = []

for i, item in enumerate(lst[0]):
    approach_1.append([item, lst[1][i], lst[2][i], lst[3][i]])
</code>```

which gives me

```<code>approach_1 = [[1, 'a', True, 14.5], [2, 'b', True, 15.6], [3, 'c', False, 12.5], [4, 'd', True, 12.3]]
</code>```

The results are what I am looking for but is there a way for me to achieve this in one line? I am able to use the following for one element:

```<code>approach_2 = [x[0] for x in lst]
</code>```

Is there anything similar to this that would return the same results as approach_1?

Body:
I am trying to figure out a clean way to get the elements at the same index of each sublist and create a new list based on those extracted elements, so first I would like a sublist containing element 0 of each earlier sublist, then same the same for element 1, 2 etc. At the moment I am using the following code to get the results I want:

lst = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [True, True, False, True], [14.5, 15.6, 12.5, 12.3]]
approach_1 = []

for i, item in enumerate(lst[0]):
    approach_1.append([item, lst[1][i], lst[2][i], lst[3][i]])

which gives me

approach_1 = [[1, 'a', True, 14.5], [2, 'b', True, 15.6], [3, 'c', False, 12.5], [4, 'd', True, 12.3]]

The results are what I am looking for but is there a way for me to achieve this in one line? I am able to use the following for one element:

approach_2 = [x[0] for x in lst]

Is there anything similar to this that would return the same results as approach_1?

Body:
The built-in zip function does exactly what you want:

>>> lst = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [True, True, False, True], [14.5, 15.6, 12.5, 12.3]]
>>> list(zip(*lst))
[(1, 'a', True, 14.5), (2, 'b', True, 15.6), (3, 'c', False, 12.5), (4, 'd', True, 12.3)]


问:
Flutter apk builds, installs but then will not open
I'm attempting to create apk for my flutter app. It works when running flutter run on both emulator and device.

When running:
flutter build apk

Get success and apk. When copying apk to device it installs but then cannot be opened. (After install button to open is grayed out and finding app in app draw opens up the app info page). Have tired apk on multiple devices.

flutter run --release works

I've followed the steps to migrate to Androidx and have checked all packages build.gradle to ensure all are compileSdkVersion 28.

I've tried running on stable, master and beta flutter branch.

Running:
flutter build apk --release gives (on flutter beta branch)

```<code>You are building a fat APK that includes binaries for android-arm, android-arm64, android-x64.
If you are deploying the app to the Play Store, it's recommended to use app bundles or split the APK to reduce the APK size.
    To generate an app bundle, run:
        flutter build appbundle --target-platform android-arm,android-arm64,android-x64
        Learn more on: https://developer.android.com/guide/app-bundle
    To split the APKs per ABI, run:
        flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi
        Learn more on:  https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split
Running Gradle task 'assembleRelease'...                            2.8s
✓ Built build/app/outputs/flutter-apk/app-release.apk (21.2MB).
</code>```

EDIT:
The plot thickens xD. I can launch the app from deeplinks, but using the app icon always launches into settings.

答:
Turns out I had the package app availability installed which was using the compileSdkVersion of 27. Changing this to 28 in that package's build.gradle seemed to fix it.

The easiest solution was just to swap that package out.

Body:
I'm attempting to create apk for my flutter app. It works when running flutter run on both emulator and device.

When running:
flutter build apk

Get success and apk. When copying apk to device it installs but then cannot be opened. (After install button to open is grayed out and finding app in app draw opens up the app info page). Have tired apk on multiple devices.

flutter run --release works

I've followed the steps to migrate to Androidx and have checked all packages build.gradle to ensure all are compileSdkVersion 28.

I've tried running on stable, master and beta flutter branch.

Running:
flutter build apk --release gives (on flutter beta branch)

You are building a fat APK that includes binaries for android-arm, android-arm64, android-x64.
If you are deploying the app to the Play Store, it's recommended to use app bundles or split the APK to reduce the APK size.
    To generate an app bundle, run:
        flutter build appbundle --target-platform android-arm,android-arm64,android-x64
        Learn more on: https://developer.android.com/guide/app-bundle
    To split the APKs per ABI, run:
        flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi
        Learn more on:  https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split
Running Gradle task 'assembleRelease'...                            2.8s
✓ Built build/app/outputs/flutter-apk/app-release.apk (21.2MB).

EDIT:
The plot thickens xD. I can launch the app from deeplinks, but using the app icon always launches into settings.


问:
Drop down menu's in VSCode are black/blank
This is my first question on here, so I apologize if it's confusing or redundant. I'm doing research for one of my professors, and I'm having a really annoying problem on my Virtual Machine. I'm running Ubuntu 18.0.4 through virtual Box and VSCode's drop down menu's/right click menu's are black. The text is unreadable but I am able to click in the box  on whatever choice I'd be hovering over.

When I try to click on a drop down menu

When I right click on anything

I've tried updating to the most recent version of VSCode (January 2020) and a complete uninstall + reinstall. I haven't been able to find anyone online that's had the same problem as me either. Has anyone experienced this bug before? If so, have you been able to fix it?
Thank you.

答:
since other answers doesnt really looks to work, you just have to disable 3d acceleration in the vm settings.
If you have trouble running it, you should increase the ram and the num of processors.</p>


问:
Metadata file '.dll' could not be found
I am working on a WPF, C# 3.0 project, and I get this error:

```<code>Error 1 Metadata file
'WORK=- \Tools\VersionManagementSystem\BusinessLogicLayer\bin\Debug
\BusinessLogicLayer.dll' could not be found C:\-=WORK=- \Tools
\VersionManagementSystem\VersionManagementSystem\CSC VersionManagementSystem
</code>```

This is how I reference my usercontrols:

```<code>xmlns:vms="clr-namespace:VersionManagementSystem"
<vms:SignOffProjectListing Margin="5"/>
</code>```

It happens after every failed build. The only way I can get the solution to compile is to comment out all my user controls and re-build the project, and then I uncomment the usercontrols and everything is fine.

I have checked build orders and dependencies configurations.

As you can see, it seems to have truncated the DLL file's absolute path... I have read that there is a bug with the length. Is this a possible problem?

It's very annoying and having to comment, build, and uncomment, the build is becoming extremely tiresome.

答:
In VS 2019, under the project References check if there are any unresolved items by expanding Analyzers:

For me, there were two .dll files with wrong paths. Right click on each and select Remove:

Build the project, then build the solution.
Done.

Title: Metadata file '.dll' could not be found

Body:
I am working on a WPF, C# 3.0 project, and I get this error:

Error 1 Metadata file
'WORK=- \Tools\VersionManagementSystem\BusinessLogicLayer\bin\Debug
\BusinessLogicLayer.dll' could not be found C:\-=WORK=- \Tools
\VersionManagementSystem\VersionManagementSystem\CSC VersionManagementSystem

This is how I reference my usercontrols:

xmlns:vms="clr-namespace:VersionManagementSystem"
<vms:SignOffProjectListing Margin="5"/>

It happens after every failed build. The only way I can get the solution to compile is to comment out all my user controls and re-build the project, and then I uncomment the usercontrols and everything is fine.

I have checked build orders and dependencies configurations.

As you can see, it seems to have truncated the DLL file's absolute path... I have read that there is a bug with the length. Is this a possible problem?

It's very annoying and having to comment, build, and uncomment, the build is becoming extremely tiresome.


问:
ShedLock: Running multiple instances runs scheduler tasks multiple times
I am using Shedlock to run my scheduler task only once if multiple instances of the service are running.

I followed the documentation and this is what I did.

This is the function that needs to run periodically

```<code>@Scheduled(fixedDelayString = "300000")
@SchedulerLock(name = "onlineIngestionTask", lockAtMostFor = 240000, lockAtLeastFor = 240000)
public void pullTasksFromRemote() {
        //Code
}
</code>```

In my config class I have the following beans

```<code>@Bean
public ScheduledLockConfiguration taskScheduler(LockProvider lockProvider) {
    return ScheduledLockConfigurationBuilder
        .withLockProvider(lockProvider)
        .withPoolSize(10)
        .withDefaultLockAtMostFor(Duration.ofMinutes(10))
        .build();
}

@Bean
public LockProvider lockProvider(DataSource dataSource) {
    return new JdbcTemplateLockProvider(dataSource);
}
</code>```

The pom includes

```<code><dependency>
    <groupId>net.javacrumbs.shedlock</groupId>
    <artifactId>shedlock-spring</artifactId>
    <version>0.14.0</version>
</dependency>

<dependency>
    <groupId>net.javacrumbs.shedlock</groupId>
    <artifactId>shedlock-provider-jdbc-template</artifactId>
    <version>0.14.0</version>
</dependency>
</code>```

I added a table to my db, the one to which jdbc connects.

```<code>CREATE TABLE shedlock(
    name VARCHAR(64),
    lock_until TIMESTAMP(3) NULL,
    locked_at TIMESTAMP(3) NULL,
    locked_by  VARCHAR(255),
    PRIMARY KEY (name)
)
</code>```

After this I tried to test the functionality by running tha pp first on port 8080. Then I use server.port=9000 to run it again on port 9000. But both these instances start running the task. Am I missing something. Is something wrong in the implementation? Can someone give any ideas. Thanks !!

答:
we recently had this issue in prod where we could see multiple runs of shedlock schedulers. if you are using spring boot 2.2.1.RELEASE onwards then use below deps for shedlock</p>

```<code><dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
<version>4.9.3</version>
</dependency>

    <dependency>
        <groupId>net.javacrumbs.shedlock</groupId>
        <artifactId>shedlock-provider-redis-spring</artifactId>
        <version>4.8.0</version>
    </dependency>
</code>```

Body:
I am using Shedlock to run my scheduler task only once if multiple instances of the service are running.

I followed the documentation and this is what I did.

This is the function that needs to run periodically

@Scheduled(fixedDelayString = "300000")
@SchedulerLock(name = "onlineIngestionTask", lockAtMostFor = 240000, lockAtLeastFor = 240000)
public void pullTasksFromRemote() {
        //Code
}

In my config class I have the following beans

@Bean
public ScheduledLockConfiguration taskScheduler(LockProvider lockProvider) {
    return ScheduledLockConfigurationBuilder
        .withLockProvider(lockProvider)
        .withPoolSize(10)
        .withDefaultLockAtMostFor(Duration.ofMinutes(10))
        .build();
}

@Bean
public LockProvider lockProvider(DataSource dataSource) {
    return new JdbcTemplateLockProvider(dataSource);
}

The pom includes

<dependency>
    <groupId>net.javacrumbs.shedlock</groupId>
    <artifactId>shedlock-spring</artifactId>
    <version>0.14.0</version>
</dependency>

<dependency>
    <groupId>net.javacrumbs.shedlock</groupId>
    <artifactId>shedlock-provider-jdbc-template</artifactId>
    <version>0.14.0</version>
</dependency>

I added a table to my db, the one to which jdbc connects.

CREATE TABLE shedlock(
    name VARCHAR(64),
    lock_until TIMESTAMP(3) NULL,
    locked_at TIMESTAMP(3) NULL,
    locked_by  VARCHAR(255),
    PRIMARY KEY (name)
)

After this I tried to test the functionality by running tha pp first on port 8080. Then I use server.port=9000 to run it again on port 9000. But both these instances start running the task. Am I missing something. Is something wrong in the implementation? Can someone give any ideas. Thanks !!

Body:
we recently had this issue in prod where we could see multiple runs of shedlock schedulers. if you are using spring boot 2.2.1.RELEASE onwards then use below deps for shedlock

<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
<version>4.9.3</version>
</dependency>

    <dependency>
        <groupId>net.javacrumbs.shedlock</groupId>
        <artifactId>shedlock-provider-redis-spring</artifactId>
        <version>4.8.0</version>
    </dependency>


问:
Disable click listener for invisible viewgroup
I've a viewgroup which is View.INVISIBLE under some circumstances. In this state, i want the viewgroup or it's children views to NOT respond to any click events.

According to the default implementation of View.INVISIBLE in android, the child views inside the viewgroup are still clickable even when the viewgroup's visibility is invisible. I know i can set the visibility to View.GONE but i don't want the entire viewgroup to be removed.

I tried setting setClickable to true on the viewgroup but it didn't work and the child views are still responding to clicks. I don't want to iterate through all the views in the viewgroups and disable them individually as this is something that i've to do frequently.

Is there a better solution to prevent all the child views in the viewgroup from receiving click events?

答:
Have you tried setEnabled(false)?

If that doesn't work, you can set all view children to disabled like this:

```<code>LinearLayout layout = (LinearLayout) findViewById(R.id.my_layout);
for (int i = 0; i < layout.getChildCount(); i++) {
    View child = layout.getChildAt(i);
    child.setEnabled(false);
}
</code>```

Body:
Have you tried setEnabled(false)?

If that doesn't work, you can set all view children to disabled like this:

LinearLayout layout = (LinearLayout) findViewById(R.id.my_layout);
for (int i = 0; i < layout.getChildCount(); i++) {
    View child = layout.getChildAt(i);
    child.setEnabled(false);
}


问:
Flutter replace "," with "."
I have a TextField where I allow numbers like 1,4. I am trying ti replace the , to a . so the number will be 1.4.

I am trying this

```<code>double alphareceipe = double.parse(_alphareceipe.text);
    alphareceipe = alphareceipe.replace("," ".");

</code>```

But get this error:

error: The method 'replace' isn't defined for the class 'double'. (undefined_method at [brewingapp] lib/screens/calculator/alphaacid.dart:227).

The total code looks like this:

```<code>import 'package:flutter/material.dart';

import 'package:firebase_admob/firebase_admob.dart';
import 'package:brewingapp/app_localizations.dart';
import 'package:flutter/services.dart';
import 'package:devicelocale/devicelocale.dart';

const String testDevice = "Mobile_id";

class AlphaAcid extends StatefulWidget {
  @override
  _AlphaAcidState createState() => _AlphaAcidState();
}

class _AlphaAcidState extends State<AlphaAcid> {

  }

  String _emiResult = "";

  final TextEditingController _weight = TextEditingController();
  final TextEditingController _alphareceipe = TextEditingController();
  final TextEditingController _alphanew = TextEditingController();

  @override
  void initState() {

    initPlatformState();

    super.initState();
  }

  @override

  String _locale;

  Future<void> initPlatformState() async {

    String currentLocale;

    // Platform messages may fail, so we use a try/catch PlatformException.

    try {
      currentLocale = await Devicelocale.currentLocale;
      print(currentLocale);
    } on PlatformException {
      print("Error obtaining current locale");
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {

      _locale = currentLocale;
    });
  }

  @override

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(AppLocalizations.of(context).translate('Hopsalpha'),),
          backgroundColor: Colors.green[800],

          //elevation: 0.0,
        ),
        body: Center(
          child: Container(

            child: Column(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _alphareceipe,
                    decoration: InputDecoration(
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                        ),

                        filled: true,
                        fillColor: Colors.green[10],
                        labelText: _locale != 'da-DK'
                            ? "Alpha acid receipe"
                            : "Alpha syre opskrift",

                        labelStyle: TextStyle(color: Colors.green[800])
                    ),
                    keyboardType: TextInputType.numberWithOptions(decimal: true),

                    inputFormatters: <TextInputFormatter>[
//                      WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _alphanew,
                    decoration: InputDecoration(
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                      ),
                      filled: true,
                      fillColor: Colors.green[10],
                      //labelText: "Final Gravity (1018)",
                      labelText: _locale != 'da-DK'
                          ? "Your alpha acid"
                          : "Din alpha syre",
                      labelStyle: TextStyle(color: Colors.green[800]),

                    ),
                    keyboardType: TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: <TextInputFormatter>[
                      //WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _weight,
                    decoration: InputDecoration(
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                      ),
                      filled: true,
                      fillColor: Colors.green[10],
                      //labelText: "Final Gravity (1018)",
                      labelText: _locale != 'da-DK'
                          ? "Weight receipe"
                          : "Vægt i opskrift",
                      labelStyle: TextStyle(color: Colors.green[800]),

                    ),
                    keyboardType: TextInputType.number,
                    inputFormatters: <TextInputFormatter>[
                      WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Flexible(
                  fit: FlexFit.loose,
                  child: FlatButton(
                    onPressed: _handleCalculation,
                    //child: Text("Calculate"),
                    child: Text(AppLocalizations.of(context).translate('calculate'),),
                    color: Colors.green[600],
                    textColor: Colors.white,
                    padding: EdgeInsets.only(top: 10.0, bottom: 10.0, left: 24.0, right: 24.0),

                  ),

                ),

                emiResultsWidget(_emiResult)
              ],

            ),
          ),
        ));
  }

  void _handleCalculation() {

    double newWeight = 0.0;
//
//
//
//
//
    double alphareceipe = double.parse(_alphareceipe.text);
    alphareceipe = alphareceipe.replace("," ".");

    int alphanew =int.parse(_alphanew.text);
    int weightreceipe = int.parse(_weight.text);
//
    try {
      newWeight = (weightreceipe * alphareceipe) / alphanew;
      _emiResult =  newWeight.toStringAsFixed(0);

      setState(() {

      });

    } //catch(e) {
    on Exception catch(e){
      print(e);
      setState(() {

      });

    }

    //_emiResult =  A.toStringAsFixed(1);
    //setState(() {

    //});
  }

  Widget emiResultsWidget(emiResult) {

    bool canShow = false;
    String _emiResult = emiResult;

    if(_emiResult.length > 0) {
      canShow = true;
    }

    return

      Container(
        margin: EdgeInsets.only(top: 30.0, left: 20.0, right: 20.0),
        alignment: FractionalOffset.center,
        color: Colors.green[50],

        child: canShow ? Column(

            mainAxisAlignment: MainAxisAlignment.center,

            children: <Widget>[

              Row(
                //crossAxisAlignment: CrossAxisAlignment.start,
                //mainAxisAlignment: MainAxisAlignment.spaceEvenly,

                  children: <Widget> [
                    Padding(
                        padding: EdgeInsets.all(10.0),
                        child:

                        Text(AppLocalizations.of(context).translate('newweight'),
                          style: TextStyle(
                            fontSize: 20.0,
                            fontWeight: FontWeight.bold,
                            color: Colors.green[800],
                          ),

                        )
                    ),
                    SizedBox(width: 20.0,),

                    Text(_emiResult,
                        style: TextStyle(
                          fontSize: 20.0,
                          fontWeight: FontWeight.bold,
                          color: Colors.green[800],

                        )
                    ),
                    SizedBox(width: 10.0,),

                  ]),

            ]

        ) : Container(),
      );

  }

}
</code>```

答: You cannot use a String function on a double. Replace the symbol on the String, then cast to double.</p>

Title: Flutter replace "," with "."

Body:
I have a TextField where I allow numbers like 1,4. I am trying ti replace the , to a . so the number will be 1.4.

I am trying this

double alphareceipe = double.parse(_alphareceipe.text);
    alphareceipe = alphareceipe.replace("," ".");

But get this error:

error: The method 'replace' isn't defined for the class 'double'. (undefined_method at [brewingapp] lib/screens/calculator/alphaacid.dart:227).

The total code looks like this:

import 'package:flutter/material.dart';

import 'package:firebase_admob/firebase_admob.dart';
import 'package:brewingapp/app_localizations.dart';
import 'package:flutter/services.dart';
import 'package:devicelocale/devicelocale.dart';

const String testDevice = "Mobile_id";

class AlphaAcid extends StatefulWidget {
  @override
  _AlphaAcidState createState() => _AlphaAcidState();
}

class _AlphaAcidState extends State<AlphaAcid> {

  }

  String _emiResult = "";

  final TextEditingController _weight = TextEditingController();
  final TextEditingController _alphareceipe = TextEditingController();
  final TextEditingController _alphanew = TextEditingController();

  @override
  void initState() {

    initPlatformState();

    super.initState();
  }

  @override

  String _locale;

  Future<void> initPlatformState() async {

    String currentLocale;

    // Platform messages may fail, so we use a try/catch PlatformException.

    try {
      currentLocale = await Devicelocale.currentLocale;
      print(currentLocale);
    } on PlatformException {
      print("Error obtaining current locale");
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {

      _locale = currentLocale;
    });
  }

  @override

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(AppLocalizations.of(context).translate('Hopsalpha'),),
          backgroundColor: Colors.green[800],

          //elevation: 0.0,
        ),
        body: Center(
          child: Container(

            child: Column(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _alphareceipe,
                    decoration: InputDecoration(
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                        ),

                        filled: true,
                        fillColor: Colors.green[10],
                        labelText: _locale != 'da-DK'
                            ? "Alpha acid receipe"
                            : "Alpha syre opskrift",

                        labelStyle: TextStyle(color: Colors.green[800])
                    ),
                    keyboardType: TextInputType.numberWithOptions(decimal: true),

                    inputFormatters: <TextInputFormatter>[
//                      WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _alphanew,
                    decoration: InputDecoration(
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                      ),
                      filled: true,
                      fillColor: Colors.green[10],
                      //labelText: "Final Gravity (1018)",
                      labelText: _locale != 'da-DK'
                          ? "Your alpha acid"
                          : "Din alpha syre",
                      labelStyle: TextStyle(color: Colors.green[800]),

                    ),
                    keyboardType: TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: <TextInputFormatter>[
                      //WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _weight,
                    decoration: InputDecoration(
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                      ),
                      filled: true,
                      fillColor: Colors.green[10],
                      //labelText: "Final Gravity (1018)",
                      labelText: _locale != 'da-DK'
                          ? "Weight receipe"
                          : "Vægt i opskrift",
                      labelStyle: TextStyle(color: Colors.green[800]),

                    ),
                    keyboardType: TextInputType.number,
                    inputFormatters: <TextInputFormatter>[
                      WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Flexible(
                  fit: FlexFit.loose,
                  child: FlatButton(
                    onPressed: _handleCalculation,
                    //child: Text("Calculate"),
                    child: Text(AppLocalizations.of(context).translate('calculate'),),
                    color: Colors.green[600],
                    textColor: Colors.white,
                    padding: EdgeInsets.only(top: 10.0, bottom: 10.0, left: 24.0, right: 24.0),

                  ),

                ),

                emiResultsWidget(_emiResult)
              ],

            ),
          ),
        ));
  }

  void _handleCalculation() {

    double newWeight = 0.0;
//
//
//
//
//
    double alphareceipe = double.parse(_alphareceipe.text);
    alphareceipe = alphareceipe.replace("," ".");

    int alphanew =int.parse(_alphanew.text);
    int weightreceipe = int.parse(_weight.text);
//
    try {
      newWeight = (weightreceipe * alphareceipe) / alphanew;
      _emiResult =  newWeight.toStringAsFixed(0);

      setState(() {

      });

    } //catch(e) {
    on Exception catch(e){
      print(e);
      setState(() {

      });

    }

    //_emiResult =  A.toStringAsFixed(1);
    //setState(() {

    //});
  }

  Widget emiResultsWidget(emiResult) {

    bool canShow = false;
    String _emiResult = emiResult;

    if(_emiResult.length > 0) {
      canShow = true;
    }

    return

      Container(
        margin: EdgeInsets.only(top: 30.0, left: 20.0, right: 20.0),
        alignment: FractionalOffset.center,
        color: Colors.green[50],

        child: canShow ? Column(

            mainAxisAlignment: MainAxisAlignment.center,

            children: <Widget>[

              Row(
                //crossAxisAlignment: CrossAxisAlignment.start,
                //mainAxisAlignment: MainAxisAlignment.spaceEvenly,

                  children: <Widget> [
                    Padding(
                        padding: EdgeInsets.all(10.0),
                        child:

                        Text(AppLocalizations.of(context).translate('newweight'),
                          style: TextStyle(
                            fontSize: 20.0,
                            fontWeight: FontWeight.bold,
                            color: Colors.green[800],
                          ),

                        )
                    ),
                    SizedBox(width: 20.0,),

                    Text(_emiResult,
                        style: TextStyle(
                          fontSize: 20.0,
                          fontWeight: FontWeight.bold,
                          color: Colors.green[800],

                        )
                    ),
                    SizedBox(width: 10.0,),

                  ]),

            ]

        ) : Container(),
      );

  }

}


问:
How to start bar from 1 instead of 0 in Vega Lite?
I'm plotting the diff time series [1.1, 0.9, 1.2, ...].

And as the values are relative multipliers, the middle is 1 and not 0.

Is there a way to tell Vega Lite to start bar with 1?

So for the value 1.1 the bar will be start: 1, end: 1.1 and for 0.9 it will be start: 1, end: 0.9?

Body:
You can use a y2 encoding with datum set to 1. For example (vega editor):

{
  "data": {
    "values": [
      {"x": "A", "y": 0.9},
      {"x": "B", "y": 0.8},
      {"x": "C", "y": 1.1},
      {"x": "D", "y": 1.2},
      {"x": "E", "y": 0.9},
      {"x": "F", "y": 1.3}
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": {"type": "nominal", "field": "x"},
    "y": {
      "type": "quantitative",
      "field": "y",
      "scale": {"domain": [0.6, 1.4]}
    },
    "y2": {"datum": 1}
  }
}


问:
Python Application Assistance
The requirements of my project are as follows:

• Create a Python application that will loop between 1 and 100

• The numbers are to be printed out alongside their squared value

• The app should stop when a squared value of 200 or more is reached

• Reconfigure the application to take in a user value as desired.
For example, if you were to input the value 8 (DO NOT USE THIS VALUE), your
application would produce all squared values from 1 to 8.

This is what I have so far,

**def sq_nos(start, end):
    for i in range(start, end):
        j = i**2
        print(i, j)
        if j > 200:
            break
start = int(input("enter start: "))
end = int(input("enter end: "))
sq_nos(start, end)**

This code is still printing the square value of 255, any solutions?

Any other feedback would be appreciated too.

答:
I think you need to check and break before printing.
Try with this code.

```<code>def sq_nos(start, end):
    for i in range(start, end):
        j = i**2
        if j > 200:
            break
        print(i, j)

#start = int(input("enter start: "))
#end = int(input("enter end: "))
sq_nos(1, 100)
</code>```

and output is

```<code>1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
11 121
12 144
13 169
14 196
</code>```

Title: Python Application Assistance

Body:
I think you need to check and break before printing.
Try with this code.

def sq_nos(start, end):
    for i in range(start, end):
        j = i**2
        if j > 200:
            break
        print(i, j)

#start = int(input("enter start: "))
#end = int(input("enter end: "))
sq_nos(1, 100)

and output is

1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
11 121
12 144
13 169
14 196


问:
ViewFactory iphone
Has anyone successfully used this class to load custom tableViewCells. I have tried to create a singleton of the viewFactory class and load the cells using the shared instance but I get the following error...

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[ViewFactory sharedMyClassName]: unrecognized selector sent to class 0x32a24'

I am using this macro to create the singleton, and following the tutorial here Anyone had any experience with this before? I realise this may be a longshot but if anyone has ever used it then please let me know.

Many thanks

Jules

答: The define creates a method called sharedViewFactory and not sharedMyClassName. It depends on the class name you pass to it. shared is prepended to the class name. So all ##classname will be replaced by ViewFactory.

Title: ViewFactory iphone


问:
Is it possible to use Docusign Gen in a custom apex button?
Docusign Gen works great for generating a document, but it won't let me set new defaults for the email messsages or signing order. With APEX custom coding these are possible to set, but i'm not sure if it's possible to have the docusign gen part run first, then send out the documents with the right email messaging and signing order.</p>

答:
This is not yet possible, but we do hope to have this capability in the future.
While I cannot promise any dates, I'll be sure to update this post when I have more information.</p>


问:
Secure authentication structure in a React Webapp
I am currently learning React and worked through some courses but still haven't completely understood how to create a proper structure for a secure web app.

For the sign in, sign up flow I use the firebase SDK. Once logged in, a user gets redirected to a private route. Right now I only have 2 user roles. Guests and signed in Users. This enables me to create private routes by using an inbuild firebase function. This is the first problem as it is not scalable once I add different roles as it would force me to send a request to the backend to check what role the user is and thus which pages he can acces.

```<code>if (firebase.auth().currentUser === null) {
        console.log("not logged in")
        return     (<Redirect
            to={{
              pathname: "/signin",
              state: {
                from: props.location
              }
            }}
          />);

    }
</code>```

So I thought that the easiest option would be to use Context, which did work. Once a user loggs in, the server sends a user object which the app refers to for the rest of the session. I followed a bunch of tutorials and they all had the same problem that when using chrome developer tools with the react features, you could just edit the state of the user and bypass the private routes etc.

Second Try:

```<code><UserContext.Consumer>{(context)=>{
          const {isLoggedIn} = context
          return(
        <Route
          {...rest}
          render={props => {

        if (isLoggedIn) {
            console.log("not logged in")
            return     (<Redirect
                to={{
                  pathname: "/signin",
                  state: {
                    from: props.location
                  }
                }}
              />);
</code>```

I'd be grateful if somebody could point me in a direction as it seems like I am missing something important.

EDIT 1: Or is it simply that once you build the app, you can no longer access these states and it's considered safe?

答:
when using chrome developer tools with the react features, you could just edit the state of the user and bypass the private routes

Your routes will never be truly private. They are part of the JavaScript bundle that gets downloaded and rendered by the browser, so they should never contain anything secret. Anyone could read this code if they really wanted to.

Consider this:

if (loggedIn) {
  return
Secret data: ABC
;
}
```

<p>The string "ABC" is contained in your app build, and is not really a secret anymore. The average user wouldn't know how to obtain it, but a developer probably would, for example by toggling some state in the developer console.</p>

<p>However, the data that comes from Firestore (or any another backend service) should be properly protected. Permission checks are done <em>server-side</em> before this data is sent to the browser. So, unless the user has the required permissions, the data will never be exposed to the wrong person, even if someone tampers with your client-side code in the developer console.</p>

<pre class="lang-js prettyprint-override"><code>if (loggedIn) {
  fetchDataFromBackend();
}
</code>```

It doesn't matter if someone changes loggedIn to true so that fetchDataFromBackend() is called; the server will make sure the data isn't returned unless the user has the proper permission (e.g. is logged in). In the case of Firebase (Firestore), this protection is achieved with Security Rules.

And, by the way, the recommended way to get the current user with Firebase is to add a listener to the Auth object:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});
```

You could put this in a top-level component and share the user object with child components through a context. That way you don't have to call firebase.auth() all over the place. Here's a good starting point if you need some inspiration: https://usehooks.com/useAuth/

Body:
I am currently learning React and worked through some courses but still haven't completely understood how to create a proper structure for a secure web app.

For the sign in, sign up flow I use the firebase SDK. Once logged in, a user gets redirected to a private route. Right now I only have 2 user roles. Guests and signed in Users. This enables me to create private routes by using an inbuild firebase function. This is the first problem as it is not scalable once I add different roles as it would force me to send a request to the backend to check what role the user is and thus which pages he can acces.

if (firebase.auth().currentUser === null) {
        console.log("not logged in")
        return     (<Redirect
            to={{
              pathname: "/signin",
              state: {
                from: props.location
              }
            }}
          />);

    }

So I thought that the easiest option would be to use Context, which did work. Once a user loggs in, the server sends a user object which the app refers to for the rest of the session. I followed a bunch of tutorials and they all had the same problem that when using chrome developer tools with the react features, you could just edit the state of the user and bypass the private routes etc.

Second Try:

<UserContext.Consumer>{(context)=>{
          const {isLoggedIn} = context
          return(
        <Route
          {...rest}
          render={props => {

        if (isLoggedIn) {
            console.log("not logged in")
            return     (<Redirect
                to={{
                  pathname: "/signin",
                  state: {
                    from: props.location
                  }
                }}
              />);

I'd be grateful if somebody could point me in a direction as it seems like I am missing something important.

EDIT 1: Or is it simply that once you build the app, you can no longer access these states and it's considered safe?

Body:
when using chrome developer tools with the react features, you could just edit the state of the user and bypass the private routes

Your routes will never be truly private. They are part of the JavaScript bundle that gets downloaded and rendered by the browser, so they should never contain anything secret. Anyone could read this code if they really wanted to.

Consider this:

if (loggedIn) {
  return <div>Secret data: ABC</div>;
}

The string "ABC" is contained in your app build, and is not really a secret anymore. The average user wouldn't know how to obtain it, but a developer probably would, for example by toggling some state in the developer console.

However, the data that comes from Firestore (or any another backend service) should be properly protected. Permission checks are done server-side before this data is sent to the browser. So, unless the user has the required permissions, the data will never be exposed to the wrong person, even if someone tampers with your client-side code in the developer console.

if (loggedIn) {
  fetchDataFromBackend();
}

It doesn't matter if someone changes loggedIn to true so that fetchDataFromBackend() is called; the server will make sure the data isn't returned unless the user has the proper permission (e.g. is logged in). In the case of Firebase (Firestore), this protection is achieved with Security Rules.

And, by the way, the recommended way to get the current user with Firebase is to add a listener to the Auth object:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

You could put this in a top-level component and share the user object with child components through a context. That way you don't have to call firebase.auth() all over the place. Here's a good starting point if you need some inspiration: https://usehooks.com/useAuth/


问:
List all posts in custom post type by taxonomy not working
I am trying to get a list of all the posts in custom post type by taxonomy, I am stuck 3 days at this code, now i study with my father and he gave me a hint why my code is'nt working he a said i have too many args i will show you the code i hope anyone can help me understand why its not working and maybe if you really kind a explanation of the code in english </p>

```<code>print_r(Array(
    "1"=>"first",
    "2"=>"second"
    ));
// just try to remove args that you don't need
//actually you need only one
$args = array(
    'tax_query' => array(
            'taxonomy' => 'your-custom-taxonomy',
            'field' => 'slug',
            'terms' => array( 'your-term' )
    ),
    'post_type' => 'your-post-type'
);
$loop = new WP_Query($args);
     if($loop->have_posts()) {
    $term = $wp_query->queried_object;
     while($loop->have_posts()) : $loop->the_post();
        //Output what you want
   echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
      endwhile;
}
</code>```

答:
So you have a custom post type called your-post-type

and you have a custom taxonomy called your-custom-taxonomy and you

want to get all the posts with a taxonomy term set called your-term.

You are doing it the right way with setting your arguments.

Notice: If you want to get all the posts of a custom post type, you do not need the whole 'tax_query' part of code.

I added some comments to describe what the code is doing:

```<code>$args = array( // define your arguments for query
    'post_type' => 'your-post-type', // standard post type is 'post', you use a custom one
    'tax_query' => array( // you check for taxonomy field values
        array(
            'taxonomy' => 'your-custom-taxonomy', // standard is 'category' you use a custom one
            'field'    => 'slug', // you want to get the terms by its slug (could also use id)
            'terms'    => 'your-term', // this is the taxonomy term slug the post has set
        ),
    ),
);
$loop = new WP_Query( $args ); // get post objects

// The Loop
if ( $loop ->have_posts() ) { // check if you received post objects
    echo "<ul>"; // open unordered list
    while ( $loop ->have_posts() ) { // loop through post objects
        $loop ->the_post();
            echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>'; // list items
    }
    echo "</ul>"; // close unordered list
    /* Restore original Post Data */
    wp_reset_postdata(); // reset to avoid conflicts
} else {
    // no posts found
}
</code>```

Hope this helps!

EDIT: If you do not know how to use WP_Query

This code will get your wordpress posts ordered by their titles and output title and content. Put this inside a template file of your theme (learn something about template files: https://developer.wordpress.org/themes/basics/template-hierarchy/).

```<code><?php

$args = array(
 'post_type' => 'post',
 'posts_per_page' => -1, // limit the number of posts if you like to
 'orderby' => 'title',
 'order' => 'ASC'
);

$custom_query = new WP_Query($args);

if ($custom_query->have_posts()) : while($custom_query->have_posts()) : $custom_query->the_post(); ?>
  <h1><?php the_title(); ?></h1>
  <?php the_content();?>
<?php endwhile; else : ?>
  <p>No posts</p>
<?php endif; wp_reset_postdata(); ?>
</code>```

You said you want to use a custom post type and do a taxonomy query. So you can adjust this with changing the arguments in $args.

Body:
I am trying to get a list of all the posts in custom post type by taxonomy, I am stuck 3 days at this code, now i study with my father and he gave me a hint why my code is'nt working he a said i have too many args i will show you the code i hope anyone can help me understand why its not working and maybe if you really kind a explanation of the code in english

print_r(Array(
    "1"=>"first",
    "2"=>"second"
    ));
// just try to remove args that you don't need
//actually you need only one
$args = array(
    'tax_query' => array(
            'taxonomy' => 'your-custom-taxonomy',
            'field' => 'slug',
            'terms' => array( 'your-term' )
    ),
    'post_type' => 'your-post-type'
);
$loop = new WP_Query($args);
     if($loop->have_posts()) {
    $term = $wp_query->queried_object;
     while($loop->have_posts()) : $loop->the_post();
        //Output what you want
   echo '
'.get_the_title().'
';
      endwhile;
}

Body:
So you have a custom post type called your-post-type

and you have a custom taxonomy called your-custom-taxonomy and you

want to get all the posts with a taxonomy term set called your-term.

You are doing it the right way with setting your arguments.

Notice: If you want to get all the posts of a custom post type, you do not need the whole 'tax_query' part of code.

I added some comments to describe what the code is doing:

$args = array( // define your arguments for query
    'post_type' => 'your-post-type', // standard post type is 'post', you use a custom one
    'tax_query' => array( // you check for taxonomy field values
        array(
            'taxonomy' => 'your-custom-taxonomy', // standard is 'category' you use a custom one
            'field'    => 'slug', // you want to get the terms by its slug (could also use id)
            'terms'    => 'your-term', // this is the taxonomy term slug the post has set
        ),
    ),
);
$loop = new WP_Query( $args ); // get post objects

// The Loop
if ( $loop ->have_posts() ) { // check if you received post objects
    echo "<ul>"; // open unordered list
    while ( $loop ->have_posts() ) { // loop through post objects
        $loop ->the_post();
            echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>'; // list items
    }
    echo "</ul>"; // close unordered list
    /* Restore original Post Data */
    wp_reset_postdata(); // reset to avoid conflicts
} else {
    // no posts found
}

Hope this helps!

EDIT: If you do not know how to use WP_Query

This code will get your wordpress posts ordered by their titles and output title and content. Put this inside a template file of your theme (learn something about template files: https://developer.wordpress.org/themes/basics/template-hierarchy/).

<?php

$args = array(
 'post_type' => 'post',
 'posts_per_page' => -1, // limit the number of posts if you like to
 'orderby' => 'title',
 'order' => 'ASC'
);

$custom_query = new WP_Query($args);

if ($custom_query->have_posts()) : while($custom_query->have_posts()) : $custom_query->the_post(); ?>
  <h1><?php the_title(); ?></h1>
  <?php the_content();?>
<?php endwhile; else : ?>
  <p>No posts</p>
<?php endif; wp_reset_postdata(); ?>

You said you want to use a custom post type and do a taxonomy query. So you can adjust this with changing the arguments in $args.


问:
Yield Google Tag Manager snippet in  in EmberJS
I have several Ember projects under the same repo and would like to be able to reuse the GTM snippet across all of their .html files.

```<code><!DOCTYPE html>
<html lang="en">
  <head>

    {{content-for "head"}}

    <link rel="stylesheet" href="assets/employer-vendor.css">
    <link rel="stylesheet" href="assets/employer.css">
  </head>
  <body>
  </body>
</html>
</code>```

Should I use ember-cli-meta-tags, ember-cli-inline-content or similar? In order to have the snippet reusable, it will have to be stored not in ember-cli-build.js, since that's within a specific project, but in a shared folder across the board.

答:
This is a great use case for writing an Ember Addon.

Ember Addon allow you to customize the build pipeline. They provide some hooks to do so. These hooks must be implemented in index.js file of the addon. The syntax of that file is a little bit uncommon these days. It's very old and hasn't be modernized yet. There is an ongoing initiative to replace it with a new format but that's not stable yet.

The hook you are looking for is contentFor. It allows you to inject content into the {{content-for}} placeholders in app/index.html (and tests/index.html). The hook gets the type as the first argument, which maps to the first argument for {{content-for}}. The second and third argument gives you access to the configuration and the existing content but both is not needed for your use case. You should return the HTML, which should be injected at this hook, from it.

Using the hook for your use case might look like this:

// index.js

'use strict';

module.exports = {
  name: require('./package').name,

  contentFor(type) {
    if (type === "head") {
      return "a string with Google Tag Manager snippet";
    }
  }
};
```

You can implement that addon as in-repo addon and later extract it into a standalone package for reusing across multiple apps.

Title: Yield Google Tag Manager snippet in <head> in EmberJS

Body:
I have several Ember projects under the same repo and would like to be able to reuse the GTM snippet across all of their .html files.

<!DOCTYPE html>

    {{content-for "head"}}

    <link rel="stylesheet" href="assets/employer-vendor.css">
    <link rel="stylesheet" href="assets/employer.css">

Should I use ember-cli-meta-tags, ember-cli-inline-content or similar? In order to have the snippet reusable, it will have to be stored not in ember-cli-build.js, since that's within a specific project, but in a shared folder across the board.

Body:
This is a great use case for writing an Ember Addon.

Ember Addon allow you to customize the build pipeline. They provide some hooks to do so. These hooks must be implemented in index.js file of the addon. The syntax of that file is a little bit uncommon these days. It's very old and hasn't be modernized yet. There is an ongoing initiative to replace it with a new format but that's not stable yet.

The hook you are looking for is contentFor. It allows you to inject content into the {{content-for}} placeholders in app/index.html (and tests/index.html). The hook gets the type as the first argument, which maps to the first argument for {{content-for}}. The second and third argument gives you access to the configuration and the existing content but both is not needed for your use case. You should return the HTML, which should be injected at this hook, from it.

Using the hook for your use case might look like this:

// index.js

'use strict';

module.exports = {
  name: require('./package').name,

  contentFor(type) {
    if (type === "head") {
      return "a string with Google Tag Manager snippet";
    }
  }
};

You can implement that addon as in-repo addon and later extract it into a standalone package for reusing across multiple apps.


问:
Python/GAE social network / cms?
After much research, I've come up with a list of what I think might be the best way of putting together a Python based social network/cms, but have some questions about how some of these components fit together.

Before I ask about the particular components, here are some of the key features of the site to be built:

a modern almost desktop-like gui

future ability to host an advanced html5 sub-application (ex.http://www.lucidchart.com)

high scalability both for functionality and user load

user ability to password protect and permission manage content on per item/group basis

typical social network features

ability to build a scaled down mobile version in the future

Here's the list of tools I'm considering using:

Google App Engine

Python
Django
Pinax
Pyjamas
wxPython

And the questions:

Google App Engine -- this is an attempt to cut to the chase as many pieces of the puzzle seem to be in place.
Question: Am I limiting my options with this choice? Example: datastore not being relational? Should I wait
for SQL support under the Business version?

Python -- I considered 'drupal' at first, but in the end decided that being dependent on modules that may or
may not exist tomorrow + limitations of its templating system are a no-no. Learning its API, too, would be useless elsewhere
whereas Python seems like a swiss army knife of languages -- good for almost anything.
Question: v.2.5.2 is required by GAE, but python.org recommends 2.5.5. Which do I install?

Django -- v.0.96 is built into GAE. You seem to be able to upgrade it.
Questions: Any reason not to upgrade to the latest version? Ways to get around the lack of HTML5 support?

Pinax (http://pinaxproject.com) Rides on top of Django and appears to provide most of the social network functionality
anyone would want.
Question:  Reasons NOT to use it? Alternatives?

Pyjamas and wxPython -- this is the part that gets a little confusing. The basic idea behind these is the ability
to build a GUI. I've considered Silverlight and Flash, before the GAE/Python route, but a few working versions of
HTML5 apps convinced me that enough of it ALREADY runs on the latest batch of browsers to chose the HTML5/Javascript
route instead.
Question: How do I extend/supplement Python/Django to build an app-like HTML5 interface? Are Pyjamas and wxPython
the way to go? Or should I change my thinking completely?

Answers to some/any of these questions would be of great help. Please excuse my ignorance if any of this doesn't make much sense.
My last venture into web programming was a decent sized LAMP website some 5-6 years ago.  On the desktop side of things,
my programming experience boils down to very high level scripting languages that I keep on learning to accomplish very specific
tasks :)

答:
As someone who has deployed a Django site to GAE, I can tell you that you are not going to reach the ideal solution. Django on GAE misses some of the best aspects of Django because the ORM doesn't work right. The best compromise may be to use Django-nonrel to add the features back in.

This introduces it's own problems though: because of the large number of files and memory used by a Django app you're code will be unloaded from memory quickly after the app becomes idle. That means that visitors will frequently hit an approximately 6 second delay on the first page view after the site's code has been unloaded from memory while GAE uncompresses the zipped modules. Once your site is busy this won't be a problem, but while your site is still young and unknown it will cause the appearance of performance problems. :-(

Second, I've also worked for a company that built a custom CMS and can tell you that the first 80% is pretty easy, especially with modern frameworks. However, the rest can be quite challenging. For example, user roles and custom content types are two challenging aspects. Therefore strongly consider standing on the backs of giants and finding a CMS or CMS framework that almost perfectly meets your needs and then extend it to do that extra bit you need.

So, that said, answering your points:

Yes, you're limiting your options but that may be OK. Most developers are more comfortable with the relational model than the nosql model. Therefore more open source software is built with it in mind. Also, GAE is a closed source platform which is also a deterrent to open source developers. App Engine Oil is a CMS framework that may suit you well and is optimized for App Engine. Also look at web2py which has support for GAE.

I've found myself to be extremely productive with Python. I used to write a lot of PHP now I find it ugly. That said, think about the total line count of code you'll have to write. If you can make Drupal work with high quality pre-made modules you may find yourself only needing 1/10th of the code. By the way, the trick with Drupal is to mainly use only high quality modules. Look at the history, make sure not to use development versions. Try to contact the authors on IRC. I'm not saying you should use Drupal but it is possible to have a reliable site with it (for example, whitehouse.gov)

You're in the classic GAE/Django problem. If you use 0.96 you get great performance but you miss a lot of the great 1.0+ features and you don't get the ORM and all of it's benefits. If you use a newer version of Django you get the performance/memory problems mentioned above.

I'm about to investigate pinax for my company. I've done a very cursor glance at it. I don't know if it has good support for non relational model backends. You'll probably need to look at django-nonrel. However know that you're going to be investing in relatively untried solutions here. A small percentage of Django users use Pinax and an even smaller percentage, if any, use it on a nonrelational backend. Therefore you're going to be in the highly experimental scenario you mentioned in point 2 above.

I can't offer personal experience on it. I've investigated pyjamas a few times.  However I like writing HTML CSS and JS. I like to have control. I like progressive enhancement and knowing what users will see if they don't have the full capabilities. Also, I think any new app that doesn't explicitly address mobile clients is implicitly shooting themself in the foot. As many as 15% of Internet users only use the Internet via their smart phone. What kind of experience will they get with pyjamas?

You didn't mention this, but one thing I consider when choosing a platform is vendor lockin and portability. If you develop your solution for GAE and find that you're not able to do what you want, will you be able to port it to another solution elsewhere? How much work will it take? If you code heavily for GAE or make commitments to its architecture, you're stuck with it or with rewriting to move. Using Django or Web2py can help mitigate this.

That said, the big benefit of Python GAE is that you get to be very productive, see your results instantly, get hosting for free while your site is small and get excellent scalability. These are not small things. There is great value there.

Title: Python/GAE social network / cms?


问:
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32)
I am creating a store procedure but while executing the procedure i am getting the particular error.

Msg 217, Level 16, State 1, Procedure SendMail_Renewapp, Line 77
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).

Can anyone please help me out from this problem.

My procedure is as follows..

```<code>`ALTER PROCEDURE [dbo].[SendMail_Renewapp]
-- Add the parameters for the stored procedure here

AS
BEGIN
declare @xml nvarchar(max)
declare @body nvarchar(max)
declare @currentdate datetime;
declare @ExpDate datetime;
declare @mailsendingdate datetime;
declare @renewtime varchar(10);
    DECLARE @AgencyId int;
DECLARE @ApplicationID int;
declare @emailid varchar(100);

set @currentdate=getdate();

                --Fetching the application details: start--
                DECLARE AppCursor CURSOR FOR
                Select top 5 applications.ap_id,applications.ap_expiry_date,agency.ag_co_email from applications  join agency on applications.ap_agency_id=agency.ag_id
                 where ap_status='AS' and ap_iame_flag='IA' and ap_expiry_date != ''
                    OPEN AppCursor
                    FETCH NEXT FROM AppCursor INTO @ApplicationID,@ExpDate,@emailid

                    WHILE @@FETCH_STATUS = 0
                    BEGIN

                     SET @renewtime = ABS(DATEDIFF(day, @currentdate, @ExpDate))
                            if(@renewtime=180)

                                BEGIN

                                    --SET @xml = CAST(( SELECT [ag_id] AS 'td','',[ag_name] AS 'td','',[ag_co_email] AS 'td','',[ag_mobile] AS 'td'FROM  beesl.dbo.Agency where @renewtime < 180
--FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))

SET @body ='<html>
<body>
   <div>
<div>
<H3>Agencies Details whose payment are still pending for last 3 months</H3>
</div>
<table cellpadding="4" cellspacing="1" bgcolor=#FFFFFF   border=1 rules=none frame=box  >
<tr  >
<th style=border:1px solid #000000;  align=left bgcolor=#c2c2c2> Agency ID </th>
 <th style=border:1px solid #000000;  align=left bgcolor=#c2c2c2> Agency Name </th>
<th style=border:1px solid #000000;   align=left bgcolor=#c2c2c2> Agency Email </th>
<th style=border:1px solid #000000;   align=left bgcolor=#c2c2c2> Contact Number </th>

</tr>'
    SET @body = @body + @xml +'</table></div></body></html>'

EXEC msdb.dbo.sp_send_dbmail
@profile_name='BEE',
@recipients='emailid@emailid.com',
@subject='Renew Applications',
--@file_attachments = 'D:\beelogo.png',
@importance= High,
--@body = 'Testing'
@body = @body,
@body_format ='HTML';

                                END

                    FETCH NEXT FROM AppCursor INTO      @ApplicationID,@ExpDate,@emailid
                END
                    CLOSE AppCursor
                    DEALLOCATE AppCursor
                --Fetching the application details: end--

  END`
</code>```

答: My problem is with a stored procedure, not a trigger, and no cursor. An EXEC command within the procedure is the reason as other answers pointed out. But I can't add GO anywhere before the EXEC command with SSMS v18.5. It gives me an error. Turns out the procedure nested inside has its own TRY/CATCH block. Adding GO at the end of that procedure doesn't solve the problem. I had to remove the TRY/CATCH block there to make it works. Not sure this is just me or it can be helpful to others.

Body:
I am creating a store procedure but while executing the procedure i am getting the particular error.

Msg 217, Level 16, State 1, Procedure SendMail_Renewapp, Line 77
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).

Can anyone please help me out from this problem.

My procedure is as follows..

`ALTER PROCEDURE [dbo].[SendMail_Renewapp]
-- Add the parameters for the stored procedure here

AS
BEGIN
declare @xml nvarchar(max)
declare @body nvarchar(max)
declare @currentdate datetime;
declare @ExpDate datetime;
declare @mailsendingdate datetime;
declare @renewtime varchar(10);
    DECLARE @AgencyId int;
DECLARE @ApplicationID int;
declare @emailid varchar(100);

set @currentdate=getdate();

                --Fetching the application details: start--
                DECLARE AppCursor CURSOR FOR
                Select top 5 applications.ap_id,applications.ap_expiry_date,agency.ag_co_email from applications  join agency on applications.ap_agency_id=agency.ag_id
                 where ap_status='AS' and ap_iame_flag='IA' and ap_expiry_date != ''
                    OPEN AppCursor
                    FETCH NEXT FROM AppCursor INTO @ApplicationID,@ExpDate,@emailid

                    WHILE @@FETCH_STATUS = 0
                    BEGIN

                     SET @renewtime = ABS(DATEDIFF(day, @currentdate, @ExpDate))
                            if(@renewtime=180)

                                BEGIN

                                    --SET @xml = CAST(( SELECT [ag_id] AS 'td','',[ag_name] AS 'td','',[ag_co_email] AS 'td','',[ag_mobile] AS 'td'FROM  beesl.dbo.Agency where @renewtime < 180
--FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))

SET @body ='

Agencies Details whose payment are still pending for last 3 months

 Agency ID
  Agency Name
 Agency Email
 Contact Number

'
    SET @body = @body + @xml +'

'

EXEC msdb.dbo.sp_send_dbmail
@profile_name='BEE',
@recipients='emailid@emailid.com',
@subject='Renew Applications',
--@file_attachments = 'D:\beelogo.png',
@importance= High,
--@body = 'Testing'
@body = @body,
@body_format ='HTML';

                                END

                    FETCH NEXT FROM AppCursor INTO      @ApplicationID,@ExpDate,@emailid
                END
                    CLOSE AppCursor
                    DEALLOCATE AppCursor
                --Fetching the application details: end--

  END`