问:
Passing environment envariables inside webpack configuration
What I want to achieve is to set an BACKEND environment variable so our VueJS project will send request to the API of that host however it always return Unexpected token :.

Below is the current code of our config/dev.env.js and I'm a little stuck now

```<code>module.exports = {
  NODE_ENV: '"development"',
  HOST: process.env.BACKEND,
  NAME: '"Jaguar Dashboard"'
}
</code>```

I just want the process.env.BACKEND to have a value like 'http://example.com' and then our VueJS project will now start nicely. How can I solve this?

UPDATE

It is working when I do it like this:

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  HOST: 'http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000',
  NAME: 'Jaguar Dashboard'
})

When I try JSON.stringify(process.env), the error(Unexpected identifier) shows in this line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: JSON.stringify(__webpack_require__.i({\"NODE_ENV\":\"development\",\"HOST\":\"http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000\",\"NAME\":Jaguar Dashboard}).BACKEND),\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6IEpTT04uc3RyaW5naWZ5KHByb2Nlc3MuZW52LkJBQ0tFTkQpLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

When I try '"'+process.env.BACKEND+'"', the error(Unexpected identifier) shows in this line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: '\"'+__webpack_require__.i({\"NODE_ENV\":\"development\",\"HOST\":\"http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000\",\"NAME\":Jaguar Dashboard}).BACKEND+'\"',\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6ICdcIicrcHJvY2Vzcy5lbnYuQkFDS0VORCsnXCInLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

But for my successful code where I just defined a string, it shows the code below on that line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: 'http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000',\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6ICdodHRwOi8vZXhhbXBsZS5jb20nLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

SCREENSHOTS OF THE CODES:

config/dev.env.js

build/webpack.base.conf.js

build/webpack.dev.conf.js

P.S.

All of these response happens when I npm run dev in our VueJS project

答:
Regarding your last edit: you're trying to access process.env but have defined no ENV variable name (like .BACKEND); is it simply a typo or is that the source of the issue here? : )
Because this definitely works:

```<code>plugins: [
    new webpack.DefinePlugin({
        'process.env': {
            BACKEND: JSON.stringify(process.env.BACKEND),
</code>```

Edit:

What helped in the end was a variable value not wrapped in double quotes:

```<code>NAME: 'Our site'

// should have been:
NAME: '"Our site"'
</code>```

Body:
What I want to achieve is to set an BACKEND environment variable so our VueJS project will send request to the API of that host however it always return Unexpected token :.

Below is the current code of our config/dev.env.js and I'm a little stuck now

module.exports = {
  NODE_ENV: '"development"',
  HOST: process.env.BACKEND,
  NAME: '"Jaguar Dashboard"'
}

I just want the process.env.BACKEND to have a value like 'http://example.com' and then our VueJS project will now start nicely. How can I solve this?

UPDATE

It is working when I do it like this:

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  HOST: 'http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000',
  NAME: 'Jaguar Dashboard'
})

When I try JSON.stringify(process.env), the error(Unexpected identifier) shows in this line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: JSON.stringify(__webpack_require__.i({\"NODE_ENV\":\"development\",\"HOST\":\"http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000\",\"NAME\":Jaguar Dashboard}).BACKEND),\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6IEpTT04uc3RyaW5naWZ5KHByb2Nlc3MuZW52LkJBQ0tFTkQpLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

When I try '"'+process.env.BACKEND+'"', the error(Unexpected identifier) shows in this line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: '\"'+__webpack_require__.i({\"NODE_ENV\":\"development\",\"HOST\":\"http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000\",\"NAME\":Jaguar Dashboard}).BACKEND+'\"',\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6ICdcIicrcHJvY2Vzcy5lbnYuQkFDS0VORCsnXCInLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

But for my successful code where I just defined a string, it shows the code below on that line:

eval("var merge = __webpack_require__(424)\nvar prodEnv = __webpack_require__(69)\n\nmodule.exports = merge(prodEnv, {\n  NODE_ENV: '\"development\"',\n  HOST: 'http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000',\n  NAME: 'Jaguar Dashboard'\n})\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMjU4LmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vY29uZmlnL2Rldi5lbnYuanM/NzYxMiJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbWVyZ2UgPSByZXF1aXJlKCd3ZWJwYWNrLW1lcmdlJylcbnZhciBwcm9kRW52ID0gcmVxdWlyZSgnLi9wcm9kLmVudicpXG5cbm1vZHVsZS5leHBvcnRzID0gbWVyZ2UocHJvZEVudiwge1xuICBOT0RFX0VOVjogJ1wiZGV2ZWxvcG1lbnRcIicsXG4gIEhPU1Q6ICdodHRwOi8vZXhhbXBsZS5jb20nLFxuICBOQU1FOiAnSmFndWFyIERhc2hib2FyZCdcbn0pXG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2NvbmZpZy9kZXYuZW52LmpzXG4vLyBtb2R1bGUgaWQgPSAyNThcbi8vIG1vZHVsZSBjaHVua3MgPSA2MCJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///258\n");

SCREENSHOTS OF THE CODES:

config/dev.env.js

build/webpack.base.conf.js

build/webpack.dev.conf.js

P.S.

All of these response happens when I npm run dev in our VueJS project

Body:
Regarding your last edit: you're trying to access process.env but have defined no ENV variable name (like .BACKEND); is it simply a typo or is that the source of the issue here? : )
Because this definitely works:

plugins: [
    new webpack.DefinePlugin({
        'process.env': {
            BACKEND: JSON.stringify(process.env.BACKEND),

Edit:

What helped in the end was a variable value not wrapped in double quotes:

NAME: 'Our site'

// should have been:
NAME: '"Our site"'


来源: stackexchange

问:
How to check if two tables are structurally same?
I have two tables in a SQL Server database. I want to check if these two tables are structurally same. I used UNION/ EXCEPT operator to check this and found that these two tables are not identical.

Here are my questions:

How do we know if two tables are the same in structure?

If they are not same, how do we get the details of differences? If a column is missing in one table how do we get the name of the missing column?

If there is a data type mismatch between a column in these two tables, can we get the name of the column with different data type?

答:
Using sys.dm_exec_describe_first_result_set you can get info about columns in table/query ... In this sample you can see how to make comparison of column name, nullability, datatype and identity

```<code>SELECT DEV.name as DEV_ColumnName,
PROD.name as PROD_ColumnName,
DEV.is_nullable as DEV_is_nullable,
PROD.is_nullable as PROD_is_nullable,
DEV.system_type_name as DEV_Datatype,
PROD.system_type_name as PROD_Datatype,
DEV.is_identity_column as DEV_is_identity,
PROD.is_identity_column as PROD_is_identity
FROM sys.dm_exec_describe_first_result_set (N'SELECT * FROM dbo.TABLE1', NULL, 0) DEV
FULL OUTER JOIN  sys.dm_exec_describe_first_result_set (N'SELECT * FROM dbo.TABLE2', NULL, 0) PROD
ON DEV.name = PROD.name
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using sys.dm_exec_describe_first_result_set you can get info about columns in table/query ... In this sample you can see how to make comparison of column name, nullability, datatype and identity

SELECT DEV.name as DEV_ColumnName,
PROD.name as PROD_ColumnName,
DEV.is_nullable as DEV_is_nullable,
PROD.is_nullable as PROD_is_nullable,
DEV.system_type_name as DEV_Datatype,
PROD.system_type_name as PROD_Datatype,
DEV.is_identity_column as DEV_is_identity,
PROD.is_identity_column as PROD_is_identity
FROM sys.dm_exec_describe_first_result_set (N'SELECT * FROM dbo.TABLE1', NULL, 0) DEV
FULL OUTER JOIN  sys.dm_exec_describe_first_result_set (N'SELECT * FROM dbo.TABLE2', NULL, 0) PROD
ON DEV.name = PROD.name


问:
Windows: The application was unable to start correctly (0xc000007b)
Here I am installing Mongodb for first time on Windows 8.1 through .msi file downloaded from https://www.mongodb.com and getting following error.

```<code>mongod.exe - Application Error
---------------------------
The application was unable to start correctly (0xc000007b). Click OK to close the application.
---------------------------
</code>```

How this error can be removed?
As per R&D, I found that its issue with some windows dependencies

答: please keep libeay32.dll and  ssleay32.dll  inside folder where mongodump.exe is present.</p>

Body:
Here I am installing Mongodb for first time on Windows 8.1 through .msi file downloaded from https://www.mongodb.com and getting following error.

mongod.exe - Application Error
---------------------------
The application was unable to start correctly (0xc000007b). Click OK to close the application.
---------------------------

How this error can be removed?
As per R&D, I found that its issue with some windows dependencies


问:
Django Rest Framework : Got AttributeError when attempting to get a value for field `data_params` on serializer `OrderCreateSerializer`
This is my models:

```<code>class Order(models.Model):
    """
    订单
    """
    order_num = models.CharField(max_length=128, unique=True)  # 订单编号
    order_status = models.CharField(max_length=12)  # 订单状态  "未支付"， "已支付，未完成"， "已完成"， "已经删除"，"其他"
    product_describe = models.TextField()  # 产品描述
    billing_type = models.CharField(max_length=16)  # 计费类型
    buytime = models.CharField(max_length=16)  # 比如：1月  永久
    count = models.IntegerField()  # 购买数量
    paytype = models.CharField(max_length=16)  # 支付方式（支付包，微信，xxx）
    cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)  # 费用（需要花费多少钱）
    account = models.ForeignKey(to=Account) # 所属账户

    ctime = models.DateTimeField(auto_now_add=True)  # 创建时间
    uptime = models.DateTimeField(auto_now=True)  # 更新时间

    def __str__(self):
        return self.product_describe
    def __unicode__(self):
        return self.product_describe
</code>```

This is my serializer:

```<code>class OrderCreateSerializer(ModelSerializer):

    data_params = serializers.DictField()  # 根据产品数据模型不同而异

    class Meta:
        model = Order
        fields = (
            "product_describe",  # 产品描述 (购买xx产品 + 参数)
            "billing_type", # 计费类型 ("包年包月")
            # "buytime", # "购买时间"
            # "count", # 数量
            # "paytype", # 支付方式
            "data_params",  # 数据
        )
    def create(self, validated_data):

        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user

        validated_data["order_num"] = generateOrderNum(userid=user.id)
        validated_data["order_status"] = "未支付"

        data_dic = validated_data.pop("data_params") #

        validated_data["buytime"] = data_dic["data"]["buytime"]
        validated_data["count"] = data_dic["data"]["count"]
        validated_data["paytype"] = ""  # 支付类型

        validated_data["cost"] = 0.00  # 所需钱
        validated_data["account"] = user.account  # 是哪个账户

        return Order.objects.create(**validated_data)
</code>```

You see, in  my serializer I have pop the data_params:

```<code>data_dic = validated_data.pop("data_params")
</code>```

But when I access this API, I get:

AttributeError at /api/financialmanage/order/add/

  Got AttributeError when attempting to get a value for field data_params on serializer OrderCreateSerializer.

  The serializer field might be named incorrectly and not match any attribute or key on the Order instance.

  Original exception text was: 'Order' object has no attribute 'data_params'.

If I don't pop data_params, I will get bellow error:

TypeError at /api/financialmanage/order/add/

  'data_params' is an invalid keyword argument for this function

EDIT

My views.py:

```<code>class OrderSerializerCreateAPIView(CreateAPIView):
    """
    create Order
    """
    serializer_class = OrderCreateSerializer
    permission_classes = []
    queryset = Order.objects.all()
</code>```

EDIT-2

In my case the data_params dictionary is necessary for me.
Because when I buy a product(such as CloudServer), which has count, vcpus, ram, disk, and bandwidth, I through the data_params to get that.

You may want to know why I must use data_params to receive the data, because, the product may be different, if the product is Wine, it can not have the vcpus property now.

答:
If you want to add the data-params argument to the serializer when it is not a field in the model you should use the def to_representation function of DRF. Should look something like this:

```<code>def to_representation(self, instance):
serialized_data = super(SerializerClass, self).to_representation(instance)
serialized_data['data-params'] = #logic goes here
return serialized_data
</code>```

And remove data-params from fields parameter of the Meta class.

Body:
This is my models:

class Order(models.Model):
    """
    订单
    """
    order_num = models.CharField(max_length=128, unique=True)  # 订单编号
    order_status = models.CharField(max_length=12)  # 订单状态  "未支付"， "已支付，未完成"， "已完成"， "已经删除"，"其他"
    product_describe = models.TextField()  # 产品描述
    billing_type = models.CharField(max_length=16)  # 计费类型
    buytime = models.CharField(max_length=16)  # 比如：1月  永久
    count = models.IntegerField()  # 购买数量
    paytype = models.CharField(max_length=16)  # 支付方式（支付包，微信，xxx）
    cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)  # 费用（需要花费多少钱）
    account = models.ForeignKey(to=Account) # 所属账户

    ctime = models.DateTimeField(auto_now_add=True)  # 创建时间
    uptime = models.DateTimeField(auto_now=True)  # 更新时间

    def __str__(self):
        return self.product_describe
    def __unicode__(self):
        return self.product_describe

This is my serializer:

class OrderCreateSerializer(ModelSerializer):

    data_params = serializers.DictField()  # 根据产品数据模型不同而异

    class Meta:
        model = Order
        fields = (
            "product_describe",  # 产品描述 (购买xx产品 + 参数)
            "billing_type", # 计费类型 ("包年包月")
            # "buytime", # "购买时间"
            # "count", # 数量
            # "paytype", # 支付方式
            "data_params",  # 数据
        )
    def create(self, validated_data):

        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user

        validated_data["order_num"] = generateOrderNum(userid=user.id)
        validated_data["order_status"] = "未支付"

        data_dic = validated_data.pop("data_params") #

        validated_data["buytime"] = data_dic["data"]["buytime"]
        validated_data["count"] = data_dic["data"]["count"]
        validated_data["paytype"] = ""  # 支付类型

        validated_data["cost"] = 0.00  # 所需钱
        validated_data["account"] = user.account  # 是哪个账户

        return Order.objects.create(**validated_data)

You see, in  my serializer I have pop the data_params:

data_dic = validated_data.pop("data_params")

But when I access this API, I get:

AttributeError at /api/financialmanage/order/add/

  Got AttributeError when attempting to get a value for field data_params on serializer OrderCreateSerializer.

  The serializer field might be named incorrectly and not match any attribute or key on the Order instance.

  Original exception text was: 'Order' object has no attribute 'data_params'.

If I don't pop data_params, I will get bellow error:

TypeError at /api/financialmanage/order/add/

  'data_params' is an invalid keyword argument for this function

EDIT

My views.py:

class OrderSerializerCreateAPIView(CreateAPIView):
    """
    create Order
    """
    serializer_class = OrderCreateSerializer
    permission_classes = []
    queryset = Order.objects.all()

EDIT-2

In my case the data_params dictionary is necessary for me.
Because when I buy a product(such as CloudServer), which has count, vcpus, ram, disk, and bandwidth, I through the data_params to get that.

You may want to know why I must use data_params to receive the data, because, the product may be different, if the product is Wine, it can not have the vcpus property now.

Body:
If you want to add the data-params argument to the serializer when it is not a field in the model you should use the def to_representation function of DRF. Should look something like this:

def to_representation(self, instance):
serialized_data = super(SerializerClass, self).to_representation(instance)
serialized_data['data-params'] = #logic goes here
return serialized_data

And remove data-params from fields parameter of the Meta class.


问:
Test string with a string list
I have a list of Id contained in an array :

```<code>var listId: string[] = [];
var newId: boolean;
for (let i in data.chunk) {
    listId.push(data.chunk[i].aliases[0]);
}
</code>```

I then want to test my new Id with this whole list. If my new Id is in the list I want to return a false, and if it is not returned a true.

```<code>for(let i of listId) {
    if(member.userId !== listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }
</code>```

I do not see how to do it .. My proposed solution does not work

答:
This will work too</p>

```<code>return !listId.some(id => member.userId === id);
</code>```

Title: Test string with a string list

Body:
I have a list of Id contained in an array :

var listId: string[] = [];
var newId: boolean;
for (let i in data.chunk) {
    listId.push(data.chunk[i].aliases[0]);
}

I then want to test my new Id with this whole list. If my new Id is in the list I want to return a false, and if it is not returned a true.

for(let i of listId) {
    if(member.userId !== listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }

I do not see how to do it .. My proposed solution does not work

Body:
This will work too

return !listId.some(id => member.userId === id);


问:
Warning: Multiple EventSystem in scene
In Unity I have two Canvas. In every Canvas has own EventSytems.But when I RUN this it gives me yellow message

Multiple EventSystems in scene... this is not supported

..and I tried inactive one of the canvas by script.After Warning not appeared But then buttons not working. How can I solve this problem ?

答:
Multiple Canvas in unity is fine, i already try that.
But multiple EventSystem is not allowed, you have to remove on of the EventSystem GameObject/Component.

One EventSystem is okay for multiple canvas.

Also it's better to place your event system object outside the Canvas, don't make it as the child of the canvas.

Title: Warning: Multiple EventSystem in scene


问:
Insert 120 second wait in Visual studio Webtest
I want to add a delay of 120 second between the execution of two web requests. I have tried using think time but it won't pause the execution for 120 sec.

Can anyone please let me know how to add wait to pause the execution for 120 second (after say 2 web request execution) and then proceed the execution for next request.

I am using visual studio 2015.

答:
You can do this </p>

```<code> Thread.Sleep(Number_Second);
</code>```

Body:
You can do this

 Thread.Sleep(Number_Second);


问:
my code didnt break and try to fill every line
i try to launch my code to crete a simple elearning website which use pymongo as database. i write the codes in google docs before it save it in pymongo.

the main problem is, my code didnt break(br) like it use to and even trying to fill all line. this only occur to short code but doesnt do the same with long one. it happen sometimes but i cant seems to get it fix. i did try to remove the css to see if the problem is from there but same thing happens. i dont know what seems to be the problem.

```<code><h4>i love food</h4>

<p>there are many food i like.</p>

<p>the food are as follow:</p>
<ul>
    <li>chicken</li>
    <li>fish</li>
    <li>nugget</li>
    </ul><br>

<p>all from above is my favourite</p>

<h4>MA 7 & EMA 26</h4><br>
</code>```

here are a simple code similar to mine. but the problem is the code stacks.

result :

```<code>i love food

there are many food like.
the food are as follow:  .chicken     all from above is my favourite
                            .fish
                            .nugget

MA 7 & EMA 26
</code>```

as you can see, some stack and some dont. im preatty sure is not the code. but  cant think of another problem.

答:
Your code works fine !

https://jsfiddle.net/zvdqk0mr/

Use

 and CSS .clear{clear:both;}

instead of
 if you facing this line break issue

https://jsfiddle.net/zvdqk0mr/1/

Body:
i try to launch my code to crete a simple elearning website which use pymongo as database. i write the codes in google docs before it save it in pymongo.

the main problem is, my code didnt break(br) like it use to and even trying to fill all line. this only occur to short code but doesnt do the same with long one. it happen sometimes but i cant seems to get it fix. i did try to remove the css to see if the problem is from there but same thing happens. i dont know what seems to be the problem.

i love food

there are many food i like.

the food are as follow:

chicken

fish

nugget

all from above is my favourite

MA 7 & EMA 26

here are a simple code similar to mine. but the problem is the code stacks.

result :

i love food

there are many food like.
the food are as follow:  .chicken     all from above is my favourite
                            .fish
                            .nugget

MA 7 & EMA 26

as you can see, some stack and some dont. im preatty sure is not the code. but  cant think of another problem.

Body:
Your code works fine !

https://jsfiddle.net/zvdqk0mr/

Use <div class="clear">&nbsp;</div> and CSS .clear{clear:both;}

instead of <br> if you facing this line break issue

https://jsfiddle.net/zvdqk0mr/1/


问:
Odoo can't open form view from wizard on button click
I have created wizard. And on button click I want to open form view with specific model record id.

```<code>@api.multi
def create_order(self):
    view = self.env.ref('purchase.purchase_order_form')
    context = self.env.context
    return {
         'name':'Name',
         'type': 'ir.actions.act_window',
         'view_type': 'form',
         'view_mode': 'form',
         'res_model': 'purchase.order',
         'views': [(view.id, 'form')],
         'view_id': view.id,
         'res_id': 264,
         'context': context,
    }
</code>```

The problem is that on button click I can't open other form view.

If I add 'target': 'new', then on button click on popup window I open form which I need:

```<code>   @api.multi
    def create_order(self):
        view = self.env.ref('purchase.purchase_order_form')
        context = self.env.context
        return {
             'name':'Name',
             'type': 'ir.actions.act_window',
             'view_type': 'form',
             'view_mode': 'form',
             'res_model': 'purchase.order',
             'views': [(view.id, 'form')],
             'view_id': view.id,
             'target': 'new',
             'res_id': 264,
             'context': context,
        }
</code>```

The problem is that on button click I need to open specific form but like popup window.
I tried set 'target': 'inline' or 'target': 'current' but nothing happens.

答:
I think the problem will resides on your param res_id, this is not needed actually. its only return the record of res_id if exists. Any way I give you an valid example. so please try:</p>

```<code>return {
        'name': _('Compose Email'),
        'type': 'ir.actions.act_window',
        'view_type': 'form',
        'view_mode': 'form',
        'res_model': 'mail.compose.message',
        'views': [(compose_form.id, 'form')],
        'view_id': compose_form.id,
        'target': 'new',
        'context': ctx,
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created wizard. And on button click I want to open form view with specific model record id.

@api.multi
def create_order(self):
    view = self.env.ref('purchase.purchase_order_form')
    context = self.env.context
    return {
         'name':'Name',
         'type': 'ir.actions.act_window',
         'view_type': 'form',
         'view_mode': 'form',
         'res_model': 'purchase.order',
         'views': [(view.id, 'form')],
         'view_id': view.id,
         'res_id': 264,
         'context': context,
    }

The problem is that on button click I can't open other form view.

If I add 'target': 'new', then on button click on popup window I open form which I need:

   @api.multi
    def create_order(self):
        view = self.env.ref('purchase.purchase_order_form')
        context = self.env.context
        return {
             'name':'Name',
             'type': 'ir.actions.act_window',
             'view_type': 'form',
             'view_mode': 'form',
             'res_model': 'purchase.order',
             'views': [(view.id, 'form')],
             'view_id': view.id,
             'target': 'new',
             'res_id': 264,
             'context': context,
        }

The problem is that on button click I need to open specific form but like popup window.
I tried set 'target': 'inline' or 'target': 'current' but nothing happens.

Body:
I think the problem will resides on your param res_id, this is not needed actually. its only return the record of res_id if exists. Any way I give you an valid example. so please try:

return {
        'name': _('Compose Email'),
        'type': 'ir.actions.act_window',
        'view_type': 'form',
        'view_mode': 'form',
        'res_model': 'mail.compose.message',
        'views': [(compose_form.id, 'form')],
        'view_id': compose_form.id,
        'target': 'new',
        'context': ctx,
    }


问:
Create file failed from mkdir()
I try to create file in my android emulator, but when i finish my code.
I can't find the file i create from android device monitor.

Here is my code:

```<code>try {
    if (Environment.getExternalStorageState()
            .equals(Environment.MEDIA_MOUNTED)) {
        System.out.println("can be read and write");
        File sdFile = android.os.Environment.getExternalStorageDirectory();

        //String path = sdFile.getPath() + File.separator + "DestPdf";
        String path = sdFile.getPath() + "/demos/file/tmp/test";
        File dirFile = new File(path);

        if (!dirFile.exists()) { // if file doesn't exist
            System.out.println("create file");
            dirFile.mkdir(); // create file
            System.out.println(dirFile.toString());
        }
    }
} catch (Exception ex) {
    ex.toString();
}
</code>```

I also add some permissions:

```<code><uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
</code>```

Here is my print out, i can see the root /storage/sdcard/demos/file/tmp/test

```<code>11-17 08:38:10.263 15501-15501/? I/System.out: can be read and write
11-17 08:38:10.263 15501-15501/? I/System.out: create file
11-17 08:38:10.264 15501-15501/? I/System.out: /storage/sdcard/demos/file/tmp/test
</code>```

But i can't find the file from android device monitor

What step i miss it ? Any help would be appreciated . Thanks in advance.

答:
For Android 6+ you need to add code to ask the user to confirm the permissions you asked in manifest.

Google for runtime permissions.

Title: Create file failed from mkdir()

Body:
I try to create file in my android emulator, but when i finish my code.
I can't find the file i create from android device monitor.

Here is my code:

try {
    if (Environment.getExternalStorageState()
            .equals(Environment.MEDIA_MOUNTED)) {
        System.out.println("can be read and write");
        File sdFile = android.os.Environment.getExternalStorageDirectory();

        //String path = sdFile.getPath() + File.separator + "DestPdf";
        String path = sdFile.getPath() + "/demos/file/tmp/test";
        File dirFile = new File(path);

        if (!dirFile.exists()) { // if file doesn't exist
            System.out.println("create file");
            dirFile.mkdir(); // create file
            System.out.println(dirFile.toString());
        }
    }
} catch (Exception ex) {
    ex.toString();
}

I also add some permissions:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

Here is my print out, i can see the root /storage/sdcard/demos/file/tmp/test

11-17 08:38:10.263 15501-15501/? I/System.out: can be read and write
11-17 08:38:10.263 15501-15501/? I/System.out: create file
11-17 08:38:10.264 15501-15501/? I/System.out: /storage/sdcard/demos/file/tmp/test

But i can't find the file from android device monitor

What step i miss it ? Any help would be appreciated . Thanks in advance.


问:
create table from selected value to be new column in new table
I have SQL (phpmyadmin) syntax like that and its return some value.

SELECT data FROM table_data WHERE data = 'input';

Value of

    data in table_data

    ==========

    data1

    data2

    data3

    data4

My Question is, how can I make a new table_column in db from selected value to be new column in my new table?

CREATE TABLE table_data_new AS SELECT data FROM table_data WHERE data = 'input';

if I use that syntax, that make new table but the column in selected value is copied to my new table. Anybody, please help me solve that problem :)

I want schema like this :

    table_new_data

    have column like this

    ==============

    data1 | data2 | data3 | data4

答:
Seems you need  a create like  (create an empty table based on an existing table )

fro sql server you can use

```<code> SELECT * INTO table_data_new  FROM table_data  WHERE 1 = 0;
</code>```

for oracle  and mysql (phpmyadmin)

```<code>CREATE TABLE table_data_new  LIKE table_data  ;
</code>```

in phpmyadmin you have a proper panel for create like  tables (panel operation)

Body:
Seems you need  a create like  (create an empty table based on an existing table )

fro sql server you can use

 SELECT * INTO table_data_new  FROM table_data  WHERE 1 = 0;

for oracle  and mysql (phpmyadmin)

CREATE TABLE table_data_new  LIKE table_data  ;

in phpmyadmin you have a proper panel for create like  tables (panel operation)


问:
How to take the values using data-list but values is already selected
Here i am using data-list i have one URL in that i am passing areaId= 2 & areaName = Chennai,Now i have to take the values and i want to make that value is selected,and again i want to change the areaName so i am changing instead of Chennai , i changed Karur means finally i am clicking submit button means i want to take the areaId & areaName

 $('.options').on('change', function() {
     var city_id = $('#options option[value="' + $('#location12').val() + '"]').data('id');
  $('#city_id').val(city_id);
  console.log(city_id);

});

function myFunction (){

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form method="POST">
<input list="options" type="name" class="form-control options" style="border-radius:0px;height: 36px;" name="location12" id="location12" placeholder="City" rel='<?php echo $_GET['areaId']?>' value='<?php echo $_GET['areaName']?>'>
 <datalist id="options">
 <option data-id="1" value="Bangalore"></option>
 <option data-id="2" value="Chennai"></option>
 <option data-id="3" value="Karur"></option>
 </datalist>
<input type="hidden" name="city_id" id="city_id">
<input type="submit" value="submit">
</form></code>```

答:
you have 3 options there, either use the default PHP value to set the text input value and dynamically set the city_id value on load/ready with JS, do the contrary and set the datalist corresponding option with adding selected="selected" in PHP and update the text input on load, or finally set them both in PHP.

here is the most simple case for PHP: setting the text input value and update city_id. For the second solution there is a bit more code as you have to test the options and add selected="selected" manually if the good one. I would personnally prefer the second because your PHP value will actually be verified against the options so that nothing will be selected if PHP value is wrong and does not correspond to any option value.

 $('.options').on('change', function() {
     var city_id = $('#options option[value="' + $('#location12').val() + '"]').data('id');
  $('#city_id').val(city_id);
  console.log(city_id);

});

//setting one of the element value based on the other's default value:
$(document).ready(function(){
    //use this to set text input based on default selected option
    //$('#location12').val($('#options option:selected').val());
    //console.log('text input is now: ' + $('#location12').val());

    //or this for the other way round
    $('#city_id').val($('#options option[value="' + $('#location12').val() + '"]').data('id'));
    console.log('city_id is now: ' + $('#city_id').val());
});

function myFunction (){

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form method="POST">
<input list="options" type="name" class="form-control options" style="border-radius:0px;height: 36px;" name="location12" id="location12" placeholder="City" rel="<?php echo $_GET['areaId']?>" value="Karur">
 <datalist id="options">
 <option data-id="1" value="Bangalore"></option>
 <option data-id="2" value="Chennai" selected="selected"></option>
 <option data-id="3" value="Karur"></option>
 </datalist>
<input type="hidden" name="city_id" id="city_id">
<input type="submit" value="submit">
</form></code>```

Body:
Here i am using data-list i have one URL in that i am passing areaId= 2 & areaName = Chennai,Now i have to take the values and i want to make that value is selected,and again i want to change the areaName so i am changing instead of Chennai , i changed Karur means finally i am clicking submit button means i want to take the areaId & areaName

 $('.options').on('change', function() {
     var city_id = $('#options option[value="' + $('#location12').val() + '"]').data('id');
  $('#city_id').val(city_id);
  console.log(city_id);

});

function myFunction (){

}

<form method="POST">
<input list="options" type="name" class="form-control options" style="border-radius:0px;height: 36px;" name="location12" id="location12" placeholder="City" rel='<?php echo $_GET['areaId']?>' value='<?php echo $_GET['areaName']?>'>
 <datalist id="options">
 <option data-id="1" value="Bangalore"></option>
 <option data-id="2" value="Chennai"></option>
 <option data-id="3" value="Karur"></option>
 </datalist>
<input type="hidden" name="city_id" id="city_id">
<input type="submit" value="submit">
</form>

Body:
you have 3 options there, either use the default PHP value to set the text input value and dynamically set the city_id value on load/ready with JS, do the contrary and set the datalist corresponding option with adding selected="selected" in PHP and update the text input on load, or finally set them both in PHP.

here is the most simple case for PHP: setting the text input value and update city_id. For the second solution there is a bit more code as you have to test the options and add selected="selected" manually if the good one. I would personnally prefer the second because your PHP value will actually be verified against the options so that nothing will be selected if PHP value is wrong and does not correspond to any option value.

 $('.options').on('change', function() {
     var city_id = $('#options option[value="' + $('#location12').val() + '"]').data('id');
  $('#city_id').val(city_id);
  console.log(city_id);

});

//setting one of the element value based on the other's default value:
$(document).ready(function(){
    //use this to set text input based on default selected option
    //$('#location12').val($('#options option:selected').val());
    //console.log('text input is now: ' + $('#location12').val());

    //or this for the other way round
    $('#city_id').val($('#options option[value="' + $('#location12').val() + '"]').data('id'));
    console.log('city_id is now: ' + $('#city_id').val());
});

function myFunction (){

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form method="POST">
<input list="options" type="name" class="form-control options" style="border-radius:0px;height: 36px;" name="location12" id="location12" placeholder="City" rel="<?php echo $_GET['areaId']?>" value="Karur">
 <datalist id="options">
 <option data-id="1" value="Bangalore"></option>
 <option data-id="2" value="Chennai" selected="selected"></option>
 <option data-id="3" value="Karur"></option>
 </datalist>
<input type="hidden" name="city_id" id="city_id">
<input type="submit" value="submit">
</form>


问:
Laravel 5.5 eloquent request in blade and many sql queries
I need output user payments history. With payment method detail. Like card or paypall data for each payment

```<code><table border="1">
        <tr>
        <th>
        </th>
        <th>
            summ
        </th>
        <th>
            date
        </th>
        <th>
            payment method
        </th>
        <th>
            subscription
        </th>
        <th></th>
        </tr>
    @foreach($user -> payments()->get() as $payment)
        <tr>
            <td>
            {{$payment->type}}
            </td>
            <td>
            {{$payment->amount}}$
            </td>
            <td>
            {{$payment->created_at}}
            </td>
            <td>
                   @if($payment -> payment_method()->first()->type == PaymentMethod::PAYPAL_ACCOUNT)
                        <div><strong>Paypal: </strong> {{ $payment -> payment_method() -> first() -> paypal_email }}</div>
                    @else
                        <div><strong>Card: </strong>{{ $payment -> payment_method() -> first() -> card_brand }} **** **** **** {{ $payment -> payment_method() -> first() -> card_last_four }}</div>
                    @endif
            </td>
            <td>
                <div><strong>plan:</strong> {{ $payment->subscription->plan->name }}</div>
                <div><strong>period:</strong> {{ $payment->period_start->format('d.m.Y')}} - {{ $payment->period_end->format('d.m.Y') }}</div>
            </td>
            <td>
                @if (!empty($payment -> void_at))
                    <div>void {{ $payment -> void_at }}</div>
                @elseif (!empty($payment->refund_at))
                    <div>refunded {{ $payment->refund_at }} </div>
                @elseif(!empty($payment->refunded_transaction_id ))
                     <div>refund</div>
                @endif
            </td>
        </tr>
    @endforeach
</table>
</code>```

This code generates many sql request's in each cycle iteration:

```<code>select * from `payment_method` where `payment_method`.`id` = '3' and `payment_method`.`deleted_at` is null limit 1

select * from `payment_method` where `payment_method`.`id` = '3' and `payment_method`.`deleted_at` is null limit 1
</code>```

My models:

User class. With realation to payment one to many

```<code>class User extends Authenticatable
{

    public function payments()
    {
        return $this->hasMany(Payment::class, $this->getForeignKey())->orderBy('created_at', 'desc');
    }

}
</code>```

Payment class with relation to payment method one to one

```<code>class Payment extends Model
{

    public function payment_method()
    {
        return $this->belongsTo(PaymentMethod::class, 'payment_method_id', 'id');
    }
</code>```

How change my code for avoid this

答:
You can try like this:

```<code>$user = User::with("payments")->find($user_id);
</code>```

and use foreach

```<code>@foreach($user->payments as $payment)
    {{$payment->type}}
@endforeach
</code>```

Off course, you can change this piece of code as you wish.

Body:
I need output user payments history. With payment method detail. Like card or paypall data for each payment

            summ

            date

            payment method

            subscription

    @foreach($user -> payments()->get() as $payment)

            {{$payment->type}}

            {{$payment->amount}}$

            {{$payment->created_at}}

                   @if($payment -> payment_method()->first()->type == PaymentMethod::PAYPAL_ACCOUNT)

Paypal:  {{ $payment -> payment_method() -> first() -> paypal_email }}

                    @else

Card: {{ $payment -> payment_method() -> first() -> card_brand }} **** **** **** {{ $payment -> payment_method() -> first() -> card_last_four }}

                    @endif

plan: {{ $payment->subscription->plan->name }}

period: {{ $payment->period_start->format('d.m.Y')}} - {{ $payment->period_end->format('d.m.Y') }}

                @if (!empty($payment -> void_at))

void {{ $payment -> void_at }}

                @elseif (!empty($payment->refund_at))

refunded {{ $payment->refund_at }}

                @elseif(!empty($payment->refunded_transaction_id ))

refund

                @endif

    @endforeach

This code generates many sql request's in each cycle iteration:

select * from `payment_method` where `payment_method`.`id` = '3' and `payment_method`.`deleted_at` is null limit 1

select * from `payment_method` where `payment_method`.`id` = '3' and `payment_method`.`deleted_at` is null limit 1

My models:

User class. With realation to payment one to many

class User extends Authenticatable
{

    public function payments()
    {
        return $this->hasMany(Payment::class, $this->getForeignKey())->orderBy('created_at', 'desc');
    }

}

Payment class with relation to payment method one to one

class Payment extends Model
{

    public function payment_method()
    {
        return $this->belongsTo(PaymentMethod::class, 'payment_method_id', 'id');
    }

How change my code for avoid this

Body:
You can try like this:

$user = User::with("payments")->find($user_id);

and use foreach

@foreach($user->payments as $payment)
    {{$payment->type}}
@endforeach

Off course, you can change this piece of code as you wish.


问:
Shifting rows in a UITableView
I have looked at several forums and read different threads, but I can't seem to find an answer. I'd really like some help. I have an array that stores Labels whose contents I display in the UITableView's row. The second row contains fresh data added to the same array and so on. My question is, everytime the labels are displayed in the UITableView, I want it to be displayed on the top row. In essence, the older ones keeps shifting one row down. I understand I need to use: "tableView:moveRowAtIndexPath:toIndexPath:" but it only seems to work with arrays whose contents are strings.

Just to clarify, I'm not displaying each element of the array on a new line. I'm displaying all the elements of the array on a single row, then changing the elements and displaying that as the next row. Except I want the second row to be above the first and so on.

答: First of all you don't need to keep the label in some array, you can keep only the string. And when add an new object to the array add it on position 0 and the do and reload of table view.</p>

Title: Shifting rows in a UITableView

ContentLicense: CC BY-SA 2.5


问:
Divide results in two columns depending on the input values? SQL Server
I am using the Nortwind database with SQL Server 2014, I try to make a query to divide the results of the orders in two different years, The format that I want in my query is

```<code>category |anio one | anio two
</code>```

where the years may vary , What I try so far is

```<code>SELECT ca.CategoryName , YEAR(o.OrderDate), SUM(ot.UnitPrice*ot.Quantity) as total
FROM Orders o
INNER JOIN [Order Details] ot ON O.OrderID = ot.OrderID
INNER JOIN Products pro ON ot.ProductID = pro.ProductID
INNER JOIN Categories ca ON pro.CategoryID = ca.CategoryID
GROUP BY ca.CategoryName,YEAR(o.OrderDate)
ORDER BY ca.CategoryName;
</code>```

This gives me the totals of each category for a different year, 1996-1997-1998 in column  YEAR(o.OrderDate)

I want to get for example

```<code>CategoryName | 1996 | 1997

Beverages   |53879,20 | 110424,00
Condiments  |19458,30 | 59679,00
....
</code>```

答:
you can use pivot to get the desired output</p>

```<code> CREATE TABLE #TEMP
 (
    Category VARCHAR(200),
    YEAR1 NUMERIC,
    Total MONEY
 )

INSERT INTO #TEMP
SELECT 'beverages', 1996, 500
union
SELECT 'beverages', 1997, 750
union
SELECT 'Condiments', 1997, 1000
union
SELECT 'Condiments', 1996, 800

SELECT *
FROM
    (
      SELECT Category,YEAR1, Total  FROM #TEMP
    ) AS SourceTable
PIVOT
   (
      AVG(Total) FOR YEAR1 IN ( [1996], [1997])
   ) AS PivotTable;
</code>```

Body:
I am using the Nortwind database with SQL Server 2014, I try to make a query to divide the results of the orders in two different years, The format that I want in my query is

category |anio one | anio two

where the years may vary , What I try so far is

SELECT ca.CategoryName , YEAR(o.OrderDate), SUM(ot.UnitPrice*ot.Quantity) as total
FROM Orders o
INNER JOIN [Order Details] ot ON O.OrderID = ot.OrderID
INNER JOIN Products pro ON ot.ProductID = pro.ProductID
INNER JOIN Categories ca ON pro.CategoryID = ca.CategoryID
GROUP BY ca.CategoryName,YEAR(o.OrderDate)
ORDER BY ca.CategoryName;

This gives me the totals of each category for a different year, 1996-1997-1998 in column  YEAR(o.OrderDate)

I want to get for example

CategoryName | 1996 | 1997

Beverages   |53879,20 | 110424,00
Condiments  |19458,30 | 59679,00
....

Body:
you can use pivot to get the desired output

 CREATE TABLE #TEMP
 (
    Category VARCHAR(200),
    YEAR1 NUMERIC,
    Total MONEY
 )

INSERT INTO #TEMP
SELECT 'beverages', 1996, 500
union
SELECT 'beverages', 1997, 750
union
SELECT 'Condiments', 1997, 1000
union
SELECT 'Condiments', 1996, 800

SELECT *
FROM
    (
      SELECT Category,YEAR1, Total  FROM #TEMP
    ) AS SourceTable
PIVOT
   (
      AVG(Total) FOR YEAR1 IN ( [1996], [1997])
   ) AS PivotTable;


问:
Immediate evaluation of CTE
I am trying to optimize a very long and complex impala query which contains multiple CTE. Each CTE is used multiple times. My expectation is that once a CTE is created, I should be able to direct impala that results of this CTE should be re-used in main query as-is instead of SCAN HDFS operation on tables involved in CTE again with the main query. Is this possible? if yes how ?

I am using impalad version 2.1.1-cdh5 RELEASE (build 7901877736e29716147c4804b0841afc4ebc9037) version

答:
Is this possible?

The very purpose of the CTE is to re-use of the results obtained from a preceding query (that uses the with clause) by a following query, say, SELECT. So i don't see a reason why it is not possible.

Use Explain on your query to find out the actual SCAN HDFS details.

For more I/O related insights use profile as in the official documentation https://www.cloudera.com/documentation/enterprise/5-7-x/topics/impala_explain_plan.html#perf_profile

Title: Immediate evaluation of CTE


问:
Find out string array lengthand each string length
Consider the following array of "strings" in C:

```<code>const char* const animals[] =
{
    "",
    "Cat",
    "Dawg",
    "Elephant",
    "Tiger",
};
</code>```

Is it possible to obtain:

The number of elements (char pointers) in the animals array?

The length of each array member, ie. size = 1 for element 0, size = 4 for element 1 and so on?

I tried using sizeof of course, but it doesnt seem to return anything that makes sense. I think it should be possible for the precompiler to figureout the amount of elements in the array as well as size of each element. For the latter, one could serach of \0 character as well do define length. I wonder however why I cant get proper array size (ie. number of elements in animals array) when using sizeof?

I would appreciate all suggestions.

Edit:

Yes I meant preprocessor, not precompiller, sorry.

Why do I need this functionality?
I am parsing incoming strings from a serial port. I need to figure out either the received string matches any string in my preconfigured table. If it does, I need the index of that item. I need the searching algorithm to be fast. Because of that, I first want to check the string size and all bytes after that, only if size matches. Because of that I thought maybe the length of each string is known at compile time.

This is my current checking function:

```<code>static int32_t  getStringIndex(const uint8_t* const buf, const uint32_t len)
{
    if (!len)
        return -1;

    int32_t arraySize = sizeof(animals) /  sizeof(animals[0]);
    uint32_t elementSize;

    // The algorithm 1st checks if the length matches. If yes, it compares the strings.
    for (int32_t i = 0; i < arraySize; i++)
    {
        elementSize = strlen(animals[i]);

        if (elementSize == len)
        {
            if (0 == memcmp(animals[i], buf, len))
            {
                return i;
            }
        }
    }

    return -1;
}
</code>```

I dont use strcmp because buf doesnt have \0 at the end.

答:
You could make use of the preprocessor to build an array of structs containing the length and the pointer to the string like this:

```<code>#include <stdio.h>

struct animalentry
{
  int size;
  const char* const name;
};

#define ANIMAL_ENTRY(a) { sizeof a - 1, a },

const struct animalentry animals[] =
{
  ANIMAL_ENTRY("")
  ANIMAL_ENTRY("Cat")
  ANIMAL_ENTRY("Dawg")
  ANIMAL_ENTRY("Tiger")
};

int main()
{
  for (int i = 0; i < sizeof animals / sizeof animals[0]; i++)
  {
    printf("Name = %s, length = %d\n", animals[i].name, animals[i].size);
  }
}
</code>```

The output will be:

```<code>Name = , length = 0
Name = Cat, length = 3
Name = Dawg, length = 4
Name = Tiger, length = 5
</code>```

This should be easy to adapt to your getStringIndex function.

Body:
Consider the following array of "strings" in C:

const char* const animals[] =
{
    "",
    "Cat",
    "Dawg",
    "Elephant",
    "Tiger",
};

Is it possible to obtain:

The number of elements (char pointers) in the animals array?

The length of each array member, ie. size = 1 for element 0, size = 4 for element 1 and so on?

I tried using sizeof of course, but it doesnt seem to return anything that makes sense. I think it should be possible for the precompiler to figureout the amount of elements in the array as well as size of each element. For the latter, one could serach of \0 character as well do define length. I wonder however why I cant get proper array size (ie. number of elements in animals array) when using sizeof?

I would appreciate all suggestions.

Edit:

Yes I meant preprocessor, not precompiller, sorry.

Why do I need this functionality?
I am parsing incoming strings from a serial port. I need to figure out either the received string matches any string in my preconfigured table. If it does, I need the index of that item. I need the searching algorithm to be fast. Because of that, I first want to check the string size and all bytes after that, only if size matches. Because of that I thought maybe the length of each string is known at compile time.

This is my current checking function:

static int32_t  getStringIndex(const uint8_t* const buf, const uint32_t len)
{
    if (!len)
        return -1;

    int32_t arraySize = sizeof(animals) /  sizeof(animals[0]);
    uint32_t elementSize;

    // The algorithm 1st checks if the length matches. If yes, it compares the strings.
    for (int32_t i = 0; i < arraySize; i++)
    {
        elementSize = strlen(animals[i]);

        if (elementSize == len)
        {
            if (0 == memcmp(animals[i], buf, len))
            {
                return i;
            }
        }
    }

    return -1;
}

I dont use strcmp because buf doesnt have \0 at the end.

Body:
You could make use of the preprocessor to build an array of structs containing the length and the pointer to the string like this:

#include <stdio.h>

struct animalentry
{
  int size;
  const char* const name;
};

#define ANIMAL_ENTRY(a) { sizeof a - 1, a },

const struct animalentry animals[] =
{
  ANIMAL_ENTRY("")
  ANIMAL_ENTRY("Cat")
  ANIMAL_ENTRY("Dawg")
  ANIMAL_ENTRY("Tiger")
};

int main()
{
  for (int i = 0; i < sizeof animals / sizeof animals[0]; i++)
  {
    printf("Name = %s, length = %d\n", animals[i].name, animals[i].size);
  }
}

The output will be:

Name = , length = 0
Name = Cat, length = 3
Name = Dawg, length = 4
Name = Tiger, length = 5

This should be easy to adapt to your getStringIndex function.


问:
GridView not refreshing?
I am working on an Android app that has only one activity and several fragments.

One of the fragments contains a GridView with a custom adapter.

The data shown in the GridView are loaded from a remote server database.

On another fragment the user can add items to the remote database, and after sending the data the app opens the fragment that contains the GridView again, but the data are not updated with the last included item.

Here you have the method:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    Log.d("MISUPICKS","ESTOE EN MISUPICKS ONCREATE");

    View view = inflater.inflate(R.layout.fragment_misupicks, container, false);

    txtbusqueda = (EditText) view.findViewById(R.id.txtbusqueda);

    botonbuscar =(Button) view.findViewById(R.id.btnbuscar);

    botonbuscar.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        String busqueda = txtbusqueda.getText().toString();
        getUpicksBusquedaFromDB(0, busqueda);
      }
    });

    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
    upicks = new ArrayList<>();

    gridLayout = new GridLayoutManager(getActivity(), 2);
    recyclerView.setLayoutManager(gridLayout);

    adapter = new UpicksAdapter(getActivity(), upicks);

    adapter.notifyDataSetChanged();

    upicks.clear();

    recyclerView.setAdapter(adapter);

    adapter.notifyDataSetChanged();

    getUpicksFromDB(0);
    return view;
}
</code>```

You can find there the method getUpicksFromDB(0) which actually loads the data from the remote server:

```<code>private void getUpicksFromDB(int id) {
    Log.d("MISUPICKS","ESTOE EN MISUPICKS getupicksfromddb");

    AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
      @Override
      protected Void doInBackground(Integer... addressesIds) {
        //  Log.d("HOLA PERFIL", "UID REGISTRADO ANTES DE CARGAR REECYCLER: " + user_id);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url("http://.../upicks_todos.php")
            .build();
        try {
          okhttp3.Response response = client.newCall(request).execute();

          JSONArray array = new JSONArray(response.body().string());

          for (int i = 0; i < array.length(); i++) {

            JSONObject object = array.getJSONObject(i);
            Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
            Upicks upicks = new Upicks(object.getInt("id_servicio"),
                object.getString("driver_servicio"),
                object.getString("inicio_servicio"),
                object.getString("lat_origen_servicio"),
                object.getString("lon_origen_servicio"),
                object.getString("lat_destino_servicio"),
                object.getString("lon_destino_servicio"),
                object.getString("cliente_servicio"),
                object.getString("final_servicio"),
                object.getString("distancia_servicio"),
                object.getString("tarifa_servicio"),
                object.getString("origen_servicio"),
                object.getString("destino_servicio"),
                object.getString("estado_servicio"),
                object.getString("tiempo_servicio")
            );

            MisUpicksFragment.this.upicks.add(upicks);
          }
        } catch (IOException e) {
          e.printStackTrace();
        } catch (JSONException e) {
          e.printStackTrace();
        }
        return null;
      }

      @Override
      protected void onPostExecute(Void aVoid) {
        adapter.notifyDataSetChanged();
      }
    };

    asyncTask.execute(id);
}
</code>```

What should I change to refresh the data every time the fragment is shown?

EDIT:

Adapter

```<code>import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.juarezserver.upick.R;
import com.juarezserver.upick.fragment.DetalleUpickFragment;

import java.util.List;

import static android.content.Context.MODE_PRIVATE;

public class UpicksAdapter extends RecyclerView.Adapter<UpicksAdapter.ViewHolder> {

    private Context context;
    private List<Upicks> upicks;
    private String emailsegundo;

    private SharedPreferences mPref;
    private  static final String PREF_NAME = "directorio";

    public UpicksAdapter(Context context, List<Upicks> upicks) {
        this.context = context;
        this.upicks = upicks;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.upick_card,parent,false);

        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

       // holder.txtapodo.setText(upicks.get(position).getid_servicio());
        holder.txtOrigen.setText(upicks.get(position).getorigen_servicio());
        holder.txtDestino.setText(upicks.get(position).getdestino_servicio());
       // holder.txtapellidos.setText(upicks.get(position).getApellidos());
        //holder.txtempresa.setText(upicks.get(position).getEmpresa());
      //  String url_foto = "http://.../usuarios/"+ upicks.get(position).getImagen();
    //    Glide.with(context).load(url_foto).into(holder.imageView);

    }

    @Override
    public int getItemCount() {
        return upicks.size();
    }

    public  class ViewHolder extends  RecyclerView.ViewHolder implements View.OnClickListener{

        public TextView txtOrigen;
        public TextView txtDestino;

        public ViewHolder(View itemView) {
            super(itemView);
            txtOrigen = (TextView) itemView.findViewById(R.id.txtOrigen);
            txtDestino = (TextView) itemView.findViewById(R.id.txtDestino);

            itemView.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            int position = getAdapterPosition();
            showPopupMenu(v,position);
        }
    }

    private void showPopupMenu(View view, int poaition) {
        PopupMenu popup = new PopupMenu(context, view);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.menu_context_upick, popup.getMenu());
        popup.setOnMenuItemClickListener(new MenuClickListener(poaition));
        popup.show();
    }

    class MenuClickListener implements PopupMenu.OnMenuItemClickListener {
        Integer pos;
        public MenuClickListener(int pos) {
            this.pos=pos;
        }

        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_favourite:

                    mPref = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE);

                    SharedPreferences.Editor editor = mPref.edit();

                    editor.putString("NOMBRE", upicks.get(pos).getinicio_servicio());
          //          editor.putString("APELLIDOS", upicks.get(pos).getApellidos());
          //          editor.putString("APODO", upicks.get(pos).getApodo());
                    //          editor.putString("CUMPLE", upicks.get(pos).getCumple());
//

                    //      editor.putString("CONYUGE", upicks.get(pos).getConyuge());
                    //       editor.putString("CUMPLE_CONYUGE", upicks.get(pos).getCumple_conyuge());
                    //       editor.putString("ANIVERSARIO_BODAS", upicks.get(pos).getAniversario_bodas());
                    //       editor.putString("EMPRESA", upicks.get(pos).getEmpresa());
                    //       editor.putString("DIRECCION_EMPRESA", upicks.get(pos).getDireccion_empresa());

                    //       editor.putString("TEL_NEGOCIO", upicks.get(pos).getTel_negocio());
                    //         editor.putString("FECHA_INGRESO", upicks.get(pos).getFecha_ingreso());
                    //       editor.putString("NUM_ROTARIO", upicks.get(pos).getNum_rotario());
                    //        editor.putString("PADRINO", upicks.get(pos).getPadrino());
                    //       editor.putString("DIRECCION_CASA", upicks.get(pos).getDireccion_casa());

                    //       editor.putString("TEL_CASA", upicks.get(pos).getTel_casa());
                    //      editor.putString("CELULAR", upicks.get(pos).getCelular());
                    //      editor.putString("EMAIL", upicks.get(pos).getEmail());

                    //   Log.d("HOLA PERFIL", "RESPONSE 2 valor=" + upicks.get(pos).getEmail_privado());
                    //    emailsegundo = "-";

                    //       if("null".equals(upicks.get(pos).getEmail_privado()))
                    //       {
                    //        emailsegundo = "-";
                    //       Log.d("HOLA PERFIL", "RESPONSE 2 no hay " + upicks.get(pos).getEmail_privado());
                    //      }
                    //    else
                    //    {
                    //         emailsegundo = upicks.get(pos).getEmail_privado();
                    //Log.d("HOLA PERFIL", "RESPONSE 2 email: " + upicks.get(pos).getEmail_privado());

                    //  }

                    //  editor.putString("EMAIL_PRIVADO", emailsegundo);

                    //      editor.putString("CLASIFICACION", upicks.get(pos).getClasificacion());
                    //    editor.putString("IMAGEN", upicks.get(pos).getImagen());

                    //    Log.d("HOLA PERFIL", "RESPONSE rotario  en direcadapter: " + upicks.get(pos).getNum_rotario());

                    //    editor.apply();

                 DetalleUpickFragment firstFragment = new DetalleUpickFragment();
                  ((MainActivity)context).getSupportFragmentManager().beginTransaction()
                           .add(R.id.frame, firstFragment).commit();

                    return true;

                default:
            }
            return false;
        }
    }
}
</code>```

答:
```<code>    i think you are going wrong in coding..
you should try like this way:

1 for set adapter-

gridLayout = new GridLayoutManager(getActivity(), 2);
    recyclerView.setLayoutManager(gridLayout);
    adapter = new UpicksAdapter(getActivity(), upicks);

2. change data on click:

     botonbuscar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

      upicks.clear(); // clear your list
                    before adding new data

     String busqueda = txtbusqueda.getText().toString();

     getUpicksBusquedaFromDB(0, busqueda);

       adapter.notifyDataSetChanged(); //for update list

     //-- Note-- Make sure your "adapter" instance will not be create "adapter = new .." again and again.

                }
            });
</code>```

Title: GridView not refreshing?

Body:
I am working on an Android app that has only one activity and several fragments.

One of the fragments contains a GridView with a custom adapter.

The data shown in the GridView are loaded from a remote server database.

On another fragment the user can add items to the remote database, and after sending the data the app opens the fragment that contains the GridView again, but the data are not updated with the last included item.

Here you have the method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    Log.d("MISUPICKS","ESTOE EN MISUPICKS ONCREATE");

    View view = inflater.inflate(R.layout.fragment_misupicks, container, false);

    txtbusqueda = (EditText) view.findViewById(R.id.txtbusqueda);

    botonbuscar =(Button) view.findViewById(R.id.btnbuscar);

    botonbuscar.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        String busqueda = txtbusqueda.getText().toString();
        getUpicksBusquedaFromDB(0, busqueda);
      }
    });

    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
    upicks = new ArrayList<>();

    gridLayout = new GridLayoutManager(getActivity(), 2);
    recyclerView.setLayoutManager(gridLayout);

    adapter = new UpicksAdapter(getActivity(), upicks);

    adapter.notifyDataSetChanged();

    upicks.clear();

    recyclerView.setAdapter(adapter);

    adapter.notifyDataSetChanged();

    getUpicksFromDB(0);
    return view;
}

You can find there the method getUpicksFromDB(0) which actually loads the data from the remote server:

private void getUpicksFromDB(int id) {
    Log.d("MISUPICKS","ESTOE EN MISUPICKS getupicksfromddb");

    AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
      @Override
      protected Void doInBackground(Integer... addressesIds) {
        //  Log.d("HOLA PERFIL", "UID REGISTRADO ANTES DE CARGAR REECYCLER: " + user_id);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url("http://.../upicks_todos.php")
            .build();
        try {
          okhttp3.Response response = client.newCall(request).execute();

          JSONArray array = new JSONArray(response.body().string());

          for (int i = 0; i < array.length(); i++) {

            JSONObject object = array.getJSONObject(i);
            Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
            Upicks upicks = new Upicks(object.getInt("id_servicio"),
                object.getString("driver_servicio"),
                object.getString("inicio_servicio"),
                object.getString("lat_origen_servicio"),
                object.getString("lon_origen_servicio"),
                object.getString("lat_destino_servicio"),
                object.getString("lon_destino_servicio"),
                object.getString("cliente_servicio"),
                object.getString("final_servicio"),
                object.getString("distancia_servicio"),
                object.getString("tarifa_servicio"),
                object.getString("origen_servicio"),
                object.getString("destino_servicio"),
                object.getString("estado_servicio"),
                object.getString("tiempo_servicio")
            );

            MisUpicksFragment.this.upicks.add(upicks);
          }
        } catch (IOException e) {
          e.printStackTrace();
        } catch (JSONException e) {
          e.printStackTrace();
        }
        return null;
      }

      @Override
      protected void onPostExecute(Void aVoid) {
        adapter.notifyDataSetChanged();
      }
    };

    asyncTask.execute(id);
}

What should I change to refresh the data every time the fragment is shown?

EDIT:

Adapter

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.juarezserver.upick.R;
import com.juarezserver.upick.fragment.DetalleUpickFragment;

import java.util.List;

import static android.content.Context.MODE_PRIVATE;

public class UpicksAdapter extends RecyclerView.Adapter<UpicksAdapter.ViewHolder> {

    private Context context;
    private List<Upicks> upicks;
    private String emailsegundo;

    private SharedPreferences mPref;
    private  static final String PREF_NAME = "directorio";

    public UpicksAdapter(Context context, List<Upicks> upicks) {
        this.context = context;
        this.upicks = upicks;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.upick_card,parent,false);

        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

       // holder.txtapodo.setText(upicks.get(position).getid_servicio());
        holder.txtOrigen.setText(upicks.get(position).getorigen_servicio());
        holder.txtDestino.setText(upicks.get(position).getdestino_servicio());
       // holder.txtapellidos.setText(upicks.get(position).getApellidos());
        //holder.txtempresa.setText(upicks.get(position).getEmpresa());
      //  String url_foto = "http://.../usuarios/"+ upicks.get(position).getImagen();
    //    Glide.with(context).load(url_foto).into(holder.imageView);

    }

    @Override
    public int getItemCount() {
        return upicks.size();
    }

    public  class ViewHolder extends  RecyclerView.ViewHolder implements View.OnClickListener{

        public TextView txtOrigen;
        public TextView txtDestino;

        public ViewHolder(View itemView) {
            super(itemView);
            txtOrigen = (TextView) itemView.findViewById(R.id.txtOrigen);
            txtDestino = (TextView) itemView.findViewById(R.id.txtDestino);

            itemView.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            int position = getAdapterPosition();
            showPopupMenu(v,position);
        }
    }

    private void showPopupMenu(View view, int poaition) {
        PopupMenu popup = new PopupMenu(context, view);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.menu_context_upick, popup.getMenu());
        popup.setOnMenuItemClickListener(new MenuClickListener(poaition));
        popup.show();
    }

    class MenuClickListener implements PopupMenu.OnMenuItemClickListener {
        Integer pos;
        public MenuClickListener(int pos) {
            this.pos=pos;
        }

        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_favourite:

                    mPref = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE);

                    SharedPreferences.Editor editor = mPref.edit();

                    editor.putString("NOMBRE", upicks.get(pos).getinicio_servicio());
          //          editor.putString("APELLIDOS", upicks.get(pos).getApellidos());
          //          editor.putString("APODO", upicks.get(pos).getApodo());
                    //          editor.putString("CUMPLE", upicks.get(pos).getCumple());
//

                    //      editor.putString("CONYUGE", upicks.get(pos).getConyuge());
                    //       editor.putString("CUMPLE_CONYUGE", upicks.get(pos).getCumple_conyuge());
                    //       editor.putString("ANIVERSARIO_BODAS", upicks.get(pos).getAniversario_bodas());
                    //       editor.putString("EMPRESA", upicks.get(pos).getEmpresa());
                    //       editor.putString("DIRECCION_EMPRESA", upicks.get(pos).getDireccion_empresa());

                    //       editor.putString("TEL_NEGOCIO", upicks.get(pos).getTel_negocio());
                    //         editor.putString("FECHA_INGRESO", upicks.get(pos).getFecha_ingreso());
                    //       editor.putString("NUM_ROTARIO", upicks.get(pos).getNum_rotario());
                    //        editor.putString("PADRINO", upicks.get(pos).getPadrino());
                    //       editor.putString("DIRECCION_CASA", upicks.get(pos).getDireccion_casa());

                    //       editor.putString("TEL_CASA", upicks.get(pos).getTel_casa());
                    //      editor.putString("CELULAR", upicks.get(pos).getCelular());
                    //      editor.putString("EMAIL", upicks.get(pos).getEmail());

                    //   Log.d("HOLA PERFIL", "RESPONSE 2 valor=" + upicks.get(pos).getEmail_privado());
                    //    emailsegundo = "-";

                    //       if("null".equals(upicks.get(pos).getEmail_privado()))
                    //       {
                    //        emailsegundo = "-";
                    //       Log.d("HOLA PERFIL", "RESPONSE 2 no hay " + upicks.get(pos).getEmail_privado());
                    //      }
                    //    else
                    //    {
                    //         emailsegundo = upicks.get(pos).getEmail_privado();
                    //Log.d("HOLA PERFIL", "RESPONSE 2 email: " + upicks.get(pos).getEmail_privado());

                    //  }

                    //  editor.putString("EMAIL_PRIVADO", emailsegundo);

                    //      editor.putString("CLASIFICACION", upicks.get(pos).getClasificacion());
                    //    editor.putString("IMAGEN", upicks.get(pos).getImagen());

                    //    Log.d("HOLA PERFIL", "RESPONSE rotario  en direcadapter: " + upicks.get(pos).getNum_rotario());

                    //    editor.apply();

                 DetalleUpickFragment firstFragment = new DetalleUpickFragment();
                  ((MainActivity)context).getSupportFragmentManager().beginTransaction()
                           .add(R.id.frame, firstFragment).commit();

                    return true;

                default:
            }
            return false;
        }
    }
}


问:
How to check if two tables are structurally same?
I have two tables in a SQL Server database. I want to check if these two tables are structurally same. I used UNION/ EXCEPT operator to check this and found that these two tables are not identical.

Here are my questions:

How do we know if two tables are the same in structure?

If they are not same, how do we get the details of differences? If a column is missing in one table how do we get the name of the missing column?

If there is a data type mismatch between a column in these two tables, can we get the name of the column with different data type?

答:
Here you can compare Tables

If you want to compare tables with the same database just provide same DATABASENAMESOURCE and DATABASENAMEDESTINATION names

```<code>use master
go

DECLARE @DB1 VARCHAR(100) = 'DATABASENAMESOURCE';
DECLARE @Table1 VARCHAR(100) = 'TABLESOURCE';

DECLARE @DB2 VARCHAR(100) = 'DATABASENAMEDESTINATION';
DECLARE @Table2 VARCHAR(100) = 'DESTINATION';

DECLARE @SQL NVARCHAR(MAX);

SET @SQL =
'
SELECT
       Table1.DBName,
       Table1.SchemaName,
       Table1.TableName,
       Table1.ColumnName,
       Table1.name DataType,
       Table1.Length,
       Table1.Precision,
       Table1.Scale,
       Table1.Is_Identity,
       Table1.Is_Nullable,
       Table2.DBName,
       Table2.SchemaName,
       Table2.TableName,
       Table2.ColumnName,
       Table2.name DataType,
       Table2.Length,
       Table2.Precision,
       Table2.Scale,
       Table2.Is_Identity,
       Table2.Is_Nullable
FROM
    (SELECT
           ''' + @DB1 + ''' DbName,
           SCHEMA_NAME(t.schema_id) SchemaName,
           t.Name TableName,
           c.Name ColumnName,
           st.Name,
           c.Max_Length Length,
           c.Precision,
           c.Scale,
           c.Is_Identity,
           c.Is_Nullable
    FROM   ' + @DB1 + '.sys.tables t
           INNER JOIN ' + @DB1 + '.sys.columns c ON t.Object_ID = c.Object_ID
           INNER JOIN sys.types st ON St.system_type_id = c.System_Type_id AND st.user_type_id = c.user_type_id
    WHERE  t.Name = ''' + @Table1 + ''') Table1
    FULL OUTER JOIN
    (SELECT
           ''' + @DB2 + ''' DbName,
           SCHEMA_NAME(t.schema_id) SchemaName,
           t.name TableName,
           c.name ColumnName,
           st.Name,
           c.max_length Length,
           c.Precision,
           c.Scale,
           c.Is_Identity,
           c.Is_Nullable
    FROM   ' + @DB2 + '.sys.tables t
           INNER JOIN ' + @DB2 + '.sys.columns c ON t.Object_ID = c.Object_ID
           INNER JOIN sys.types st ON St.system_type_id = c.System_Type_id AND st.user_type_id = c.user_type_id
    WHERE  t.Name = ''' + @Table2 + ''') Table2
    ON Table1.ColumnName = Table2.ColumnName
ORDER BY CASE WHEN Table1.ColumnName IS NULL THEN 2 ELSE 1 END, Table1.ColumnName
'

EXEC sp_executesql @SQL
</code>```

Body:
Here you can compare Tables

If you want to compare tables with the same database just provide same DATABASENAMESOURCE and DATABASENAMEDESTINATION names

use master
go

DECLARE @DB1 VARCHAR(100) = 'DATABASENAMESOURCE';
DECLARE @Table1 VARCHAR(100) = 'TABLESOURCE';

DECLARE @DB2 VARCHAR(100) = 'DATABASENAMEDESTINATION';
DECLARE @Table2 VARCHAR(100) = 'DESTINATION';

DECLARE @SQL NVARCHAR(MAX);

SET @SQL =
'
SELECT
       Table1.DBName,
       Table1.SchemaName,
       Table1.TableName,
       Table1.ColumnName,
       Table1.name DataType,
       Table1.Length,
       Table1.Precision,
       Table1.Scale,
       Table1.Is_Identity,
       Table1.Is_Nullable,
       Table2.DBName,
       Table2.SchemaName,
       Table2.TableName,
       Table2.ColumnName,
       Table2.name DataType,
       Table2.Length,
       Table2.Precision,
       Table2.Scale,
       Table2.Is_Identity,
       Table2.Is_Nullable
FROM
    (SELECT
           ''' + @DB1 + ''' DbName,
           SCHEMA_NAME(t.schema_id) SchemaName,
           t.Name TableName,
           c.Name ColumnName,
           st.Name,
           c.Max_Length Length,
           c.Precision,
           c.Scale,
           c.Is_Identity,
           c.Is_Nullable
    FROM   ' + @DB1 + '.sys.tables t
           INNER JOIN ' + @DB1 + '.sys.columns c ON t.Object_ID = c.Object_ID
           INNER JOIN sys.types st ON St.system_type_id = c.System_Type_id AND st.user_type_id = c.user_type_id
    WHERE  t.Name = ''' + @Table1 + ''') Table1
    FULL OUTER JOIN
    (SELECT
           ''' + @DB2 + ''' DbName,
           SCHEMA_NAME(t.schema_id) SchemaName,
           t.name TableName,
           c.name ColumnName,
           st.Name,
           c.max_length Length,
           c.Precision,
           c.Scale,
           c.Is_Identity,
           c.Is_Nullable
    FROM   ' + @DB2 + '.sys.tables t
           INNER JOIN ' + @DB2 + '.sys.columns c ON t.Object_ID = c.Object_ID
           INNER JOIN sys.types st ON St.system_type_id = c.System_Type_id AND st.user_type_id = c.user_type_id
    WHERE  t.Name = ''' + @Table2 + ''') Table2
    ON Table1.ColumnName = Table2.ColumnName
ORDER BY CASE WHEN Table1.ColumnName IS NULL THEN 2 ELSE 1 END, Table1.ColumnName
'

EXEC sp_executesql @SQL


问:
spring CORS and angular not working : HTTP status code 403 error
I am new to angular and spring-security.I am having problem with CORS when trying to log in from angular login-form page using basic authentication to the rest endpoint. My Angular code is running on http://localhost:4200 and rest end point on http://localhost:8181. My angular login-form tries to make request to http://localhost:8181/token which I have specified in my login controller. Even though I have added cors configuration in server side, I get this error :-

Failed to load http://localhost:8181/token: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

(angular) login.service.ts:-

```<code>@Injectable()
export class LoginService {
  constructor(private http: Http) {}

  sendCredential(username: string, password: string) {
    const url = 'http://localhost:8181/token';
    const encodedCredential = username + ':' + password;
    const basicHeader = 'Basic ' + btoa(encodedCredential);
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-wwww-form-urlencoded');
    headers.append('Authorization' ,  basicHeader);
    const opts = new RequestOptions({headers: headers});
    return this.http.get(url, opts);
  }
</code>```

}

(spring) SecurityConfig.java

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static final String[] PUBLIC_MATCHERS = {
            "/css/**",
            "/js/**",
            "/image/**",
            "/book/**",
            "/user/**"
    };

@Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .cors().and()
                .csrf().disable()
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(PUBLIC_MATCHERS)
                .permitAll()
                .anyRequest()
                .authenticated();
    }
 @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT","OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
    }
</code>```

LoginController.java

```<code>@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/token")
    public Map<String, String> token(HttpSession session, HttpServletRequest request) {
        String remoteHost = request.getRemoteHost();
        int portNumber = request.getRemotePort();
        String remoteAddr = request.getRemoteAddr();

        System.out.println(remoteHost + ":" + portNumber);
        System.out.println(remoteAddr);

        return Collections.singletonMap("token", session.getId());
    }
}
</code>```

答:
Try this configuration. It should work fine for you.

```<code>@Bean
CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
        configuration.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
</code>```

Since you are using spring security / authentication. You should use setAllowCredentials(true).

Body:
I am new to angular and spring-security.I am having problem with CORS when trying to log in from angular login-form page using basic authentication to the rest endpoint. My Angular code is running on http://localhost:4200 and rest end point on http://localhost:8181. My angular login-form tries to make request to http://localhost:8181/token which I have specified in my login controller. Even though I have added cors configuration in server side, I get this error :-

Failed to load http://localhost:8181/token: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

(angular) login.service.ts:-

@Injectable()
export class LoginService {
  constructor(private http: Http) {}

  sendCredential(username: string, password: string) {
    const url = 'http://localhost:8181/token';
    const encodedCredential = username + ':' + password;
    const basicHeader = 'Basic ' + btoa(encodedCredential);
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-wwww-form-urlencoded');
    headers.append('Authorization' ,  basicHeader);
    const opts = new RequestOptions({headers: headers});
    return this.http.get(url, opts);
  }

}

(spring) SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static final String[] PUBLIC_MATCHERS = {
            "/css/**",
            "/js/**",
            "/image/**",
            "/book/**",
            "/user/**"
    };

@Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .cors().and()
                .csrf().disable()
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(PUBLIC_MATCHERS)
                .permitAll()
                .anyRequest()
                .authenticated();
    }
 @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT","OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
    }

LoginController.java

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/token")
    public Map<String, String> token(HttpSession session, HttpServletRequest request) {
        String remoteHost = request.getRemoteHost();
        int portNumber = request.getRemotePort();
        String remoteAddr = request.getRemoteAddr();

        System.out.println(remoteHost + ":" + portNumber);
        System.out.println(remoteAddr);

        return Collections.singletonMap("token", session.getId());
    }
}

Body:
Try this configuration. It should work fine for you.

@Bean
CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
        configuration.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

Since you are using spring security / authentication. You should use setAllowCredentials(true).


问:
jquery max validation not working
I have used jQuery validation but max is not working.

$("#tax").validate({
  // Specify the validation rules
  rules: {
    igst: {
      digits: true,
      max: 2
    }
  },
  // Specify the validation error messages
  messages: {
    igst: {
      digits: "Please enter a valid number.",
      max: "Please enter a value less than or equal to 2."
    }
  },
  submitHandler: function(form) {
    form.submit();
  }
});
```

答:
I think you are confused with what max is for. It means that the value of the igst field has to be a number less than or equal to 2 (0, 1, 2)

https://jsfiddle.net/xzua16f8/

If I am not wrong, what you are looking for is maxlength, which means the number could be anything not more than 2 digits.

https://jsfiddle.net/xzua16f8/1/

Anyway, the max and maxlength both works fine, you can check the fiddles.

Title: jquery max validation not working


问:
Why is data transfer speed slower for multiple smaller files than a huge file?
I have always noticed that when for example a react project or a whole website for an instance whose size sums up to say 350-450 MB takes a longer time to transfer than a 2-3 GB video file or for the matter of fact any number of files that are bundled into one file like a .zip/.rar/.iso.

Some SCs :-

Transferring some react projects:-

Transferring a movie:-

I scoured the web but unfortunately found no relevant posts/answers.

Maybe I didn't use the necessary keywords...idk

If possible, a detailed explanation would be really helpful :)

Even if the explanation dives into OS concepts it's cool.
I just wanna know why

答:
There is actually a lot going on behind the 'scenes' when you transfer a file:

Opening the original file

Map the path string to something the operating system actually understands

Security is checked (FILE_ACCESS): are you allowed to read and delete the file?

More security is checked (FILE_SHARE): is you are allowed, is anyone else doing something with the file?

Creating the new file

Map the path string to something the operating system actually understands

Again security (FILE_ACCESS): are you allowed to create a file here? And the directory
above it, and above that...

Create the actual new file, and put it into the file system lookup table

Set the default file attributes

Disallow others to read/write/delete the new file (FILE_SHARE)

The actual transfer

Read 4k bytes

Write 4k bytes, and repeat

The original file is removed

Set last modified date of the new file

The new file is closed

I'm sure I'm already missing a ton of steps here, but I'm here to illustrate a lot of stuff is going on before and after the actual transfer. Even if the file is empty (0 bytes) we still have to do all this. That's apart from the already given answers such as fragmentation.