问:
xamarin.forms (android) cannot update app in appstore "android:exported" attribute missing
as of today something must have changed because we cannot update our app in the appstore.

we are given this error upon upload:

```<code>Warning: If an activity, service, or broadcast receiver uses intent filters and doesn't have an explicitly-declared value for android:exported, your app can't be installed on a device that runs Android 12 or higher.
</code>```

In the docs is gives this example on how to fix this:

```<code><service android:name="com.example.app.backgroundService"
         android:exported="false">
    <intent-filter>
        <action android:name="com.example.app.START_BACKGROUND" />
    </intent-filter>
</service>
</code>```

The problem is that this is regarding java and android studio but doesnt translate well into xamarin.forms.

This is my manifest:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionName="1.172" package="com.interiorcircle.interiorcircledroid" android:installLocation="auto" android:versionCode="329">
    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="31" />
    <application android:label="Interior Circle" android:theme="@style/MainTheme" android:icon="@mipmap/launcher_foreground">
        <provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
        </provider>
        <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="asd" />
    </application>
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-feature android:name="android.hardware.location" android:required="false" />
    <uses-feature android:name="android.hardware.location.gps" android:required="false" />
    <uses-feature android:name="android.hardware.location.network" android:required="false" />
</manifest>
</code>```

EDIT:

i have noticed int he obj folder builds that in the manifest, these here do NOT have the attribute in question:

```<code><service android:name="crc6494e14b9856016c30.PNFirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
    <receiver android:name="crc6494e14b9856016c30.PushNotificationActionReceiver" />
    <receiver android:name="crc6494e14b9856016c30.PushNotificationDeletedReceiver" />
    <activity android:configChanges="orientation|screenSize|uiMode" android:name="crc646957603ea1820544.MediaPickerActivity" />
</code>```

has anyone made a similar experience and maybe already solved this issue?

答:
The problem is produced, as I found in my question, by the firebase nuget package, that just lacks the android:exported attribute.

HOwever, you can add this by adding this line into your manifest in between application tags:

```<code><receiver android:name="crc6494e14b9856016c30.PNFirebaseMessagingService" android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</receiver>
</code>```

AS this is such a arbritary namespace, it might not work for ever, so keep in mind that this namespace might change.

I also opend a git issue with this exact problem so that the devs can fix it themselves.

Best

Body:
as of today something must have changed because we cannot update our app in the appstore.

we are given this error upon upload:

Warning: If an activity, service, or broadcast receiver uses intent filters and doesn't have an explicitly-declared value for android:exported, your app can't be installed on a device that runs Android 12 or higher.

In the docs is gives this example on how to fix this:

<service android:name="com.example.app.backgroundService"
         android:exported="false">
    <intent-filter>
        <action android:name="com.example.app.START_BACKGROUND" />
    </intent-filter>
</service>

The problem is that this is regarding java and android studio but doesnt translate well into xamarin.forms.

This is my manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionName="1.172" package="com.interiorcircle.interiorcircledroid" android:installLocation="auto" android:versionCode="329">
    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="31" />
    <application android:label="Interior Circle" android:theme="@style/MainTheme" android:icon="@mipmap/launcher_foreground">
        <provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
        </provider>
        <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="asd" />
    </application>
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-feature android:name="android.hardware.location" android:required="false" />
    <uses-feature android:name="android.hardware.location.gps" android:required="false" />
    <uses-feature android:name="android.hardware.location.network" android:required="false" />
</manifest>

EDIT:

i have noticed int he obj folder builds that in the manifest, these here do NOT have the attribute in question:

<service android:name="crc6494e14b9856016c30.PNFirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
    <receiver android:name="crc6494e14b9856016c30.PushNotificationActionReceiver" />
    <receiver android:name="crc6494e14b9856016c30.PushNotificationDeletedReceiver" />
    <activity android:configChanges="orientation|screenSize|uiMode" android:name="crc646957603ea1820544.MediaPickerActivity" />

has anyone made a similar experience and maybe already solved this issue?

Body:
The problem is produced, as I found in my question, by the firebase nuget package, that just lacks the android:exported attribute.

HOwever, you can add this by adding this line into your manifest in between application tags:

<receiver android:name="crc6494e14b9856016c30.PNFirebaseMessagingService" android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</receiver>

AS this is such a arbritary namespace, it might not work for ever, so keep in mind that this namespace might change.

I also opend a git issue with this exact problem so that the devs can fix it themselves.

Best


来源: stackexchange

问:
How can I make a new array from a event emitter ( gives bytes array), where new arrays first element will be '10' and last '13'?
I have incoming bytes of arrays once a time. It kind of looks like this

[10,12,34,58,62]

[83,33,23,44,13]

[10,12,34,58,62]

[34, 77,54,23,87]

[83,33,23,44,13]

[10,12,34,58,62]

[83,33,23,44,66]

[13]
…continues.

So, it renders each array every time. I needed them to be rendered like

[10,12,34,58,62,83,33,23,44,13]

[10,12,34,58,62,34,77,54,23,87,83,33,23,44,13]

[10,12,34,58,62,83,33,23,44,66,13].

The first element will be 10 and the last 13.
Can anyone help me with the code? Thanks in advance.

答:
If your incoming bytes is 2d array then try this.

let arr = [
  [10, 12, 34, 58, 62],
  [83, 33, 23, 44, 13],
  [10, 12, 34, 58, 62],
  [34, 77, 54, 23, 87],
  [83, 33, 23, 44, 13],
  [10, 12, 34, 58, 62],
  [83, 33, 23, 44, 66],
  [13]
]
let openedArr = []
for (let value of arr) {
  openedArr = [...openedArr, ...value]
}

let resultArr = []
let child = []

for (let value of openedArr) {
  child.push(value)
  if (value == 13) {
    resultArr.push(child)
    child = []
  }
}
console.log(resultArr)```

Explaination

Make an new array by spreading all incoming array.

Create two arrays resultArr and Child Array

Push every array elements to Child array

If there is 13, then push child array to resultArr, and empty child array.

ContentLicense: CC BY-SA 4.0

Body:
If your incoming bytes is 2d array then try this.

let arr = [
  [10, 12, 34, 58, 62],
  [83, 33, 23, 44, 13],
  [10, 12, 34, 58, 62],
  [34, 77, 54, 23, 87],
  [83, 33, 23, 44, 13],
  [10, 12, 34, 58, 62],
  [83, 33, 23, 44, 66],
  [13]
]
let openedArr = []
for (let value of arr) {
  openedArr = [...openedArr, ...value]
}

let resultArr = []
let child = []

for (let value of openedArr) {
  child.push(value)
  if (value == 13) {
    resultArr.push(child)
    child = []
  }
}
console.log(resultArr)

Explaination

Make an new array by spreading all incoming array.

Create two arrays resultArr and Child Array

Push every array elements to Child array

If there is 13, then push child array to resultArr, and empty child array.


问:
Java Hibernate Many To One Question
I am having problem with my Hibernate Mapping.
I have a many to one mapping between my entity.
The two tables in my Oracle DB are the following...

```<code>Employee
--------------------------
EMPLOYEE_ID
EMPLOYEE_FIRST_NAME
EMPLOYEE_LAST_NAME
HEALTH_PLAN_ID
Health_Plan
------------------=
HEALTH_PLAN_ID
HEALTH_PLAN_NAME
HEALTH_PLAN_RATE
</code>```

And my mapping...

```<code>@Entity
@Table(name = "Employee")
@SequenceGenerator(name = "employee_seq", sequenceName = "employee_seq")
public class Employee {
    private int employeeId;
    private String firstName;
    private String lastName;
    private HealthPlan plan;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "employee_seq")
    @Column(name = "employee_id", nullable = false)
    public int getEmployeeId() {
        return employeeId;
    }
    @Column(name = "employee_first_name", nullable = false)
    public String getFirstName() {
        return firstName;
    }
    @Column(name = "employee_last_name", nullable = false)
    public String getLastName() {
        return lastName;
    }
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "HEALTH_PLAN_ID")
    public HealthPlan getPlan() {
        return plan;
    }
}

@Entity
@Table(name = "HEALTH_PLAN")
@SequenceGenerator(name = "HEALTH_PLAN_SEQ", sequenceName = "HEALTH_PLAN_SEQ")
public class HealthPlan {
    private int healthPlanId;
    private String healthPlanName;
    private double healthPlanRate;
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "HEALTH_PLAN_SEQ")
    @Column(nullable = false, name = "HEALTH_PLAN_ID")
    public int getHealthPlanId() {
        return healthPlanId;
    }
    @Column(nullable = false, name = "HEALTH_PLAN_NAME", unique = true)
    public String getHealthPlanName() {
        return healthPlanName;
    }
    @Column(nullable = false, name = "HEALTH_PLAN_RATE")
    public double getHealthPlanRate() {
        return healthPlanRate;
    }
}
</code>```

When I ran below code....

```<code>    public static void main(String[] args) throws SQLException {
        HealthPlanDaoImpl healthDao = new HealthPlanDaoImpl();
        EmployeeDaoImpl empDao = new EmployeeDaoImpl();

        HealthPlan plan = new HealthPlan();
        plan.setHealthPlanName("PLAN B");
        plan.setHealthPlanRate(5.0);

        Employee emp = new Employee();
        emp.setPlan(plan);
        emp.setFirstName("Jane");
        emp.setLastName("Doe");
        boolean isSuccess = empDao.addEmployee(emp);
        System.out.println(isSuccess);

    }
public class EmployeeDaoImpl{
    public  boolean addEmployee(Employee emp) {
      boolean bolReturn = true;

      Session session = HibernateUtil.beginTransaction();
      try {
          session.save(emp);
          HibernateUtil.commitTransaction();
      } catch (Exception e) {
          e.printStackTrace();
          bolReturn = false;
          HibernateUtil.rollbackTransaction();
      }
      return bolReturn;
    }
}
</code>```

In the Health_Plan Table, the HEALTH_PLAN_ID = 3 (Which is correct!!!)
In the Employee Table, the HEALTH_PLAN_ID = 1850 (Where did this value came from???  I expect this to be 3 also.)

I tried several times and I notice that in the Employee Table HEALTH_PLAN_ID just increment by 300.
I think I already set the cascade option.

Any hints?

答:
I do not know the exact reason of the issue , but I can see some issues with the code right away .
1.In health plan table the annotation says GenerationType.SEQUENCE where as in the employee table it says GenerationType.AUTO
2.In the employee table @Column(name = "employee_id", nullable = false) . employee_id is neither the name of the variable in the entity class nor the name of the actual column. Three columns in that entity class has this problem .

Probably if you fix this, it can solve your issue ?

ContentLicense: CC BY-SA 3.0

Title: Java Hibernate Many To One Question

Body:
I am having problem with my Hibernate Mapping.
I have a many to one mapping between my entity.
The two tables in my Oracle DB are the following...

Employee
--------------------------
EMPLOYEE_ID
EMPLOYEE_FIRST_NAME
EMPLOYEE_LAST_NAME
HEALTH_PLAN_ID
Health_Plan
------------------=
HEALTH_PLAN_ID
HEALTH_PLAN_NAME
HEALTH_PLAN_RATE

And my mapping...

@Entity
@Table(name = "Employee")
@SequenceGenerator(name = "employee_seq", sequenceName = "employee_seq")
public class Employee {
    private int employeeId;
    private String firstName;
    private String lastName;
    private HealthPlan plan;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "employee_seq")
    @Column(name = "employee_id", nullable = false)
    public int getEmployeeId() {
        return employeeId;
    }
    @Column(name = "employee_first_name", nullable = false)
    public String getFirstName() {
        return firstName;
    }
    @Column(name = "employee_last_name", nullable = false)
    public String getLastName() {
        return lastName;
    }
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "HEALTH_PLAN_ID")
    public HealthPlan getPlan() {
        return plan;
    }
}

@Entity
@Table(name = "HEALTH_PLAN")
@SequenceGenerator(name = "HEALTH_PLAN_SEQ", sequenceName = "HEALTH_PLAN_SEQ")
public class HealthPlan {
    private int healthPlanId;
    private String healthPlanName;
    private double healthPlanRate;
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "HEALTH_PLAN_SEQ")
    @Column(nullable = false, name = "HEALTH_PLAN_ID")
    public int getHealthPlanId() {
        return healthPlanId;
    }
    @Column(nullable = false, name = "HEALTH_PLAN_NAME", unique = true)
    public String getHealthPlanName() {
        return healthPlanName;
    }
    @Column(nullable = false, name = "HEALTH_PLAN_RATE")
    public double getHealthPlanRate() {
        return healthPlanRate;
    }
}

When I ran below code....

    public static void main(String[] args) throws SQLException {
        HealthPlanDaoImpl healthDao = new HealthPlanDaoImpl();
        EmployeeDaoImpl empDao = new EmployeeDaoImpl();

        HealthPlan plan = new HealthPlan();
        plan.setHealthPlanName("PLAN B");
        plan.setHealthPlanRate(5.0);

        Employee emp = new Employee();
        emp.setPlan(plan);
        emp.setFirstName("Jane");
        emp.setLastName("Doe");
        boolean isSuccess = empDao.addEmployee(emp);
        System.out.println(isSuccess);

    }
public class EmployeeDaoImpl{
    public  boolean addEmployee(Employee emp) {
      boolean bolReturn = true;

      Session session = HibernateUtil.beginTransaction();
      try {
          session.save(emp);
          HibernateUtil.commitTransaction();
      } catch (Exception e) {
          e.printStackTrace();
          bolReturn = false;
          HibernateUtil.rollbackTransaction();
      }
      return bolReturn;
    }
}

In the Health_Plan Table, the HEALTH_PLAN_ID = 3 (Which is correct!!!)
In the Employee Table, the HEALTH_PLAN_ID = 1850 (Where did this value came from???  I expect this to be 3 also.)

I tried several times and I notice that in the Employee Table HEALTH_PLAN_ID just increment by 300.
I think I already set the cascade option.

Any hints?


问:
How to group into batches after assigning rank
I have a table that I'm first trying to group based on unique column values (using dense_rank) and then further group those items into batches of 5. Below is my table:

video_id
frame_id
verb

video_a
frame_1
walk

video_a
frame_2
run

video_a
frame_3
sit

video_a
frame_4
walk

video_a
frame_5
walk

video_a
frame_6
walk

video_b
frame_7
stand

video_b
frame_8
stand

video_b
frame_9
run

video_b
frame_10
run

video_b
frame_11
sit

video_b
frame_12
run

video_b
frame_13
run

And below is what I'm trying to get:

video_id
frame_id
verb
batch_of_five

video_a
frame_1
walk
1

video_a
frame_2
run
1

video_a
frame_3
sit
1

video_a
frame_4
walk
1

video_a
frame_5
walk
1

video_a
frame_6
walk
2

video_b
frame_7
stand
3

video_b
frame_8
stand
3

video_b
frame_9
run
3

video_b
frame_10
run
3

video_b
frame_11
sit
3

video_b
frame_12
run
4

video_b
frame_13
run
4

Where each video_id has a unique rank and each batch of 10 within each ranked video_id has its own unique rank (and each batch of 10 overall has a unique id regardless of whether they belong to the same video_id or not).

I'm able to group based on the video_id column but am having trouble grouping those items further so that they are both in batches of 10 and unique across all video_ids. I thought about using a group by clause but I'm trying to keep the other columns intact as well (verb column).

Here is my presto query so far:

```<code>SELECT
    *
FROM (
    SELECT
        *,
        -- Give each unique video_id a unique rank
        DENSE_RANK() OVER (ORDER BY video_id) AS video_batch
    FROM videos
)

</code>```

答:
Calculate frame rank (partition by video_id), divide by 6 (integer division) to get batch number in video_id partition. Then rank again to get absolute batch number:

```<code>with sample_data as(
select 'video_a' as video_id, 'frame_1' as frame_id , 'walk' as verb union all
select 'video_a', 'frame_2' , 'run'   union all
select 'video_a', 'frame_3' , 'sit'   union all
select 'video_a', 'frame_4' , 'walk'  union all
select 'video_a', 'frame_5' , 'walk'  union all
select 'video_a', 'frame_6' , 'walk'  union all
select 'video_b', 'frame_7' , 'stand' union all
select 'video_b', 'frame_8' , 'stand' union all
select 'video_b', 'frame_9' , 'run'   union all
select 'video_b', 'frame_10', 'run'   union all
select 'video_b', 'frame_11', 'sit'   union all
select 'video_b', 'frame_12', 'run'   union all
select 'video_b', 'frame_13', 'run'
)

select s.*,
       dense_rank() over(order by video_id, rnk_frame / 6) batch_of_five
from
(
select video_id, frame_id, verb,
       CAST(regexp_extract(frame_id,'_(\d*)$',1) AS INT) frame_number,
       dense_rank() over(partition by video_id order by CAST(regexp_extract(frame_id,'_(\d*)$',1) AS INT)) rnk_frame
  from sample_data
)s
order by video_id, frame_number;
</code>```

Result:

```<code>video_id    frame_id    verb    frame_number    rnk_frame   batch_of_five
video_a     frame_1     walk    1                1           1
video_a     frame_2     run     2                2           1
video_a     frame_3     sit     3                3           1
video_a     frame_4     walk    4                4           1
video_a     frame_5     walk    5                5           1
video_a     frame_6     walk    6                6           2
video_b     frame_7     stand   7                1           3
video_b     frame_8     stand   8                2           3
video_b     frame_9     run     9                3           3
video_b     frame_10    run     10               4           3
video_b     frame_11    sit     11               5           3
video_b     frame_12    run     12               6           4
video_b     frame_13    run     13               7           4
</code>```

I extracted frame_number to sort as integer, not as string, to get the same sort order as in your question (some sorting column is absolutely necessary), if you already have rank as you mentioned in question, you can use it instead.

Body:
I have a table that I'm first trying to group based on unique column values (using dense_rank) and then further group those items into batches of 5. Below is my table:

video_id
frame_id
verb

video_a
frame_1
walk

video_a
frame_2
run

video_a
frame_3
sit

video_a
frame_4
walk

video_a
frame_5
walk

video_a
frame_6
walk

video_b
frame_7
stand

video_b
frame_8
stand

video_b
frame_9
run

video_b
frame_10
run

video_b
frame_11
sit

video_b
frame_12
run

video_b
frame_13
run

And below is what I'm trying to get:

video_id
frame_id
verb
batch_of_five

video_a
frame_1
walk
1

video_a
frame_2
run
1

video_a
frame_3
sit
1

video_a
frame_4
walk
1

video_a
frame_5
walk
1

video_a
frame_6
walk
2

video_b
frame_7
stand
3

video_b
frame_8
stand
3

video_b
frame_9
run
3

video_b
frame_10
run
3

video_b
frame_11
sit
3

video_b
frame_12
run
4

video_b
frame_13
run
4

Where each video_id has a unique rank and each batch of 10 within each ranked video_id has its own unique rank (and each batch of 10 overall has a unique id regardless of whether they belong to the same video_id or not).

I'm able to group based on the video_id column but am having trouble grouping those items further so that they are both in batches of 10 and unique across all video_ids. I thought about using a group by clause but I'm trying to keep the other columns intact as well (verb column).

Here is my presto query so far:

SELECT
    *
FROM (
    SELECT
        *,
        -- Give each unique video_id a unique rank
        DENSE_RANK() OVER (ORDER BY video_id) AS video_batch
    FROM videos
)

Body:
Calculate frame rank (partition by video_id), divide by 6 (integer division) to get batch number in video_id partition. Then rank again to get absolute batch number:

with sample_data as(
select 'video_a' as video_id, 'frame_1' as frame_id , 'walk' as verb union all
select 'video_a', 'frame_2' , 'run'   union all
select 'video_a', 'frame_3' , 'sit'   union all
select 'video_a', 'frame_4' , 'walk'  union all
select 'video_a', 'frame_5' , 'walk'  union all
select 'video_a', 'frame_6' , 'walk'  union all
select 'video_b', 'frame_7' , 'stand' union all
select 'video_b', 'frame_8' , 'stand' union all
select 'video_b', 'frame_9' , 'run'   union all
select 'video_b', 'frame_10', 'run'   union all
select 'video_b', 'frame_11', 'sit'   union all
select 'video_b', 'frame_12', 'run'   union all
select 'video_b', 'frame_13', 'run'
)

select s.*,
       dense_rank() over(order by video_id, rnk_frame / 6) batch_of_five
from
(
select video_id, frame_id, verb,
       CAST(regexp_extract(frame_id,'_(\d*)$',1) AS INT) frame_number,
       dense_rank() over(partition by video_id order by CAST(regexp_extract(frame_id,'_(\d*)$',1) AS INT)) rnk_frame
  from sample_data
)s
order by video_id, frame_number;

Result:

video_id    frame_id    verb    frame_number    rnk_frame   batch_of_five
video_a     frame_1     walk    1                1           1
video_a     frame_2     run     2                2           1
video_a     frame_3     sit     3                3           1
video_a     frame_4     walk    4                4           1
video_a     frame_5     walk    5                5           1
video_a     frame_6     walk    6                6           2
video_b     frame_7     stand   7                1           3
video_b     frame_8     stand   8                2           3
video_b     frame_9     run     9                3           3
video_b     frame_10    run     10               4           3
video_b     frame_11    sit     11               5           3
video_b     frame_12    run     12               6           4
video_b     frame_13    run     13               7           4

I extracted frame_number to sort as integer, not as string, to get the same sort order as in your question (some sorting column is absolutely necessary), if you already have rank as you mentioned in question, you can use it instead.


问:
Spring JPA DDL file generation - how to delete or clean file before generating
I am using this setup to generate a ddl file:

```<code>spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=./ddl/schema.sql
</code>```

The generation is executed via a specific test in Maven validation phase:

```<code>@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
@TestPropertySource(locations = "/ddl.properties")
public class GenerateDDL {

    @Autowired
    private EntityManager em;

    @Test
    public void generateDDL() throws IOException {
        em.close();
        em.getEntityManagerFactory().close();
    }

}
</code>```

This is working fine, with on problem: the generator does not create a new file but just appends always it's stuff.

Is there a way or setting to let generator always create a new file or clean up the old?

Deleting it within the test would delete it after generation. We also need the file to be published on git thus it is not generated within target.

UPDATE
There seems at least no solution within Hibernate (until Hibernate 6):
https://hibernate.atlassian.net/browse/HHH-11817

Is there a way to hook into Spring context creation - before persistence context is created? There i could delete the file.

答:
Short example using Gradle and Springboot.
Assuming you have a project property defining your environment, and "dev" is the one creating DDL files for Postgres.

Excerpt from application.yml:

```<code>spring:
  jpa:
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    database: POSTGRESQL
    properties:
      javax.persistence.schema-generation.database.action: drop-and-create
      javax.persistence.schema-generation.scripts.action: drop-and-create
      javax.persistence.schema-generation.scripts.create-target: ./sql/create-postgres.sql
      javax.persistence.schema-generation.scripts.create-source: metadata
      javax.persistence.schema-generation.scripts.drop-target: ./sql/drop-postgres.sql
      javax.persistence.schema-generation.scripts.drop-source: metadata
</code>```

Add some code in bootRun task to delete the files:

```<code>bootRun {
def defaultProfile = 'devtest'
def profile = project.hasProperty("env") ? project.getProperty("env") : defaultProfile
if (profile == 'dev') {delete 'sql/create-postgres.sql'; delete 'sql/drop-postgres.sql';}
</code>```

...}

Body:
I am using this setup to generate a ddl file:

spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=./ddl/schema.sql

The generation is executed via a specific test in Maven validation phase:

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
@TestPropertySource(locations = "/ddl.properties")
public class GenerateDDL {

    @Autowired
    private EntityManager em;

    @Test
    public void generateDDL() throws IOException {
        em.close();
        em.getEntityManagerFactory().close();
    }

}

This is working fine, with on problem: the generator does not create a new file but just appends always it's stuff.

Is there a way or setting to let generator always create a new file or clean up the old?

Deleting it within the test would delete it after generation. We also need the file to be published on git thus it is not generated within target.

UPDATE
There seems at least no solution within Hibernate (until Hibernate 6):
https://hibernate.atlassian.net/browse/HHH-11817

Is there a way to hook into Spring context creation - before persistence context is created? There i could delete the file.

Body:
Short example using Gradle and Springboot.
Assuming you have a project property defining your environment, and "dev" is the one creating DDL files for Postgres.

Excerpt from application.yml:

spring:
  jpa:
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    database: POSTGRESQL
    properties:
      javax.persistence.schema-generation.database.action: drop-and-create
      javax.persistence.schema-generation.scripts.action: drop-and-create
      javax.persistence.schema-generation.scripts.create-target: ./sql/create-postgres.sql
      javax.persistence.schema-generation.scripts.create-source: metadata
      javax.persistence.schema-generation.scripts.drop-target: ./sql/drop-postgres.sql
      javax.persistence.schema-generation.scripts.drop-source: metadata

Add some code in bootRun task to delete the files:

bootRun {
def defaultProfile = 'devtest'
def profile = project.hasProperty("env") ? project.getProperty("env") : defaultProfile
if (profile == 'dev') {delete 'sql/create-postgres.sql'; delete 'sql/drop-postgres.sql';}

...}


问:
How to get Firebase collection data as dictionary in Swift
I want to read data from Firebase and return the output as a Dict to my ViewController.
I did not manage to get the data returned in a valid way.

This is how I read the data:

```<code>  func getCollectionData()  -> Dictionary<String, String> {
        var returnValue: String = ""

        db.collection(user).getDocuments() { (querySnapshot, err) in

            if let err = err {
                print("Error getting documents: \(err)")
                returnValue = ""
            } else {
                for document in querySnapshot!.documents {

                    let returnValue = document.data() as? Dictionary<String, String>
                    print (returnValue)
                }
            }

        }
        return returnValue
    }

</code>```

Error:

```<code>Cannot convert return expression of type 'String' to return type 'Dictionary<String, String>'
</code>```

Why is returnValue String again?
I fiddled around a lot, but never found a solution, to return the data in a good way.

The output of print(returnValue) shows it's a dictionary

```<code>Optional(["url": "https://firebasestorage.googleapis.com:443/v0/b/.....9c5e73f", "email": "a@b.com"])
</code>```

In my ViewController I want to use the data to fill a tableView:

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = Array(myReturnedDict.values)[indexPath.row]
        return cell
    }
</code>```

EDIT:

I still get an empty Dictionary back as a returned value:

```<code>func getCollectionData()  -> Dictionary<String, String> {
        var returnValue = [String: String]()

        db.collection(user).getDocuments() { (querySnapshot, err) in

            if let err = err {
                print("Error getting documents: \(err)")
                returnValue = ["No":"data"]
            } else {
                for document in querySnapshot!.documents {
                    print (user)

                    returnValue = (document.data() as? Dictionary<String, String>)!

                    //print (returnValue)

                }
            }

        }
        return returnValue
}
</code>```

Can somebody help me?

答:
You created var returnValue: String = "" and use it default value "".
To avoid it you need to change returnValue to type Dictionary<String, String> and set returnValue not like

```<code>let returnValue = document.data() as? Dictionary<String, String>
</code>```

but

```<code>returnValue = document.data() as? Dictionary<String, String>
</code>```

Body:
I want to read data from Firebase and return the output as a Dict to my ViewController.
I did not manage to get the data returned in a valid way.

This is how I read the data:

  func getCollectionData()  -> Dictionary<String, String> {
        var returnValue: String = ""

        db.collection(user).getDocuments() { (querySnapshot, err) in

            if let err = err {
                print("Error getting documents: \(err)")
                returnValue = ""
            } else {
                for document in querySnapshot!.documents {

                    let returnValue = document.data() as? Dictionary<String, String>
                    print (returnValue)
                }
            }

        }
        return returnValue
    }

Error:

Cannot convert return expression of type 'String' to return type 'Dictionary<String, String>'

Why is returnValue String again?
I fiddled around a lot, but never found a solution, to return the data in a good way.

The output of print(returnValue) shows it's a dictionary

Optional(["url": "https://firebasestorage.googleapis.com:443/v0/b/.....9c5e73f", "email": "a@b.com"])

In my ViewController I want to use the data to fill a tableView:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = Array(myReturnedDict.values)[indexPath.row]
        return cell
    }

EDIT:

I still get an empty Dictionary back as a returned value:

func getCollectionData()  -> Dictionary<String, String> {
        var returnValue = [String: String]()

        db.collection(user).getDocuments() { (querySnapshot, err) in

            if let err = err {
                print("Error getting documents: \(err)")
                returnValue = ["No":"data"]
            } else {
                for document in querySnapshot!.documents {
                    print (user)

                    returnValue = (document.data() as? Dictionary<String, String>)!

                    //print (returnValue)

                }
            }

        }
        return returnValue
}

Can somebody help me?

Body:
You created var returnValue: String = "" and use it default value "".
To avoid it you need to change returnValue to type Dictionary<String, String> and set returnValue not like

let returnValue = document.data() as? Dictionary<String, String>

but

returnValue = document.data() as? Dictionary<String, String>


问:
How to correctly check if a result set is ActiveRecord::Associations::CollectionProxy
I want to check if my result set is of type ActiveRecord::Associations::CollectionProxy

for example my models are as follows

```<code>class Dashboard < ApplicationRecord
  has_and_belongs_to_many :organisations
end
</code>```
```<code>class Organisation < ApplicationRecord
  has_and_belongs_to_many :dashboards
end
</code>```

When i do organisation.dashboards i want to check if its ActiveRecord::Associations::CollectionProxy

but something like the below does not work.

```<code>expect(organisation.dashboards).to be(ActiveRecord::Associations::CollectionProxy)
</code>```

Any help in this would be really great, Thanks.

答:
You can use rspec Type matchers here

expect(obj).to be_kind_of(type): calls obj.kind_of?(type), which returns true if type is in obj's class hierarchy or is a module and is included in a class in obj's class hierarchy.

expect(organisation.dashboards).to be_kind_of(ActiveRecord::Associations::CollectionProxy)
```
<p>OR</p>
<pre class="lang-rb prettyprint-override"><code>expect(organisation.dashboards).to be_a_kind_of(ActiveRecord::Associations::CollectionProxy)
</code>```

OR

expect(organisation.dashboards).to be_a(ActiveRecord::Associations::CollectionProxy)
```

Body:
I want to check if my result set is of type ActiveRecord::Associations::CollectionProxy

for example my models are as follows

class Dashboard < ApplicationRecord
  has_and_belongs_to_many :organisations
end

class Organisation < ApplicationRecord
  has_and_belongs_to_many :dashboards
end

When i do organisation.dashboards i want to check if its ActiveRecord::Associations::CollectionProxy

but something like the below does not work.

expect(organisation.dashboards).to be(ActiveRecord::Associations::CollectionProxy)

Any help in this would be really great, Thanks.

Body:
You can use rspec Type matchers here

expect(obj).to be_kind_of(type): calls obj.kind_of?(type), which returns true if type is in obj's class hierarchy or is a module and is included in a class in obj's class hierarchy.

expect(organisation.dashboards).to be_kind_of(ActiveRecord::Associations::CollectionProxy)

OR

expect(organisation.dashboards).to be_a_kind_of(ActiveRecord::Associations::CollectionProxy)

OR

expect(organisation.dashboards).to be_a(ActiveRecord::Associations::CollectionProxy)


问:
Resizing wpf window programmatically in c#
I have a wpf window with two usercontrols inside of which the second is only shown when needed. I only set the MinWidth of the window in XAML, the MinHeight is provided through databinding an ist set depending on if the second usercontrol is shown. Now: How can I set the size of the window to different values than the MinWidth/Height during runtime. I tried setting the values before the Show(), after the Show(), in various events (Initialized, Loaded, etc.). I tried with and without UpdateLayout(), I tried setting the Height/Width through databinding. Nothing works! But when I debug the approaches I see that the Height/Width properties of the window are set to the expected values, but ActualHeight/Width stay. I thought it would be a bagatelle but it turned out it is not (to me). Thy for any help.</p>

答:
Have you tried to set

```<code>Application.Current.MainWindow.Height = 100;
</code>```

Short addition: I just did a short test, in code:

```<code>public partial class MainWindow : Window, INotifyPropertyChanged
{
    private int _height;
    public int CustomHeight
    {
        get { return _height; }
        set
        {
            if (value != _height)
            {
                _height = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("CustomHeight"));
            }
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        CustomHeight = 500;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        CustomHeight = 100;
    }
}
</code>```

and the XAML:

```<code><Window x:Class="WindowSizeTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="{Binding CustomHeight, Mode=TwoWay}" Width="525">
    <Grid>
        <Button Click="Button_Click">Test</Button>
    </Grid>
</Window>
</code>```

Click on the Button sets the window height. Is that what you´re looking for?

Body:
Have you tried to set

Application.Current.MainWindow.Height = 100;

Short addition: I just did a short test, in code:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private int _height;
    public int CustomHeight
    {
        get { return _height; }
        set
        {
            if (value != _height)
            {
                _height = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("CustomHeight"));
            }
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        CustomHeight = 500;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        CustomHeight = 100;
    }
}

and the XAML:

<Window x:Class="WindowSizeTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="{Binding CustomHeight, Mode=TwoWay}" Width="525">
    <Grid>
        <Button Click="Button_Click">Test</Button>
    </Grid>
</Window>

Click on the Button sets the window height. Is that what you´re looking for?


问:
Enemy Shoot Closest Object Within Shooting Range
I would like the Enemy(Monster) to shoot players in Shooting Range of the Enemy and return closest players within the Range
I'm quite new to Unity and currently using Unity 2017,2D at the moment, for now.
Thanks so much for your Help Guys!

public class Monster : MonoBehaviour {

```<code>[SerializeField]
GameObject Bullet;

public float fireRate;
float nextFire;

// Use this for initialization
void Start () {
    fireRate = 1f;
    nextFire = Time.time;
}

// Update is called once per frame
void Update () {
    CheckIfTimeToFire ();
}

void CheckIfTimeToFire()
{
    if (Time.time > nextFire)
    {
        Instantiate (Bullet, transform.position, Quaternion.identity);
        nextFire = Time.time + fireRate;
    }

}
</code>```

}

Here is the Bullet Script

public class Bullet : MonoBehaviour {

```<code>public float moveSpeed = 3f;

Rigidbody2D rb;

PlayerAI target;

Vector2 moveDirection;

// Use this for initialization
void Start () {
    rb = GetComponent<Rigidbody2D> ();
    target = GameObject.FindObjectOfType<PlayerAI>();
    moveDirection = (target.transform.position - transform.position).normalized * moveSpeed;
    rb.velocity = new Vector2 (moveDirection.x, moveDirection.y);
    Destroy (this.gameObject, 2);
}

void OnTriggerEnter2D (Collider2D col)
{
    if (col.gameObject.name.Equals ("Player"))
    {
        Debug.Log ("Hit!");
        Destroy (gameObject);
    }
}
</code>```

}

答:
Assuming you have a small number of players, a convenient method would be to hold a reference to players as a collection and iterate to get transform.position of each player. Then you can check the distance to the monster to get the minimum distance.

I also suggest doing the logical check on Monster rather than on Bullet, and pass target to Bullet. So that you can choose not to instantiate a bullet if no player is in range.

```<code>public class Monster : MonoBehaviour
{
    ...

    public float range;

    private PlayerAI[] players;

    ...

    private void Awake()
    {
        players = FindObjectsOfType<PlayerAI>();
    }

    ...

    private void CheckIfTimeToFire()
    {
        if (Time.time < nextFire)
        {
            return;
        }

        PlayerAI closestPlayer = null;
        float closestPlayerDistance = float.MaxValue;

        foreach (PlayerAI player in players)
        {
            float playerDistance = Vector3.Distance(transform.position, player.transform.position);

            if (playerDistance > range ||
                playerDistance > closestPlayerDistance)
            {
                // Skip to next player.
                continue;
            }

            closestPlayer = player;
            closestPlayerDistance = playerDistance;
        }

        if (closestPlayer == null)
        {
            // No player in range. Do nothing.
            return;
        }

        GameObject bullet = Instantiate (Bullet, transform.position, Quaternion.identity);
        bullet.GetComponent<Bullet>().Initialize(closestPlayer.transform);
        nextFire = Time.time + fireRate;
    }

    ...
}

public class Bullet : MonoBehaviour
{
    ...
    private Transform target;

    ...

    public void Initialize(Transform target)
    {
        this.target = target;
    }

    ...
}
</code>```

In the example, I get the players on Awake() of a Monster, but if you are instantiating them in runtime you can hold the PlayerAI collection in a separate manager class. In this case a list could be more useful.

```<code>public void PlayerManager : MonoBehaviour
{
    public List<PlayerAI> Players { get; private set; }

    ...

    private void Awake()
    {
        while (playerCount < totalPlayerCount)
        {
            SpawnPlayer();
        }
    }

    private void SpawnPlayer()
    {
        PlayerAI player = Instantiate(player, ...);
        Players.Add(player);
    }

    // Remove a dead player, etc.
    private void OnPlayerDied(PlayerAI player)
    {
        Players.Remove(player);
    }

    ...
}

public class Monster : MonoBehaviour
{
    ...

    private PlayerManager playerManager;

    ...

    private void Awake()
    {
        playerManager = FindObjectOfType<PlayerManager>();
    }

    void CheckIfTimeToFire()
    {
        ...

        foreach (PlayerAI player in playerManager.Players)
        {
            ...
        }
        ...
    }
}
</code>```

Body:
I would like the Enemy(Monster) to shoot players in Shooting Range of the Enemy and return closest players within the Range
I'm quite new to Unity and currently using Unity 2017,2D at the moment, for now.
Thanks so much for your Help Guys!

public class Monster : MonoBehaviour {

[SerializeField]
GameObject Bullet;

public float fireRate;
float nextFire;

// Use this for initialization
void Start () {
    fireRate = 1f;
    nextFire = Time.time;
}

// Update is called once per frame
void Update () {
    CheckIfTimeToFire ();
}

void CheckIfTimeToFire()
{
    if (Time.time > nextFire)
    {
        Instantiate (Bullet, transform.position, Quaternion.identity);
        nextFire = Time.time + fireRate;
    }

}

}

Here is the Bullet Script

public class Bullet : MonoBehaviour {

public float moveSpeed = 3f;

Rigidbody2D rb;

PlayerAI target;

Vector2 moveDirection;

// Use this for initialization
void Start () {
    rb = GetComponent<Rigidbody2D> ();
    target = GameObject.FindObjectOfType<PlayerAI>();
    moveDirection = (target.transform.position - transform.position).normalized * moveSpeed;
    rb.velocity = new Vector2 (moveDirection.x, moveDirection.y);
    Destroy (this.gameObject, 2);
}

void OnTriggerEnter2D (Collider2D col)
{
    if (col.gameObject.name.Equals ("Player"))
    {
        Debug.Log ("Hit!");
        Destroy (gameObject);
    }
}

}

Body:
Assuming you have a small number of players, a convenient method would be to hold a reference to players as a collection and iterate to get transform.position of each player. Then you can check the distance to the monster to get the minimum distance.

I also suggest doing the logical check on Monster rather than on Bullet, and pass target to Bullet. So that you can choose not to instantiate a bullet if no player is in range.

public class Monster : MonoBehaviour
{
    ...

    public float range;

    private PlayerAI[] players;

    ...

    private void Awake()
    {
        players = FindObjectsOfType<PlayerAI>();
    }

    ...

    private void CheckIfTimeToFire()
    {
        if (Time.time < nextFire)
        {
            return;
        }

        PlayerAI closestPlayer = null;
        float closestPlayerDistance = float.MaxValue;

        foreach (PlayerAI player in players)
        {
            float playerDistance = Vector3.Distance(transform.position, player.transform.position);

            if (playerDistance > range ||
                playerDistance > closestPlayerDistance)
            {
                // Skip to next player.
                continue;
            }

            closestPlayer = player;
            closestPlayerDistance = playerDistance;
        }

        if (closestPlayer == null)
        {
            // No player in range. Do nothing.
            return;
        }

        GameObject bullet = Instantiate (Bullet, transform.position, Quaternion.identity);
        bullet.GetComponent<Bullet>().Initialize(closestPlayer.transform);
        nextFire = Time.time + fireRate;
    }

    ...
}

public class Bullet : MonoBehaviour
{
    ...
    private Transform target;

    ...

    public void Initialize(Transform target)
    {
        this.target = target;
    }

    ...
}

In the example, I get the players on Awake() of a Monster, but if you are instantiating them in runtime you can hold the PlayerAI collection in a separate manager class. In this case a list could be more useful.

public void PlayerManager : MonoBehaviour
{
    public List<PlayerAI> Players { get; private set; }

    ...

    private void Awake()
    {
        while (playerCount < totalPlayerCount)
        {
            SpawnPlayer();
        }
    }

    private void SpawnPlayer()
    {
        PlayerAI player = Instantiate(player, ...);
        Players.Add(player);
    }

    // Remove a dead player, etc.
    private void OnPlayerDied(PlayerAI player)
    {
        Players.Remove(player);
    }

    ...
}

public class Monster : MonoBehaviour
{
    ...

    private PlayerManager playerManager;

    ...

    private void Awake()
    {
        playerManager = FindObjectOfType<PlayerManager>();
    }

    void CheckIfTimeToFire()
    {
        ...

        foreach (PlayerAI player in playerManager.Players)
        {
            ...
        }
        ...
    }
}


问:
how to change the columns in a dataframe into lists?
I have data formatted as a dataframe.

```<code>a1 <- c(1,2,3,4,5)
a2 <- c(2,4,6,7,8)
b1 <- c(2,5,8,1,2)
b2 <- c(3,1,2,5,6)
c  <- c("g","h","i","j","k")
abc <- cbind(a1,a2,b1,b2,c)
</code>```

I would like to change "abc" into two lists.

```<code>list <- list()
list[[1]] <- cbind(a1,a2,c)
list[[2]] <- cbind(b2,b2,c)
</code>```

thanks in advance!

Body:
I have data formatted as a dataframe.

a1 <- c(1,2,3,4,5)
a2 <- c(2,4,6,7,8)
b1 <- c(2,5,8,1,2)
b2 <- c(3,1,2,5,6)
c  <- c("g","h","i","j","k")
abc <- cbind(a1,a2,b1,b2,c)

I would like to change "abc" into two lists.

list <- list()
list[[1]] <- cbind(a1,a2,c)
list[[2]] <- cbind(b2,b2,c)

thanks in advance!

Body:
If I’m understanding:

a1 <- c(1,2,3,4,5)
a2 <- c(2,4,6,7,8)
b1 <- c(2,5,8,1,2)
b2 <- c(3,1,2,5,6)
c1 <- c("g","h","i","j","k")
abc <- data.frame(a1,a2,b1,b2,c1)

my_list <- list(
    as.list(abc[, c("a1", "a2", "c1")]),
    as.list(abc[, c("b1", "b2", "c1")])
)


问:
Read an image with the alpha channel and EXIF rotation
I'm using OpenCV to read a PNG image in Python. I need to read the image in RGBA and respect the possible EXIF flags, such as image rotation.

When I try to read the image via cv2.imread("path", cv2.IMREAD_UNCHANGED), the EXIF flags are ignored (as per the documentation).

When I try to read the image via cv2.imread("path", cv2.IMREAD_ANYCOLOR), alpha channel is erased.

Is there a way to have both? Should I use another lib (like PIL)?

答:
I ended up using PIL and rotating the image from the EXIF data manually. Here is a snippet that helps in dealing with the rotation:

import cv2

import numpy as np

from PIL import Image

_EXIF_ORIENTATION_FLAG_ID = 0x112

_EXIF_ORIENTATION_2_OPENCV_ROTATION = {

    3: cv2.ROTATE_180,

    6: cv2.ROTATE_90_CLOCKWISE,

    8: cv2.ROTATE_90_COUNTERCLOCKWISE

}

# ...

with Image.open(path) as pil_image:

    pixels = np.array(pil_image)

    exif = pil_image.getexif()

if exif is not None and _EXIF_ORIENTATION_FLAG_ID in exif:

    orientation = exif.get(_EXIF_ORIENTATION_FLAG_ID)

    if orientation is not None and orientation != 1:

        pixels = cv2.rotate(pixels, EXIF_ORIENTATION_2_OPENCV_ROTATION[orientation])

```


问:
How to Polyfill node core modules in webpack 5
webpack 5 no longer do auto-polyfilling for node core modules.
How to fix it please?

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

答:
With create-react-app v17 and scripts 5.0.0 you need to add a fallback to your webpack.config.js and install 'process'.</p>
```<code>   `module.exports = function (webpackEnv) {
      .........
      return {
       .........
      resolve: {
      ..........
      fallback: { "process": require.resolve("process/browser") },`
</code>```

Body:
With create-react-app v17 and scripts 5.0.0 you need to add a fallback to your webpack.config.js and install 'process'.

   `module.exports = function (webpackEnv) {
      .........
      return {
       .........
      resolve: {
      ..........
      fallback: { "process": require.resolve("process/browser") },`


问:
Including JSON files as part of Python package
I`m writing a package with a "local database" consisting of a folder and subfolders with json files. My database.py module imports these files with a relative path to them (DB_PATH). When installing the package, load fails since files are not found. Is there a way to import those files as part of the package, or a standard way to handle cases like this?

My python code database.py:

```<code>DB_PATH = "./db"

def getIndex():
    filename = f"{DB_PATH}/index.json"

    with open(filename) as f:
        data = json.load(f)

    return data
</code>```

File system:

```<code>package
 ┣folder
 ┃ ┗project
 ┃   ┣db
 ┃   ┃ ┣ index.json
 ┃   ┃ ┗config
 ┃   ┃   ┣ conf_1.json
 ┃   ┃   ┣ conf_2.json
 ┃   ┃   ┗ ...
 ┃   ┗ database.py
 ┗setup.py
</code>```

答:
If you use a setup.py, add this line:

```<code>import glob

setup(
    ...
    data_files=glob.glob('project/db/**')
)
</code>```

In your database.py

```<code>import os.path

DB_PATH = os.path.join(os.path.dirname(__file__), 'db')
</code>```

The variable __file__ contains the absolute path of the current python script database.py. Use dirname to get the parent folder and join to add database directory in the path.

Body:
I`m writing a package with a "local database" consisting of a folder and subfolders with json files. My database.py module imports these files with a relative path to them (DB_PATH). When installing the package, load fails since files are not found. Is there a way to import those files as part of the package, or a standard way to handle cases like this?

My python code database.py:

DB_PATH = "./db"

def getIndex():
    filename = f"{DB_PATH}/index.json"

    with open(filename) as f:
        data = json.load(f)

    return data

File system:

package
 ┣folder
 ┃ ┗project
 ┃   ┣db
 ┃   ┃ ┣ index.json
 ┃   ┃ ┗config
 ┃   ┃   ┣ conf_1.json
 ┃   ┃   ┣ conf_2.json
 ┃   ┃   ┗ ...
 ┃   ┗ database.py
 ┗setup.py

Body:
If you use a setup.py, add this line:

import glob

setup(
    ...
    data_files=glob.glob('project/db/**')
)

In your database.py

import os.path

DB_PATH = os.path.join(os.path.dirname(__file__), 'db')

The variable __file__ contains the absolute path of the current python script database.py. Use dirname to get the parent folder and join to add database directory in the path.


问:
Fix spacing between items in multi-carousel
I'm trying to use the react-multi-carousel library to construct a responsive carousel with fixed size items. I want to fix the spacing between the items as well. However, with react-multi-carousel, the space between items depends on the number of items to be displayed (specified in "responsive"). Is there a way to make the carousel responsive with the space between the elements being the input rather than number of elements? i.e I want to show fixed size elements with 32 px space between them on 1024 devices(16 px in smaller device) and don't care how many items are displayed.

```<code>import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";
const responsive = {
  superLargeDesktop: {
    // the naming can be any, depends on you.
    breakpoint: { max: 4000, min: 3000 },
    items: 5
  },
  desktop: {
    breakpoint: { max: 3000, min: 1024 },
    items: 3
  },
  tablet: {
    breakpoint: { max: 1024, min: 464 },
    items: 2
  },
  mobile: {
    breakpoint: { max: 464, min: 0 },
    items: 1
  }
};
<Carousel responsive={responsive}>
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
  <div>Item 4</div>
</Carousel>;
</code>```

The problem with this approach is the space between 2 items becomes very large and looks strange. I would rather fix the space and adjust the items based on that. One workaround I thought of doing was calculating the number of items based on the screen width whenever the window resizes. i.e

```<code>    breakpoint: { max: 4000, min: 3000 },
    items: window.innerWidth/WidthOfItemPlusMargin
</code>```

I have to listen to window resize events for this. Is there a better way?

答:
Create a class for your item

```<code>.carouselItem{
    padding-right: 40px
}
</code>```

Add 2 props to Carousel

Use itemClass to use your class

Add partialVisible={false} for the carousel to fix itself whenever your items are being cut from view

```<code><Carousel itemClass={styles.carouselItem} partialVisible={false}>
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
  <div>Item 4</div>
</Carousel>
</code>```

Body:
I'm trying to use the react-multi-carousel library to construct a responsive carousel with fixed size items. I want to fix the spacing between the items as well. However, with react-multi-carousel, the space between items depends on the number of items to be displayed (specified in "responsive"). Is there a way to make the carousel responsive with the space between the elements being the input rather than number of elements? i.e I want to show fixed size elements with 32 px space between them on 1024 devices(16 px in smaller device) and don't care how many items are displayed.

import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";
const responsive = {
  superLargeDesktop: {
    // the naming can be any, depends on you.
    breakpoint: { max: 4000, min: 3000 },
    items: 5
  },
  desktop: {
    breakpoint: { max: 3000, min: 1024 },
    items: 3
  },
  tablet: {
    breakpoint: { max: 1024, min: 464 },
    items: 2
  },
  mobile: {
    breakpoint: { max: 464, min: 0 },
    items: 1
  }
};
<Carousel responsive={responsive}>

Item 1

Item 2

Item 3

Item 4

</Carousel>;

The problem with this approach is the space between 2 items becomes very large and looks strange. I would rather fix the space and adjust the items based on that. One workaround I thought of doing was calculating the number of items based on the screen width whenever the window resizes. i.e

    breakpoint: { max: 4000, min: 3000 },
    items: window.innerWidth/WidthOfItemPlusMargin

I have to listen to window resize events for this. Is there a better way?

Body:
Create a class for your item

.carouselItem{
    padding-right: 40px
}

Add 2 props to Carousel

Use itemClass to use your class

Add partialVisible={false} for the carousel to fix itself whenever your items are being cut from view

<Carousel itemClass={styles.carouselItem} partialVisible={false}>
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
  <div>Item 4</div>
</Carousel>


问:
Display all line numbers for user names starting with "admin" from passwd file
How do I find all the occurance of a particular text in a file with a shell script. (Not using grep command)</p>

答: awk  '/^admin/ {print NR;}' /etc/passwd</p>

Body: awk  '/^admin/ {print NR;}' /etc/passwd


问:
How to return a tag from a method in react js?
I want to return a tag from a method so that once I call the method the tags are returned and these tags are used to call a component.

```<code>const Populate =() =>
{
  let tags = [];
  analysisinfo.forEach((_item,index) =>
  {
   if(analysisinfo[index].id!== defaultid)
    tags.push(<AU props={analysisinfo[index]} instance ={index}/>);
    console.log({tags});
   }
 return tags;
</code>```

let me explain in-detail the analysisinfo is an useState array which contains the below values. These values are being passed into this method.

```<code>0:
cpu: true
hdd: true
id: "00000000000000000000000000000000"
ram: true
</code>```

And pushes these values into tags[]. I want them pushed into array in the form of a <>, so that  when I return it calls the <AU..../> tag component which takes the above values as props.

答:
Use a combination of filter and map:

```<code>const Populate = () => (
    <>
        {
            analysisinfo
                .filter(i => i.id !== defaultid)
                .map((i, idx) => (
                    <AU props={i} instance={idx} />
                ))
         }
    </>
);
</code>```

Body:
I want to return a tag from a method so that once I call the method the tags are returned and these tags are used to call a component.

const Populate =() =>
{
  let tags = [];
  analysisinfo.forEach((_item,index) =>
  {
   if(analysisinfo[index].id!== defaultid)
    tags.push(<AU props={analysisinfo[index]} instance ={index}/>);
    console.log({tags});
   }
 return tags;

let me explain in-detail the analysisinfo is an useState array which contains the below values. These values are being passed into this method.

0:
cpu: true
hdd: true
id: "00000000000000000000000000000000"
ram: true

And pushes these values into tags[]. I want them pushed into array in the form of a <>, so that  when I return it calls the <AU..../> tag component which takes the above values as props.

Body:
Use a combination of filter and map:

const Populate = () => (
    <>
        {
            analysisinfo
                .filter(i => i.id !== defaultid)
                .map((i, idx) => (
                    <AU props={i} instance={idx} />
                ))
         }
    </>
);


问:
Serverless Framework - Value not found at "self" source
I have the following serverless.yml file:

```<code>org: bizrob
app: flexipod-2-queue
service: flexipod-2-queue

frameworkVersion: "^2.72.2"

custom:
  region: eu-west-1

provider:
  name: aws
  runtime: nodejs14.x

plugins:
  - serverless-prune-plugin
  - serverless-offline
  - serverless-webpack
  - serverless-plugin-resource-tagging
  - serverless-step-functions

functions:
  cronHandler:
    handler: flexipod-2-queue/flexipodJob.dataFeedsJob
    events:
      # Invoke Lambda function every 2nd minute from Mon-Fri
      - schedule: cron(0/8 * ? * MON *)
    environment:
      REGION: ${self:custom.region}
      API_VERSION_S3: "2006-03-01"
      API_VERSION_SQS: "2012-11-05"
      SQS_QUEUE_URL: !Ref "MyQueue"

resources:
  Resources:
    MyQueue:
      Type: "AWS::SQS::Queue"
      Properties:
        QueueName: "flexipod"
</code>```

When I run serverless deploy, I get the following error:

Cannot resolve variable at "functions.cronHandler.environment.REGION":
Value not found at "self" source

Anyone see what I've done wrong please?

答: Thanks to @eli6 for the tip about serverless print. I don't know the root cause of the problem but after restarting vscode serverless print and serverless deploy then worked</p>

Body:
I have the following serverless.yml file:

org: bizrob
app: flexipod-2-queue
service: flexipod-2-queue

frameworkVersion: "^2.72.2"

custom:
  region: eu-west-1

provider:
  name: aws
  runtime: nodejs14.x

plugins:
  - serverless-prune-plugin
  - serverless-offline
  - serverless-webpack
  - serverless-plugin-resource-tagging
  - serverless-step-functions

functions:
  cronHandler:
    handler: flexipod-2-queue/flexipodJob.dataFeedsJob
    events:
      # Invoke Lambda function every 2nd minute from Mon-Fri
      - schedule: cron(0/8 * ? * MON *)
    environment:
      REGION: ${self:custom.region}
      API_VERSION_S3: "2006-03-01"
      API_VERSION_SQS: "2012-11-05"
      SQS_QUEUE_URL: !Ref "MyQueue"

resources:
  Resources:
    MyQueue:
      Type: "AWS::SQS::Queue"
      Properties:
        QueueName: "flexipod"

When I run serverless deploy, I get the following error:

Cannot resolve variable at "functions.cronHandler.environment.REGION":
Value not found at "self" source

Anyone see what I've done wrong please?


问:
AttributeError: 'Word2Vec' object has no attribute 'wmdistance'
When I run my.py file containing the following code:
The following error is generated:
Traceback (most recent call last):
File "Checking.py", line 34, in
distance = model.wmdistance(sentance_a,sentance_b)
AttributeError: 'Word2Vec' object has no attribute 'wmdistance'</p>
```<code> from time import time
    from nltk.tokenize import sent_tokenize,word_tokenize
    from nltk.corpus import stopwords
    start_nb = time()

    data = 'The different Modi TV host in prime minister  chat Jim Corbett meet the'
    sentences = [sent_tokenize(x.lower()) for x in data]
    #sentences = [[w for w in sentence if w not in stopwords.words("english")] for x in sentence]

    sentance_a = 'Modi has a chat with Bear Grylls and Jim Corbett'
    sentance_b ='The prime minister meet the TV host in a National Park'
    sentance_a = sentance_a.lower().split()
    sentance_b = sentance_b.lower().split()

    from nltk.corpus import stopwords
    from nltk import download
    download('stopwords')

    stop_words = stopwords.words('english')
    sentance_a = [w for w in sentance_a if w not in stop_words]
    sentance_b = [w for w in sentance_b if w not in stop_words]

    start = time()
    import os
    from gensim import models as gsm

    from gensim.models import Word2Vec
    bigram = gsm.phrases.Phrases(sentences)
    bigram = gsm.phrases.Phraser(bigram)
    trigram = gsm.phrases.Phrases(bigram[sentences])
    trigram = gsm.phrases.Phraser(trigram)

    model = gsm.Word2Vec(trigram[bigram[sentences]], min_count=2, workers=3, sg=1)
    distance = model.wmdistance(sentance_a,sentance_b)
    print("It took: %.4f"%(time()-start))

    print(distance)
</code>```

答:
As Rivers pointed out, in recent Gensim versions you'll have to use KeyedVectors. They can be accessed by model.wv which adds then up to

```<code>distance = model.wv.wmdistance(sentance_a,sentance_b)
</code>```

Body:
When I run my.py file containing the following code:
The following error is generated:
Traceback (most recent call last):
File "Checking.py", line 34, in
distance = model.wmdistance(sentance_a,sentance_b)
AttributeError: 'Word2Vec' object has no attribute 'wmdistance'

 from time import time
    from nltk.tokenize import sent_tokenize,word_tokenize
    from nltk.corpus import stopwords
    start_nb = time()

    data = 'The different Modi TV host in prime minister  chat Jim Corbett meet the'
    sentences = [sent_tokenize(x.lower()) for x in data]
    #sentences = [[w for w in sentence if w not in stopwords.words("english")] for x in sentence]

    sentance_a = 'Modi has a chat with Bear Grylls and Jim Corbett'
    sentance_b ='The prime minister meet the TV host in a National Park'
    sentance_a = sentance_a.lower().split()
    sentance_b = sentance_b.lower().split()

    from nltk.corpus import stopwords
    from nltk import download
    download('stopwords')

    stop_words = stopwords.words('english')
    sentance_a = [w for w in sentance_a if w not in stop_words]
    sentance_b = [w for w in sentance_b if w not in stop_words]

    start = time()
    import os
    from gensim import models as gsm

    from gensim.models import Word2Vec
    bigram = gsm.phrases.Phrases(sentences)
    bigram = gsm.phrases.Phraser(bigram)
    trigram = gsm.phrases.Phrases(bigram[sentences])
    trigram = gsm.phrases.Phraser(trigram)

    model = gsm.Word2Vec(trigram[bigram[sentences]], min_count=2, workers=3, sg=1)
    distance = model.wmdistance(sentance_a,sentance_b)
    print("It took: %.4f"%(time()-start))

    print(distance)

Body:
As Rivers pointed out, in recent Gensim versions you'll have to use KeyedVectors. They can be accessed by model.wv which adds then up to

distance = model.wv.wmdistance(sentance_a,sentance_b)


问:
A minimal reproducible example to show asynchronous behavior using callbacks in Python
Background: To me it seems clear, that the conecpt of callbacks is flexible, but I also thought, it makes code much faster. However, the following example works, but it cannot show that time can be saved using a callback Ref1:

```<code>import time
from time import sleep

def callbackFunc(delay):
  time.sleep(delay)
  print("callback:     message 3 delay " + str(delay))

def saysomething(delay, callback):
  print("saysomething: message 2 delay " + str(delay))
  callback(delay) # hier muss ich schon wissen, dass nur "delay" benötigt wird...
  time.sleep(2)

if __name__ == '__main__':
  t0 = time.time()
  print("main:         message 1.")
  saysomething(2, callbackFunc)
  print("main:         message 4.")
  print("\ntime: ",time.time() - t0)
</code>```

Output

```<code>main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  4.01
</code>```

So how can I achive something like this

```<code>main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  2  !!!!!!!!!!!!!
</code>```

Perhaps it was even possible to switch the order of messages 3 & 4? Or do I get anything wrong?

Perhaps, these answers here and here and the following code from here which does not use callbacks but shows asynchronous behavior help?

答: This is irrelevant w.r.t. the SWIG callbacks used by the routing library.</p>

Body:
Background: To me it seems clear, that the conecpt of callbacks is flexible, but I also thought, it makes code much faster. However, the following example works, but it cannot show that time can be saved using a callback Ref1:

import time
from time import sleep

def callbackFunc(delay):
  time.sleep(delay)
  print("callback:     message 3 delay " + str(delay))

def saysomething(delay, callback):
  print("saysomething: message 2 delay " + str(delay))
  callback(delay) # hier muss ich schon wissen, dass nur "delay" benötigt wird...
  time.sleep(2)

if __name__ == '__main__':
  t0 = time.time()
  print("main:         message 1.")
  saysomething(2, callbackFunc)
  print("main:         message 4.")
  print("\ntime: ",time.time() - t0)

Output

main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  4.01

So how can I achive something like this

main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  2  !!!!!!!!!!!!!

Perhaps it was even possible to switch the order of messages 3 & 4? Or do I get anything wrong?

Perhaps, these answers here and here and the following code from here which does not use callbacks but shows asynchronous behavior help?


问:
XAML - Design view different to running view
I am having to move an HTA to Powershell/WPF and, for now, for good or ill, I need to leave the UI as it is. So...please leave aside any comment on aesthetics, use of page elements, etc. we'll deal with those in v2!

Using Visual Studio CE 2022 v17.0.5, at design-time, I get the 20-px margin I want at both the left-hand and right-hand ends of my TabGroup. However, at run-time, the right-hand end's margin has gone.

What am I missing?

Here's the XAML:

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="Application Deployment" Icon="/DeployApplication.ico" Height="780" Width="800">
    <Canvas Height="780" Width="800">
            <Grid Name="grdTop">
                    <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="20"/>
                            <ColumnDefinition Width="200"/>
                            <ColumnDefinition Width="20"/>
                            <ColumnDefinition Width="200"/>
                            <ColumnDefinition Width="20"/>
                            <ColumnDefinition Width="200"/>
                            <ColumnDefinition Width="120"/>
                            <ColumnDefinition Width="20"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                            <RowDefinition Height="5"/>
                            <RowDefinition Height="20"/>
                            <RowDefinition Height="5"/>
                            <RowDefinition Height="20"/>
                            <RowDefinition Height="5"/>
                            <RowDefinition Height="20"/>
                            <RowDefinition Height="5"/>
                    </Grid.RowDefinitions>
                    <CheckBox Name="chkWriteLog" Height="18" Width="158" Grid.Column="1" Grid.Row="1" Content="_Write to a log file" HorizontalAlignment="Left" VerticalAlignment="Top"/>
                    <CheckBox Name="chkSendLog" Height="18" Width="158" Grid.Column="1" Grid.Row="3" Content="_Send log via email" HorizontalAlignment="Left" VerticalAlignment="Top"/>
                    <CheckBox Name="chkUseEventLog" Height="18" Width="158" Grid.Column="1" Grid.Row="5" Content="Use E_vent log" HorizontalAlignment="Left" VerticalAlignment="Top"/>

                    <ListBox Name="lisEmailAddress" Height="23" Width="320" Grid.Column="5" Grid.Row="1" d:ItemsSource="{d:SampleData ItemCount=5}"/>
                    <TextBox Name="txtCustomEmailAddress" Height="23" Width="320" Grid.Column="5" Grid.Row="3" TextWrapping="Wrap" VerticalAlignment="Top"/>
            </Grid>
            <Grid Name="grdSeparator1" Canvas.Top="75">
                    <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="800"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                            <RowDefinition Height="5"/>
                            <RowDefinition Height="5"/>
                    </Grid.RowDefinitions>
                    <Rectangle Grid.Column="0" Grid.Row="1" Margin="20,0,20,0" Width="780" Fill="Black" Height="3"/>
            </Grid>
            <Grid Name="grdTabContainer" Canvas.Top="95">
                    <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="800"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                            <RowDefinition Height="605"/>
                            <RowDefinition Height="5"/>
                    </Grid.RowDefinitions>
                    <TabControl x:Name="tabMain" Height="600" Width="760" Grid.Column="0" Grid.Row="0" Margin="20,0,20,0" HorizontalAlignment="Left" VerticalAlignment="Top">
                            <TabItem Header="Application">
                            </TabItem>
                            <TabItem Header="Deployment type">
                            </TabItem>
                            <TabItem Header="Distribution">
                            </TabItem>
                    </TabControl>
            </Grid>
      </Canvas>
</Window>
```

Designtime

Runtime

答:
Depending on the OS and its styling the window will have a border with different size at runtime while at designtime there is no such border.

You can proove that with this window content:

<Window
  ...
  Width="800"
  Height="450"
  mc:Ignorable="d">
  <Grid>
    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">
      <Run Text="Width: " /><Run Text="{Binding ActualWidth, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" />
      <Run Text="Height: " /><Run Text="{Binding ActualHeight, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" />
    </TextBlock>
  </Grid>
</Window>
```
<ul>
<li>Designtime: <code>Width: 800 Height: 434.04</code></li>
<li>Runtime: <code>Width: 784 Height: 411</code></li>
</ul>
<p>If you want to fix that (without touching your layout style) change your XAML to</p>
<pre class="lang-xml prettyprint-override"><code><Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="Application Deployment"
    Icon="/DeployApplication.ico"

    SizeToContent="WidthAndHeight"> <!-- automatic resize of the window -->

  <!-- set the size here -->
  <Grid Width="800" Height="780">

    <!-- your canvas goes here -->

  </Grid>
</Window>
</code>```

Body:
I am having to move an HTA to Powershell/WPF and, for now, for good or ill, I need to leave the UI as it is. So...please leave aside any comment on aesthetics, use of page elements, etc. we'll deal with those in v2!

Using Visual Studio CE 2022 v17.0.5, at design-time, I get the 20-px margin I want at both the left-hand and right-hand ends of my TabGroup. However, at run-time, the right-hand end's margin has gone.

What am I missing?

Here's the XAML:

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="Application Deployment" Icon="/DeployApplication.ico" Height="780" Width="800">
    <Canvas Height="780" Width="800">
            <Grid Name="grdTop">
                    <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="20"/>
                            <ColumnDefinition Width="200"/>
                            <ColumnDefinition Width="20"/>
                            <ColumnDefinition Width="200"/>
                            <ColumnDefinition Width="20"/>
                            <ColumnDefinition Width="200"/>
                            <ColumnDefinition Width="120"/>
                            <ColumnDefinition Width="20"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                            <RowDefinition Height="5"/>
                            <RowDefinition Height="20"/>
                            <RowDefinition Height="5"/>
                            <RowDefinition Height="20"/>
                            <RowDefinition Height="5"/>
                            <RowDefinition Height="20"/>
                            <RowDefinition Height="5"/>
                    </Grid.RowDefinitions>
                    <CheckBox Name="chkWriteLog" Height="18" Width="158" Grid.Column="1" Grid.Row="1" Content="_Write to a log file" HorizontalAlignment="Left" VerticalAlignment="Top"/>
                    <CheckBox Name="chkSendLog" Height="18" Width="158" Grid.Column="1" Grid.Row="3" Content="_Send log via email" HorizontalAlignment="Left" VerticalAlignment="Top"/>
                    <CheckBox Name="chkUseEventLog" Height="18" Width="158" Grid.Column="1" Grid.Row="5" Content="Use E_vent log" HorizontalAlignment="Left" VerticalAlignment="Top"/>

                    <ListBox Name="lisEmailAddress" Height="23" Width="320" Grid.Column="5" Grid.Row="1" d:ItemsSource="{d:SampleData ItemCount=5}"/>
                    <TextBox Name="txtCustomEmailAddress" Height="23" Width="320" Grid.Column="5" Grid.Row="3" TextWrapping="Wrap" VerticalAlignment="Top"/>
            </Grid>
            <Grid Name="grdSeparator1" Canvas.Top="75">
                    <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="800"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                            <RowDefinition Height="5"/>
                            <RowDefinition Height="5"/>
                    </Grid.RowDefinitions>
                    <Rectangle Grid.Column="0" Grid.Row="1" Margin="20,0,20,0" Width="780" Fill="Black" Height="3"/>
            </Grid>
            <Grid Name="grdTabContainer" Canvas.Top="95">
                    <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="800"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                            <RowDefinition Height="605"/>
                            <RowDefinition Height="5"/>
                    </Grid.RowDefinitions>
                    <TabControl x:Name="tabMain" Height="600" Width="760" Grid.Column="0" Grid.Row="0" Margin="20,0,20,0" HorizontalAlignment="Left" VerticalAlignment="Top">
                            <TabItem Header="Application">
                            </TabItem>
                            <TabItem Header="Deployment type">
                            </TabItem>
                            <TabItem Header="Distribution">
                            </TabItem>
                    </TabControl>
            </Grid>
      </Canvas>
</Window>

Designtime

Runtime

Body:
Depending on the OS and its styling the window will have a border with different size at runtime while at designtime there is no such border.

You can proove that with this window content:

<Window
  ...
  Width="800"
  Height="450"
  mc:Ignorable="d">
  <Grid>
    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">
      <Run Text="Width: " /><Run Text="{Binding ActualWidth, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" />
      <Run Text="Height: " /><Run Text="{Binding ActualHeight, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" />
    </TextBlock>
  </Grid>
</Window>

Designtime: Width: 800 Height: 434.04

Runtime: Width: 784 Height: 411

If you want to fix that (without touching your layout style) change your XAML to

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="Application Deployment"
    Icon="/DeployApplication.ico"

    SizeToContent="WidthAndHeight"> <!-- automatic resize of the window -->

  <!-- set the size here -->
  <Grid Width="800" Height="780">

    <!-- your canvas goes here -->

  </Grid>
</Window>


问:
how to run one specific data from a data provider in phpunit
If I want to run a test with just one data from the data provider how would I do it?

I tried the solution on this thread and did not work
Cannot run single test with data provider in PHPUnit

答:
If data sets have names containing spaces, not only quoting will work, you can also use "\ " (at least in a shell like sh or bash)</p>
```<code>phpunit --filter ClassName::testCase@data\ set\ name
</code>```

Body:
If data sets have names containing spaces, not only quoting will work, you can also use "\ " (at least in a shell like sh or bash)

phpunit --filter ClassName::testCase@data\ set\ name


问:
You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)
below is what I need to do.

To run the specs, you'll need to install RSpec. First, run gem install bundler in the root directory of your project. Then, run bundle install. To run a single spec file, run a command like this: bundle exec rspec spec/00_hello_spec.rb. To run all of the specs at once, run bundle exec rspec.

So, I typed gem install bundler in Terminal, and got the error:

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory.

and this was in the project file in atom

```<code>source "https://rubygems.org"
gem "rspec", "~> 3.2.0"
</code>```

My question is:

It seems like terminal is giving me the response because I'm not supposed to change anything on ruby, and I need to bundle install inside of atom? Could anyone tell me how to use atom or run anything in atom?

答:
To fix this, I ran

brew reinstall ruby
```
<p>which showed me this message</p>
<blockquote>
```==> Caveats
==> ruby
By default, binaries installed by gem will be placed into:
  /opt/homebrew/lib/ruby/gems/3.1.0/bin

You may want to add this to your PATH.

ruby is keg-only, which means it was not symlinked into /opt/homebrew,
because macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have ruby first in your PATH, run:
  echo 'export PATH="/opt/homebrew/opt/ruby/bin:$PATH"' >> ~/.profile
```
</blockquote>
<p>So I added these two lines to my <code>~/.bashrc</code> file</p>
<pre class="lang-sh prettyprint-override"><code>export PATH="/opt/homebrew/opt/ruby/bin:$PATH"
export PATH="/opt/homebrew/lib/ruby/gems/3.1.0/bin:$PATH"
</code>```

Then I opened a new Terminal.app window and ran my gem install command again and it worked.

Body:
below is what I need to do.

To run the specs, you'll need to install RSpec. First, run gem install bundler in the root directory of your project. Then, run bundle install. To run a single spec file, run a command like this: bundle exec rspec spec/00_hello_spec.rb. To run all of the specs at once, run bundle exec rspec.

So, I typed gem install bundler in Terminal, and got the error:

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory.

and this was in the project file in atom

source "https://rubygems.org"
gem "rspec", "~> 3.2.0"

My question is:

It seems like terminal is giving me the response because I'm not supposed to change anything on ruby, and I need to bundle install inside of atom? Could anyone tell me how to use atom or run anything in atom?

Body:
To fix this, I ran

brew reinstall ruby

which showed me this message

==> Caveats
==> ruby
By default, binaries installed by gem will be placed into:
  /opt/homebrew/lib/ruby/gems/3.1.0/bin

You may want to add this to your PATH.

ruby is keg-only, which means it was not symlinked into /opt/homebrew,
because macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have ruby first in your PATH, run:
  echo 'export PATH="/opt/homebrew/opt/ruby/bin:$PATH"' >> ~/.profile

So I added these two lines to my ~/.bashrc file

export PATH="/opt/homebrew/opt/ruby/bin:$PATH"
export PATH="/opt/homebrew/lib/ruby/gems/3.1.0/bin:$PATH"

Then I opened a new Terminal.app window and ran my gem install command again and it worked.


问:
Laravel migrations run with no error but integer field is not created
I'm trying to migrate a migration file. Some integer fields triggered an error:

$table->integer('age',11)->default('0');

There were a few of those. After reading other posts, and trying a few things, I changed it to:

$table->integer('age',11)->default(0)->change();

This time, no error raised, but the created table miss and those fields!

Please find the whole file below:

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateReservationAnniversairesTable extends Migration
{
    public function up()
    {
        Schema::create('reservation_anniversaires', function (Blueprint $table) {

        $table->increments('id',11);
        $table->string('nom',50)->nullable()->default('NULL');
        $table->string('gsm',30)->nullable()->default('NULL');
        $table->string('prenom',50)->nullable()->default('NULL');
        $table->string('email',100);
        $table->integer('age',11)->default(0)->change();
        $table->time('heure_debut');
        $table->time('heure_fin');
        $table->string('gateau',100)->nullable()->default('NULL');
        $table->string('impression',100)->nullable()->default('NULL');
        $table->integer('nbre_enfants',11)->default(0)->change();
        $table->integer('acompte',11)->default(0)->change();
        $table->text('remarques');
        $table->tinyInteger('salle',4)->default(0)->change();
        $table->time('heure_gouter');
        $table->date('date');
        $table->string('formule',50)->nullable()->default('NULL');
        $table->integer('actif',11)->default(1)->change();
        $table->string('couleur',30)->nullable()->default('NULL');
        $table->integer('rappel',11)->default(0)->change();
        $table->integer('confirm',11)->default(0)->change();
        $table->integer('pizzas',11)->default(0)->change();
        $table->integer('sandwiches',11)->default(0)->change();
        $table->string('options')->nullable()->default('NULL');
        $table->integer('annif_confirme',11)->default(0)->change();
        $table->string('created',30);
        $table->string('modified',30);
        $table->tinyInteger('confirm_enfants',1)->default(0)->change();
        $table->tinyInteger('invitations',1)->default(0)->change();
        $table->string('adresse')->nullable()->default('NULL');
        $table->integer('invitsEnvoyees',11)->default(0)->change();
        $table->float('paiement')->default(0)->change();
        $table->string('paiement_methode',50)->nullable()->default('NULL');
        $table->integer('enfants_presents',11)->default(0)->change();
        $table->integer('parts_gateau',11)->default(0)->change();
        $table->float('options_montant')->default(0)->change();
        $table->string('deco_salle',50)->nullable()->default('NULL');
        $table->string('formule_theme',50)->nullable()->default('NULL');
        $table->string('photos',50)->nullable()->default('NULL');
        $table->string('grimage',50)->nullable()->default('NULL');
        $table->string('clown',50)->nullable()->default('NULL');
        $table->string('sculpture',50)->nullable()->default('NULL');

        });
    }

    public function down()
    {
        Schema::dropIfExists('reservation_anniversaires');
    }
}
</code>```

答:
You can't set length, but you can use different types of integer:

```<code>$table->bigInteger()
$table->mediumInteger()
$table->integer()
$table->smallInteger()
$table->tinyInteger()
</code>```

You can check documentation as well.

Body:
I'm trying to migrate a migration file. Some integer fields triggered an error:

$table->integer('age',11)->default('0');

There were a few of those. After reading other posts, and trying a few things, I changed it to:

$table->integer('age',11)->default(0)->change();

This time, no error raised, but the created table miss and those fields!

Please find the whole file below:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateReservationAnniversairesTable extends Migration
{
    public function up()
    {
        Schema::create('reservation_anniversaires', function (Blueprint $table) {

        $table->increments('id',11);
        $table->string('nom',50)->nullable()->default('NULL');
        $table->string('gsm',30)->nullable()->default('NULL');
        $table->string('prenom',50)->nullable()->default('NULL');
        $table->string('email',100);
        $table->integer('age',11)->default(0)->change();
        $table->time('heure_debut');
        $table->time('heure_fin');
        $table->string('gateau',100)->nullable()->default('NULL');
        $table->string('impression',100)->nullable()->default('NULL');
        $table->integer('nbre_enfants',11)->default(0)->change();
        $table->integer('acompte',11)->default(0)->change();
        $table->text('remarques');
        $table->tinyInteger('salle',4)->default(0)->change();
        $table->time('heure_gouter');
        $table->date('date');
        $table->string('formule',50)->nullable()->default('NULL');
        $table->integer('actif',11)->default(1)->change();
        $table->string('couleur',30)->nullable()->default('NULL');
        $table->integer('rappel',11)->default(0)->change();
        $table->integer('confirm',11)->default(0)->change();
        $table->integer('pizzas',11)->default(0)->change();
        $table->integer('sandwiches',11)->default(0)->change();
        $table->string('options')->nullable()->default('NULL');
        $table->integer('annif_confirme',11)->default(0)->change();
        $table->string('created',30);
        $table->string('modified',30);
        $table->tinyInteger('confirm_enfants',1)->default(0)->change();
        $table->tinyInteger('invitations',1)->default(0)->change();
        $table->string('adresse')->nullable()->default('NULL');
        $table->integer('invitsEnvoyees',11)->default(0)->change();
        $table->float('paiement')->default(0)->change();
        $table->string('paiement_methode',50)->nullable()->default('NULL');
        $table->integer('enfants_presents',11)->default(0)->change();
        $table->integer('parts_gateau',11)->default(0)->change();
        $table->float('options_montant')->default(0)->change();
        $table->string('deco_salle',50)->nullable()->default('NULL');
        $table->string('formule_theme',50)->nullable()->default('NULL');
        $table->string('photos',50)->nullable()->default('NULL');
        $table->string('grimage',50)->nullable()->default('NULL');
        $table->string('clown',50)->nullable()->default('NULL');
        $table->string('sculpture',50)->nullable()->default('NULL');

        });
    }

    public function down()
    {
        Schema::dropIfExists('reservation_anniversaires');
    }
}

Body:
You can't set length, but you can use different types of integer:

$table->bigInteger()
$table->mediumInteger()
$table->integer()
$table->smallInteger()
$table->tinyInteger()

You can check documentation as well.


问:
NextJS: Reload iFrame from another component
I have a NextJS application, with the following page:

Page:

```<code>import Layout from "@/components/app/Layout";
import Sidebar from "@/components/app/Sidebar";

export default function SiteIndex() {
  return (
    <Layout>
      <div className="flex">
        <Sidebar />
        <div className="m-5">
            <iframe src="/page.htm"></iframe>
        </div>
      </div>

    </Layout>
  );
}
</code>```

This page has an iframe, a parent Layout component, and one more component called Sidebar.

Parent Layout:

```<code>export default function Layout({ children }) {
    return (
        <div>
            <div class="h-12 bg-gray-200 flex">
                <div className="m-2 grow">Parent Layout</div>
                <button className="bg-blue-500 text-white p-3">Reload iFrame Button</button>
            </div>
            <div>{children}</div>
        </div>
    )
}
</code>```

Sidebar:

```<code>export default function Sidebar() {

    return (
        <div className="w-64 border border-r-100 m-5">
            <div>Sidebar</div>

            <button className="bg-blue-500 text-white p-3">Reload iFrame Button</button>
        </div>
    )
}
</code>```

Both Layout and Sidebar have a button. I want to be able to reload the iframe on the press of any of those buttons. How can I achieve this in react/nextjs project? primarily I'm looking for the best way to reload an iFrame within reactjs.

答:
Would it work for your application to add a key={keyValue} to the iframe? You can then set the value of that key whenever the button gets pressed. This should cause a re-render.

```<code>export default function SiteIndex() {
const [keyValue, setKeyValue] = useState(0);

  return (
    <Layout onButtonClick={() => setKeyValue(keyValue + 1)} >
      <div className="flex">
        <Sidebar onButtonClick={() => setKeyValue(keyValue + 1)}  />
        <div className="m-5">
            <iframe src="/page.htm" key={keyValue}></iframe>
        </div>
      </div>
    </Layout>
  );
}
</code>```

And in your component

Body:
I have a NextJS application, with the following page:

Page:

import Layout from "@/components/app/Layout";
import Sidebar from "@/components/app/Sidebar";

export default function SiteIndex() {
  return (
    <Layout>

        <Sidebar />

    </Layout>
  );
}

This page has an iframe, a parent Layout component, and one more component called Sidebar.

Parent Layout:

export default function Layout({ children }) {
    return (

Parent Layout

                <button className="bg-blue-500 text-white p-3">Reload iFrame Button</button>

{children}

    )
}

Sidebar:

export default function Sidebar() {

    return (

Sidebar

            <button className="bg-blue-500 text-white p-3">Reload iFrame Button</button>

    )
}

Both Layout and Sidebar have a button. I want to be able to reload the iframe on the press of any of those buttons. How can I achieve this in react/nextjs project? primarily I'm looking for the best way to reload an iFrame within reactjs.

Body:
Would it work for your application to add a key={keyValue} to the iframe? You can then set the value of that key whenever the button gets pressed. This should cause a re-render.

export default function SiteIndex() {
const [keyValue, setKeyValue] = useState(0);

  return (
    <Layout onButtonClick={() => setKeyValue(keyValue + 1)} >
      <div className="flex">
        <Sidebar onButtonClick={() => setKeyValue(keyValue + 1)}  />
        <div className="m-5">
            <iframe src="/page.htm" key={keyValue}></iframe>
        </div>
      </div>
    </Layout>
  );
}

And in your component


答:
I believe you want to set the length of the age column integer type.

Unfortunately, the second parameter is not for setting the column length. You can set the column length for char and string types only, but not for integer.

Illuminate\Database\Schema\Blueprint :

```<code>integer($column, $autoIncrement = false, $unsigned = false)
</code>```

Automatically, migration will create the integer type with length 11. So you don't have to bother.

```<code>$table->integer('age')->default(0);
</code>```

There were a few of those. After reading other posts, and trying a few things, I changed it to:

```<code>$table->integer('age',11)->default(0)->change();
</code>```

The change method is only used to update the column, not to create the column. You won't see the error, because migration ignore it.

To update the table, you must have a schema like this:

```<code>Schema::table('reservation_anniversaires', function (Blueprint $table) {
    ...
});

// Schema::create for creating
</code>```

Title: Laravel migrations run with no error but integer field is not created

Body:
I believe you want to set the length of the age column integer type.

Unfortunately, the second parameter is not for setting the column length. You can set the column length for char and string types only, but not for integer.

Illuminate\Database\Schema\Blueprint :

integer($column, $autoIncrement = false, $unsigned = false)

Automatically, migration will create the integer type with length 11. So you don't have to bother.

$table->integer('age')->default(0);

There were a few of those. After reading other posts, and trying a few things, I changed it to:

$table->integer('age',11)->default(0)->change();

The change method is only used to update the column, not to create the column. You won't see the error, because migration ignore it.

To update the table, you must have a schema like this:

Schema::table('reservation_anniversaires', function (Blueprint $table) {
    ...
});

// Schema::create for creating