问:
How to split text by character in Pandas
I am currently using this code:

```<code>df['name'] = df['name'].str.split("",expand=True,n=20)
</code>```

Error:

ValueError: split() requires a non-empty pattern match.

The error is at this line inside Pandas code

```<code>-> 1387             f = lambda x: regex.split(x, maxsplit=n)
</code>```

It works on some Python environment but not all, even if Pandas version is same

I am getting this error in some python enviorment such as Google colab. Probably related to Regex version. I was wondering, is there any alternative to this line that is equally fast?

答:
first param of split is optional if you are not adding any meaningful data to split then why don't you just ignore this param.

```<code>df['name'] = df['name'].str.split(expand=True,n=20)
</code>```

by default, it will split by spaces

if you want to split by every character then write a meaningful regular expression to split on

if you want to split by any number or character then use like

```<code>df['names'].str.split(r"[a-zA-Z0-9]",expand=True, n=20)
</code>```

if you want to split by anything then

```<code> df['names'].str.split(r".?",expand=True, n=20)
</code>```

Body:
I am currently using this code:

df['name'] = df['name'].str.split("",expand=True,n=20)

Error:

ValueError: split() requires a non-empty pattern match.

The error is at this line inside Pandas code

-> 1387             f = lambda x: regex.split(x, maxsplit=n)

It works on some Python environment but not all, even if Pandas version is same

I am getting this error in some python enviorment such as Google colab. Probably related to Regex version. I was wondering, is there any alternative to this line that is equally fast?

Body:
first param of split is optional if you are not adding any meaningful data to split then why don't you just ignore this param.

df['name'] = df['name'].str.split(expand=True,n=20)

by default, it will split by spaces

if you want to split by every character then write a meaningful regular expression to split on

if you want to split by any number or character then use like

df['names'].str.split(r"[a-zA-Z0-9]",expand=True, n=20)

if you want to split by anything then

 df['names'].str.split(r".?",expand=True, n=20)


来源: stackexchange

问:
Passing key-event through to a component in Vue and Typescript
I'm kind of new to Vue, so please correct me if I'm formulating the question in a wrong way.

Use Case:

I have a very simple form it contains a TextField "Name" and a Button "Create".
When the user have written a name then I wish that the user can press "Enter" to create the entity.

Code and findings:

I followed the instructions on how to pass events to a input field from the page below

https://v2.vuejs.org/v2/guide/events.html

When I use a input field it works as expected. Like this <input @keyup.enter="createCollection" />

But we are using TextField in a component for various reasons and I cannot get it to work.
I have tried to get it working by trying a lot of different things, but for simplicity I just mention how I do now(or think it should work.).

```<code>      <FormValidatedText
        :label-text="$t('COLLECTION_CREATE')"
        :value="collection.name"
        :min-length="3"
        :max-length="30"
        :required="true"
        :input-id="'collection'"
        :invalid="!formIsValid"
        class="inline-form-field"
        @input="collectionFormNameChanged($event)"
        @validation="validCollectionName = $event"
        @keyup.enter="createCollection()"
      />
</code>```

Other information and code:

The Component

```<code><template>
  <div :class="{ invalid: touched && (valid === false || invalid === true) }">
    <label class="small-label" :for="inputId">{{ labelText }}</label>
    <input :id="inputId" type="text" class="field-value" :value="value" @input="onTextChange" @blur="isTouched" />
    <ul v-if="touched && !valid" class="field-value-errors">
      <li v-for="(error, index) in errors" :key="index">
        {{ $t(error.message, { variable: error.variable }) }}
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { Component, Mixins } from 'vue-property-decorator';
import ValidateTextMixin from '@/components/Form/ValidateTextMixin.vue';
@Component
export default class FormValidatedText extends Mixins(ValidateTextMixin) {}
</script>
</code>```

The Mixin that the Component uses

```<code><script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
@Component
export default class ValidateTextMixin extends Vue {
  @Prop({ default: '' }) value!: string;
  @Prop({ required: true }) readonly inputId!: string;
  @Prop({ required: true }) readonly labelText!: string;
  @Prop({ default: false }) readonly required!: boolean;
  @Prop({ default: false }) readonly invalid!: boolean;
  @Prop() readonly minLength?: number;
  @Prop() readonly maxLength?: number;

  protected changed: boolean = false;
  protected touched: boolean = false;
  protected valid: boolean = false;
  protected errors: any[] = [];

  onTextChange($event: { target: HTMLInputElement }) {
    this.isValid($event.target.value);
    this.$emit('input', $event.target.value);
  }

  isValid(value: string) {
    this.valid = true;
    this.errors = [];
    if (this.required && !value) {
      this.valid = false;
      this.errors.push({ message: 'REQUIRED_FIELD_ERROR' });
    }
    if (this.minLength && value.length < this.minLength) {
      this.valid = false;
      this.errors.push({
        message: 'MINLENGTH_ERROR',
        variable: this.minLength
      });
    }
    if (this.maxLength && value.length > this.maxLength) {
      this.valid = false;
      this.errors.push({
        message: 'MAXLENGTH_ERROR',
        variable: this.maxLength
      });
    }
    this.$emit('validation', this.valid);
  }

  isTouched() {
    if (!this.touched) {
      this.isValid(this.value);
    }
    this.touched = true;
  }
}
</script>

</code>```

Thanks for you help

Final implementation

Based on the answer from Ahmad Mobaraki. Please give him your vote if you think this is helpful =)

The component

```<code><script lang="ts">
import { Component, Mixins } from 'vue-property-decorator';
import ValidateTextMixin from '@/components/Form/ValidateTextMixin.vue';
@Component
export default class FormValidatedText extends Mixins(ValidateTextMixin) {

  created() {
    window.addEventListener('keyup', (event) => {
      if (event.keyCode == 13) { // on enter
        this.$emit('enterpressed');
      }
    });
  }
}
</script>
</code>```

And the usage of the Component

```<code>      <FormValidatedText
        :label-text="$t('COLLECTION_CREATE')"
        :value="collection.name"
        :min-length="3"
        :max-length="30"
        :required="true"
        :input-id="'collection'"
        :invalid="!formIsValid"
        class="inline-form-field"
        @input="collectionFormNameChanged($event)"
        @validation="validCollectionName = $event"
        @enterpressed="createCollection"
      />
</code>```

答:
I don't think Vue support key events on elements other than input tag. To do this you have to register a custom event handler for your component, like this:

```<code>{
    created: function () {
            window.addEventListener('keyup', this.myMethod)
    },
    methods: {
        myMethod: function () {
            // stuff
        }
    }
}
</code>```

So in your case, you should do something like this:

1- Register event in your component:

```<code>export default class FormValidatedText extends Mixins(ValidateTextMixin) {
     created: function () {
          window.addEventListener('keyup', (event) =>{
               if (e.keyCode == 13) { // on enter
                 this.$emit('enterpressed')
                }
          })
     },
}
</code>```

2- Listen to it in the parent component:

```<code>   <FormValidatedText
         .
         .
         .
        @enterpressed="createCollection()"
   />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm kind of new to Vue, so please correct me if I'm formulating the question in a wrong way.

Use Case:

I have a very simple form it contains a TextField "Name" and a Button "Create".
When the user have written a name then I wish that the user can press "Enter" to create the entity.

Code and findings:

I followed the instructions on how to pass events to a input field from the page below

https://v2.vuejs.org/v2/guide/events.html

When I use a input field it works as expected. Like this <input @keyup.enter="createCollection" />

But we are using TextField in a component for various reasons and I cannot get it to work.
I have tried to get it working by trying a lot of different things, but for simplicity I just mention how I do now(or think it should work.).

      <FormValidatedText
        :label-text="$t('COLLECTION_CREATE')"
        :value="collection.name"
        :min-length="3"
        :max-length="30"
        :required="true"
        :input-id="'collection'"
        :invalid="!formIsValid"
        class="inline-form-field"
        @input="collectionFormNameChanged($event)"
        @validation="validCollectionName = $event"
        @keyup.enter="createCollection()"
      />

Other information and code:

The Component

<template>

    {{ labelText }}
    <input :id="inputId" type="text" class="field-value" :value="value" @input="onTextChange" @blur="isTouched" />

        {{ $t(error.message, { variable: error.variable }) }}

</template>

The Mixin that the Component uses

Thanks for you help

Final implementation

Based on the answer from Ahmad Mobaraki. Please give him your vote if you think this is helpful =)

The component

And the usage of the Component

      <FormValidatedText
        :label-text="$t('COLLECTION_CREATE')"
        :value="collection.name"
        :min-length="3"
        :max-length="30"
        :required="true"
        :input-id="'collection'"
        :invalid="!formIsValid"
        class="inline-form-field"
        @input="collectionFormNameChanged($event)"
        @validation="validCollectionName = $event"
        @enterpressed="createCollection"
      />

Body:
I don't think Vue support key events on elements other than input tag. To do this you have to register a custom event handler for your component, like this:

{
    created: function () {
            window.addEventListener('keyup', this.myMethod)
    },
    methods: {
        myMethod: function () {
            // stuff
        }
    }
}

So in your case, you should do something like this:

1- Register event in your component:

export default class FormValidatedText extends Mixins(ValidateTextMixin) {
     created: function () {
          window.addEventListener('keyup', (event) =>{
               if (e.keyCode == 13) { // on enter
                 this.$emit('enterpressed')
                }
          })
     },
}

2- Listen to it in the parent component:

   <FormValidatedText
         .
         .
         .
        @enterpressed="createCollection()"
   />


问:
I can't fill 'input' and 'textarea'
I have an issue with <input> and <textarea> tag.

I'm trying to receive a information by clients, but those tags does not work.

I cannot click the fields, and fill the fields with texts.

Only cursor changes into I when the mouse is hovering the fields.

I don't know what is the problem..

I didn't change any settings for texts, but it doesn't work.

I'm using those fields with HTML which use Three.js.

Please help me.

Below codes are whole about it.

It's just pop-up.

.userInfo {
  vertical-align: middle;
  width: 90%;
  height: 40px;
  border-radius: 4px;
  background-color: #ffffff;
  color: black;
  margin-bottom: 50px;
  margin-left: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <textarea class='userInfo' id='userName' placeholder='Name'></textarea>
  <!--  <input type='text' style='color:black;' class='userInfo' id='userName' /> I tried textarea becuase
                                                                                input tag does not work.-->
</div></code>```

Thanks for your help :)

答:
In

document.addEventListener('mouseup', funMouseUp, true);

function funMouseUp()
{
//    event.preventDefault(); // IT WAS THE PROBLEM

    ...
}
```

And also on mousedown event.

event.preventDefault(); was the problem.

Title: I can't fill 'input' and 'textarea'

Body:
I have an issue with <input> and <textarea> tag.

I'm trying to receive a information by clients, but those tags does not work.

I cannot click the fields, and fill the fields with texts.

Only cursor changes into I when the mouse is hovering the fields.

I don't know what is the problem..

I didn't change any settings for texts, but it doesn't work.

I'm using those fields with HTML which use Three.js.

Please help me.

Below codes are whole about it.

It's just pop-up.

.userInfo {
  vertical-align: middle;
  width: 90%;
  height: 40px;
  border-radius: 4px;
  background-color: #ffffff;
  color: black;
  margin-bottom: 50px;
  margin-left: 50px;
}

  <textarea class='userInfo' id='userName' placeholder='Name'></textarea>

Thanks for your help :)

Body:
In

document.addEventListener('mouseup', funMouseUp, true);

function funMouseUp()
{
//    event.preventDefault(); // IT WAS THE PROBLEM

    ...
}

And also on mousedown event.

event.preventDefault(); was the problem.


问:
Print the result of a Python def
I want to read the date and time of a image by using Pillow.
And now I want to print the result of the def to be shure I got the Date and Time. But when I type print(defname) I just get some weird numbers as the output.

My code:

```<code>import os
import time
import shutil
import re
from PIL import Image, ExifTags
from PIL.ExifTags import TAGS

def get_date_taken(path):
    return Image.open(r"E:\insert_folder\DSC_3389.jpg")._getexif()[36867]

print(get_date_taken)
</code>```

One more thing... If you understand what I want to do and if you understand my code, could you pls check if there is any fault in my code?
Thanks to you guys! <3

答:
you are just printing the definition of your function. To print the return value you have to call your function with the path:</p>

```<code>print(get_date_taken("path of your image"))
</code>```

Title: Print the result of a Python def

Body:
I want to read the date and time of a image by using Pillow.
And now I want to print the result of the def to be shure I got the Date and Time. But when I type print(defname) I just get some weird numbers as the output.

My code:

import os
import time
import shutil
import re
from PIL import Image, ExifTags
from PIL.ExifTags import TAGS

def get_date_taken(path):
    return Image.open(r"E:\insert_folder\DSC_3389.jpg")._getexif()[36867]

print(get_date_taken)

One more thing... If you understand what I want to do and if you understand my code, could you pls check if there is any fault in my code?
Thanks to you guys! <3

Body:
you are just printing the definition of your function. To print the return value you have to call your function with the path:

print(get_date_taken("path of your image"))


问:
The given value of type String from the data source cannot be converted to type nvarchar of the specified target column
I've tested it with and without explicit conversion in the datatable columns, but it kept throwing me the exception System.InvalidOperationException.

FYI, those columns with typeof(string) are all nvarchar in my database. I'm passing in a List called test which is of a user-defined type.

I wasn't going to use sqlbulkcopy initially, but ever since porting over to azure database, I need a faster insertion query.

Any advice would be appreciated.

var dt = new DataTable();
dt.Columns.Add("LinkID", typeof(string));
dt.Columns.Add("RoadName", typeof(string));
dt.Columns.Add("RoadCategory", typeof(string));
dt.Columns.Add("SpeedBand");
dt.Columns.Add("MinimumSpeed", typeof(string));
dt.Columns.Add("MaximumSpeed", typeof(string));
dt.Columns.Add("StartLatitude");
dt.Columns.Add("StartLongitude");
dt.Columns.Add("EndLatitude");
dt.Columns.Add("EndLongitude");
dt.Columns.Add("Distance", typeof(string));

for (int i = 0; i < test.Count; i++)
{
    dt.Rows.Add(test[i].LinkID, test[i].RoadName, test[i].RoadCategory,
       test[i].SpeedBand, test[i].MinimumSpeed, test[i].MaximumSpeed,
       test[i].StartLatitude, test[i].StartLongitude, test[i].EndLatitude,
       test[i].EndLongitude, test[i].Distance);
}

string sqlConnectionString = "//secret";

using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
    try
    {
        conn.Open();
    }
    catch (Exception e)
    {
        Debug.WriteLine(e);
    }

    using (var sqlBulk = new SqlBulkCopy(conn))
    {
        //sqlBulk.BatchSize = 1000;
        sqlBulk.DestinationTableName = "dbo.TrafficSpeedBands";

        try
        {
            // Write from the source to the destination.
            sqlBulk.WriteToServer(dt);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }
}
```

答:
i've switched to using a dataAdapter and it works now</p>

```<code>string sqlConnectionString = "//secret";

            using (SqlConnection conn = new SqlConnection(sqlConnectionString))
            {
                try
                {
                    conn.Open();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }
                Debug.WriteLine("Connection opened");
                var table = new DataTable();

                // read the table structure from the database
                using (var adapter = new SqlDataAdapter($"SELECT TOP 0 * FROM dbo.TrafficSpeedBands", conn))
                {
                    adapter.Fill(table);
                };

                Debug.WriteLine("Filling in rows");
                for (var i = 0; i < test.Count; i++)
                {
                    var row = table.NewRow();
                    row["LinkID"] = test[i].LinkID;
                    row["RoadName"] = test[i].RoadName;
                    row["RoadCategory"] = test[i].RoadCategory;
                    row["SpeedBand"] = test[i].SpeedBand;
                    row["MinimumSpeed"] = test[i].MinimumSpeed;
                    row["MaximumSpeed"] = test[i].MaximumSpeed;
                    row["StartLatitude"] = test[i].StartLatitude;
                    row["StartLongitude"] = test[i].StartLongitude;
                    row["EndLatitude"] = test[i].EndLatitude;
                    row["EndLongitude"] = test[i].EndLongitude;
                    row["Distance"] = test[i].Distance;

                    table.Rows.Add(row);
                }

                using (var sqlBulk = new SqlBulkCopy(conn))
                {
                    Debug.WriteLine("Ready to load live");
                    sqlBulk.DestinationTableName = "dbo.TrafficSpeedBands";

                    try
                    {
                        // Write from the source to the destination.
                        sqlBulk.WriteToServer(table);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }

                    Debug.WriteLine("Done");
                }

                conn.Close();
            }
</code>```

Body:
i've switched to using a dataAdapter and it works now

string sqlConnectionString = "//secret";

            using (SqlConnection conn = new SqlConnection(sqlConnectionString))
            {
                try
                {
                    conn.Open();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }
                Debug.WriteLine("Connection opened");
                var table = new DataTable();

                // read the table structure from the database
                using (var adapter = new SqlDataAdapter($"SELECT TOP 0 * FROM dbo.TrafficSpeedBands", conn))
                {
                    adapter.Fill(table);
                };

                Debug.WriteLine("Filling in rows");
                for (var i = 0; i < test.Count; i++)
                {
                    var row = table.NewRow();
                    row["LinkID"] = test[i].LinkID;
                    row["RoadName"] = test[i].RoadName;
                    row["RoadCategory"] = test[i].RoadCategory;
                    row["SpeedBand"] = test[i].SpeedBand;
                    row["MinimumSpeed"] = test[i].MinimumSpeed;
                    row["MaximumSpeed"] = test[i].MaximumSpeed;
                    row["StartLatitude"] = test[i].StartLatitude;
                    row["StartLongitude"] = test[i].StartLongitude;
                    row["EndLatitude"] = test[i].EndLatitude;
                    row["EndLongitude"] = test[i].EndLongitude;
                    row["Distance"] = test[i].Distance;

                    table.Rows.Add(row);
                }

                using (var sqlBulk = new SqlBulkCopy(conn))
                {
                    Debug.WriteLine("Ready to load live");
                    sqlBulk.DestinationTableName = "dbo.TrafficSpeedBands";

                    try
                    {
                        // Write from the source to the destination.
                        sqlBulk.WriteToServer(table);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }

                    Debug.WriteLine("Done");
                }

                conn.Close();
            }


问:
MySQLi PHP error
I have following function  </p>

```<code><?php

  error_reporting(E_ALL); ini_set("display_errors", true);
  @ $dbh= new mysqli('localhost', 'root', 'hsenidsoft', '1005');
  $stmt = $dbh->prepare("CALL populateDefaultTrainStructureTest(?,?)");
  $startdate = '2011-05-16';
  $counter =1 ;
  $stmt->bindValue(1, $startdate, PDO::PARAM_DATE);

  $stmt->bindValue(2, $counter, PDO::PARAM_INT);
  $stmt->execute();
?>
</code>```

<p>when i execute the function i got </p>

```<code>Fatal error: Call to undefined method mysqli_stmt::bindValue() in /var/www/sp.php on line 8 error

var_dump($stmt)

    object(mysqli_stmt)
#2 (9) { ["affected_rows"]=> int(0) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(2) ["field_count"]=> int(0) ["errno"]=> int(0) ["error"]=> string(0) "" ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) } Fatal error: Call to undefined method mysqli_stmt::bindValue() in /var/www/sp.php on line 11
</code>```

答: There is no bindValue function but there is mysqli_stmt::bind_param

ContentLicense: CC BY-SA 3.0

Title: MySQLi PHP error

Body:
I have following function

<?php

  error_reporting(E_ALL); ini_set("display_errors", true);
  @ $dbh= new mysqli('localhost', 'root', 'hsenidsoft', '1005');
  $stmt = $dbh->prepare("CALL populateDefaultTrainStructureTest(?,?)");
  $startdate = '2011-05-16';
  $counter =1 ;
  $stmt->bindValue(1, $startdate, PDO::PARAM_DATE);

  $stmt->bindValue(2, $counter, PDO::PARAM_INT);
  $stmt->execute();
?>

when i execute the function i got

Fatal error: Call to undefined method mysqli_stmt::bindValue() in /var/www/sp.php on line 8 error

var_dump($stmt)

    object(mysqli_stmt)
#2 (9) { ["affected_rows"]=> int(0) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(2) ["field_count"]=> int(0) ["errno"]=> int(0) ["error"]=> string(0) "" ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) } Fatal error: Call to undefined method mysqli_stmt::bindValue() in /var/www/sp.php on line 11


问:
The type or namespace name 'Products' does not exist in the namespace 'Umbraco.Web.PublishedContentModels'
I am maintaining an Umbraco solution (version 7.15.3).
Recently a bug has been discovered: Upon navigating to a certain page it fails with the following error:

The type or namespace name 'Products' does not exist in the namespace
  'Umbraco.Web.PublishedContentModels' (are you missing an assembly
  reference?)

This isn't really surprising, there have been several version upgrades recently, performed by people who are no longer with the company. For instance, the ModelBuilder (which I believe is related to this) was recently upgraded from version 3.0.7 to 3.0.10.

Not knowing much about the issue, I first trried to hunt down the Umbraco.Web.PublishedContentModels. To my surprise it wasn't in umbraco\Umbraco.Web\Lib or umbraco\Umbraco.Web\bin and when I built the solution it wasn't generated.

I eventually found it in a folder that looked like this:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\74e32662\fd1a65f5\assembly\dl3\09bc313a\c9c37261_f6d1d501

Strange thing is, while the UAT server has one such location, the production server has 4 (the paths only differ in the last folder name).

Luckily, while this error shows up in production, and when I run the project locally, the page just works on the UAT environment. So I took the dll from UAT and copied to umbraco\UmbracoWeb\bin on the production server. This fixed the issue, but it's just a temporary solution. Unless I fix it properly, the next time someone makes a change and redeploys production, the problem will likely come back.

I have a page called Products.cshtml which has the following on the first two lines:

```<code>@inherits Umbraco.Web.Mvc.UmbracoTemplatePage<ContentModels.Products>
@using ContentModels = Umbraco.Web.PublishedContentModels;
</code>```

The 'Products' bit at the first line is underlined and it gives me the same error in VS as the one I get at runtime. Suspecting the upgrade of the ModelBuilder assembly might have been the cause, I tried checking out a version from before the upgrade. But the error is still there.

The solution also has another project that is referenced from the Umbraco project. It has a class called Products, but I don't know if this is in any way related. The Products class doesn't inherit anything.

How can I fix this? Is there a way to recreate the correct Umbraco.Web.PublishedContentModels dll and have it referenced properly?

答:
ModelsBuilder is driven by a few settings that are held in your web.config, and can be configured to behave in a number of different ways -  see here for reference - Models Builder Documentation

It sounds like you've got this set to PureLive

My preference has always been to include these as part of my source code, by generating them when something changes and having them as part of my solution

Whenever you make a change to a Document Type via Umbraco Admin, these files will get regenerated and can be checked in as part of your source control. They can then be compiled into a dll / project of your choice.

Hope this helps

Body:
I am maintaining an Umbraco solution (version 7.15.3).
Recently a bug has been discovered: Upon navigating to a certain page it fails with the following error:

The type or namespace name 'Products' does not exist in the namespace
  'Umbraco.Web.PublishedContentModels' (are you missing an assembly
  reference?)

This isn't really surprising, there have been several version upgrades recently, performed by people who are no longer with the company. For instance, the ModelBuilder (which I believe is related to this) was recently upgraded from version 3.0.7 to 3.0.10.

Not knowing much about the issue, I first trried to hunt down the Umbraco.Web.PublishedContentModels. To my surprise it wasn't in umbraco\Umbraco.Web\Lib or umbraco\Umbraco.Web\bin and when I built the solution it wasn't generated.

I eventually found it in a folder that looked like this:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\74e32662\fd1a65f5\assembly\dl3\09bc313a\c9c37261_f6d1d501

Strange thing is, while the UAT server has one such location, the production server has 4 (the paths only differ in the last folder name).

Luckily, while this error shows up in production, and when I run the project locally, the page just works on the UAT environment. So I took the dll from UAT and copied to umbraco\UmbracoWeb\bin on the production server. This fixed the issue, but it's just a temporary solution. Unless I fix it properly, the next time someone makes a change and redeploys production, the problem will likely come back.

I have a page called Products.cshtml which has the following on the first two lines:

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage<ContentModels.Products>
@using ContentModels = Umbraco.Web.PublishedContentModels;

The 'Products' bit at the first line is underlined and it gives me the same error in VS as the one I get at runtime. Suspecting the upgrade of the ModelBuilder assembly might have been the cause, I tried checking out a version from before the upgrade. But the error is still there.

The solution also has another project that is referenced from the Umbraco project. It has a class called Products, but I don't know if this is in any way related. The Products class doesn't inherit anything.

How can I fix this? Is there a way to recreate the correct Umbraco.Web.PublishedContentModels dll and have it referenced properly?


问:
Group multiple columns and rank within the group
Hi,

I am looking set ranking within group, not able to figure out how to do it.

```<code>Below is the test data,
df = pd.DataFrame()

names = ['California','New York','California','New York', 'California','New York', 'California', 'California', 'California', 'California']
types = ['Student','Student','Student','Student','Student', 'Pleasure', 'Pleasure', 'Pleasure','Business', 'Business']

df['names'] = names
df['type'] = types

df.groupby(['names', 'type']).size().reset_index(name='counts')

Below is the output
    names       type        counts
0   California  Business    2
1   California  Pleasure    2
2   California  Student     3
3   New York    Pleasure    1
4   New York    Student     2
</code>```

I would like to get the below output, Ranking is based on columns names and counts(desc). In California type Business & Pleasure has the same counts, for me it doesn't matter if the result rank is 2,3 or 2,2.

```<code>        names   type      counts Rank
0   California  Business  2      2
1   California  Pleasure  2      2
2   California  Student   3      1
3   New York    Pleasure  1      2
4   New York    Student   2      1
</code>```

Any ideas/solutions

Thanks

答:
Use GroupBy.rank with casting floats to integers by Series.astype:

```<code>df['Rank'] = df.groupby('names')['counts'].rank(ascending=False, method='dense').astype(int)
print(df)
        names      type  counts  Rank
0  California  Business       2     2
1  California  Pleasure       2     2
2  California   Student       3     1
3    New York  Pleasure       1     2
4    New York   Student       2     1
</code>```

Body:
Hi,

I am looking set ranking within group, not able to figure out how to do it.

Below is the test data,
df = pd.DataFrame()

names = ['California','New York','California','New York', 'California','New York', 'California', 'California', 'California', 'California']
types = ['Student','Student','Student','Student','Student', 'Pleasure', 'Pleasure', 'Pleasure','Business', 'Business']

df['names'] = names
df['type'] = types

df.groupby(['names', 'type']).size().reset_index(name='counts')

Below is the output
    names       type        counts
0   California  Business    2
1   California  Pleasure    2
2   California  Student     3
3   New York    Pleasure    1
4   New York    Student     2

I would like to get the below output, Ranking is based on columns names and counts(desc). In California type Business & Pleasure has the same counts, for me it doesn't matter if the result rank is 2,3 or 2,2.

        names   type      counts Rank
0   California  Business  2      2
1   California  Pleasure  2      2
2   California  Student   3      1
3   New York    Pleasure  1      2
4   New York    Student   2      1

Any ideas/solutions

Thanks

Body:
Use GroupBy.rank with casting floats to integers by Series.astype:

df['Rank'] = df.groupby('names')['counts'].rank(ascending=False, method='dense').astype(int)
print(df)
        names      type  counts  Rank
0  California  Business       2     2
1  California  Pleasure       2     2
2  California   Student       3     1
3    New York  Pleasure       1     2
4    New York   Student       2     1


问:
How to optimize query with Inline Function in it?
I have a table TAB_1 with following Schema

```<code>    CAR_NO(Varchar)  START_DATE(Date)  ACTUAL_ARRIVAL_TIME(Number)  SOURCE_POINT(Varchar)
   END_POINT(Varchar)
</code>```

Table TAB_2 with following Schema

```<code>CAR_NO(Varchar)   ACTL_TIME_OF_ARRVL(Date)  EVENT_CODE(Varchar)
</code>```

My query is :

```<code> SELECT DISTINCT CAR_NO,START_DATE FROM TAB_1 WHERE
(TRUNC(START_DATE +CASE WHEN ACTUAL_ARRIVAL_TIME=0 THEN NULL ELSE ACTUAL_ARRIVAL_TIME END/1440)='10-Feb-2020' )
    AND SOURCE_POINT=END_POINT
    UNION
    SELECT DISTINCT  CAR_NO,START_DATE FROM TAB_2 WHERE EVENT_CODE='TD'
    AND TRUNC( ACTL_TIME_OF_ARRVL)='10-Feb-2020'
</code>```

Column ACTUAL_ARRIVAL_TIME stores the time value in minutes,Column ACTL_TIME_OF_ARRVL stores the date as timestamp value , I am trying to find all the cars which terminate on 10-Feb-2020 .Data can be absent from any of the tables so I have used UNION Operation here ,on top of this query I have to apply more operations ,so overall it is taking time of 35 seconds aprox. Please guide to optimize this query .

答:
I would suggest starting by rewriting the query as:

```<code>SELECT CAR_NO, START_DATE
FROM TAB_1
WHERE SOURCE_POINT = END_POINT AND
      TRUNC(START_DATE + ACTUAL_ARRIVAL_TIME * INTERVAL '1' MINUTE) = DATE '2020-02-10'
UNION -- ON PURPOSE TO REMOVE DUPLICATES
SELECT CAR_NO, START_DATE
FROM TAB_2
WHERE EVENT_CODE = 'TD' AND
      TRUNC(ACTL_TIME_OF_ARRVL) = DATE '2020-02-10' ;
</code>```

Then for this query, you can define the following function-based indexes:

```<code>create index idx_tab_1_f1 on tab_1 (TRUNC(START_DATE + ACTUAL_ARRIVAL_TIME * INTERVAL '1' MINUTE), SOURCE_POINT, END_POINT);

create index idx_tab_2_f2 on tab_2 (EVENT_CODE, TRUNC(ACTL_TIME_OF_ARRVL));
</code>```

You can also rephrase the query if you want to include the time component of the date in the index.  It is unclear whether that would be useful for other queries.

Body:
I have a table TAB_1 with following Schema

    CAR_NO(Varchar)  START_DATE(Date)  ACTUAL_ARRIVAL_TIME(Number)  SOURCE_POINT(Varchar)
   END_POINT(Varchar)

Table TAB_2 with following Schema

CAR_NO(Varchar)   ACTL_TIME_OF_ARRVL(Date)  EVENT_CODE(Varchar)

My query is :

 SELECT DISTINCT CAR_NO,START_DATE FROM TAB_1 WHERE
(TRUNC(START_DATE +CASE WHEN ACTUAL_ARRIVAL_TIME=0 THEN NULL ELSE ACTUAL_ARRIVAL_TIME END/1440)='10-Feb-2020' )
    AND SOURCE_POINT=END_POINT
    UNION
    SELECT DISTINCT  CAR_NO,START_DATE FROM TAB_2 WHERE EVENT_CODE='TD'
    AND TRUNC( ACTL_TIME_OF_ARRVL)='10-Feb-2020'

Column ACTUAL_ARRIVAL_TIME stores the time value in minutes,Column ACTL_TIME_OF_ARRVL stores the date as timestamp value , I am trying to find all the cars which terminate on 10-Feb-2020 .Data can be absent from any of the tables so I have used UNION Operation here ,on top of this query I have to apply more operations ,so overall it is taking time of 35 seconds aprox. Please guide to optimize this query .

Body:
I would suggest starting by rewriting the query as:

SELECT CAR_NO, START_DATE
FROM TAB_1
WHERE SOURCE_POINT = END_POINT AND
      TRUNC(START_DATE + ACTUAL_ARRIVAL_TIME * INTERVAL '1' MINUTE) = DATE '2020-02-10'
UNION -- ON PURPOSE TO REMOVE DUPLICATES
SELECT CAR_NO, START_DATE
FROM TAB_2
WHERE EVENT_CODE = 'TD' AND
      TRUNC(ACTL_TIME_OF_ARRVL) = DATE '2020-02-10' ;

Then for this query, you can define the following function-based indexes:

create index idx_tab_1_f1 on tab_1 (TRUNC(START_DATE + ACTUAL_ARRIVAL_TIME * INTERVAL '1' MINUTE), SOURCE_POINT, END_POINT);

create index idx_tab_2_f2 on tab_2 (EVENT_CODE, TRUNC(ACTL_TIME_OF_ARRVL));

You can also rephrase the query if you want to include the time component of the date in the index.  It is unclear whether that would be useful for other queries.


问:
ServiceStack OrmLite "Like" Linq
In my database I have field string(max) called GROUPS where i store groups for my record separated by semicolon ;. I use Service Stack ORM Lite and Linq to get records that have selected group assigned to. Using SQL i can achieve this using LIKE query in example:

```<code>WHERE GROUPS LIKE 'selected_group' OR GROUPS LIKE '%;selected_group' OR GROUPS LIKE '%;selected_group;%' OR GROUPS LIKE 'selected_group;%'
</code>```

I need to do the same in C# Linq Query but I have problem. I dont know how to create query for the edge examples. If I search group named "cat" using my expression :

```<code>q = q.Where(x => x.Groups.Contains($";cat;") || x.Groups.Contains($";cat")
       || x.Groups.Contains($"cat;") || x.Groups.Equals("cat"));
</code>```

I will get records that have this group. But query also return records with group "caterpillar" if those records have 2 groups "house;caterpillar". SQL Expression would exculde this kind of sittuation. Is there any clever solution to this problem directly in C# code ?

答:
Sounds like you want to use .EndsWith() instead, e.g:

```<code>q.Where(x => x.Groups.EndsWith(";cat;"))
</code>```

The OrmLite docs contains more OrmLite Example queries.

Title: ServiceStack OrmLite "Like" Linq

Body:
In my database I have field string(max) called GROUPS where i store groups for my record separated by semicolon ;. I use Service Stack ORM Lite and Linq to get records that have selected group assigned to. Using SQL i can achieve this using LIKE query in example:

WHERE GROUPS LIKE 'selected_group' OR GROUPS LIKE '%;selected_group' OR GROUPS LIKE '%;selected_group;%' OR GROUPS LIKE 'selected_group;%'

I need to do the same in C# Linq Query but I have problem. I dont know how to create query for the edge examples. If I search group named "cat" using my expression :

q = q.Where(x => x.Groups.Contains($";cat;") || x.Groups.Contains($";cat")
       || x.Groups.Contains($"cat;") || x.Groups.Equals("cat"));

I will get records that have this group. But query also return records with group "caterpillar" if those records have 2 groups "house;caterpillar". SQL Expression would exculde this kind of sittuation. Is there any clever solution to this problem directly in C# code ?

Body:
Sounds like you want to use .EndsWith() instead, e.g:

q.Where(x => x.Groups.EndsWith(";cat;"))

The OrmLite docs contains more OrmLite Example queries.


问:
Android studio cannot debug Fragment
I have an AppCompatDialogFragment fragment, I set different breakpoints, tried all lifecycle methods such as onCreate and onCreateDialog but it is not stopping on any one them. Normal activities can be debugged normally. This is an example of my implementation :

```<code>public class SettingsDialogFragment extends AppCompatDialogFragment {
   // Implementation
}
</code>```

I also set some logcat logs and that is working fine, so basically everything works but debugger is not stopping at any breakpoints within the fragment.

I am using Linux, could this be the reason? Is there a specific configuration setting on Android Studio to debug fragments?

答:
Thanks to @Mahabub Karim for the solution. Indeed, the solution to my problem was commenting the debug section on the app.build, which had minifyEnabled. It also works by just commenting the produardFiles line aswell:</p>

```<code>    buildTypes {
        debug {
            minifyEnabled true
//            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
</code>```

Title: Android studio cannot debug Fragment

Body:
I have an AppCompatDialogFragment fragment, I set different breakpoints, tried all lifecycle methods such as onCreate and onCreateDialog but it is not stopping on any one them. Normal activities can be debugged normally. This is an example of my implementation :

public class SettingsDialogFragment extends AppCompatDialogFragment {
   // Implementation
}

I also set some logcat logs and that is working fine, so basically everything works but debugger is not stopping at any breakpoints within the fragment.

I am using Linux, could this be the reason? Is there a specific configuration setting on Android Studio to debug fragments?

Body:
Thanks to @Mahabub Karim for the solution. Indeed, the solution to my problem was commenting the debug section on the app.build, which had minifyEnabled. It also works by just commenting the produardFiles line aswell:

    buildTypes {
        debug {
            minifyEnabled true
//            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}


问:
Error in setState while trying to update bookings
Inside the deleteBaseBooking function, I want to set this.state.checkIndexStatus[key] = null using setstate. However, it is giving an error:

```<code>deleteBaseBookings(){
        for(var key in this.state.checkIndexStatus){
            if(this.state.checkIndexStatus[key]){
                ids.push(key)
                this.updateState(key)
                console.log(ids);
            }
        }
    }

updateState = (key) => {
        this.setState({
            this.state.checkIndexStatus[key] = null
        })
    }
</code>```

I need to update the checkIndexStatus[key] = null , so that it takes null next time and previous IDs will be deleted

答:
I think you have syntax Error

You must use : instead of = in setState
you've use a name that is for react or Js you must change your word's name

```<code> deleteBaseBookings(){
            for(var key in this.state.checkIndexStatus){
                if(this.state.checkIndexStatus[key]){
                    ids.push(key)
                    this.updateState(key)
                    console.log(ids);
                }
            }
        }

    updateState = (key) => {
            this.setState({
                this.state.checkIndexStatus[key] : null
            })
        }
</code>```

Body:
Inside the deleteBaseBooking function, I want to set this.state.checkIndexStatus[key] = null using setstate. However, it is giving an error:

deleteBaseBookings(){
        for(var key in this.state.checkIndexStatus){
            if(this.state.checkIndexStatus[key]){
                ids.push(key)
                this.updateState(key)
                console.log(ids);
            }
        }
    }

updateState = (key) => {
        this.setState({
            this.state.checkIndexStatus[key] = null
        })
    }

I need to update the checkIndexStatus[key] = null , so that it takes null next time and previous IDs will be deleted

Body:
I think you have syntax Error

You must use : instead of = in setState
you've use a name that is for react or Js you must change your word's name

 deleteBaseBookings(){
            for(var key in this.state.checkIndexStatus){
                if(this.state.checkIndexStatus[key]){
                    ids.push(key)
                    this.updateState(key)
                    console.log(ids);
                }
            }
        }

    updateState = (key) => {
            this.setState({
                this.state.checkIndexStatus[key] : null
            })
        }


问:
how to find off_t size correctly
I have below piece of code in my module and im compiling it with ICC compiler.

```<code>/**
 * Static (compile-time) assertion.
 * Basically, use COND to dimension an array.  If COND is false/zero the
 * array size will be -1 and we'll get a compilation error.
 */

    #define STATIC_ASSERT(COND) \
       do { \
          (void) sizeof(char [1 - 2*!(COND)]); \
       } while (0)
     #define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + \
                         (((off_t) 1 << 31) << 31))
       STATIC_ASSERT(LARGE_OFF_T % 2147483629 == 721 &&
                     LARGE_OFF_T % 2147483647 == 1);
</code>```

the above assertion fails with array size must be grater than 0.

Can anyone help me understand when does this assertion fail and how to fix it ?
I have tried compiling with _DFILE_OFFSET_BITS=64 but in vain.

答:
The code attempts to determine whether off_t is at least 64 bits wide, including a sign bit.

In STATIC_ASSERT, if COND is true, 1 - 2*!(COND) evaluates as 1-2*!1 = 1-2*0 = 1, and the array size is 1, which is fine. If COND is false, it evaluates as 1-2*!0 = 1-2*1 = -1, which causes the compiler to issue a diagnostic. So STATIC_ASSERT acts to generate a compiler message if COND is false.

LARGE_OFF_T attempts to perform some arithmetic in the off_t type. If off_t is at least 64 bits wide, (off_t) 1 << 31) << 31 evaluates to 262. Then the whole expression evaluates to 262 − 1 + 262 = 263−1. This number has a remainder of 721 modulo 2147483629 and 1 modulo 2147483647, so it passes the test and does not cause the compiler to issue a diagnostic.

If off_t is, say, 32 bits wide and unsigned, (off_t) 1 << 31) << 31 evaluates to 0, and the whole expression evaluates to 0 − 1 + 0 = 232−1 (since unsigned arithmetic wraps), which has a remainder modulo 2147483629 of 37, so it fails the test, and the compiler generates a diagnostic.

The test is not reliable if off_t is signed. If off_t is signed and 32 bits wide, the behavior of (off_t) 1 << 31 is not defined by the C standard. If it is signed and less than 63 bits wide, the behavior of ((off_t) 1 << 31) << 31 is undefined, and, if it is signed and less than 64 bits wide, the final addition is undefined.

If the test is failing for you, you need to correct it by adjusting the build conditions so that off_t is an integer type that is at least 64 bits wide. There is insufficient information in the question to say how to do this.

There are indications in the code that it expects off_t to be a signed type. If it were known to be unsigned, then one could ensure it were at least 64 bits simply by testing 18446744073709551615u <= (off_t) -1. And value that the code attempts to construct, 263−1, is the maximum value of a 64-bit signed integer, rather than an unsigned integer. This is unfortunate because, as indicated above, if off_t is signed and less than 64 bits wide, the operations have undefined behavior. A better approach might be to test 9223372036854775807 == (off_t) 9223372036854775807, because overflow during conversion to a signed integer type is at least implementation-defined, rather than not defined by the C standard. One might also settle for 64 <= sizeof(off_t) * CHAR_BIT. (CHAR_BIT is defined in <limits.h>.)

Title: how to find off_t size correctly

Body:
I have below piece of code in my module and im compiling it with ICC compiler.

/**
 * Static (compile-time) assertion.
 * Basically, use COND to dimension an array.  If COND is false/zero the
 * array size will be -1 and we'll get a compilation error.
 */

    #define STATIC_ASSERT(COND) \
       do { \
          (void) sizeof(char [1 - 2*!(COND)]); \
       } while (0)
     #define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + \
                         (((off_t) 1 << 31) << 31))
       STATIC_ASSERT(LARGE_OFF_T % 2147483629 == 721 &&
                     LARGE_OFF_T % 2147483647 == 1);

the above assertion fails with array size must be grater than 0.

Can anyone help me understand when does this assertion fail and how to fix it ?
I have tried compiling with _DFILE_OFFSET_BITS=64 but in vain.


问:
Can I create a custom JUnit 5 annotation @Defect("Ticket-ID") and map that to @Tag("Ticket-ID")
I want to know how to add a parameter to an annotation, and then use that parameter to help compose an annotation.

As a simple example, suppose I want to define @Defect(<Ticket-ID>).  Among other things, that annotation will add @Tag(<Ticket-Id>).

Can I do this?  If so, what would the code look like?

答:
I think you can't map @Defect() to @Tag(), don't see the point on it also. You would be only changing Tag name.
What you can do is, create an interface to map @Tag("Defect") and then add a value as a parameter to it:

```<code>@Target({TYPE, METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Test
@Tag("Defect")
@interface Defect {
    int value();
}
</code>```

Then you could use it like:

```<code>@Defect("JiraIssue-1234");
</code>```

You can also get the value you pass as parameter like:

```<code>AnnotationSupport.findAnnotation(_extensionContext.getElement(), Defect.class).get().value()
</code>```

Body:
I think you can't map @Defect() to @Tag(), don't see the point on it also. You would be only changing Tag name.
What you can do is, create an interface to map @Tag("Defect") and then add a value as a parameter to it:

@Target({TYPE, METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Test
@Tag("Defect")
@interface Defect {
    int value();
}

Then you could use it like:

@Defect("JiraIssue-1234");

You can also get the value you pass as parameter like:

AnnotationSupport.findAnnotation(_extensionContext.getElement(), Defect.class).get().value()


问:
How do I HTTP GET a .js file and extract 'exports' variables?
I am writing a site in Laravel to complement a game written in Node. It pulls information directly from the game's .js files stored on GitHub and the plan is to use Vue to generate some nice HTML to display the data.

The .js files are of the form:

```<code>'use strict'

let x = {...};

exports.x = x;
</code>```

I can import the files using a PHP request (simply using 'file') and pass them to JS with either jQuery.getScript or axios.get (so far). However, I am having real trouble coming up with a way to extract the 'x' values here under exports. If I were writing a JS app in node, I would simply do the following:

```<code>var xFile = require('xFile');

var x = xFile.x;
</code>```

However, I can't figure out how to do that here as both GET methods return a string, not a JS file. JSON.parse() doesn't work, and I would like to come up with a solution that doesn't just replace the non-JSON text as I would need a reusable solution for other files. I don't suppose anybody has any ideas?

Thanks so much!

答: I managed to figure it out! It's a little janky, but you can run a node file in PHP with the exec command. I just wrote a node file to import the file and return the useful data. This probably isn't an optimal solution, but it works for me since I'm much more confident with JS than with PHP.

Body:
I am writing a site in Laravel to complement a game written in Node. It pulls information directly from the game's .js files stored on GitHub and the plan is to use Vue to generate some nice HTML to display the data.

The .js files are of the form:

'use strict'

let x = {...};

exports.x = x;

I can import the files using a PHP request (simply using 'file') and pass them to JS with either jQuery.getScript or axios.get (so far). However, I am having real trouble coming up with a way to extract the 'x' values here under exports. If I were writing a JS app in node, I would simply do the following:

var xFile = require('xFile');

var x = xFile.x;

However, I can't figure out how to do that here as both GET methods return a string, not a JS file. JSON.parse() doesn't work, and I would like to come up with a solution that doesn't just replace the non-JSON text as I would need a reusable solution for other files. I don't suppose anybody has any ideas?

Thanks so much!


问:
Npgsql exception: Column c.consrc does not exist
I have a Postgres 12 database that currently only consists of one simple table:

```<code>CREATE TABLE public.messages
(
    sender text COLLATE pg_catalog."default",
    "timestamp" timestamp with time zone,
    message_id bigint,
    text text COLLATE pg_catalog."default",
    priority bigint,
    parameters text[] COLLATE pg_catalog."default"
)
</code>```

No I want to use Npgsql to build a GUI with C# and Entity Framework. I installed the Nuget package:

```<code>Install-Package EntityFramework6.Npgsql
</code>```

and it succeeded:

```<code>Successfully installed 'EntityFramework6.Npgsql 6.4.0' to TestClient
</code>```

Next, I installed the Npgsql integration for VS 2019 (found here). When I try to add an ADO.NET Entity Data Model to my project by right-clicking it in the solution explorer, I can add a connection and the connection test ist successful (done in the Wizard). I can go on and select my table, but as soon as I press Finish, I get an error:

This is the console output:

Unable to generate the model because of the following exception:
  'System.Data.Entity.Core.EntityCommandExecutionException: An error
  occurred while executing the command definition. See the inner
  exception for details. ---> Npgsql.PostgresException: 42703: Column
  c.consrc does not exist

What can I do?

答: PG12 removed the pg_constraint.consrc, this is tracked by PG12 removed the pg_constraint.consrc. Downgrading to PG11 should work until a fix is released.</p>

Body:
I have a Postgres 12 database that currently only consists of one simple table:

CREATE TABLE public.messages
(
    sender text COLLATE pg_catalog."default",
    "timestamp" timestamp with time zone,
    message_id bigint,
    text text COLLATE pg_catalog."default",
    priority bigint,
    parameters text[] COLLATE pg_catalog."default"
)

No I want to use Npgsql to build a GUI with C# and Entity Framework. I installed the Nuget package:

Install-Package EntityFramework6.Npgsql

and it succeeded:

Successfully installed 'EntityFramework6.Npgsql 6.4.0' to TestClient

Next, I installed the Npgsql integration for VS 2019 (found here). When I try to add an ADO.NET Entity Data Model to my project by right-clicking it in the solution explorer, I can add a connection and the connection test ist successful (done in the Wizard). I can go on and select my table, but as soon as I press Finish, I get an error:

This is the console output:

Unable to generate the model because of the following exception:
  'System.Data.Entity.Core.EntityCommandExecutionException: An error
  occurred while executing the command definition. See the inner
  exception for details. ---> Npgsql.PostgresException: 42703: Column
  c.consrc does not exist

What can I do?


问:
How to free() an array of structs allocated by malloc()?
I've been working on a project that uses structs as storage for strings. I declared a struct consists of char type members:

```<code>struct datastore1
{
    char name[50];
    char address[50];
    char email[50];
    char number[50];
    char idnum[50];
};
</code>```

I'm aware that I can just do char *name, char *address... but let's say we specified it with max length of 50. Then on my function which uses the struct, I malloc'ed it with index size of 30:

```<code>struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));
</code>```

Supposedly I finished copying all strings into the struct by accessing each index, How should i free the allocated memory that was used after calling malloc? I tried doing free(dsdata) on the end of the program but I am not sure if it's the right way. Should i free each indexes individually? Please enlighten me. Thank you in advance for the feedback!

答:
How should i free the allocated memory that was used after calling malloc?

Consider below example,

```<code>struct datastore1 *obj1 = malloc(sizeof(struct datastore1));
free(obj1);
</code>```

Here obj1 is pointing to the block of memory of size same as size of datastore1 in order to free you need to send the address which is allocated by malloc.

likewise,

```<code>struct datastore1 *obj2 = malloc(3 * sizeof(struct datastore1));
free(obj2);
</code>```

obj2 is pointing to a block of contiguous memory of size 3 * sizeof(datastore1) you need to pass the base address to free

Should i free each indexes individually?

NO, Since block of memory is allocated only once and you need to free exactly one time.

Let me extend it further,

```<code>struct datastore1 *obj3[3];
for(int i=0;i<3;i++)
   obj3[i] = malloc(sizeof(struct datastore1));

for(int i=0;i<3;i++)
    free(obj3[i]);
</code>```

Here obj3 is array of pointer and each index is pointing to different part of memory and hence need to be freed individually.

Note: For simplicity I haven't considered return value from malloc. Null check has to be done on malloc return value.

Body:
I've been working on a project that uses structs as storage for strings. I declared a struct consists of char type members:

struct datastore1
{
    char name[50];
    char address[50];
    char email[50];
    char number[50];
    char idnum[50];
};

I'm aware that I can just do char *name, char *address... but let's say we specified it with max length of 50. Then on my function which uses the struct, I malloc'ed it with index size of 30:

struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));

Supposedly I finished copying all strings into the struct by accessing each index, How should i free the allocated memory that was used after calling malloc? I tried doing free(dsdata) on the end of the program but I am not sure if it's the right way. Should i free each indexes individually? Please enlighten me. Thank you in advance for the feedback!

Body:
How should i free the allocated memory that was used after calling malloc?

Consider below example,

struct datastore1 *obj1 = malloc(sizeof(struct datastore1));
free(obj1);

Here obj1 is pointing to the block of memory of size same as size of datastore1 in order to free you need to send the address which is allocated by malloc.

likewise,

struct datastore1 *obj2 = malloc(3 * sizeof(struct datastore1));
free(obj2);

obj2 is pointing to a block of contiguous memory of size 3 * sizeof(datastore1) you need to pass the base address to free

Should i free each indexes individually?

NO, Since block of memory is allocated only once and you need to free exactly one time.

Let me extend it further,

struct datastore1 *obj3[3];
for(int i=0;i<3;i++)
   obj3[i] = malloc(sizeof(struct datastore1));

for(int i=0;i<3;i++)
    free(obj3[i]);

Here obj3 is array of pointer and each index is pointing to different part of memory and hence need to be freed individually.

Note: For simplicity I haven't considered return value from malloc. Null check has to be done on malloc return value.


问:
Why functions locals and arguments are pushed to the stack?
how functions are stored on memory i.e : the data segment as normal variables expressions or on the code segment
in either one What is pushed to the stack
  a pointer? or the whole function and why do we need to push the local variables and arguments too if they are already stored in the data segment ?</p>

答:
Functions are stored in memory. Often a separate segment is used to store the executable code. The memory manager can protect this memory against alteration. With virtual memory, any code not used can be swapped out and will be restored when the code (function) must execute.

Global data is stored in global memory.

Local data is allocated on the stack. These data are called "automatic variables".

When a function is called, the return address is stored on the stack, preceded by the parameters of the function.

So, no, the function itself (the executable code) is not stored on the stack. Only its parameters, local data and the return address.

Note: this simplified description is based on Intel. Other architectures can have different concepts for "stack".


问:
aspnet_compiler.exe finding multiple types in global alias, but I can't!
Inheriting a new project today, trying to make hundreds of warnings go away, and stumped on this. ASP.NET MVC 2, framework 4.0 project which compiles just fine in VS2010, but when the build process hands off to aspnet_compiler.exe, I get the following (cut and pasted from the Output window):

```<code>AfterBuild:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe -v temp -p C:\data\crecare\CreCare20110403\CreCare.Mvc\\..\CreCare.Mvc
ASPNETCOMPILER : warning CS1685: The predefined type 'System.Runtime.CompilerServices.ExtensionAttribute' is defined in multiple assemblies in the global alias; using definition from 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Core.dll'
</code>```

Both a search in the Object Browser and a tedious assembly-by-assembly review of the references in the project do not turn up any multiple definition. As far as I can tell the previous team did not try to build any extensions in previous ASP.NET versions (one cause of this error, I have learned ); I think this has targeted 4.0 from the start.

It's only a warning and I suppose I can ignore it (you can't even /nowarn with aspnet_compiler.exe, so I have to look at them) -- but it rubs me wrong. Any suggestions for how to hunt this down?  Should that "\..\" in the path to the project worry me? I'm running 64-bit windows; it's not looking at the x86 and 64 at the same time?

It's worth noting that the using the Object Browser in VS2010 in the solution only finds the type in the assembly that aspnet_compiler.exe finds; a search for the type only gives one result. Is aspnet_compiler.exe looking in places that VS2010 doesn't?

答:
Just like you said this is due to Mono.Cecil.

This warning can become an error if you do have a reference to Mono.Cecil.Dll and implement extension methods / because when doing the compiler gives precedence to the Mono.Cecil implementation.

I don't get why db4o assemblies that are supposed to be for .net 4 are not taking this into account, but we can confirm the same as we've looked into the same issue.

As long as you only copy to output the Mono.Cecil (we add as a link and set it to copy to output) instead of using a normal reference, all works fine. The warning is annoying, but given the weird situation around these assemblies on db4o, we preferred not dealing with building its source for now.

Body:
Inheriting a new project today, trying to make hundreds of warnings go away, and stumped on this. ASP.NET MVC 2, framework 4.0 project which compiles just fine in VS2010, but when the build process hands off to aspnet_compiler.exe, I get the following (cut and pasted from the Output window):

AfterBuild:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe -v temp -p C:\data\crecare\CreCare20110403\CreCare.Mvc\\..\CreCare.Mvc
ASPNETCOMPILER : warning CS1685: The predefined type 'System.Runtime.CompilerServices.ExtensionAttribute' is defined in multiple assemblies in the global alias; using definition from 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Core.dll'

Both a search in the Object Browser and a tedious assembly-by-assembly review of the references in the project do not turn up any multiple definition. As far as I can tell the previous team did not try to build any extensions in previous ASP.NET versions (one cause of this error, I have learned ); I think this has targeted 4.0 from the start.

It's only a warning and I suppose I can ignore it (you can't even /nowarn with aspnet_compiler.exe, so I have to look at them) -- but it rubs me wrong. Any suggestions for how to hunt this down?  Should that "\..\" in the path to the project worry me? I'm running 64-bit windows; it's not looking at the x86 and 64 at the same time?

It's worth noting that the using the Object Browser in VS2010 in the solution only finds the type in the assembly that aspnet_compiler.exe finds; a search for the type only gives one result. Is aspnet_compiler.exe looking in places that VS2010 doesn't?


问:
No XHProf runs specified in the URL
I have configured XHProf on linux server but on accessing xhprof_html/index.php, instead of displaying logged slow queries, it just displays this "No XHProf runs specified in the URL." What does this refer to? </p>

答:
Seems to me that you were trying to reach the index.php file with ?run= query parameter set to something.

In order to really list the runs, it should be accessed without any arguments. The profiling files are usually stored in the system temporary directory, usually /tmp on Linux.

Title: No XHProf runs specified in the URL


问:
Creating and filling a dataframe per row from the script (i.e. without using separate vectors for the columns)
I'm trying to create a data frame from a list of "records", i.e. per row (compare to loading a CSV file, but now from within the R script file), but all the examples I can find create the data frame from vectors containing the individual columns.

The closest thing I found was starting with an empty data frame and then add the rows using rbind and list's, but then the original column names get lost and all columns have class character.

```<code>> generations <- data.frame(launch_date=as.Date(integer(), origin="1970-01-01"), generation=character(), stringsAsFactors=FALSE)
> generations
[1] launch_date generation
<0 rows> (or 0-length row.names)
</code>```

All fine here. And now:

```<code>> generations <- rbind(generations,list("2010-09-01", "Generation 1"), stringsAsFactors=FALSE)
> generations
  X.2010.09.01. X.Generation.1.
1    2010-09-01    Generation 1
> str(generations)
'data.frame':   1 obs. of  2 variables:
 $ X.2010.09.01.  : chr "2010-09-01"
 $ X.Generation.1.: chr "Generation 1"
</code>```

Original column names and classes gone :(

The reason to want something like this is that maintaining the data in separate vectors is cumbersome and invites making mistakes. So the idea here was to use an rbind with a bunch of list's where dates and names can be maintained together (i.e. pairwise, per "record"/row).

How to go about this one?

答:
You are on (one of possible many) right track with rbind. The loss of column names is due to you passing rbind a list instead of a data.frame. If instead we pass it two data.frame objects:

This is the same initialization code as in your example:

```<code>generations <- data.frame(launch_date=as.Date(integer(), origin="1970-01-01"), generation=character(), stringsAsFactors=FALSE)
</code>```

But now we pass another data.frame as the second argument to rbind:

```<code>generations <- rbind(generations,
                     data.frame(launch_date=as.Date("2010-09-01", origin="1970-01-01"), generation="Generation 1", stringsAsFactors=FALSE))
</code>```

Now

```<code>str(generations)
</code>```

Returns:

```<code>'data.frame':   0 obs. of  2 variables:
$ launch_date: 'Date' num(0)
$ generation : chr
</code>```

Body:
I'm trying to create a data frame from a list of "records", i.e. per row (compare to loading a CSV file, but now from within the R script file), but all the examples I can find create the data frame from vectors containing the individual columns.

The closest thing I found was starting with an empty data frame and then add the rows using rbind and list's, but then the original column names get lost and all columns have class character.

> generations <- data.frame(launch_date=as.Date(integer(), origin="1970-01-01"), generation=character(), stringsAsFactors=FALSE)
> generations
[1] launch_date generation
<0 rows> (or 0-length row.names)

All fine here. And now:

> generations <- rbind(generations,list("2010-09-01", "Generation 1"), stringsAsFactors=FALSE)
> generations
  X.2010.09.01. X.Generation.1.
1    2010-09-01    Generation 1
> str(generations)
'data.frame':   1 obs. of  2 variables:
 $ X.2010.09.01.  : chr "2010-09-01"
 $ X.Generation.1.: chr "Generation 1"

Original column names and classes gone :(

The reason to want something like this is that maintaining the data in separate vectors is cumbersome and invites making mistakes. So the idea here was to use an rbind with a bunch of list's where dates and names can be maintained together (i.e. pairwise, per "record"/row).

How to go about this one?

Body:
You are on (one of possible many) right track with rbind. The loss of column names is due to you passing rbind a list instead of a data.frame. If instead we pass it two data.frame objects:

This is the same initialization code as in your example:

generations <- data.frame(launch_date=as.Date(integer(), origin="1970-01-01"), generation=character(), stringsAsFactors=FALSE)

But now we pass another data.frame as the second argument to rbind:

generations <- rbind(generations,
                     data.frame(launch_date=as.Date("2010-09-01", origin="1970-01-01"), generation="Generation 1", stringsAsFactors=FALSE))

Now

str(generations)

Returns:

'data.frame':   0 obs. of  2 variables:
$ launch_date: 'Date' num(0)
$ generation : chr


问:
How to fix a "NameError: name 'color' is not defined"?
here is my code :

```<code>size = (1280, 850)
Win = pygame.display.set_mode(size)
class Particle:
    color = (255, 255, 0)
    ID = 0

    def __init__(self, rect):
        Particle.ID += 1
        self.color = (color)
        self.ID = Particle.ID
        self.rect = rect

    def move(self, x, y):
        self.rect.move(x, y)

    def draw(self):
        pygame.draw.rect(Win, self.color, self.rect)

    def collide(self, rect1):
        return self.rect.colliderect(rect1)
</code>```

When I run my project, I have : "self.color = (color)
NameError: name 'color' is not defined" but color is defined...It is at the beginning of my class "Particle"...

Thank you to help me !

答: Remove the line self.color = (color) in order to make your code working.

Body:
here is my code :

size = (1280, 850)
Win = pygame.display.set_mode(size)
class Particle:
    color = (255, 255, 0)
    ID = 0

    def __init__(self, rect):
        Particle.ID += 1
        self.color = (color)
        self.ID = Particle.ID
        self.rect = rect

    def move(self, x, y):
        self.rect.move(x, y)

    def draw(self):
        pygame.draw.rect(Win, self.color, self.rect)

    def collide(self, rect1):
        return self.rect.colliderect(rect1)

When I run my project, I have : "self.color = (color)
NameError: name 'color' is not defined" but color is defined...It is at the beginning of my class "Particle"...

Thank you to help me !


问:
Append a numpy array with different first dimensions
My program creates a numpy array within a for loop. For example it creates array with shape (100*30*10), then (160*30*10) and then may be (120*30*10) . I have to append the above to an empty numpy array such that , at the end of the loop, it will be a numpy  array with shape (380*30*10) (i.e sum  of 100+160+120) . The second and third dimension doesnt change in the numpy array.

How can I do the above in python. I tried the following.

```<code>np_model = np.append(np_model,np_temp1)
print("Appended model shape is",np_model.shape)
np_label = np.append(np_label,np_temp2)
print("Appended label shape is",np_label.shape)
</code>```

The np_model is an empty array which I have defined as np_model = np.empty(1,30,10) and np_label as np_label = np.empty(1 ,str)

np_temp1 corresponds to array within each for loop like 100*30*10,120*30*10 etc and np_temp2 is a string with "item1","item2" etc

The np_label is a string numpy array with 1 label corresponding to np_temp1.shape[0]. But the result I get in np_model is flattened array with size 380*30*10 = 1140000

Any help is appreciated.

答:
As @Nullman suggested in comment(np.vstack)

You can create empty array like this >>> np_model = np.empty((0,30,10))

>>> np_model = np.empty((0,30,10))

>>> a = np.random.rand(100,30,10)
>>> b = np.random.rand(160,30,10)
>>> c = np.random.rand(120,30,10)

# It can done by one-line like`np_model = np.vstack((a,b,c))`
# but i guess you have loop dependency here
>>> np_model = np.vstack((np_model,a))
>>> np_model = np.vstack((np_model,b))
>>> np_model = np.vstack((np_model,c))

>>> np_model.shape
(380, 30, 10)
```

Body:
My program creates a numpy array within a for loop. For example it creates array with shape (100*30*10), then (160*30*10) and then may be (120*30*10) . I have to append the above to an empty numpy array such that , at the end of the loop, it will be a numpy  array with shape (380*30*10) (i.e sum  of 100+160+120) . The second and third dimension doesnt change in the numpy array.

How can I do the above in python. I tried the following.

np_model = np.append(np_model,np_temp1)
print("Appended model shape is",np_model.shape)
np_label = np.append(np_label,np_temp2)
print("Appended label shape is",np_label.shape)

The np_model is an empty array which I have defined as np_model = np.empty(1,30,10) and np_label as np_label = np.empty(1 ,str)

np_temp1 corresponds to array within each for loop like 100*30*10,120*30*10 etc and np_temp2 is a string with "item1","item2" etc

The np_label is a string numpy array with 1 label corresponding to np_temp1.shape[0]. But the result I get in np_model is flattened array with size 380*30*10 = 1140000

Any help is appreciated.


问:
Option[Int] as index in loop
I am new at Scala so I do not know if I will ask something obvious.

I am currently trying to define a function which can or can not receive a parameter called "position". This parameter is an Int (in case the user decides to pass it). Otherwise, it should be considered as a "None" (because it will mean that nothing has been passed as parameter).
If it is a None, then: position = series.length - 1. I am trying to use Option here, since I do not want the user to pass a position if he does not require it.

```<code>def example(series: Vector[Double], position: Option[Int]): Vector[Double] = {
  position match {
    case Some(value) =>  value
    case None => series.length - 1
  }
  for (i <- position until series.length) {
    ...
  }
}
</code>```

But when I try to use it in an loop as an Integer, it gives me an error (Type mismatch. Requiered: CanBuildFrom[Nothing, Int, NotInferedCol[Int]]. Found: Int).

I have been trying different things to make this "position" as an optional value, but I can't figure it out.

答:
The issue in your code is that this:

```<code>position match {
  case Some(value) =>  value
  case None => series.length - 1
}
</code>```

is an expression that doesn't mutate the value of position, which is probably what you may have assumed.

You have to bind the value produced by the expression to use it in the code underneath it:

```<code>val positionWithDefault =
  position match {
    case Some(value) => value
    case None => series.length - 1
  }
for (i <- positionWithDefault until series.length) {
  ...
}
</code>```

Furthermore, as noted in a comment, the behavior of the match expression is the same you'd get out of getOrElse

```<code>for (i <- position.getOrElse(series.length - 1) until series.length) {
  ...
}
</code>```

Title: Option[Int] as index in loop

Body:
I am new at Scala so I do not know if I will ask something obvious.

I am currently trying to define a function which can or can not receive a parameter called "position". This parameter is an Int (in case the user decides to pass it). Otherwise, it should be considered as a "None" (because it will mean that nothing has been passed as parameter).
If it is a None, then: position = series.length - 1. I am trying to use Option here, since I do not want the user to pass a position if he does not require it.

def example(series: Vector[Double], position: Option[Int]): Vector[Double] = {
  position match {
    case Some(value) =>  value
    case None => series.length - 1
  }
  for (i <- position until series.length) {
    ...
  }
}

But when I try to use it in an loop as an Integer, it gives me an error (Type mismatch. Requiered: CanBuildFrom[Nothing, Int, NotInferedCol[Int]]. Found: Int).

I have been trying different things to make this "position" as an optional value, but I can't figure it out.

Body:
The issue in your code is that this:

position match {
  case Some(value) =>  value
  case None => series.length - 1
}

is an expression that doesn't mutate the value of position, which is probably what you may have assumed.

You have to bind the value produced by the expression to use it in the code underneath it:

val positionWithDefault =
  position match {
    case Some(value) => value
    case None => series.length - 1
  }
for (i <- positionWithDefault until series.length) {
  ...
}

Furthermore, as noted in a comment, the behavior of the match expression is the same you'd get out of getOrElse

for (i <- position.getOrElse(series.length - 1) until series.length) {
  ...
}


问:
How to loop over array values in a karate feature
I am trying to loop over array values in a karate feature file.
In a Feature1.feature - Scenario1, I have some values in the array ["UUID1","UUID2","UUID3"] and I want to call another feature file (Feature2.feature) (having a code to call a DELETE endpoint) of a service

Feature2.feature:

```<code> @ignore

Feature: Delete

  Background:

    * url baseUrl
    * headers {content-type:'application/json'}

  Scenario: Delete Test Assets

    Given headers {uid: '#(UId)', cid:'#(CId)'}
    And path 'type', Type, 'id', AssetId
    When method delete
    Then status 204
</code>```

What approach should I use to Feature1.feature to call the Feature2.feature in a loop?

答:
If you have an array of primitives, you need to convert it into an array of JSON objects before doing a "loop call". Refer to the docs for karate.mapWithKey(): https://github.com/intuit/karate#json-transforms

So do this:

```<code>* def data =  ["UUID1","UUID2","UUID3"]
* def data = karate.mapWithKey(data, 'uid')
* call read('second.feature') data
</code>```

And in second.feature:

```<code>* headers { uid: '#(uid)' }
</code>```

Of course, read the docs for call if needed: https://github.com/intuit/karate#data-driven-features

Body:
I am trying to loop over array values in a karate feature file.
In a Feature1.feature - Scenario1, I have some values in the array ["UUID1","UUID2","UUID3"] and I want to call another feature file (Feature2.feature) (having a code to call a DELETE endpoint) of a service

Feature2.feature:

 @ignore

Feature: Delete

  Background:

    * url baseUrl
    * headers {content-type:'application/json'}

  Scenario: Delete Test Assets

    Given headers {uid: '#(UId)', cid:'#(CId)'}
    And path 'type', Type, 'id', AssetId
    When method delete
    Then status 204

What approach should I use to Feature1.feature to call the Feature2.feature in a loop?

Body:
If you have an array of primitives, you need to convert it into an array of JSON objects before doing a "loop call". Refer to the docs for karate.mapWithKey(): https://github.com/intuit/karate#json-transforms

So do this:

* def data =  ["UUID1","UUID2","UUID3"]
* def data = karate.mapWithKey(data, 'uid')
* call read('second.feature') data

And in second.feature:

* headers { uid: '#(uid)' }

Of course, read the docs for call if needed: https://github.com/intuit/karate#data-driven-features


问:
How to add bridging header to Flutter Plugin
I'm trying to create Flutter plugin, which uses Swift and has one pod dependency (NearbyMessages)

First of all, I've added it to .podspec

```<code>#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
  s.name             = 'flutter_nearby_messages'
  s.version          = '0.0.1'
  s.summary          = 'A new flutter plugin project.'
  s.description      = <<-DESC
A new flutter plugin project.
                       DESC
  s.homepage         = 'http://example.com'
  s.license          = { :file => '../LICENSE' }
  s.author           = { 'Your Company' => 'email@example.com' }
  s.source           = { :path => '.' }
  s.source_files = 'Classes/**/*'
  s.public_header_files = 'Classes/**/*.h'
  s.dependency 'Flutter'
  //************ I've added this lines ***************
  s.dependency 'NearbyMessages'
  s.xcconfig = { 'SWIFT_OBJC_BRIDGING_HEADER' => 'Classes/bridging_header.h' }
  //********* ^^ I've added this lines ^^ ************
  s.static_framework = true
  s.ios.deployment_target = '8.0'
end
</code>```

After pod install and initial empty project built, everything seems to be fine

I've tried using it in Objective-C:

```<code>#import "FlutterNearbyMessagesPlugin.h"
#import <NearbyMessages/GNSMessages.h>
#import <flutter_nearby_messages/flutter_nearby_messages-Swift.h>

@implementation FlutterNearbyMessagesPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    GNSMessageManager *messageManager =
    [[GNSMessageManager alloc] initWithAPIKey:@"API_KEY"];
  [SwiftFlutterNearbyMessagesPlugin registerWithRegistrar:registrar];
}
@end
</code>```

And it works, but when I try:

```<code>public class SwiftFlutterNearbyMessagesPlugin: NSObject, FlutterPlugin {
    private var client: GNSMessageManager? = nil
</code>```

XCode says Use of undeclared type GNSMessageManager

I understand, that I need bridging header, and I've already tried to creating it, but it seems not to be linked at all.

Bridging header contains just one line: #import <NearbyMessages/GNSMessages.h>

So my question is, how to add bridging header to flutter plugin?

答:
The only solution that worked for me for adding a Bridging Header file to a Flutter plugin was putting the header file in Classes folder and then adding this to .podspec:

```<code>s.public_header_files = 'Classes/**/*.h'
</code>```

Body:
I'm trying to create Flutter plugin, which uses Swift and has one pod dependency (NearbyMessages)

First of all, I've added it to .podspec

#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
  s.name             = 'flutter_nearby_messages'
  s.version          = '0.0.1'
  s.summary          = 'A new flutter plugin project.'
  s.description      = <<-DESC
A new flutter plugin project.
                       DESC
  s.homepage         = 'http://example.com'
  s.license          = { :file => '../LICENSE' }
  s.author           = { 'Your Company' => 'email@example.com' }
  s.source           = { :path => '.' }
  s.source_files = 'Classes/**/*'
  s.public_header_files = 'Classes/**/*.h'
  s.dependency 'Flutter'
  //************ I've added this lines ***************
  s.dependency 'NearbyMessages'
  s.xcconfig = { 'SWIFT_OBJC_BRIDGING_HEADER' => 'Classes/bridging_header.h' }
  //********* ^^ I've added this lines ^^ ************
  s.static_framework = true
  s.ios.deployment_target = '8.0'
end

After pod install and initial empty project built, everything seems to be fine

I've tried using it in Objective-C:

#import "FlutterNearbyMessagesPlugin.h"
#import <NearbyMessages/GNSMessages.h>
#import <flutter_nearby_messages/flutter_nearby_messages-Swift.h>

@implementation FlutterNearbyMessagesPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    GNSMessageManager *messageManager =
    [[GNSMessageManager alloc] initWithAPIKey:@"API_KEY"];
  [SwiftFlutterNearbyMessagesPlugin registerWithRegistrar:registrar];
}
@end

And it works, but when I try:

public class SwiftFlutterNearbyMessagesPlugin: NSObject, FlutterPlugin {
    private var client: GNSMessageManager? = nil

XCode says Use of undeclared type GNSMessageManager

I understand, that I need bridging header, and I've already tried to creating it, but it seems not to be linked at all.

Bridging header contains just one line: #import <NearbyMessages/GNSMessages.h>

So my question is, how to add bridging header to flutter plugin?

Body:
The only solution that worked for me for adding a Bridging Header file to a Flutter plugin was putting the header file in Classes folder and then adding this to .podspec:

s.public_header_files = 'Classes/**/*.h'


问:
All service calls from silverlight failing
I have a strange issue. All the webservice calls from silverlight application in my computer are failing. When I checked with fiddler, I can see that all the services are properly returning data. But the service calls in silverlight end up in the Communication Exception. The remote server returned an error: Not found.

I am using silverlight 4.0.

Any help would be appreciated.

答: The issue was really small. The disk space in C: drive of my machine was very low. Once some space got freed up, the issue got resolved. Thanks to all who helped.</p>


问:
How to make tablayout tabitem text size equal?
I tried other StackOverflow answer
How to make tablayout text size equal?
but it's not working in my case so I ask this question please help me out.</p>

```<code><com.google.android.material.tabs.TabLayout
                android:id="@+id/tabslayout"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:layout_alignParentBottom="true"
                android:layout_gravity="bottom"
                android:background="@color/white"
                android:minHeight="?android:attr/actionBarSize"
                app:tabBackground="@color/gray"
                app:tabContentStart="72dp"
                app:tabTextAppearance="@style/MineCustomTabText"
                app:tabTextColor="@color/black">

                <com.google.android.material.tabs.TabItem
                    android:id="@+id/TAB_OPINION"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text=""
                    app:tabMode="scrollable"
                    app:tabGravity="fill"
                    app:tabIndicatorHeight="5dp"/>

                <com.google.android.material.tabs.TabItem
                    android:id="@+id/TAB_FUNFACTS"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text=""
                    app:tabMode="scrollable"
                    app:tabGravity="fill"
                    app:tabIndicatorHeight="5dp"/>
            </com.google.android.material.tabs.TabLayout>
</code>```

答:
making the tablayout scrollable does the work for me.</p>

```<code>                app:tabMode="scrollable"

</code>```

Body:
I tried other StackOverflow answer
How to make tablayout text size equal?
but it's not working in my case so I ask this question please help me out.

<com.google.android.material.tabs.TabLayout
                android:id="@+id/tabslayout"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:layout_alignParentBottom="true"
                android:layout_gravity="bottom"
                android:background="@color/white"
                android:minHeight="?android:attr/actionBarSize"
                app:tabBackground="@color/gray"
                app:tabContentStart="72dp"
                app:tabTextAppearance="@style/MineCustomTabText"
                app:tabTextColor="@color/black">

                <com.google.android.material.tabs.TabItem
                    android:id="@+id/TAB_OPINION"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text=""
                    app:tabMode="scrollable"
                    app:tabGravity="fill"
                    app:tabIndicatorHeight="5dp"/>

                <com.google.android.material.tabs.TabItem
                    android:id="@+id/TAB_FUNFACTS"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text=""
                    app:tabMode="scrollable"
                    app:tabGravity="fill"
                    app:tabIndicatorHeight="5dp"/>
            </com.google.android.material.tabs.TabLayout>

Body:
making the tablayout scrollable does the work for me.

                app:tabMode="scrollable"


问:
Pandas .agg() dropping columns (lambda function)
I have a df (df.shape = (14762, 35)).

```<code>Number    Day        Colour   City ...
123       Monday     Red      London ...
234       Monday     Blue     Paris ...
234       Wednesday  Yellow   Paris ...
345       Tuesday    Green    Berlin ...
</code>```

I am trying to groupby and aggregate the df to produce

```<code>Number    Day                Colour        City ...
123       Monday             Red           London ...
234       Monday, Wednesday  Blue, Yellow  Paris ...
345       Tuesday            Green         Berlin ...
</code>```

I'm using

```<code>df.groupby('Number').agg(lambda s: ', '.join({*s}))
</code>```

However, my new df has a shape (5435, 22). The problem is in the aggregate step lambda function. The groupby step works fine. Just wondering why the .agg or .join might drop certain columns. I've read about nuisance columns during groupby, but I don't think that is the problem.

I've printed the .dtypes and the columns being dropped are object, int64 and float64.

I'm using Python 3.6.9 and pandas 0.25.3.

答:
I would expect float64 and int64 to be dropped as the join function will raise a TypeError. You might be facing the same problem, i.e. inability to use the join on other object columns also.

You can fix that by changing the aggregating function to -

lambda x: ', '.join([str(i) for i in x])

Body:
I have a df (df.shape = (14762, 35)).

Number    Day        Colour   City ...
123       Monday     Red      London ...
234       Monday     Blue     Paris ...
234       Wednesday  Yellow   Paris ...
345       Tuesday    Green    Berlin ...

I am trying to groupby and aggregate the df to produce

Number    Day                Colour        City ...
123       Monday             Red           London ...
234       Monday, Wednesday  Blue, Yellow  Paris ...
345       Tuesday            Green         Berlin ...

I'm using

df.groupby('Number').agg(lambda s: ', '.join({*s}))

However, my new df has a shape (5435, 22). The problem is in the aggregate step lambda function. The groupby step works fine. Just wondering why the .agg or .join might drop certain columns. I've read about nuisance columns during groupby, but I don't think that is the problem.

I've printed the .dtypes and the columns being dropped are object, int64 and float64.

I'm using Python 3.6.9 and pandas 0.25.3.


问:
How to configure a Spring @Component differently when testing
I am trying to learn Spring by writing an app which queries information from 2 LDAP sources via 2 Service classes.

I have an ActiveDirectory source:

```<code>@Component
public class AdLdapService implements LdapService {
    @Override
    public Optional<LdapMember> getUserById(String accountName) throws Exception {
    }
}
</code>```

and this is configured using

```<code>@Configuration
public class AdLdapConfiguration {

    @Autowired
    Environment env;

    @Bean("ad-context")
    public LdapContextSource contextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(env.getRequiredProperty("ldap.ad.url"));
        contextSource.setBase(env.getRequiredProperty("ldap.ad.base"));
        contextSource.setUserDn(env.getRequiredProperty("ldap.ad.user"));
        contextSource.setPassword(env.getRequiredProperty("ldap.ad.password"));
        return contextSource;
    }

    @Bean("ad-template")
    public LdapTemplate ldapTemplate() {
        return new LdapTemplate(contextSource());
    }
}
</code>```

I also have a second pair of classes for accessing a different LDAP source. This all works fine.

Now I want to add some unit tests to test the 2 services and, rather than using a live LDAP, I thought it would be better to create a small embedded LDAP on the fly and test against that. This is where I've got stuck.

I want to create 2 separate LDAPs and populate them from 2 LDIF files. My 2 LdapService implementations should then link to the relevant embedded LDAPs.

My Spring knowledge is still very limited and I don't know the elegant way to set this up.

答:
You can start off with a test that will load the application context with the configuration of your choice:

```<code>@RunWith(SpringRunner.class)
@ContextConfiguration(...<YOUR_CONFIG_GOES_HERE>)
public void MySampleLdapTest {

    @Autowired
    public LdapTemplate testTemplate;

    @Test
    public void testLdap() {
      testTemplate.doWhateverYouNeedAndVerifyTheResult();
    }
}

</code>```

Now if you need to run the Ldap Service in-memory its certainly an integration test.
You can do one of the following:

Use TestContainers framework to fire up the Ldap Service Docker image and interact with it.

Find some in-memory implementation of Ldap Server and integrate with the test.

Use @MockBean annotation if you want to mock a bean that interacts with the LdapService but you still want to load the application context with a bunch of your beans. This is a special annotation that alters the application context : if there was a bean of that type - it will place a mock onto the application context instead (a regular mock created with mockito), if there was no bean at all - it will create the mock and add one to the app context anyway.

Last but not the least, all these tests are significantly slower than a regular mockito style unit testing. In general spring tests is a wonderful tool but its for integration tests, not for unit tests. If you can do a unit test without spring at all with mockito - it can be even a better choice.

Body:
I am trying to learn Spring by writing an app which queries information from 2 LDAP sources via 2 Service classes.

I have an ActiveDirectory source:

@Component
public class AdLdapService implements LdapService {
    @Override
    public Optional<LdapMember> getUserById(String accountName) throws Exception {
    }
}

and this is configured using

@Configuration
public class AdLdapConfiguration {

    @Autowired
    Environment env;

    @Bean("ad-context")
    public LdapContextSource contextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(env.getRequiredProperty("ldap.ad.url"));
        contextSource.setBase(env.getRequiredProperty("ldap.ad.base"));
        contextSource.setUserDn(env.getRequiredProperty("ldap.ad.user"));
        contextSource.setPassword(env.getRequiredProperty("ldap.ad.password"));
        return contextSource;
    }

    @Bean("ad-template")
    public LdapTemplate ldapTemplate() {
        return new LdapTemplate(contextSource());
    }
}

I also have a second pair of classes for accessing a different LDAP source. This all works fine.

Now I want to add some unit tests to test the 2 services and, rather than using a live LDAP, I thought it would be better to create a small embedded LDAP on the fly and test against that. This is where I've got stuck.

I want to create 2 separate LDAPs and populate them from 2 LDIF files. My 2 LdapService implementations should then link to the relevant embedded LDAPs.

My Spring knowledge is still very limited and I don't know the elegant way to set this up.

Body:
You can start off with a test that will load the application context with the configuration of your choice:

@RunWith(SpringRunner.class)
@ContextConfiguration(...<YOUR_CONFIG_GOES_HERE>)
public void MySampleLdapTest {

    @Autowired
    public LdapTemplate testTemplate;

    @Test
    public void testLdap() {
      testTemplate.doWhateverYouNeedAndVerifyTheResult();
    }
}

Now if you need to run the Ldap Service in-memory its certainly an integration test.
You can do one of the following:

Use TestContainers framework to fire up the Ldap Service Docker image and interact with it.

Find some in-memory implementation of Ldap Server and integrate with the test.

Use @MockBean annotation if you want to mock a bean that interacts with the LdapService but you still want to load the application context with a bunch of your beans. This is a special annotation that alters the application context : if there was a bean of that type - it will place a mock onto the application context instead (a regular mock created with mockito), if there was no bean at all - it will create the mock and add one to the app context anyway.

Last but not the least, all these tests are significantly slower than a regular mockito style unit testing. In general spring tests is a wonderful tool but its for integration tests, not for unit tests. If you can do a unit test without spring at all with mockito - it can be even a better choice.


答:
You don't have variable color in your __init__(), so it's senseless to assign class variable to instance variable - it will have it by default. But you can do something like

```<code>MyParticle = Particle(some_rect)
MyParticle.color = (255, 0, 255)
</code>```

Title: How to fix a "NameError: name 'color' is not defined"?

Body:
You don't have variable color in your __init__(), so it's senseless to assign class variable to instance variable - it will have it by default. But you can do something like

MyParticle = Particle(some_rect)
MyParticle.color = (255, 0, 255)