问:
GraphQL: field.resolve() result is undefined inside directive
I've been following all the results I found on Google on how to make an AuthDirective but I can't make it work.

I'll leave all the files to see if I'm making an error on the implementation but I guess not because I tested even without having any conditions inside the field.resolve.

One particular thing I found is that field.resolve, comes with 4 args, the first of them is always undefined, not sure if that could be it but just as an additional tip.

So here's the code:

This is a part of my typedefs

```<code>directive @isAuthenticated on FIELD_DEFINITION

scalar Date

type User {
    id: ID,
    name: String
    email: String
    password: String
    createdAt: Date
}

type Token {
    token: String
}

# IF I REMOVE @isAuthenticated this works!
type Query {
    user(name: String): User! @isAuthenticated
    users: [User!]! @isAuthenticated
}

type Mutation {
    createUser(name: String, email: String, password: String): Boolean!
    login(email: String!, password: String!): Token!
}
</code>```

Here is my schema:

```<code>import path from 'path';
import { makeExecutableSchema } from 'graphql-tools';
import { fileLoader, mergeResolvers, mergeTypes } from 'merge-graphql-schemas';
import schemaDirectives from './Directives';

const typedefsArray = fileLoader(path.join(__dirname, './**/*.graphql'));
const resolversArray = fileLoader(path.join(__dirname, './**/*.resolvers.ts'));

const typeDefs = mergeTypes(typedefsArray);
const resolvers = mergeResolvers(resolversArray);
const schema = makeExecutableSchema({ typeDefs, resolvers, schemaDirectives });

export default schema;
</code>```

Here is my AuthDirective

```<code>import { defaultFieldResolver } from 'graphql';
import { AuthenticationError, SchemaDirectiveVisitor } from 'apollo-server-express';

class AuthDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field: any) {
    const { resolver = defaultFieldResolver } = field;

    field.resolve = async function (...args: any) {
      const [_, __, context] = args;
      const { req } = context;
      const accessToken = req.headers.authorization
        ? req.headers.authorization.replace('Bearer ', '')
        : null;

      if (accessToken) {
        // here I was doing jwt.verify(accessToken) but I removed it for now to simplify
        const result = await resolver.apply(this, args);
        return result; // <--- THIS IS ALWAYS UNDEFINED
      } else {
        throw new AuthenticationError('Unauthorized field');
      }
    };
  }
}

export default AuthDirective;
</code>```

which lives under ./Directives and is being exported from an index as:

```<code>import AuthDirective from './auth';

export default {
  isAuthenticated: AuthDirective
}
</code>```

Finally my user resolver. Like I said before, if I remove the directive from the user graphql query its working as it should:

```<code>import jwt from 'jsonwebtoken';
import { AuthenticationError, UserInputError } from 'apollo-server-express';
import { IUser } from './IUser';
import UserModel from './user.schema';
import { Config } from '../../config';

const { APP_SECRET } = Config;

const createToken = async (user: IUser, secret: string, expiresIn: string) => {
  const { id, email, name } = user;
  return jwt.sign({ id, email, name }, secret, { expiresIn });
};

const userResolvers = {
  Query: {
    user: (_: any, { name }: { name: string }) => UserModel.findOne({ name }).exec(),
    users: () => UserModel.find({}).exec()
  },
  Mutation: {
    createUser: async (_: any, args: IUser) => {
      await new UserModel(args).save();
      return true;
    },
    login: async (_: any, { email, password }: IUser) => {
      const user = await UserModel.findOne({ email }).exec();

      if (!user) {
        throw new UserInputError('No user found with this login credentials.');
      }

      const isValid = await user.validatePassword(password);

      if (!isValid) {
        throw new AuthenticationError('Invalid password.');
      }

      return { token: createToken(user, APP_SECRET, '30m') };
    }
  }
};

export default userResolvers;
</code>```

and my server:

```<code>import morgan from 'morgan';
import express from 'express';
import bodyParser from 'body-parser';
import compression from 'compression';
import depthLimit from 'graphql-depth-limit';
import { ApolloServer } from 'apollo-server-express';

import { Config, DBConfig } from './config';
import schema from './domain';
const { PORT } = Config;

const app = express();

const apolloServer = new ApolloServer({
  schema,
  validationRules: [depthLimit(7)],
  context: ({ req, res }: any) => ({ req, res })
});

app.use(express.json());
app.use(compression());
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({ extended: true }));
apolloServer.applyMiddleware({ app });

DBConfig.init();

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

</code>```

答:
There is no resolver property on field, so this

```<code>const { resolver = defaultFieldResolver } = field;
</code>```

will always result in resolver having the value of defaultFieldResolver. If you're using the directive on some field that had a custom resolver, that custom resolver is never being called -- only the default behavior is used, which could indeed return undefined.

You need to make sure you're using the correct property:

```<code>const { resolve = defaultFieldResolver } = field;
</code>```

or you can rename the resulting variable when you destructure field:

```<code>const { resolve: resolver = defaultFieldResolver } = field;
</code>```

Body:
I've been following all the results I found on Google on how to make an AuthDirective but I can't make it work.

I'll leave all the files to see if I'm making an error on the implementation but I guess not because I tested even without having any conditions inside the field.resolve.

One particular thing I found is that field.resolve, comes with 4 args, the first of them is always undefined, not sure if that could be it but just as an additional tip.

So here's the code:

This is a part of my typedefs

directive @isAuthenticated on FIELD_DEFINITION

scalar Date

type User {
    id: ID,
    name: String
    email: String
    password: String
    createdAt: Date
}

type Token {
    token: String
}

# IF I REMOVE @isAuthenticated this works!
type Query {
    user(name: String): User! @isAuthenticated
    users: [User!]! @isAuthenticated
}

type Mutation {
    createUser(name: String, email: String, password: String): Boolean!
    login(email: String!, password: String!): Token!
}

Here is my schema:

import path from 'path';
import { makeExecutableSchema } from 'graphql-tools';
import { fileLoader, mergeResolvers, mergeTypes } from 'merge-graphql-schemas';
import schemaDirectives from './Directives';

const typedefsArray = fileLoader(path.join(__dirname, './**/*.graphql'));
const resolversArray = fileLoader(path.join(__dirname, './**/*.resolvers.ts'));

const typeDefs = mergeTypes(typedefsArray);
const resolvers = mergeResolvers(resolversArray);
const schema = makeExecutableSchema({ typeDefs, resolvers, schemaDirectives });

export default schema;

Here is my AuthDirective

import { defaultFieldResolver } from 'graphql';
import { AuthenticationError, SchemaDirectiveVisitor } from 'apollo-server-express';

class AuthDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field: any) {
    const { resolver = defaultFieldResolver } = field;

    field.resolve = async function (...args: any) {
      const [_, __, context] = args;
      const { req } = context;
      const accessToken = req.headers.authorization
        ? req.headers.authorization.replace('Bearer ', '')
        : null;

      if (accessToken) {
        // here I was doing jwt.verify(accessToken) but I removed it for now to simplify
        const result = await resolver.apply(this, args);
        return result; // <--- THIS IS ALWAYS UNDEFINED
      } else {
        throw new AuthenticationError('Unauthorized field');
      }
    };
  }
}

export default AuthDirective;

which lives under ./Directives and is being exported from an index as:

import AuthDirective from './auth';

export default {
  isAuthenticated: AuthDirective
}

Finally my user resolver. Like I said before, if I remove the directive from the user graphql query its working as it should:

import jwt from 'jsonwebtoken';
import { AuthenticationError, UserInputError } from 'apollo-server-express';
import { IUser } from './IUser';
import UserModel from './user.schema';
import { Config } from '../../config';

const { APP_SECRET } = Config;

const createToken = async (user: IUser, secret: string, expiresIn: string) => {
  const { id, email, name } = user;
  return jwt.sign({ id, email, name }, secret, { expiresIn });
};

const userResolvers = {
  Query: {
    user: (_: any, { name }: { name: string }) => UserModel.findOne({ name }).exec(),
    users: () => UserModel.find({}).exec()
  },
  Mutation: {
    createUser: async (_: any, args: IUser) => {
      await new UserModel(args).save();
      return true;
    },
    login: async (_: any, { email, password }: IUser) => {
      const user = await UserModel.findOne({ email }).exec();

      if (!user) {
        throw new UserInputError('No user found with this login credentials.');
      }

      const isValid = await user.validatePassword(password);

      if (!isValid) {
        throw new AuthenticationError('Invalid password.');
      }

      return { token: createToken(user, APP_SECRET, '30m') };
    }
  }
};

export default userResolvers;

and my server:

import morgan from 'morgan';
import express from 'express';
import bodyParser from 'body-parser';
import compression from 'compression';
import depthLimit from 'graphql-depth-limit';
import { ApolloServer } from 'apollo-server-express';

import { Config, DBConfig } from './config';
import schema from './domain';
const { PORT } = Config;

const app = express();

const apolloServer = new ApolloServer({
  schema,
  validationRules: [depthLimit(7)],
  context: ({ req, res }: any) => ({ req, res })
});

app.use(express.json());
app.use(compression());
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({ extended: true }));
apolloServer.applyMiddleware({ app });

DBConfig.init();

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Body:
There is no resolver property on field, so this

const { resolver = defaultFieldResolver } = field;

will always result in resolver having the value of defaultFieldResolver. If you're using the directive on some field that had a custom resolver, that custom resolver is never being called -- only the default behavior is used, which could indeed return undefined.

You need to make sure you're using the correct property:

const { resolve = defaultFieldResolver } = field;

or you can rename the resulting variable when you destructure field:

const { resolve: resolver = defaultFieldResolver } = field;


来源: stackexchange

问:
Use column if it exists, another if doesn't in SQL Server
I have a number of SQL Server databases (different versions from 2012 to 2019). The schema in each one is very similar but not exactly the same.  For example, there's table ORDERS, which has about 50 columns - and one column is called differently in two different databases:

in DB1: select p_user from orders

in DB2: select userpk from orders

Note that I showed two databases above, but there are actually more than 20 - some are DB1 type, the others are DB2 type

I can't do much about these differences - they are historic - and changing the schema to match is not an option.

I want to be able to run the same SQL statement against all of these databases at once.  I'd like to write the query in such a way that it would use one column if it exists and another if it doesn't.  For example:

```<code>select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        orders.p_user
    else
        orders.userpk
    end
from orders
</code>```

This unfortunately doesn't work, as SQL server seems to try to evaluate both results regardless of whether the condition is true or false.  The same thing happens if I use IIF function.

If I simply run

```<code>select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        'orders.p_user'
    else
        'orders.userpk'
    end
</code>```

then I do get the correct string, which means my condition is correct.

How can I formulate the SQL statement to use one or the other column based on whether the first one exists?

答:
I ended up using dynamic sql like so:

```<code>declare @query nvarchar(1000)
set @query  =  concat(
'select count(distinct ', (case when COL_LENGTH('orders', 'p_user') IS NOT NULL then 'orders.p_user' else 'orders.userpk' end), ')
from orders'
);
execute sp_executesql @query
</code>```

This solved my immediate issue.

ContentLicense: CC BY-SA 4.0

Body:
I have a number of SQL Server databases (different versions from 2012 to 2019). The schema in each one is very similar but not exactly the same.  For example, there's table ORDERS, which has about 50 columns - and one column is called differently in two different databases:

in DB1: select p_user from orders

in DB2: select userpk from orders

Note that I showed two databases above, but there are actually more than 20 - some are DB1 type, the others are DB2 type

I can't do much about these differences - they are historic - and changing the schema to match is not an option.

I want to be able to run the same SQL statement against all of these databases at once.  I'd like to write the query in such a way that it would use one column if it exists and another if it doesn't.  For example:

select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        orders.p_user
    else
        orders.userpk
    end
from orders

This unfortunately doesn't work, as SQL server seems to try to evaluate both results regardless of whether the condition is true or false.  The same thing happens if I use IIF function.

If I simply run

select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        'orders.p_user'
    else
        'orders.userpk'
    end

then I do get the correct string, which means my condition is correct.

How can I formulate the SQL statement to use one or the other column based on whether the first one exists?

Body:
I ended up using dynamic sql like so:

declare @query nvarchar(1000)
set @query  =  concat(
'select count(distinct ', (case when COL_LENGTH('orders', 'p_user') IS NOT NULL then 'orders.p_user' else 'orders.userpk' end), ')
from orders'
);
execute sp_executesql @query

This solved my immediate issue.


问:
How does one have parameters in a pytorch model not be leafs and be in the computation graph?
I am trying to update/change the parameters of a neural net model and then having the forward pass of the updated neural net be in the computation graph (no matter how many changes/updates we do).

I tried this idea but whenever I do it pytorch sets my updated tensors (inside the model) to be leafs, which kills the flow of gradients to the networks I want to receive gradients. It kills the flow of gradients because leaf nodes are not part of the computation graph the way I want them to be (since they aren't truly leafs).

I've tried multiple things but nothing seems to work. I created a dummy code that is self contained that prints the gradients of the networks I desire to have gradients:

```<code>import torch
import torch.nn as nn

import copy

from collections import OrderedDict

# img = torch.randn([8,3,32,32])
# targets = torch.LongTensor([1, 2, 0, 6, 2, 9, 4, 9])
# img = torch.randn([1,3,32,32])
# targets = torch.LongTensor([1])
x = torch.randn(1)
target = 12.0*x**2

criterion = nn.CrossEntropyLoss()

#loss_net = nn.Sequential(OrderedDict([('conv0',nn.Conv2d(in_channels=3,out_channels=10,kernel_size=32))]))
loss_net = nn.Sequential(OrderedDict([('fc0', nn.Linear(in_features=1,out_features=1))]))

hidden = torch.randn(size=(1,1),requires_grad=True)
updater_net = nn.Sequential(OrderedDict([('fc0',nn.Linear(in_features=1,out_features=1))]))
print(f'updater_net.fc0.weight.is_leaf = {updater_net.fc0.weight.is_leaf}')
#
nb_updates = 2
for i in range(nb_updates):
    print(f'i = {i}')
    new_params = copy.deepcopy( loss_net.state_dict() )
    ## w^<t> := f(w^<t-1>,delta^<t-1>)
    for (name, w) in loss_net.named_parameters():
        print(f'name = {name}')
        print(w.size())
        hidden = updater_net(hidden).view(1)
        print(hidden.size())
        #delta = ((hidden**2)*w/2)
        delta = w + hidden
        wt = w + delta
        print(wt.size())
        new_params[name] = wt
        #del loss_net.fc0.weight
        #setattr(loss_net.fc0, 'weight', nn.Parameter( wt ))
        #setattr(loss_net.fc0, 'weight', wt)
        #loss_net.fc0.weight = wt
        #loss_net.fc0.weight = nn.Parameter( wt )
    ##
    loss_net.load_state_dict(new_params)
#
print()
print(f'updater_net.fc0.weight.is_leaf = {updater_net.fc0.weight.is_leaf}')
outputs = loss_net(x)
loss_val = 0.5*(target - outputs)**2
loss_val.backward()
print()
print(f'-- params that dont matter if they have gradients --')
print(f'loss_net.grad = {loss_net.fc0.weight.grad}')
print('-- params we want to have gradients --')
print(f'hidden.grad = {hidden.grad}')
print(f'updater_net.fc0.weight.grad = {updater_net.fc0.weight.grad}')
print(f'updater_net.fc0.bias.grad = {updater_net.fc0.bias.grad}')
</code>```

if anyone knows how to do this please give me a ping...I set the the number of times to update to be 2 because the update operation should be in the computation graph an arbitrary number of times...so it MUST work for 2.

Strongly related post:

SO: How does one have parameters in a pytorch model not be leafs and be in the computation graph?

pytorch forum: https://discuss.pytorch.org/t/how-does-one-have-the-parameters-of-a-model-not-be-leafs/70076

Cross-posted:

Quora: https://www.quora.com/unanswered/How-does-one-have-parameters-in-a-PyTorch-model-not-be-leaves-and-be-in-the-computation-graph

reddit: https://www.reddit.com/r/pytorch/comments/f5gu3g/how_does_one_have_parameters_in_a_pytorch_model/

答:
DOESNT WORK PROPERLY cuz the named parameter modules get deleted.

Seems this works:

```<code>import torch
import torch.nn as nn

from torchviz import make_dot

import copy

from collections import OrderedDict

# img = torch.randn([8,3,32,32])
# targets = torch.LongTensor([1, 2, 0, 6, 2, 9, 4, 9])
# img = torch.randn([1,3,32,32])
# targets = torch.LongTensor([1])
x = torch.randn(1)
target = 12.0*x**2

criterion = nn.CrossEntropyLoss()

#loss_net = nn.Sequential(OrderedDict([('conv0',nn.Conv2d(in_channels=3,out_channels=10,kernel_size=32))]))
loss_net = nn.Sequential(OrderedDict([('fc0', nn.Linear(in_features=1,out_features=1))]))

hidden = torch.randn(size=(1,1),requires_grad=True)
updater_net = nn.Sequential(OrderedDict([('fc0',nn.Linear(in_features=1,out_features=1))]))
print(f'updater_net.fc0.weight.is_leaf = {updater_net.fc0.weight.is_leaf}')
#
def del_attr(obj, names):
    if len(names) == 1:
        delattr(obj, names[0])
    else:
        del_attr(getattr(obj, names[0]), names[1:])
def set_attr(obj, names, val):
    if len(names) == 1:
        setattr(obj, names[0], val)
    else:
        set_attr(getattr(obj, names[0]), names[1:], val)

nb_updates = 2
for i in range(nb_updates):
    print(f'i = {i}')
    new_params = copy.deepcopy( loss_net.state_dict() )
    ## w^<t> := f(w^<t-1>,delta^<t-1>)
    for (name, w) in list(loss_net.named_parameters()):
        hidden = updater_net(hidden).view(1)
        #delta = ((hidden**2)*w/2)
        delta = w + hidden
        wt = w + delta
        del_attr(loss_net, name.split("."))
        set_attr(loss_net, name.split("."), wt)
    ##
#
print()
print(f'updater_net.fc0.weight.is_leaf = {updater_net.fc0.weight.is_leaf}')
print(f'loss_net.fc0.weight.is_leaf = {loss_net.fc0.weight.is_leaf}')
outputs = loss_net(x)
loss_val = 0.5*(target - outputs)**2
loss_val.backward()
print()
print(f'-- params that dont matter if they have gradients --')
print(f'loss_net.grad = {loss_net.fc0.weight.grad}')
print('-- params we want to have gradients --')
print(f'hidden.grad = {hidden.grad}') # None because this is not a leaf, it is overriden in the for loop above.
print(f'updater_net.fc0.weight.grad = {updater_net.fc0.weight.grad}')
print(f'updater_net.fc0.bias.grad = {updater_net.fc0.bias.grad}')
make_dot(loss_val)
</code>```

output:

```<code>updater_net.fc0.weight.is_leaf = True
i = 0
i = 1

updater_net.fc0.weight.is_leaf = True
loss_net.fc0.weight.is_leaf = False

-- params that dont matter if they have gradients --
loss_net.grad = None
-- params we want to have gradients --
hidden.grad = None
updater_net.fc0.weight.grad = tensor([[0.7152]])
updater_net.fc0.bias.grad = tensor([-7.4249])
</code>```

Acknowledgement: mighty albanD from pytorch team: https://discuss.pytorch.org/t/how-does-one-have-the-parameters-of-a-model-not-be-leafs/70076/9?u=pinocchio

Body:
I am trying to update/change the parameters of a neural net model and then having the forward pass of the updated neural net be in the computation graph (no matter how many changes/updates we do).

I tried this idea but whenever I do it pytorch sets my updated tensors (inside the model) to be leafs, which kills the flow of gradients to the networks I want to receive gradients. It kills the flow of gradients because leaf nodes are not part of the computation graph the way I want them to be (since they aren't truly leafs).

I've tried multiple things but nothing seems to work. I created a dummy code that is self contained that prints the gradients of the networks I desire to have gradients:

import torch
import torch.nn as nn

import copy

from collections import OrderedDict

# img = torch.randn([8,3,32,32])
# targets = torch.LongTensor([1, 2, 0, 6, 2, 9, 4, 9])
# img = torch.randn([1,3,32,32])
# targets = torch.LongTensor([1])
x = torch.randn(1)
target = 12.0*x**2

criterion = nn.CrossEntropyLoss()

#loss_net = nn.Sequential(OrderedDict([('conv0',nn.Conv2d(in_channels=3,out_channels=10,kernel_size=32))]))
loss_net = nn.Sequential(OrderedDict([('fc0', nn.Linear(in_features=1,out_features=1))]))

hidden = torch.randn(size=(1,1),requires_grad=True)
updater_net = nn.Sequential(OrderedDict([('fc0',nn.Linear(in_features=1,out_features=1))]))
print(f'updater_net.fc0.weight.is_leaf = {updater_net.fc0.weight.is_leaf}')
#
nb_updates = 2
for i in range(nb_updates):
    print(f'i = {i}')
    new_params = copy.deepcopy( loss_net.state_dict() )
    ## w^<t> := f(w^<t-1>,delta^<t-1>)
    for (name, w) in loss_net.named_parameters():
        print(f'name = {name}')
        print(w.size())
        hidden = updater_net(hidden).view(1)
        print(hidden.size())
        #delta = ((hidden**2)*w/2)
        delta = w + hidden
        wt = w + delta
        print(wt.size())
        new_params[name] = wt
        #del loss_net.fc0.weight
        #setattr(loss_net.fc0, 'weight', nn.Parameter( wt ))
        #setattr(loss_net.fc0, 'weight', wt)
        #loss_net.fc0.weight = wt
        #loss_net.fc0.weight = nn.Parameter( wt )
    ##
    loss_net.load_state_dict(new_params)
#
print()
print(f'updater_net.fc0.weight.is_leaf = {updater_net.fc0.weight.is_leaf}')
outputs = loss_net(x)
loss_val = 0.5*(target - outputs)**2
loss_val.backward()
print()
print(f'-- params that dont matter if they have gradients --')
print(f'loss_net.grad = {loss_net.fc0.weight.grad}')
print('-- params we want to have gradients --')
print(f'hidden.grad = {hidden.grad}')
print(f'updater_net.fc0.weight.grad = {updater_net.fc0.weight.grad}')
print(f'updater_net.fc0.bias.grad = {updater_net.fc0.bias.grad}')

if anyone knows how to do this please give me a ping...I set the the number of times to update to be 2 because the update operation should be in the computation graph an arbitrary number of times...so it MUST work for 2.

Strongly related post:

SO: How does one have parameters in a pytorch model not be leafs and be in the computation graph?

pytorch forum: https://discuss.pytorch.org/t/how-does-one-have-the-parameters-of-a-model-not-be-leafs/70076

Cross-posted:

Quora: https://www.quora.com/unanswered/How-does-one-have-parameters-in-a-PyTorch-model-not-be-leaves-and-be-in-the-computation-graph

reddit: https://www.reddit.com/r/pytorch/comments/f5gu3g/how_does_one_have_parameters_in_a_pytorch_model/

Body:
DOESNT WORK PROPERLY cuz the named parameter modules get deleted.

Seems this works:

import torch
import torch.nn as nn

from torchviz import make_dot

import copy

from collections import OrderedDict

# img = torch.randn([8,3,32,32])
# targets = torch.LongTensor([1, 2, 0, 6, 2, 9, 4, 9])
# img = torch.randn([1,3,32,32])
# targets = torch.LongTensor([1])
x = torch.randn(1)
target = 12.0*x**2

criterion = nn.CrossEntropyLoss()

#loss_net = nn.Sequential(OrderedDict([('conv0',nn.Conv2d(in_channels=3,out_channels=10,kernel_size=32))]))
loss_net = nn.Sequential(OrderedDict([('fc0', nn.Linear(in_features=1,out_features=1))]))

hidden = torch.randn(size=(1,1),requires_grad=True)
updater_net = nn.Sequential(OrderedDict([('fc0',nn.Linear(in_features=1,out_features=1))]))
print(f'updater_net.fc0.weight.is_leaf = {updater_net.fc0.weight.is_leaf}')
#
def del_attr(obj, names):
    if len(names) == 1:
        delattr(obj, names[0])
    else:
        del_attr(getattr(obj, names[0]), names[1:])
def set_attr(obj, names, val):
    if len(names) == 1:
        setattr(obj, names[0], val)
    else:
        set_attr(getattr(obj, names[0]), names[1:], val)

nb_updates = 2
for i in range(nb_updates):
    print(f'i = {i}')
    new_params = copy.deepcopy( loss_net.state_dict() )
    ## w^<t> := f(w^<t-1>,delta^<t-1>)
    for (name, w) in list(loss_net.named_parameters()):
        hidden = updater_net(hidden).view(1)
        #delta = ((hidden**2)*w/2)
        delta = w + hidden
        wt = w + delta
        del_attr(loss_net, name.split("."))
        set_attr(loss_net, name.split("."), wt)
    ##
#
print()
print(f'updater_net.fc0.weight.is_leaf = {updater_net.fc0.weight.is_leaf}')
print(f'loss_net.fc0.weight.is_leaf = {loss_net.fc0.weight.is_leaf}')
outputs = loss_net(x)
loss_val = 0.5*(target - outputs)**2
loss_val.backward()
print()
print(f'-- params that dont matter if they have gradients --')
print(f'loss_net.grad = {loss_net.fc0.weight.grad}')
print('-- params we want to have gradients --')
print(f'hidden.grad = {hidden.grad}') # None because this is not a leaf, it is overriden in the for loop above.
print(f'updater_net.fc0.weight.grad = {updater_net.fc0.weight.grad}')
print(f'updater_net.fc0.bias.grad = {updater_net.fc0.bias.grad}')
make_dot(loss_val)

output:

updater_net.fc0.weight.is_leaf = True
i = 0
i = 1

updater_net.fc0.weight.is_leaf = True
loss_net.fc0.weight.is_leaf = False

-- params that dont matter if they have gradients --
loss_net.grad = None
-- params we want to have gradients --
hidden.grad = None
updater_net.fc0.weight.grad = tensor([[0.7152]])
updater_net.fc0.bias.grad = tensor([-7.4249])

Acknowledgement: mighty albanD from pytorch team: https://discuss.pytorch.org/t/how-does-one-have-the-parameters-of-a-model-not-be-leafs/70076/9?u=pinocchio


问:
How can I implement a boolean tag search in SQL?
Given a table of items, a table of tags and a join table between them, what is a good and efficient way to implement queries of the form:

p1 AND p2 AND ... AND pn AND NOT n1 AND NOT n2 ... AND NOT nk

I am using SQL. So to find all items that match all tags p1...pn and none of n1...nk?

Is there a good "standard" solution for this?

答:
I think this is what you're looking for:

```<code>SELECT * FROM TABLE_NAME WHERE COLUMN1 IN ('value1','value2','value3') AND COLUMN1 NOT IN ('value4','value5','value6')
</code>```

If not, let me know.  I may have misunderstood your question.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

Body:
I think this is what you're looking for:

SELECT * FROM TABLE_NAME WHERE COLUMN1 IN ('value1','value2','value3') AND COLUMN1 NOT IN ('value4','value5','value6')

If not, let me know.  I may have misunderstood your question.

OwnerDisplayName: Chris Ballance


问:
Delete some characters from a column in MySQL
I have ONE column in MySQl table which contains this format:

https://open.spotify.com/track/AAABBBCCC

and I'd like to leave just AAABBBCCC, and not the entire column! The last parte is always the same.

Is that possible? Thanks and sorry for my english!

答:
You can use SQL REPLACE function to do that.

```<code>UPDATE your_table_name
SET your_column_name = REPLACE(your_column_name, 'https://open.spotify.com/track/', '')
</code>```

For more information you can read SQL statement to remove part of a string

Body:
You can use SQL REPLACE function to do that.

UPDATE your_table_name
SET your_column_name = REPLACE(your_column_name, 'https://open.spotify.com/track/', '')

For more information you can read SQL statement to remove part of a string


答:
Use REPLACE to delete the wanted text from your column:</p>

```<code>UPDATE Table1 SET Column1 =  REPLACE(Column1,'https://open.spotify.com/track/','')
</code>```

Title: Delete some characters from a column in MySQL

Body:
I have ONE column in MySQl table which contains this format:

https://open.spotify.com/track/AAABBBCCC

and I'd like to leave just AAABBBCCC, and not the entire column! The last parte is always the same.

Is that possible? Thanks and sorry for my english!

Body:
Use REPLACE to delete the wanted text from your column:

UPDATE Table1 SET Column1 =  REPLACE(Column1,'https://open.spotify.com/track/','')


问:
JSON POST to PHP using VB.NET
I'm trying to POST some data using VB.NET to PHP.
The PHP script, shown below, is just two lines for experimentation.

```<code>$arr = array('code' => '110', 'description' => $_POST['updateDate']);
echo json_encode($arr);
</code>```

In VB I have tried to POST using WebClient, HttpClient and HttpWebRequest.
Only WebClient worked as expected. The other two returned "Undefined index: updateDate" meaning that POST was not correct. Below is the VB code.

```<code>Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Web.Script.Serialization
Imports System.Collections.Generic
Imports System.Collections.Specialized
Imports System.Net.Http
Imports System.Threading.Tasks
Imports System.Windows.Forms

Public Class frmMain
    Dim hclient As HttpClient = New HttpClient

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim request As HttpWebRequest
        Dim response As HttpWebResponse
        Dim byteArray() As Byte
        Dim dataStream As Stream
        Dim reader As StreamReader

        Dim sresponse As String
        Dim serializer As New JavaScriptSerializer()
        Dim responseBytes As Byte()

        Dim client As New WebClient
        Dim postData As New NameValueCollection
        postData.Add("updateDate", "17-02-2020")
        responseBytes = client.UploadValues("http://localhost/srvMoveTimesARGUS/srvMoveTimesARGUS.php", postData)
        sresponse = Encoding.UTF8.GetString(responseBytes)

        Dim updateData As New List(Of field) From {
            New field With {.fieldValue = "17-02-2020", .fieldName = "updateDate"}
        }
        Dim arrayJson As String
        arrayJson = serializer.Serialize(updateData)

        '---------------------------------------------------------
        'With hclient
        '   .BaseAddress = New Uri("http://localhost/srvMoveTimesARGUS/srvMoveTimesARGUS.php")
        '   .DefaultRequestHeaders.Accept.Clear()
        '   .DefaultRequestHeaders.Accept.Add(New Headers.MediaTypeWithQualityHeaderValue("application/json"))
        'End With

        'PostAsync(arrayJson)
        '---------------------------------------------------------

        '---------------------------------------------------------
        'byteArray = Encoding.UTF8.GetBytes(arrayJson)
        'request = HttpWebRequest.Create("http://localhost/srvMoveTimesARGUS/srvMoveTimesARGUS.php")

        'request.Method = "POST"
        'request.ContentType = "application/json"
        ''request.Accept = "application/json"
        'request.ContentLength = byteArray.Length
        ''request.Expect = "application/json"

        'dataStream = request.GetRequestStream
        'dataStream.Write(byteArray, 0, byteArray.Length)
        'dataStream.Close()

        'response = request.GetResponse
        'dataStream = response.GetResponseStream()
        'reader = New StreamReader(dataStream)
        'sresponse = reader.ReadToEnd

        'reader.Close()
        'dataStream.Close()
        'response.Close()
        '---------------------------------------------------------
    End Sub

    Private Async Function PostAsync(ByVal jsonString As String) As Task

        Dim content As New Net.Http.StringContent(jsonString, System.Text.Encoding.UTF8, "application/json")
        Dim response As Net.Http.HttpResponseMessage = Await hclient.PostAsync("", content)

        Dim result As String = Await response.Content.ReadAsStringAsync()

        MessageBox.Show(result)
    End Function
End Class

Public Class field
  Public Property fieldName As String
  Public Property fieldValue As String
End Class
</code>```

Variable arrayJson that holds the serialised string takes the value

```<code>"[{""fieldName"":""updateDate"",""fieldValue"":""17-02-2020""}]"
</code>```

答:
https://www.php.net/manual/en/reserved.variables.post.php

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

If you want to access the raw request body it will be in the stream php://input and can be accessed simply with:

```<code>$json_string = file_get_contents('php://input');
</code>```

Title: JSON POST to PHP using VB.NET

Body:
I'm trying to POST some data using VB.NET to PHP.
The PHP script, shown below, is just two lines for experimentation.

$arr = array('code' => '110', 'description' => $_POST['updateDate']);
echo json_encode($arr);

In VB I have tried to POST using WebClient, HttpClient and HttpWebRequest.
Only WebClient worked as expected. The other two returned "Undefined index: updateDate" meaning that POST was not correct. Below is the VB code.

Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Web.Script.Serialization
Imports System.Collections.Generic
Imports System.Collections.Specialized
Imports System.Net.Http
Imports System.Threading.Tasks
Imports System.Windows.Forms

Public Class frmMain
    Dim hclient As HttpClient = New HttpClient

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim request As HttpWebRequest
        Dim response As HttpWebResponse
        Dim byteArray() As Byte
        Dim dataStream As Stream
        Dim reader As StreamReader

        Dim sresponse As String
        Dim serializer As New JavaScriptSerializer()
        Dim responseBytes As Byte()

        Dim client As New WebClient
        Dim postData As New NameValueCollection
        postData.Add("updateDate", "17-02-2020")
        responseBytes = client.UploadValues("http://localhost/srvMoveTimesARGUS/srvMoveTimesARGUS.php", postData)
        sresponse = Encoding.UTF8.GetString(responseBytes)

        Dim updateData As New List(Of field) From {
            New field With {.fieldValue = "17-02-2020", .fieldName = "updateDate"}
        }
        Dim arrayJson As String
        arrayJson = serializer.Serialize(updateData)

        '---------------------------------------------------------
        'With hclient
        '   .BaseAddress = New Uri("http://localhost/srvMoveTimesARGUS/srvMoveTimesARGUS.php")
        '   .DefaultRequestHeaders.Accept.Clear()
        '   .DefaultRequestHeaders.Accept.Add(New Headers.MediaTypeWithQualityHeaderValue("application/json"))
        'End With

        'PostAsync(arrayJson)
        '---------------------------------------------------------

        '---------------------------------------------------------
        'byteArray = Encoding.UTF8.GetBytes(arrayJson)
        'request = HttpWebRequest.Create("http://localhost/srvMoveTimesARGUS/srvMoveTimesARGUS.php")

        'request.Method = "POST"
        'request.ContentType = "application/json"
        ''request.Accept = "application/json"
        'request.ContentLength = byteArray.Length
        ''request.Expect = "application/json"

        'dataStream = request.GetRequestStream
        'dataStream.Write(byteArray, 0, byteArray.Length)
        'dataStream.Close()

        'response = request.GetResponse
        'dataStream = response.GetResponseStream()
        'reader = New StreamReader(dataStream)
        'sresponse = reader.ReadToEnd

        'reader.Close()
        'dataStream.Close()
        'response.Close()
        '---------------------------------------------------------
    End Sub

    Private Async Function PostAsync(ByVal jsonString As String) As Task

        Dim content As New Net.Http.StringContent(jsonString, System.Text.Encoding.UTF8, "application/json")
        Dim response As Net.Http.HttpResponseMessage = Await hclient.PostAsync("", content)

        Dim result As String = Await response.Content.ReadAsStringAsync()

        MessageBox.Show(result)
    End Function
End Class

Public Class field
  Public Property fieldName As String
  Public Property fieldValue As String
End Class

Variable arrayJson that holds the serialised string takes the value

"[{""fieldName"":""updateDate"",""fieldValue"":""17-02-2020""}]"

Body:
https://www.php.net/manual/en/reserved.variables.post.php

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

If you want to access the raw request body it will be in the stream php://input and can be accessed simply with:

$json_string = file_get_contents('php://input');


问:
How to print even and odd position characters of an array of strings in Java?
Question

Given a string S of length N, that is indexed from 0 to N-1, print it's even indexed and odd indexed characters as 2 space separated strings on a single line.
  Assume input starts at index position 0(which is considered even)

Input

The first line contains an integer, T (the number of test cases).
  Each line i of the T subsequent lines contain a String, S.

Output

For each string S, print it's even-indexed characters, followed by space, followed by odd-indexed characters.

Sample Input

2

Hacker

Rank

Sample Output

Hce akr

Rn ak

The Code I Wrote

```<code>public static void main(String[] args)
{
    Scanner scan    =   new Scanner(System.in);
    int T   =   scan.nextInt();
    scan.nextLine();

    for(int i=0 ; i<T ; i++)
    {
        String  myString    =   scan.nextLine();

        int evn =   0,
            odd =   0,
            len =   myString.length();

        char    strE[]  =   new char[50],
                strO[]  =   new char[50];

        for(int j=0 ; j<len ; j++)
        {
            if(j%2 == 0)
            {
                strE[evn]   =   myString.charAt(j);
                evn++;
            }
            if(j%2 == 1)
            {
                strO[odd]   =   myString.charAt(j);
                odd++;
            }
        }
        System.out.print(strE);
        System.out.print(" ");
        System.out.println(strO);
    }
}
</code>```

My Output

Hce akr

Rn ak

The Problem

As you can see, my program successfully meets the test case, and other test cases (using custom input) but every time the HackerRank compiler tells me that my program did not meet the test case.

Clearly, my program is producing the required output but every time the HackerRank compiler tells me that I got the solution wrong.

Could anyone please tell me where I am making a mistake?

Further Modifications

I then decided to change the last 3 lines of print statements into one statement as follows:

```<code>System.out.println(strE + " " + strO);
</code>```

However, this time the program did not produce the desired output and rather printed some garbage values as follows:

[C@5c3f3b9b [C@3b626c6d

[C@3abc8690 [C@2f267610

My Doubts

1. In the first case, when I was printing the two strings separately using 2 print statements, I was getting a correct output everytime but the HackerRank compiler rejected it. Why?

2. In the second case, when I modified the program by using one print statement instead of 3 to get the desired result, the program gave a completely different output and rather printed garbage values! Why?

Here is a link to the HackerRank problem for more info:
hackerrank.com/challenges/30-review-loop

All help and guidance is greatly appreciated and thanks a lot in advance!

答:
```<code>import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
        int T;
        T = s.nextInt();
        String[] str = new String[T];
        int i;
        for(i=0;i<T;i++) {
            str[i] = s.next();
        }
        for(i=0;i<T;i++) {
            char[] even = new char[5000];
            char[] odd = new char[5000];
            int ev =0,od=0;
            for(int j= 0;j< str[i].length();j++) {
                if(j%2== 0) {
                    even[ev] = str[i].charAt(j);
                    ev++;
                }else {
                    odd[od] = str[i].charAt(j);
                    od++;
                }
            }
            String strEven = new String(even);
            String strOdd = new String(odd);
           System.out.print(strEven.trim());
           System.out.print(" ");
           System.out.println(strOdd.trim());

        }
        s.close();
    }
}
</code>```

I am sure that this will work You've forgotten to convert it to a string and also increase the size of the character array

ContentLicense: CC BY-SA 3.0

Body:
Question

Given a string S of length N, that is indexed from 0 to N-1, print it's even indexed and odd indexed characters as 2 space separated strings on a single line.
  Assume input starts at index position 0(which is considered even)

Input

The first line contains an integer, T (the number of test cases).
  Each line i of the T subsequent lines contain a String, S.

Output

For each string S, print it's even-indexed characters, followed by space, followed by odd-indexed characters.

Sample Input

2

Hacker

Rank

Sample Output

Hce akr

Rn ak

The Code I Wrote

public static void main(String[] args)
{
    Scanner scan    =   new Scanner(System.in);
    int T   =   scan.nextInt();
    scan.nextLine();

    for(int i=0 ; i<T ; i++)
    {
        String  myString    =   scan.nextLine();

        int evn =   0,
            odd =   0,
            len =   myString.length();

        char    strE[]  =   new char[50],
                strO[]  =   new char[50];

        for(int j=0 ; j<len ; j++)
        {
            if(j%2 == 0)
            {
                strE[evn]   =   myString.charAt(j);
                evn++;
            }
            if(j%2 == 1)
            {
                strO[odd]   =   myString.charAt(j);
                odd++;
            }
        }
        System.out.print(strE);
        System.out.print(" ");
        System.out.println(strO);
    }
}

My Output

Hce akr

Rn ak

The Problem

As you can see, my program successfully meets the test case, and other test cases (using custom input) but every time the HackerRank compiler tells me that my program did not meet the test case.

Clearly, my program is producing the required output but every time the HackerRank compiler tells me that I got the solution wrong.

Could anyone please tell me where I am making a mistake?

Further Modifications

I then decided to change the last 3 lines of print statements into one statement as follows:

System.out.println(strE + " " + strO);

However, this time the program did not produce the desired output and rather printed some garbage values as follows:

[C@5c3f3b9b [C@3b626c6d

[C@3abc8690 [C@2f267610

My Doubts

1. In the first case, when I was printing the two strings separately using 2 print statements, I was getting a correct output everytime but the HackerRank compiler rejected it. Why?

2. In the second case, when I modified the program by using one print statement instead of 3 to get the desired result, the program gave a completely different output and rather printed garbage values! Why?

Here is a link to the HackerRank problem for more info:
hackerrank.com/challenges/30-review-loop

All help and guidance is greatly appreciated and thanks a lot in advance!

Body:
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
        int T;
        T = s.nextInt();
        String[] str = new String[T];
        int i;
        for(i=0;i<T;i++) {
            str[i] = s.next();
        }
        for(i=0;i<T;i++) {
            char[] even = new char[5000];
            char[] odd = new char[5000];
            int ev =0,od=0;
            for(int j= 0;j< str[i].length();j++) {
                if(j%2== 0) {
                    even[ev] = str[i].charAt(j);
                    ev++;
                }else {
                    odd[od] = str[i].charAt(j);
                    od++;
                }
            }
            String strEven = new String(even);
            String strOdd = new String(odd);
           System.out.print(strEven.trim());
           System.out.print(" ");
           System.out.println(strOdd.trim());

        }
        s.close();
    }
}

I am sure that this will work You've forgotten to convert it to a string and also increase the size of the character array


问:
rephrase definition for android orientation angle "roll"
The definition of 'roll' in android is:

angle between a plane perpendicular to the device's screen and a plane perpendicular to the ground

See here.

Maybe I'm missing something, but there seem to be many planes perpendicular to the ground giving many different angles.

Could someone please rephrase this definition using e.g planes parallel to ground or screen, north direction, gravity direction?

NB! I am asking for a rephrasing using different words. I know the official definition as I have stated. Please don't repost the official definition.

答:
values[2]: Roll, angle of rotation about the y axis. This value represents the angle between a plane perpendicular to the device's screen and a plane perpendicular to the ground. Assuming that the bottom edge of the device faces the user and that the screen is face-up, tilting the left edge of the device toward the ground creates a positive roll angle. The range of values is -π/2 to π/2.

The plane "perpendicular to the ground" here is just a reference for how "tilted" (rolled) the device is. Imagine the device flat on a table next to a wall. If you lift the edge of the device so it is tilted to the side, the angle of roll is the angle between the plane of the device and the plane of the wall. This is because we have constrained the x axis (pitch) so that you are looking at roll. Now, if you lift the top of the device towards you, the roll stays the same while the pitch changes, because the device is still at the same angle towards the wall along it's y axis.


问:
Simple encode and decode pipeline with gstreamer?
I'm trying to create a simple gstreamer1-0 pipeline that encodes and decodes h264 a webcam feed hopefully using the most basic elements possible. I already have (theoretically) all standard, good, bad and ugly gstreamer libraries installed. I used the word "Theoretically" because I don't have root privileges and I have to request IT to download/install every single library I might need and it's quite a pain.

I've tried the following pipeline but it didn't work:

```<code>gst-launch-1.0 v4l2src ! autovideoconvert ! x264enc bitrate=256 ! decodebin ! autovideosink
</code>```

I get the following output:

```<code>Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
Redistribute latency...
Missing element: H.264 decoder
ERROR: from element /GstPipeline:pipeline0/GstDecodeBin:decodebin0: Your GStreamer installation is missing a plug-in.
Additional debug info:
gstdecodebin2.c(3977): gst_decode_bin_expose (): /GstPipeline:pipeline0/GstDecodeBin:decodebin0:
no suitable plugins found
Execution ended after 0:00:01.795803500
Setting pipeline to PAUSED ...
Setting pipeline to READY ...
Setting pipeline to NULL ...
Freeing pipeline ...
</code>```

So according to that I'm missing a block to my plugin to decode h264 right?

Now I've read this forum and I've no idea how to install the decoder block. If somebody can explain to me how to do that in order to get that simple pipeline running?

答:
In centos 7, you can install it via yum:

```<code>sudo yum install -y http://download1.rpmfusion.org/free/el/updates/7/x86_64/g/gstreamer1-libav-1.10.4-2.el7.x86_64.rpm
</code>```

and then check it again:

```<code>gst-inspect-1.0 | grep 264
</code>```

now you can see the decoders

Body:
I'm trying to create a simple gstreamer1-0 pipeline that encodes and decodes h264 a webcam feed hopefully using the most basic elements possible. I already have (theoretically) all standard, good, bad and ugly gstreamer libraries installed. I used the word "Theoretically" because I don't have root privileges and I have to request IT to download/install every single library I might need and it's quite a pain.

I've tried the following pipeline but it didn't work:

gst-launch-1.0 v4l2src ! autovideoconvert ! x264enc bitrate=256 ! decodebin ! autovideosink

I get the following output:

Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
Redistribute latency...
Missing element: H.264 decoder
ERROR: from element /GstPipeline:pipeline0/GstDecodeBin:decodebin0: Your GStreamer installation is missing a plug-in.
Additional debug info:
gstdecodebin2.c(3977): gst_decode_bin_expose (): /GstPipeline:pipeline0/GstDecodeBin:decodebin0:
no suitable plugins found
Execution ended after 0:00:01.795803500
Setting pipeline to PAUSED ...
Setting pipeline to READY ...
Setting pipeline to NULL ...
Freeing pipeline ...

So according to that I'm missing a block to my plugin to decode h264 right?

Now I've read this forum and I've no idea how to install the decoder block. If somebody can explain to me how to do that in order to get that simple pipeline running?

Body:
In centos 7, you can install it via yum:

sudo yum install -y http://download1.rpmfusion.org/free/el/updates/7/x86_64/g/gstreamer1-libav-1.10.4-2.el7.x86_64.rpm

and then check it again:

gst-inspect-1.0 | grep 264

now you can see the decoders


问:
I am getting an error when reversing an array by iterating it till half
I have tried to reverse an array by running it till half so that if it has odd number of element then middle one is left out as it is not needed to be swapped and if it's even then every element will be swapped but I don't know where I'm wrong.

import java.io.*;
import java.util.*;

public class Main{

    public static void main(String[] args) throws Exception {
        // write your code here
        Scanner scn = new Scanner(System.in);
        int x = scn.nextInt();
        int[] arr = new int[x];
        for(int i = 0 ; i < arr.length ; i++)
        {
            arr[i] = scn.nextInt();
        }
        int temp = x;
        for(int i = 0  ; i < temp / 2 ;i++)
        {
            int temp1 = arr[i];
            arr[i] = arr[x - 1];
            arr[x - 1] = temp1;
            x--;
        }
        for(int z=0;z<arr.length;z++)
        {
            System.out.println(arr[z]);
        }
    }
}
```

答:
You were very close in your attempt.  See the following with changes.</p>

```<code>       for(int i = 0  ; i < temp / 2 ;i++)
        {
            int temp1 = arr[i];
            arr[i] = arr[x - 1]; // should be arr[x - i - 1]
            arr[x - 1] = temp1;  // should be arr[x - i - 1]
            x--; // delete this line
        }

</code>```

Body:
You were very close in your attempt.  See the following with changes.

       for(int i = 0  ; i < temp / 2 ;i++)
        {
            int temp1 = arr[i];
            arr[i] = arr[x - 1]; // should be arr[x - i - 1]
            arr[x - 1] = temp1;  // should be arr[x - i - 1]
            x--; // delete this line
        }


问:
Postgres as default database in Processmaker
By default Processmaker 3.0.1.8 uses MYSQL database. We don't want to increase our work of maintaining two databases. we cannot let go Postgres but to use Processmaker we need to also use Mysql. Is there anyone who has used ProcessMaker 3.0.1.8 with postgres 9.2+. </p>

答: ProcessMaker 4 now works with Postgres, MySQL, and MS SQL, so we recommend you migrate to it if you are interested in using Postgres.  You can get the source on github:  ProcessMaker Open Source</p>


问:
How can I safely make a float *x into a const float *const *y?
I have a function audioReceived (float * input, int bufferSize, int nChannels) inside of which I want to call a function from a library that needs const float *const *inputBuffers.

Obviously casting const float *const *inputBuffers = (const float* const*)input; compiles but is a terrible idea, crashes the program, kills kittens, etc. Nobody ever needs to modify the original float* input, it's incoming audio data that's being processed.

How do I do it the right way?

EDIT: Here's some more code. audioReceived is:

```<code>void testApp::audioReceived (float * input, int bufferSize, int nChannels){

     Vamp::RealTime rt = Vamp::RealTime::fromMilliseconds(ofGetSystemTime());
     float const *const tmp[] = { input, 0 };
     Vamp::Plugin::FeatureSet fs = myPlugin->process(tmp, rt);
 }
</code>```

Library function process is virtually defined in base class:

```<code> /**
 * Process a single block of input data.
 *
 * If the plugin's inputDomain is TimeDomain, inputBuffers will
 * point to one array of floats per input channel, and each of
 * these arrays will contain blockSize consecutive audio samples
 * (the host will zero-pad as necessary).  The timestamp in this
 * case will be the real time in seconds of the start of the
 * supplied block of samples.
 *
 * If the plugin's inputDomain is FrequencyDomain, inputBuffers
 * will point to one array of floats per input channel, and each
 * of these arrays will contain blockSize/2+1 consecutive pairs of
 * real and imaginary component floats corresponding to bins
 * 0..(blockSize/2) of the FFT output.  That is, bin 0 (the first
 * pair of floats) contains the DC output, up to bin blockSize/2
 * which contains the Nyquist-frequency output.  There will
 * therefore be blockSize+2 floats per channel in total.  The
 * timestamp will be the real time in seconds of the centre of the
 * FFT input window (i.e. the very first block passed to process
 * might contain the FFT of half a block of zero samples and the
 * first half-block of the actual data, with a timestamp of zero).
 *
 * Return any features that have become available after this
 * process call.  (These do not necessarily have to fall within
 * the process block, except for OneSamplePerStep outputs.)
 */
virtual FeatureSet process(const float *const *inputBuffers,
               RealTime timestamp) = 0;
</code>```

and here in the actual header:

```<code>FeatureSet process(const float *const *inputBuffers, Vamp::RealTime timestamp);
</code>```

I think the EXC_BAD_ACCESS may be stemming from the library function wanting a zero-padded array, and my not giving it one. (a) Does that sound reasonable, and (b) If so, is it time to ask a different SO question?

Thanks all for your help so far, it's very enlightening/clarifying/educational/interesting.

答:
Semantics is important here. From the parameter names, I can guess that the function you want to call accepts multiple buffers, so it wants an array of pointers to float (i.e. an array of arrays). Since you only have an array, you need to create an array that contains the original pointer, and pass that to the function.

If the function has a separate argument for the length of the array it is being passed (i.e. the number of buffers), then taking the address using the unary & operator and passing a length of 1 should be enough, otherwise you need to create a temporary null terminated array:

```<code>float const *const tmp[] = { input, 0 };
</code>```

and pass that to the function.

Body:
I have a function audioReceived (float * input, int bufferSize, int nChannels) inside of which I want to call a function from a library that needs const float *const *inputBuffers.

Obviously casting const float *const *inputBuffers = (const float* const*)input; compiles but is a terrible idea, crashes the program, kills kittens, etc. Nobody ever needs to modify the original float* input, it's incoming audio data that's being processed.

How do I do it the right way?

EDIT: Here's some more code. audioReceived is:

void testApp::audioReceived (float * input, int bufferSize, int nChannels){

     Vamp::RealTime rt = Vamp::RealTime::fromMilliseconds(ofGetSystemTime());
     float const *const tmp[] = { input, 0 };
     Vamp::Plugin::FeatureSet fs = myPlugin->process(tmp, rt);
 }

Library function process is virtually defined in base class:

 /**
 * Process a single block of input data.
 *
 * If the plugin's inputDomain is TimeDomain, inputBuffers will
 * point to one array of floats per input channel, and each of
 * these arrays will contain blockSize consecutive audio samples
 * (the host will zero-pad as necessary).  The timestamp in this
 * case will be the real time in seconds of the start of the
 * supplied block of samples.
 *
 * If the plugin's inputDomain is FrequencyDomain, inputBuffers
 * will point to one array of floats per input channel, and each
 * of these arrays will contain blockSize/2+1 consecutive pairs of
 * real and imaginary component floats corresponding to bins
 * 0..(blockSize/2) of the FFT output.  That is, bin 0 (the first
 * pair of floats) contains the DC output, up to bin blockSize/2
 * which contains the Nyquist-frequency output.  There will
 * therefore be blockSize+2 floats per channel in total.  The
 * timestamp will be the real time in seconds of the centre of the
 * FFT input window (i.e. the very first block passed to process
 * might contain the FFT of half a block of zero samples and the
 * first half-block of the actual data, with a timestamp of zero).
 *
 * Return any features that have become available after this
 * process call.  (These do not necessarily have to fall within
 * the process block, except for OneSamplePerStep outputs.)
 */
virtual FeatureSet process(const float *const *inputBuffers,
               RealTime timestamp) = 0;

and here in the actual header:

FeatureSet process(const float *const *inputBuffers, Vamp::RealTime timestamp);

I think the EXC_BAD_ACCESS may be stemming from the library function wanting a zero-padded array, and my not giving it one. (a) Does that sound reasonable, and (b) If so, is it time to ask a different SO question?

Thanks all for your help so far, it's very enlightening/clarifying/educational/interesting.

Body:
Semantics is important here. From the parameter names, I can guess that the function you want to call accepts multiple buffers, so it wants an array of pointers to float (i.e. an array of arrays). Since you only have an array, you need to create an array that contains the original pointer, and pass that to the function.

If the function has a separate argument for the length of the array it is being passed (i.e. the number of buffers), then taking the address using the unary & operator and passing a length of 1 should be enough, otherwise you need to create a temporary null terminated array:

float const *const tmp[] = { input, 0 };

and pass that to the function.


问:
Decorator assignment
Suppose decorator

```<code>@app.callback(
    Output("plot_1", "figure"),
    [Input("checklist", "value"),
     Input("radio", "value")])
</code>```

which is repeated in code several times. The only difference between the copies is different plot names.

How is it possible to assign that decorator to another decorator and use the latter?

```<code>@new_callback("plot_1")
</code>```

答:
Decorator syntax is just a shortcut for function application; app.callback is just a function. Create a new function that calls it with fixed arguments.

```<code>def new_callback(plot):
    return app.callback(
          Output(plot, "figure"),
          [
              Input("checklist", "value"),
              Input("radio", "value")
          ]
    )
</code>```

app.callback itself is not actually the decorator; it's a function that returns the decorator (i.e., the function that takes the function to be decorated as an argument).

```<code>@app.callback(...)
def foo():
    ...
</code>```

is equivalent to

```<code>def foo():
    ...

foo = app.callback(...)(foo)
</code>```

Title: Decorator assignment

Body:
Suppose decorator

@app.callback(
    Output("plot_1", "figure"),
    [Input("checklist", "value"),
     Input("radio", "value")])

which is repeated in code several times. The only difference between the copies is different plot names.

How is it possible to assign that decorator to another decorator and use the latter?

@new_callback("plot_1")

Body:
Decorator syntax is just a shortcut for function application; app.callback is just a function. Create a new function that calls it with fixed arguments.

def new_callback(plot):
    return app.callback(
          Output(plot, "figure"),
          [
              Input("checklist", "value"),
              Input("radio", "value")
          ]
    )

app.callback itself is not actually the decorator; it's a function that returns the decorator (i.e., the function that takes the function to be decorated as an argument).

@app.callback(...)
def foo():
    ...

is equivalent to

def foo():
    ...

foo = app.callback(...)(foo)


问:
Python function import not working in Django using Spyder
My Django project has the following folder structure where controllers is where I keep all custom .py files:

```<code>C:.
│   db.sqlite3
│   manage.py
│
├───myApp
│   │   admin.py
│   │   apps.py
│   │   forms.py
│   │   models.py
│   │   tests.py
│   │   urls.py
│   │   views.py
│   │   widgets.py
│   │   __init__.py
│   │
│   ├───controllers
│   │   │   helpers.py
│   │   │   function.py
│   │   │   __init__.py
│   │   │
</code>```

Inside controllers/function.py I want to import the file helpers.py.

Scenario 1: If I type from .helpers import foo and run this in Django, then I am able to import helpers.py, but if I run this same import in Spyder then I get: ImportError: attempted relative import with no known parent package

Scenario 2: If I type from helpers import foo (without the "dot") and run this in Django, then I get: ModuleNotFoundError: No module named 'helpers' but it works in Spyder!

What am I missing here with the paths (or relative paths). I need to be able to have one python script that works in Django and Spyder without having to remove the . everywhere.

答:
Q : "If I run this same import in Spyder" => do you mean in spyder's integrated python shell ?
  A : "correct"

Then it's to be expected.

In the functions.py module, you can use a relative import (and that's actually what you want) because it will be resolved relatively to the current module ("functions.py").

When you're in the interactive shell, you are NOT in a module that's part of a package so relative imports cannot work here, and you have to use an absolute import (or an import relative to your current working directory, which is supposed to be first in your sys.path - unless something (IDE or else) messed with it of course.

IOW:

in your module, keep the explicit relative import (which should always work AND resolve to the correct "helpers" module or sub-package)

in your shell, use a qualified path that matches your current sys.path

EDIT

I don't fully comprehend what you mean by both "explicit relative import" and "qualified path"

"explicit relative import" : from .helpers import foo - it's a relative import (relative to the functions module), and it's explicit (the syntax used explicitely means "look for a 'helpers' module or subpackage in the same package as me and at the same level")

"qualified path": well yes not the best possible formulation I guess. I meant a "more or less absolute" import using the full python qualified path from your package's top to your module. The point is that what constitutes "your package's top" depends on what's in your sys.path, which in turn might (or not, depending on a few factors) depend on your current working directory.

By default, python inserts the current directory in first position of your sys.path. Then it uses the sys.path to find modules or packages (warning: the path listed in sys.path should NOT be the full path to your packages, but path to the directories containing your packages).

IOW, if you open a terminal, cd to your django's project root directory and launch a (standard) python shell, your project's root will come first in sys.path and the qualified name to your helpers module will be myapps.controllers.helpers. But if you were in myapps instead then the full path would be controllers.helpers...

The only sane way is actually to make sure you never have any of your project's packages path directly in your sys.path (IOW to always run your code from the project's root). This not only solves those pesky import issues, but also avoids the infamous "double import trap"

"In the functions.py module, you can use a relative import". You mean I can use the .?

Yes. Actually you even should use it unless you have a compelling reason not to, as it will prevent potential shadowing of the helpers module by another module by the same name that would come before in your sys.path - and it makes very explicit which helpers module or package you're importing from.

This is what I am doing in Scenario 1 and it does not work in Spyder.

As I already mentionned in a comment, "does not work in Spyder" is not enough to tell exactly what's wrong, because we don't know exactly what you're doing that "does not work in Spyder" - nor the exact error message AND full traceback FWIW, both of which are usually required for "does not work" questions (unless the issue is obvious of course).

But if it's (as I understood it) "launching a python shell in Spyder and typing from . helpers import xxx" then it will indeed not "work" - you can only use this syntax in module code, AND the module has to be part of a package, AND the directory containing this package has to be in your sys.path.

Which is why, in a python shell, you must use an absolute import ("from xxx import yyy"). But then, which exact path depends on what's in your sys.path - which partly depends on your current working directory (at least for a plain Python shell - I don't use Spyder so I can't tell what it's doing behind your back).

Now if Spyder is not totally braindead, it should use your django project's root as first element in sys.path (or at least have this directory in sys.path), so the full qualified path (from myapp.controllers.helpers import foo) should work. If it doesn't, check your cwd (os.getcwd()) and your sys.path, and edit your question with:

a complete description of what you were doing exactly

the exact error message and full traceback

your cwd and sys.path

Also, you probably want to read some documentation on Python's import system - which, to be fair, can be a king size PITA sometimes.

Body:
My Django project has the following folder structure where controllers is where I keep all custom .py files:

C:.
│   db.sqlite3
│   manage.py
│
├───myApp
│   │   admin.py
│   │   apps.py
│   │   forms.py
│   │   models.py
│   │   tests.py
│   │   urls.py
│   │   views.py
│   │   widgets.py
│   │   __init__.py
│   │
│   ├───controllers
│   │   │   helpers.py
│   │   │   function.py
│   │   │   __init__.py
│   │   │

Inside controllers/function.py I want to import the file helpers.py.

Scenario 1: If I type from .helpers import foo and run this in Django, then I am able to import helpers.py, but if I run this same import in Spyder then I get: ImportError: attempted relative import with no known parent package

Scenario 2: If I type from helpers import foo (without the "dot") and run this in Django, then I get: ModuleNotFoundError: No module named 'helpers' but it works in Spyder!

What am I missing here with the paths (or relative paths). I need to be able to have one python script that works in Django and Spyder without having to remove the . everywhere.


问:
Plot several graphs in Pytorch tensorboard
I am training a dynamic neural network, meaning that each epoch I tweak the architecture and get a different computational graph.
I want to plot the graph for each epoch using tensorboard, but when I use SummaryWriter.add_graph() at the end of each epoch it simply overwrites the previous one.

Any ideas how to plot several graphs using pytorch + tensorboard? It seems achievable as each graph has a “tag” but I found no option to change this tag to plot several of them.

Thanks,
Elad

答:
If you still want to use SummaryWriter, there is the optionn of using the method "add_scalars":

Example:

```<code>summary.add_scalars(f'loss/check_info', {
    'score': score[iteration],
    'score_nf': score_nf[iteration],
}, iteration)
</code>```

Body:
If you still want to use SummaryWriter, there is the optionn of using the method "add_scalars":

Example:

summary.add_scalars(f'loss/check_info', {
    'score': score[iteration],
    'score_nf': score_nf[iteration],
}, iteration)


问:
Addition to an integer variable which already has a set value
Its my second day of learning how to code. I chose C++ as my first language and decided to make a cpp project. This project has 4 question and 2 answers for each question (Yes and No). In the end it must cout you a result which depends on how many answers were correct. Everything i did was working except 1 thing.
So for example if you answered at least 3 of the questions incorrectly you will receive cout << "You are stupid";
And if the amount of incorrect answer is lower than 3 then you will receive a cout << "You are smart";

As i mentioned before, i did everything right except one thing.
In order to keep track of how many questions were correct/incorrect ive set a variable:

```<code>int amount_of_correct_answers;
amount_of_correct_answers = 0;
</code>```

Then i made it so that if the answer is correct, it will add 1 to this variable

```<code>if(answer == true_answer)
{
 amount_of_correct_answers + 1;
}
else
{
 amount_of_correct_answers + 0;
 }
</code>```

So in the end of the test you see the result(if you are stupid or smart). My question is:
How do i add/substract from a variable? How do i add 1 to a variable thats set as 0 if the answer is correct? Because the code i wrote above didnt work. I think i am on the right track and my problem is syntax because i have no idea how to add/substract to/from a variable with a set value.

P.S. Keep in mind that i am very new to coding as i mentioned before, so please explain it in simple words or an example. Thank you

答:
All this does:

```<code>amount_of_correct_answers + 1;
</code>```

Is add 1 to the value of amount_of_correct_answers and discard the result.  You need to assign the value back to the variable:

```<code>amount_of_correct_answers = amount_of_correct_answers + 1;
</code>```

Body:
Its my second day of learning how to code. I chose C++ as my first language and decided to make a cpp project. This project has 4 question and 2 answers for each question (Yes and No). In the end it must cout you a result which depends on how many answers were correct. Everything i did was working except 1 thing.
So for example if you answered at least 3 of the questions incorrectly you will receive cout << "You are stupid";
And if the amount of incorrect answer is lower than 3 then you will receive a cout << "You are smart";

As i mentioned before, i did everything right except one thing.
In order to keep track of how many questions were correct/incorrect ive set a variable:

int amount_of_correct_answers;
amount_of_correct_answers = 0;

Then i made it so that if the answer is correct, it will add 1 to this variable

if(answer == true_answer)
{
 amount_of_correct_answers + 1;
}
else
{
 amount_of_correct_answers + 0;
 }

So in the end of the test you see the result(if you are stupid or smart). My question is:
How do i add/substract from a variable? How do i add 1 to a variable thats set as 0 if the answer is correct? Because the code i wrote above didnt work. I think i am on the right track and my problem is syntax because i have no idea how to add/substract to/from a variable with a set value.

P.S. Keep in mind that i am very new to coding as i mentioned before, so please explain it in simple words or an example. Thank you

Body:
All this does:

amount_of_correct_answers + 1;

Is add 1 to the value of amount_of_correct_answers and discard the result.  You need to assign the value back to the variable:

amount_of_correct_answers = amount_of_correct_answers + 1;


问:
Python Lists: Appending a string and removing ALL quotations
The code below is taken from a larger project I'm working on.

The aim of this section is to get the output formatted as a list, with no quotation marks anywhere.

However when I try format the output as a list, it has quotation marks around the outside, I've looked through multiple forums and couldn't find anyone whose had the exact issue.

Coded Input:

```<code>colourChart = []
tempColour = tempAlpha

tempColour = "%s" % (', '.join(tempColour)) #! Creates a string, I need it in a List format.
print("What I need it to be formatted as:\n [" + tempColour + "]")

colourChart.append(tempColour) #! Takes previous string, appends to List, adds quotes tho :(
print("What it actually gets formatted as:\n",colourChart)
</code>```

Output:

```<code>What I need it to be formatted as:
 [colourAlpha(0.3), colourAlpha(0.4), colourAlpha(0.5), colourAlpha(0.6)]

What it actually gets formatted as:
 ['colourAlpha(0.3), colourAlpha(0.4), colourAlpha(0.5), colourAlpha(0.6)']
</code>```

This link has the Python script I was testing this with:
https://drive.google.com/drive/folders/1y1-SkyUoDYrR1UU0ssJd6izjfNsbwZUJ?usp=sharing

答:
Join creates a string and the string is what is getting appeneded to colourChart. Use extend.</p>

```<code>data = ['A', 'B', 'C']

data_result = []

data_result.append(', '.join(data))

data_result
Out[21]: ['A, B, C']

data_result_2 = []

data_result_2.extend(data)

data_result_2
Out[24]: ['A', 'B', 'C']

In [25]:
</code>```

Body:
The code below is taken from a larger project I'm working on.

The aim of this section is to get the output formatted as a list, with no quotation marks anywhere.

However when I try format the output as a list, it has quotation marks around the outside, I've looked through multiple forums and couldn't find anyone whose had the exact issue.

Coded Input:

colourChart = []
tempColour = tempAlpha

tempColour = "%s" % (', '.join(tempColour)) #! Creates a string, I need it in a List format.
print("What I need it to be formatted as:\n [" + tempColour + "]")

colourChart.append(tempColour) #! Takes previous string, appends to List, adds quotes tho :(
print("What it actually gets formatted as:\n",colourChart)

Output:

What I need it to be formatted as:
 [colourAlpha(0.3), colourAlpha(0.4), colourAlpha(0.5), colourAlpha(0.6)]

What it actually gets formatted as:
 ['colourAlpha(0.3), colourAlpha(0.4), colourAlpha(0.5), colourAlpha(0.6)']

This link has the Python script I was testing this with:
https://drive.google.com/drive/folders/1y1-SkyUoDYrR1UU0ssJd6izjfNsbwZUJ?usp=sharing

Body:
Join creates a string and the string is what is getting appeneded to colourChart. Use extend.

data = ['A', 'B', 'C']

data_result = []

data_result.append(', '.join(data))

data_result
Out[21]: ['A, B, C']

data_result_2 = []

data_result_2.extend(data)

data_result_2
Out[24]: ['A', 'B', 'C']

In [25]:


问:
SQLAlchemy insert from a JSON list to database
I have a list with a JSON like so:

```<code>print(type(listed)) # <class 'list'>
print (listed)

[
   {
       "email": "x@gmail.com",
       "fullname": "xg gf",
       "points": 5,
       "image_url", "https://imgur.com/random.pmg"
   },
   {
        ... similar json for the next user and so on
   }
]
</code>```

I'm trying to insert them into my postgres database that has a model like this:

```<code>class Users(db.Model):
    __tablename__ = 'users'

    email = db.Column(db.String(), primary_key=True)
    displayName = db.Column(db.String())
    image = db.Column(db.String())
    points = db.Column(db.Integer())
</code>```

But I'm quite stuck, I've tried several approaches but none worked, anyone can guide me with an example on how to do it properly?

答:
Using marshmallow-sqlalchemy

validate the incoming JSON

create general utilities for loading and dumping data

Define schemas

schema.py

```<code>from marshmallow import EXCLUDE
from marshmallow_sqlalchemy import ModelSchema
from app import db

class UserSchema(ModelSchema):
    class Meta(ModelSchema.Meta):
        model = Users
        sqla_session = db.session

user_schema_full = UserSchema(only=(
    'email',
    'displayName',
    'image',
    'points'
))

</code>```

utils.py

Exact details below don't matter but create general utility for going from JSON to ORM objects and ORM objects to JSON. schema_partial used for auto generated primary keys.

```<code>def loadData(data, schema_partial, many=False,
             schema_full=None, instance=None):
    try:
        if instance is not None:
            answer = schema_full.load(data, instance=instance, many=many)
        else:
            answer = schema_partial.load(data, many=many)
    except ValidationError as errors:
        raise InvalidData(errors, status_code=400)
    return answer

def loadUser(data, instance=None, many=False):
    return loadData(data=data,
                    schema_partial=user_schema_full,
                    many=many,
                    schema_full=user_schema_full,
                    instance=instance)

def dumpData(load_object, schema, many=False):
    try:
        answer = schema.dump(load_object, many=many)
    except ValidationError as errors:
        raise InvalidDump(errors, status_code=400)
    return answer

def dumpUser(load_object, many=False):
    return dumpData(load_object, schema=user_schema_full, many=many)
</code>```

Use loadUser and dumpUser within api to produce clean flat code.
api.py

```<code>@app.route('/users/', methods=['POST'])
def post_users():
    """Post many users"""
    users_data = request.get_json()
    users =  loadUser(users_data, many=True)
    for user in users:
        db.session.add(user)

    object_dump = dumpUser(users, many=True)

    db.session.commit()

    return jsonify(object_dump), 201
</code>```

Body:
I have a list with a JSON like so:

print(type(listed)) # <class 'list'>
print (listed)

[
   {
       "email": "x@gmail.com",
       "fullname": "xg gf",
       "points": 5,
       "image_url", "https://imgur.com/random.pmg"
   },
   {
        ... similar json for the next user and so on
   }
]

I'm trying to insert them into my postgres database that has a model like this:

class Users(db.Model):
    __tablename__ = 'users'

    email = db.Column(db.String(), primary_key=True)
    displayName = db.Column(db.String())
    image = db.Column(db.String())
    points = db.Column(db.Integer())

But I'm quite stuck, I've tried several approaches but none worked, anyone can guide me with an example on how to do it properly?

Body:
Using marshmallow-sqlalchemy

validate the incoming JSON

create general utilities for loading and dumping data

Define schemas

schema.py

from marshmallow import EXCLUDE
from marshmallow_sqlalchemy import ModelSchema
from app import db

class UserSchema(ModelSchema):
    class Meta(ModelSchema.Meta):
        model = Users
        sqla_session = db.session

user_schema_full = UserSchema(only=(
    'email',
    'displayName',
    'image',
    'points'
))

utils.py

Exact details below don't matter but create general utility for going from JSON to ORM objects and ORM objects to JSON. schema_partial used for auto generated primary keys.

def loadData(data, schema_partial, many=False,
             schema_full=None, instance=None):
    try:
        if instance is not None:
            answer = schema_full.load(data, instance=instance, many=many)
        else:
            answer = schema_partial.load(data, many=many)
    except ValidationError as errors:
        raise InvalidData(errors, status_code=400)
    return answer

def loadUser(data, instance=None, many=False):
    return loadData(data=data,
                    schema_partial=user_schema_full,
                    many=many,
                    schema_full=user_schema_full,
                    instance=instance)

def dumpData(load_object, schema, many=False):
    try:
        answer = schema.dump(load_object, many=many)
    except ValidationError as errors:
        raise InvalidDump(errors, status_code=400)
    return answer

def dumpUser(load_object, many=False):
    return dumpData(load_object, schema=user_schema_full, many=many)

Use loadUser and dumpUser within api to produce clean flat code.
api.py

@app.route('/users/', methods=['POST'])
def post_users():
    """Post many users"""
    users_data = request.get_json()
    users =  loadUser(users_data, many=True)
    for user in users:
        db.session.add(user)

    object_dump = dumpUser(users, many=True)

    db.session.commit()

    return jsonify(object_dump), 201


问:
How to implement 'Autodesk.AEC.LevelsExtension' and 'Autodesk.AEC.Minimap3DExtension'
I have tried to implement 'Autodesk.AEC.LevelsExtension'. and 'Autodesk.AEC.Minimap3DExtension' but it doesn't work for me. I have implemented what you recommend in the post https://forge.autodesk.com/blog/new-rvt-svf-model-derivative-parameter-generates-additional-content-including-rooms-and-spaces

I use the following to convert the model, but I still don't have information about the levels.

```<code>  var format_type = "svf";
  var format_views = ["2d", "3d"];
  Axios({
    method: "POST",
    url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
    headers: {
      "content-type": "application/json",
      Authorization: "Bearer " + access_token,
      'x-ads-force': true
   },
   data: JSON.stringify({
   input: {
    urn: urn
   },
   output: {
    formats: [
      {
        type: format_type,
        views: format_views,
        "advanced": {
          "generateMasterViews": true
          }
        }
      ]
    }
  })
})
</code>```

Note: I use the Autodesk rac_basic_sample_project.rvt and rac_advanced_sample_project.rvt models

答:
We were able to find the solution by using the downloadAecModelData () method</p>

```<code>function onDocumentLoadSuccess(viewerDocument) {
  var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
  viewer.loadDocumentNode(viewerDocument, defaultModel);
  viewerDocument.downloadAecModelData()
}
</code>```

Body:
I have tried to implement 'Autodesk.AEC.LevelsExtension'. and 'Autodesk.AEC.Minimap3DExtension' but it doesn't work for me. I have implemented what you recommend in the post https://forge.autodesk.com/blog/new-rvt-svf-model-derivative-parameter-generates-additional-content-including-rooms-and-spaces

I use the following to convert the model, but I still don't have information about the levels.

  var format_type = "svf";
  var format_views = ["2d", "3d"];
  Axios({
    method: "POST",
    url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
    headers: {
      "content-type": "application/json",
      Authorization: "Bearer " + access_token,
      'x-ads-force': true
   },
   data: JSON.stringify({
   input: {
    urn: urn
   },
   output: {
    formats: [
      {
        type: format_type,
        views: format_views,
        "advanced": {
          "generateMasterViews": true
          }
        }
      ]
    }
  })
})

Note: I use the Autodesk rac_basic_sample_project.rvt and rac_advanced_sample_project.rvt models

Body:
We were able to find the solution by using the downloadAecModelData () method

function onDocumentLoadSuccess(viewerDocument) {
  var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
  viewer.loadDocumentNode(viewerDocument, defaultModel);
  viewerDocument.downloadAecModelData()
}


问:
MySQL innacurate calculation with average and datetime
I'm having problems with time average calculations. I have a table with a lot of records, the table structure is user id, begin and end time of work (if you want, you can download the table script here) and I need to get the effective working time average of each user, so I go like this for the average:

```<code>select iduser, sec_to_time(avg(timestampdiff(second, begin, end)))
from test
group by iduser;
</code>```

So far so good, it returns:

```<code>USER1 00:25:55.9327
USER2 05:47:44.8713
USER3 03:13:43.4724
</code>```

However, the problem is when I try to calculate the average of all users (no grouping):

```<code>select sec_to_time(avg(timestampdiff(second,begin, end))),avg(timestampdiff(second,begin, end))
from test;
</code>```

it returns '03:26:18.9014', but according to my calculations, it should return 03:09:07.333. I checked with constant values and excel test

```<code>select sec_to_time((time_to_sec("00:25:55.9327")+time_to_sec("05:47:44.8713")+time_to_sec("3:13:43.4724"))/3);
</code>```

So far I don't understand why it's returning '03:26:18.9014', it's innacurate according to the other calculations. Do anybody have an idea why is this happening?

答: I figured it out, it's statistic math basics, I can't get the same result if there are different number of records in the groups, each user would have to have the same number of records</p>

Body:
I'm having problems with time average calculations. I have a table with a lot of records, the table structure is user id, begin and end time of work (if you want, you can download the table script here) and I need to get the effective working time average of each user, so I go like this for the average:

select iduser, sec_to_time(avg(timestampdiff(second, begin, end)))
from test
group by iduser;

So far so good, it returns:

USER1 00:25:55.9327
USER2 05:47:44.8713
USER3 03:13:43.4724

However, the problem is when I try to calculate the average of all users (no grouping):

select sec_to_time(avg(timestampdiff(second,begin, end))),avg(timestampdiff(second,begin, end))
from test;

it returns '03:26:18.9014', but according to my calculations, it should return 03:09:07.333. I checked with constant values and excel test

select sec_to_time((time_to_sec("00:25:55.9327")+time_to_sec("05:47:44.8713")+time_to_sec("3:13:43.4724"))/3);

So far I don't understand why it's returning '03:26:18.9014', it's innacurate according to the other calculations. Do anybody have an idea why is this happening?


问:
Reading attributes from an XML file using javascript
I'm having a few issues reading the height and width attributes about an image that has been processed into individual tiles, from an xml file created during this process.

The contents of this file are as such:

```<code><IMAGE_PROPERTIES WIDTH="61504" HEIGHT="25408" NUMTILES="32233" NUMIMAGES="1" VERSION="1.8" TILESIZE="256" />
</code>```

To read the xml file I have used the following code:

```<code><!-- language: lang-js -->

var xhr = new XMLHttpRequest();
xhr.open('GET', path, true);
xhr.timeout = 2000;
xhr.onload = function () {
    var xmlDoc = this.responseXML;
    console.log(xmlDoc);
    var x = xmlDoc.getElementsByTagName("IMAGE_PROPERTIES")[0];
    console.log(x);
};

<!-- end snippet -->
</code>```

How do I now access the height and width attributes?

答: Use the getAttribute function on the element (x in your case) that you found.  See https://www.w3schools.com/xml/met_element_getattribute.asp</p>

Body:
I'm having a few issues reading the height and width attributes about an image that has been processed into individual tiles, from an xml file created during this process.

The contents of this file are as such:

<IMAGE_PROPERTIES WIDTH="61504" HEIGHT="25408" NUMTILES="32233" NUMIMAGES="1" VERSION="1.8" TILESIZE="256" />

To read the xml file I have used the following code:

var xhr = new XMLHttpRequest();
xhr.open('GET', path, true);
xhr.timeout = 2000;
xhr.onload = function () {
    var xmlDoc = this.responseXML;
    console.log(xmlDoc);
    var x = xmlDoc.getElementsByTagName("IMAGE_PROPERTIES")[0];
    console.log(x);
};

How do I now access the height and width attributes?


问:
Why does my promise chain not run sequentially when I use an exported module, but it does when I don't export the module?
I'm trying to get data as a csv from a URL in one file, and then convert that csv in another javascript file to a JSON object using a promise chain. The problem is, it's trying to convert the csv to json before the callback has actually retrieved the csv.

(Note: I realise I'm using the request library which is now deprecated, and will change it once I have the promise chain working).

File 1 (getting the csv data from the url) is below. I need to poll the url until it's populated with the data (usually takes about 5 mins - there are authentication steps beforehand, but they work fine so I'm omitting them to simplify this.) This returns a promise, which is exported as get_csv(). The promise resolves for a csv string.

```<code>const request = require('request');

const csv_url = foo;

module.exports.get_csv = () => {
  return new Promise ((resolve, reject) => {
    function poll_url () {
      request.get({url: csv_url
      }, (error, response, body) => {
        if (error) console.error(error);
        data_csv = body;
        if (data_csv === ''){
          console.log("data_csv is blank.");
        } else {
          clearInterval(intervalID);
          console.log("data_csv has been populated!");
          resolve(data_csv);
        }
      })
    }

    pollURL()
    var intervalID = setInterval(poll_url, 60000);
  })
};
</code>```

JS file 2 (changing the csv data to json) is below. It's meant to just add a .then() to the promise from file 1, which would transform the data from csv to json and then console.log() the json data.

```<code>const data = require('./get_csv_data');   // File 1
const csv = require('csvtojson');

new Promise ((resolve, reject) => {
  const data_csv_string = data.get_csv()
  resolve(data_csv_string);
})

.then(
  (data_csv_string) => {
    console.log(data_csv_string);                        // for debugging - giving undefined
    csv({output: "json"}).fromString(data_csv_string)    // "Cannot read property 'toString' of undefined"
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)
</code>```

The problem is the .then() of file 2 doesn't wait for the first promise's callback to be completed. The console prints out:

```<code>undefined
(node:10691) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'toString' of undefined
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv has been populated!
</code>```

What I can't wrap my head around is, if I put the .then() clause below at the end of File 1, it does work. What am I doing wrong?

```<code>.then(
  (data_csv_string) => {
    console.log(data_csv_string);
    csv({output: "json"}).fromString(data_csv_string)
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)
</code>```

答:
setInterval should be avoided for use cases like this because in some circumstances, multiple invocations of the callback can be enqueued and then dequeued "rapid-fire". It is better to explicitly invoke the retry attempts when you know you are ready; this gives you more control.

There are a number of problems with your code.

For example:

```<code>pollURL()
var intervalID = setInterval(poll_url, 60000)
</code>```

These lines kick-off the polling, even if the first attempt is successful, which might not be what you want.

Here is a refactoring (untested, obviously):

const request = require('request')

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

const repeatUntil = ({fn, condition, interval}) => {
    const go = async (...args) => {
        const result = await fn(...args)
        if(condition(result)) return result
        else {
            await delay(interval)
            await go(...args)
        }
    }
    return go
}

const getURL = (url) => new Promise((resolve, reject) =>
    request.get({url}, (error, response, body) => {
        if (error) return reject(error)
        resolve({response, body})
    }))

const csv_url = 'http://example.com'
const condition = ({body}) => !!body
const interval = 60000
const getCSV = repeatUntil({ fn: () => getURL(csv_url), condition, interval })

module.exports.getCSV = getCSV
```

<p><strong>File 1</strong></p>

<pre class="lang-js prettyprint-override"><code>const getCSV = require('./get-csv')   // File 1
const csvToJSON = require('csvtojson')

getCSV()
    .then(({body}) => {
        const json = csvToJSON({output: "json"}).fromString(body)
        console.log(json)
    })

</code>```

Body:
I'm trying to get data as a csv from a URL in one file, and then convert that csv in another javascript file to a JSON object using a promise chain. The problem is, it's trying to convert the csv to json before the callback has actually retrieved the csv.

(Note: I realise I'm using the request library which is now deprecated, and will change it once I have the promise chain working).

File 1 (getting the csv data from the url) is below. I need to poll the url until it's populated with the data (usually takes about 5 mins - there are authentication steps beforehand, but they work fine so I'm omitting them to simplify this.) This returns a promise, which is exported as get_csv(). The promise resolves for a csv string.

const request = require('request');

const csv_url = foo;

module.exports.get_csv = () => {
  return new Promise ((resolve, reject) => {
    function poll_url () {
      request.get({url: csv_url
      }, (error, response, body) => {
        if (error) console.error(error);
        data_csv = body;
        if (data_csv === ''){
          console.log("data_csv is blank.");
        } else {
          clearInterval(intervalID);
          console.log("data_csv has been populated!");
          resolve(data_csv);
        }
      })
    }

    pollURL()
    var intervalID = setInterval(poll_url, 60000);
  })
};

JS file 2 (changing the csv data to json) is below. It's meant to just add a .then() to the promise from file 1, which would transform the data from csv to json and then console.log() the json data.

const data = require('./get_csv_data');   // File 1
const csv = require('csvtojson');

new Promise ((resolve, reject) => {
  const data_csv_string = data.get_csv()
  resolve(data_csv_string);
})

.then(
  (data_csv_string) => {
    console.log(data_csv_string);                        // for debugging - giving undefined
    csv({output: "json"}).fromString(data_csv_string)    // "Cannot read property 'toString' of undefined"
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)

The problem is the .then() of file 2 doesn't wait for the first promise's callback to be completed. The console prints out:

undefined
(node:10691) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'toString' of undefined
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv has been populated!

What I can't wrap my head around is, if I put the .then() clause below at the end of File 1, it does work. What am I doing wrong?

.then(
  (data_csv_string) => {
    console.log(data_csv_string);
    csv({output: "json"}).fromString(data_csv_string)
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)

Body:
setInterval should be avoided for use cases like this because in some circumstances, multiple invocations of the callback can be enqueued and then dequeued "rapid-fire". It is better to explicitly invoke the retry attempts when you know you are ready; this gives you more control.

There are a number of problems with your code.

For example:

pollURL()
var intervalID = setInterval(poll_url, 60000)

These lines kick-off the polling, even if the first attempt is successful, which might not be what you want.

Here is a refactoring (untested, obviously):

const request = require('request')

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

const repeatUntil = ({fn, condition, interval}) => {
    const go = async (...args) => {
        const result = await fn(...args)
        if(condition(result)) return result
        else {
            await delay(interval)
            await go(...args)
        }
    }
    return go
}

const getURL = (url) => new Promise((resolve, reject) =>
    request.get({url}, (error, response, body) => {
        if (error) return reject(error)
        resolve({response, body})
    }))

const csv_url = 'http://example.com'
const condition = ({body}) => !!body
const interval = 60000
const getCSV = repeatUntil({ fn: () => getURL(csv_url), condition, interval })

module.exports.getCSV = getCSV

File 1

const getCSV = require('./get-csv')   // File 1
const csvToJSON = require('csvtojson')

getCSV()
    .then(({body}) => {
        const json = csvToJSON({output: "json"}).fromString(body)
        console.log(json)
    })