问:
android onCheckedChanged for radiogroup
I'm writing an Activity in android where I have two radio buttons under a RadioGroup. One of them is checked by default. But I can't trigger the event in onCreate method so that I can do something in that. The onCheckedChanged is running fine when clicked on.

```<code>RadioGroup ItemtypeGroup = (RadioGroup) findViewById(R.id.rechargeItemtype);
    RadioButton providerRadio = (RadioButton) findViewById(R.id.a);
    providerRadio.performClick();

    ItemtypeGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged (RadioGroup group,int checkedId){

            Log.d("chk", "id" + checkedId);

            if (checkedId == R.id.a) {
                //some code
            } else if (checkedId == R.id.b) {
                //some code
            }
        }
    });
</code>```

答:
Even though @dannys answer is ok I would like to have the default value taken from the XML layout definition file rather then setting it in code.

That's why I use this approach to:

store the default value form the radio group

clear all check's

initialize the OnCheckedChangeListener

check the default again (which was stored previously) which triggers the listener

This could look like this in code with the first_radio_button as the default radio button:

```<code>// call this in any init method
_myRadioGroup    = _myViewContainingTheRadioGroup.findViewById(R.id.my_radio_group);
int defaultValue = _myRadioGroup.getCheckedRadioButtonId();
_myRadioGroup.clearCheck();
_myRadioGroup.setOnCheckedChangeListener(_myRadioGroupCheckedChangeListener);
_myRadioGroup.check(defaultValue);
</code>```

Place the OnCheckedChangeListener somewhere in your class:

```<code>private RadioGroup.OnCheckedChangeListener _myRadioGroupCheckedChangeListener = new RadioGroup.OnCheckedChangeListener()
{
  @Override
  public void onCheckedChanged(RadioGroup group, int checkedId)
  {
    switch(group.findViewById(checkedId).getId())
    {
      case R.id.first_radio_button:
        // do stuff
        break;
      case R.id.second_radio_button:
        // do stuff
        break;
      // ...
    }
  }
};
</code>```

This is my radio group xml

```<code>  <RadioGroup
    android:id="@+id/my_radio_group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RadioButton
      android:id="@+id/first_radio_button"
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:checked="true"
      android:text="@string/first_radio_button_text"/>

    <RadioButton
      android:id="@+id/second_radio_button"
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:text="@string/second_radio_button_text"/>

    // ...

  </RadioGroup>
</code>```

Title: android onCheckedChanged for radiogroup

Body:
I'm writing an Activity in android where I have two radio buttons under a RadioGroup. One of them is checked by default. But I can't trigger the event in onCreate method so that I can do something in that. The onCheckedChanged is running fine when clicked on.

RadioGroup ItemtypeGroup = (RadioGroup) findViewById(R.id.rechargeItemtype);
    RadioButton providerRadio = (RadioButton) findViewById(R.id.a);
    providerRadio.performClick();

    ItemtypeGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged (RadioGroup group,int checkedId){

            Log.d("chk", "id" + checkedId);

            if (checkedId == R.id.a) {
                //some code
            } else if (checkedId == R.id.b) {
                //some code
            }
        }
    });

Body:
Even though @dannys answer is ok I would like to have the default value taken from the XML layout definition file rather then setting it in code.

That's why I use this approach to:

store the default value form the radio group

clear all check's

initialize the OnCheckedChangeListener

check the default again (which was stored previously) which triggers the listener

This could look like this in code with the first_radio_button as the default radio button:

// call this in any init method
_myRadioGroup    = _myViewContainingTheRadioGroup.findViewById(R.id.my_radio_group);
int defaultValue = _myRadioGroup.getCheckedRadioButtonId();
_myRadioGroup.clearCheck();
_myRadioGroup.setOnCheckedChangeListener(_myRadioGroupCheckedChangeListener);
_myRadioGroup.check(defaultValue);

Place the OnCheckedChangeListener somewhere in your class:

private RadioGroup.OnCheckedChangeListener _myRadioGroupCheckedChangeListener = new RadioGroup.OnCheckedChangeListener()
{
  @Override
  public void onCheckedChanged(RadioGroup group, int checkedId)
  {
    switch(group.findViewById(checkedId).getId())
    {
      case R.id.first_radio_button:
        // do stuff
        break;
      case R.id.second_radio_button:
        // do stuff
        break;
      // ...
    }
  }
};

This is my radio group xml

  <RadioGroup
    android:id="@+id/my_radio_group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RadioButton
      android:id="@+id/first_radio_button"
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:checked="true"
      android:text="@string/first_radio_button_text"/>

    <RadioButton
      android:id="@+id/second_radio_button"
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:text="@string/second_radio_button_text"/>

    // ...

  </RadioGroup>


来源: stackexchange

问:
SAS proc sql - is this the correct usage?
This works but wanted a health check as to if i have done this correct with proc sql connect to i.e do i need to have separate "select * from connection to's"?

```<code>proc sql;
connect to database (database=test user="&srvuser" password="&srvpass") ;
create table bob as
select t1._ as bob1
      ,t2._ as bob2
      ,t3._ as bob3
      ,t1._-t2._ as bob4
from (select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1)) t1
,(select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'R')) t2
,(select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL)) t3;
disconnect from database;
quit;
run;
</code>```

Thanks

答:
Since you are pulling from the same database just push the join into the database. While you are at it assign names to the variables when you create them.

```<code>create table bob as
select bob1
     , bob2
     , bob3
     , bob1-bob2 as bob4
from connection to database
(select t1.bob1
      , t2.bob2
      , t3.bob3
 from
  (select count(*) as bob1
   from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1
  ) t1
, (select count(*) as bob2
   from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'R'
   ) t2
, (select count(*) as bob3
   from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL
  ) t3
);
</code>```

Since you are generating those counts from querying the same table (dataset) you can to it with a single query by using CASE instead of WHERE.

```<code>(select sum(case when (RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1) then 1
            else 0 end) as bob1
      , sum(case when (RR_MSG_CODE  = 'R') then 1
            else 0 end) as bob2
      , sum(case when (RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL) then 1
            else 0 end) as bob3
 from DAVE.IMAGE_MSG_LOG
)
</code>```

Although you might want to add the common conditions to the where clause to have it process fewer records.

```<code>where RR_MSG_CODE in ('R','D')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This works but wanted a health check as to if i have done this correct with proc sql connect to i.e do i need to have separate "select * from connection to's"?

proc sql;
connect to database (database=test user="&srvuser" password="&srvpass") ;
create table bob as
select t1._ as bob1
      ,t2._ as bob2
      ,t3._ as bob3
      ,t1._-t2._ as bob4
from (select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1)) t1
,(select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'R')) t2
,(select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL)) t3;
disconnect from database;
quit;
run;

Thanks

Body:
Since you are pulling from the same database just push the join into the database. While you are at it assign names to the variables when you create them.

create table bob as
select bob1
     , bob2
     , bob3
     , bob1-bob2 as bob4
from connection to database
(select t1.bob1
      , t2.bob2
      , t3.bob3
 from
  (select count(*) as bob1
   from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1
  ) t1
, (select count(*) as bob2
   from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'R'
   ) t2
, (select count(*) as bob3
   from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL
  ) t3
);

Since you are generating those counts from querying the same table (dataset) you can to it with a single query by using CASE instead of WHERE.

(select sum(case when (RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1) then 1
            else 0 end) as bob1
      , sum(case when (RR_MSG_CODE  = 'R') then 1
            else 0 end) as bob2
      , sum(case when (RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL) then 1
            else 0 end) as bob3
 from DAVE.IMAGE_MSG_LOG
)

Although you might want to add the common conditions to the where clause to have it process fewer records.

where RR_MSG_CODE in ('R','D')


问:
How to correctly take a Date object passed with state in React into datepicker?
I'm using DatePicker with my react app. I pass an object which contains a date field from one component to another via location.state. This is an editing component, where I can change the values of these fields. But the console swears with invalid time exception. I read I should do something with parseISO but still it does nothing. How to properly use it? (settings is a this.state field)</p>

```<code>...
import DatePicker from 'react-datepicker'
import 'react-datepicker/dist/react-datepicker.css'
import { parseISO, format } from 'date-fns'
...

            <DatePicker
              name="saleDateFrom"
              selected={parseISO(settings.saleDateFrom)}
              onChange={this.handleChangeFrom}
              dateFormat="MMMM dd, yyyy hh:mm:ss aa"
            />
</code>```

答:
You can use Date.parse(settings.saleDateFrom) to get the time since epoch.

If you need it as a data object.

new Date(Date.parse(settings.saleDateFrom))

Body:
I'm using DatePicker with my react app. I pass an object which contains a date field from one component to another via location.state. This is an editing component, where I can change the values of these fields. But the console swears with invalid time exception. I read I should do something with parseISO but still it does nothing. How to properly use it? (settings is a this.state field)

...
import DatePicker from 'react-datepicker'
import 'react-datepicker/dist/react-datepicker.css'
import { parseISO, format } from 'date-fns'
...

            <DatePicker
              name="saleDateFrom"
              selected={parseISO(settings.saleDateFrom)}
              onChange={this.handleChangeFrom}
              dateFormat="MMMM dd, yyyy hh:mm:ss aa"
            />


问:
How to use sort V horizontally?
I have this table:

```<code>flame#43    king#402    Picnic#51   Sar#360     far#66
flame#61    king#63     Picknic#67  Sar#66      far#65
flame#63    king#60     Packnic#69  Sar#64      far#58
</code>```

My desired output is:

```<code>flame#43  Picnick#51 far#66     Sar#360  king#402

flame#61  king#63    far#65     Sar#66   Picknic#67

far#58    king#60    flame#63   Sar#64   Packnic#69
</code>```

Does anyone know how to sort horizontally based on value when we have a text also?

I tried to used sort -V in variable combinations \with combination with  sort kn  .Also I tried to modified this code

```<code>awk ' {split( $0, a, " " ); asort( a );
for( i = 1; i <= length(a); i++ ) printf( "%s ", a[i] );
printf( "\n" ); }'
</code>```

which sorts tables only when we have a numeric value table horizontally.

答:
You can use asort with your own comparison function

```<code>awk 'function trailing_number_compare(i1, v1, i2, v2,    _a, _l, _r, _n)
{
    _n = split(v1, _a, "#");
    _l = 0 + _a[2];

    _n = split(v2, _a, "#");
    _r = 0 + _a[2];

    if (_l < _r)
        return -1
    else if (_l == _r)
        return 0
    else
        return 1
}

{
    split($0, a, FS);
    n = asort(a, b, "trailing_number_compare");
    for(i = 1; i <= n; i++)
    {
        printf("%s ", b[i]);
    }
    printf("\n");
}' "$@"
</code>```

The input from the question

flame#43    king#402    Picnic#51   Sar#360     far#66
flame#61    king#63     Picknic#67  Sar#66      far#65
flame#63    king#60     Packnic#69  Sar#64      far#58
```

<p>results in this output</p>

<pre class="lang-none prettyprint-override"><code>flame#43 Picnic#51 far#66 Sar#360 king#402
flame#61 king#63 far#65 Sar#66 Picknic#67
far#58 king#60 flame#63 Sar#64 Packnic#69
</code>```

The function trailing_number_compare is based on the example in https://www.gnu.org/software/gawk/manual/html_node/Array-Sorting-Functions.html

The function arguments starting with _ are used as local variables.

Explanation:

function trailing_number_compare(i1, v1, i2, v2,    _a, _l, _r, _n) { ...}

Define a function to be passed to asort for user-defined comparison of two items. It will get arguments index 1 i1, value 1 v1, index 2 i2 and value 2 v2. The other arguments will not be set by the caller and are used as local variables in the function.

_n = split(v1, _a, "#");

split v1 into array _a at delimiter "#", _n will be the number of fields and could be used for checking or iterating over the array.

_l = 0 + _a[2];

assign 2nd field to _l. Adding 0 forces numeric context.

Similar for v2 and _r...

Finally do the comparison of _l and _r, the return value is used by asort

The action to be executed with all input lines is very similar to the original code, except that I use FS (field separator) to split the input and call asortwith input and output array and the user defined comparison function.

Title: How to use sort V horizontally?

Body:
I have this table:

flame#43    king#402    Picnic#51   Sar#360     far#66
flame#61    king#63     Picknic#67  Sar#66      far#65
flame#63    king#60     Packnic#69  Sar#64      far#58

My desired output is:

flame#43  Picnick#51 far#66     Sar#360  king#402

flame#61  king#63    far#65     Sar#66   Picknic#67

far#58    king#60    flame#63   Sar#64   Packnic#69

Does anyone know how to sort horizontally based on value when we have a text also?

I tried to used sort -V in variable combinations \with combination with  sort kn  .Also I tried to modified this code

awk ' {split( $0, a, " " ); asort( a );
for( i = 1; i <= length(a); i++ ) printf( "%s ", a[i] );
printf( "\n" ); }'

which sorts tables only when we have a numeric value table horizontally.

Body:
You can use asort with your own comparison function

awk 'function trailing_number_compare(i1, v1, i2, v2,    _a, _l, _r, _n)
{
    _n = split(v1, _a, "#");
    _l = 0 + _a[2];

    _n = split(v2, _a, "#");
    _r = 0 + _a[2];

    if (_l < _r)
        return -1
    else if (_l == _r)
        return 0
    else
        return 1
}

{
    split($0, a, FS);
    n = asort(a, b, "trailing_number_compare");
    for(i = 1; i <= n; i++)
    {
        printf("%s ", b[i]);
    }
    printf("\n");
}' "$@"

The input from the question

flame#43    king#402    Picnic#51   Sar#360     far#66
flame#61    king#63     Picknic#67  Sar#66      far#65
flame#63    king#60     Packnic#69  Sar#64      far#58

results in this output

flame#43 Picnic#51 far#66 Sar#360 king#402
flame#61 king#63 far#65 Sar#66 Picknic#67
far#58 king#60 flame#63 Sar#64 Packnic#69

The function trailing_number_compare is based on the example in https://www.gnu.org/software/gawk/manual/html_node/Array-Sorting-Functions.html

The function arguments starting with _ are used as local variables.

Explanation:

function trailing_number_compare(i1, v1, i2, v2,    _a, _l, _r, _n) { ...}

Define a function to be passed to asort for user-defined comparison of two items. It will get arguments index 1 i1, value 1 v1, index 2 i2 and value 2 v2. The other arguments will not be set by the caller and are used as local variables in the function.

_n = split(v1, _a, "#");

split v1 into array _a at delimiter "#", _n will be the number of fields and could be used for checking or iterating over the array.

_l = 0 + _a[2];

assign 2nd field to _l. Adding 0 forces numeric context.

Similar for v2 and _r...

Finally do the comparison of _l and _r, the return value is used by asort

The action to be executed with all input lines is very similar to the original code, except that I use FS (field separator) to split the input and call asortwith input and output array and the user defined comparison function.


问:
Get latest record when grouped by two columns SQL Server
I have a table that tracks version history.I want to get only the latest version along with the date for each id in the table.
The below will give me the latest date for each id,version combination.How can I select only the top record? I can store this in a temp table and then use join to get only the top record for each id,version combination.Is there a better way to accomplish this in a single step?

Sample data

```<code>id  version     timestamp
123 1.5         2015-03-28 08:21:04.563
123 1.0         2015-03-21 12:58:24.730
234 1.5         2016-10-15 23:08:09.550
345 1.5         2016-05-10 15:18:09.707
345 1.5         2016-09-02 21:30:00.657
</code>```

Expected output

```<code>id  version     timestamp
123 1.5         2015-03-28 08:21:04.563
234 1.5         2016-10-15 23:08:09.550
345 1.5         2016-09-02 21:30:00.657
</code>```

Query

```<code>select  id,version,max(dt_create)
from version_history (nolock)
group by id,version
order by id
</code>```

I have tried this but I get the same result as above

```<code>select * from
(
    select  id,version,dt_create,row_number() over (partition by id,version order by dt_create desc) as a
    from version_history (nolock)
) b
where a=1
order by id
</code>```

答:
All the above answers do not really select the latest on 2 columns. Just 1 column maxed timestamp.

If a previous version can have a later build date (eg a security bugfix) as a higher version then the setup could be like this:

```<code>DECLARE @table TABLE (ID INT, [Version] DECIMAL(18, 2), [TimeStamp] DATETIME)

INSERT INTO @table
VALUES
 (123,1.5,'2015-03-28 08:21:04.563')
,(123,1.0,'2015-03-21 12:58:24.730')
,(123,1.0,'2016-03-21 12:58:24.730') --new
,(234,1.5,'2016-10-15 23:08:09.550')
,(345,1.5,'2016-05-10 15:18:09.707')
,(345,1.5,'2016-09-02 21:30:00.657')
</code>```

The earlier answers would then result in 4 records now including the ID 123 with 1.0 version with 2016 date.
If thats not the intention then this would be the solution:

```<code>SELECT T.ID,
       MAX(T.[TimeStamp]) AS [MaxTimeStamp],
       T3.[Version] AS [MaxVersion]
FROM @table T
JOIN (
        SELECT T4.ID,
           MAX(T4.[Version]) AS [MaxVersion]
        FROM @table T4
        GROUP BY T4.ID
    ) as T2 ON T.id = T2.id
JOIN @table T3
    ON T.ID = T3.ID
    --AND T2.ID = T3.ID --works fine somehow with or without thise line
    AND T.[TimeStamp] = T3.[TimeStamp]
    AND T3.[Version] = T2.[MaxVersion]
GROUP BY T.ID, T3.[Version]
</code>```

I needed an extra join for this, but I'm wondering whether it could be without an extra join.

ContentLicense: CC BY-SA 3.0

Body:
I have a table that tracks version history.I want to get only the latest version along with the date for each id in the table.
The below will give me the latest date for each id,version combination.How can I select only the top record? I can store this in a temp table and then use join to get only the top record for each id,version combination.Is there a better way to accomplish this in a single step?

Sample data

id  version     timestamp
123 1.5         2015-03-28 08:21:04.563
123 1.0         2015-03-21 12:58:24.730
234 1.5         2016-10-15 23:08:09.550
345 1.5         2016-05-10 15:18:09.707
345 1.5         2016-09-02 21:30:00.657

Expected output

id  version     timestamp
123 1.5         2015-03-28 08:21:04.563
234 1.5         2016-10-15 23:08:09.550
345 1.5         2016-09-02 21:30:00.657

Query

select  id,version,max(dt_create)
from version_history (nolock)
group by id,version
order by id

I have tried this but I get the same result as above

select * from
(
    select  id,version,dt_create,row_number() over (partition by id,version order by dt_create desc) as a
    from version_history (nolock)
) b
where a=1
order by id

Body:
All the above answers do not really select the latest on 2 columns. Just 1 column maxed timestamp.

If a previous version can have a later build date (eg a security bugfix) as a higher version then the setup could be like this:

DECLARE @table TABLE (ID INT, [Version] DECIMAL(18, 2), [TimeStamp] DATETIME)

INSERT INTO @table
VALUES
 (123,1.5,'2015-03-28 08:21:04.563')
,(123,1.0,'2015-03-21 12:58:24.730')
,(123,1.0,'2016-03-21 12:58:24.730') --new
,(234,1.5,'2016-10-15 23:08:09.550')
,(345,1.5,'2016-05-10 15:18:09.707')
,(345,1.5,'2016-09-02 21:30:00.657')

The earlier answers would then result in 4 records now including the ID 123 with 1.0 version with 2016 date.
If thats not the intention then this would be the solution:

SELECT T.ID,
       MAX(T.[TimeStamp]) AS [MaxTimeStamp],
       T3.[Version] AS [MaxVersion]
FROM @table T
JOIN (
        SELECT T4.ID,
           MAX(T4.[Version]) AS [MaxVersion]
        FROM @table T4
        GROUP BY T4.ID
    ) as T2 ON T.id = T2.id
JOIN @table T3
    ON T.ID = T3.ID
    --AND T2.ID = T3.ID --works fine somehow with or without thise line
    AND T.[TimeStamp] = T3.[TimeStamp]
    AND T3.[Version] = T2.[MaxVersion]
GROUP BY T.ID, T3.[Version]

I needed an extra join for this, but I'm wondering whether it could be without an extra join.


问:
MySQL EXIT HANDLER is not catching all the errors?
My MySQL procedure looks like:

```<code>create procedure create_feed (_id int)
begin
    declare exit handler for sqlexception
    begin
        rollback;
        select false;
    end;

    start transaction;

    insert into t1(id)
    values (_id);

    insert into wrong_table_name (id, createdtime)
    values (
        _id,
        CURRENT_TIMESTAMP
    );

    commit;
    select true;
end//
</code>```

After I　called this procedure, the t1 table is updated, and the value 'true' is returned. The wrong_table_name does not exist at all. Why?

答:
I recommend that you use a function instead of a procedure if you want it to return a value. Another option is to use out parameters if you want your procedure to return one or more values.

Nonetheless, I am surprised by your results. If wrong_table_name does not exist, then that proc should return true. As for t1 being updated, that would happen if you are using a non-transactional storage engine like MyISAM, which ignores the rollback.

I tested your code in MySQL 5.5.8, and it worked properly for me. Namely, it always entered the exit handler when wrong_table_name did not exist.

Body:
My MySQL procedure looks like:

create procedure create_feed (_id int)
begin
    declare exit handler for sqlexception
    begin
        rollback;
        select false;
    end;

    start transaction;

    insert into t1(id)
    values (_id);

    insert into wrong_table_name (id, createdtime)
    values (
        _id,
        CURRENT_TIMESTAMP
    );

    commit;
    select true;
end//

After I　called this procedure, the t1 table is updated, and the value 'true' is returned. The wrong_table_name does not exist at all. Why?


问:
Swift 5.1 @propertyWrapper - 'self' used in property access before all stored properties are initialized
I am trying to use Swift 5.1 property wrappers but every time I think I have a cool use case for it, I eventually hit the problem where I can't use them inside of my View Model's initializer.

Take this extremely simple example.

class NoProblem {
  var foo = "ABC"
  let upperCased: String

  init(dependencies: AppDependencies) {
    self.upperCased = foo.uppercased()
  }
}
```

<pre class="lang-swift prettyprint-override"><code>@propertyWrapper
struct Box<Value> {
  private var box: Value

  init(wrappedValue: Value) {
    box = wrappedValue
  }

  var wrappedValue: Value {
    get { box }
    set { box = newValue }
  }
}

class OhNoes {
  @Box var foo = "ABC"
  let upperCased: String

  init(dependencies: AppDependencies) {
    self.upperCased = foo.uppercased()
  }
}
</code>```

In NoProblem, everything works as expected. However in OhNoes I get this error: 'self' used in property access 'foo' before all stored properties are initialized.

Of course this is an extremely simplified example, but I get the same problem when doing an @Property wrapper for observable properties, or an @Injected wrapper like in this article, etc.

And no, sadly making it a lay property won't work either: Property 'foo' with a wrapper cannot also be lazy.

This is also a pretty big problem in SwiftUI, see this example:

class AppStore: ObservableObject {
  let foo = "foo"
}

struct ContentView: View {
  @EnvironmentObject private var store: AppStore
  private let foo: String

  init() {
    foo = store.foo // error: 'self' used before all stored properties are initialized
  }

  var body: some View {
    Text("Hello world")
  }
}
```

答:
EDIT:

Actually a better workaround would be to directly use _foo.wrappedValue.uppercased() instead of foo.uppercased().

This solves also the other issue with the double initialization.

Thinking deeper about this, that's definitely the intended behavior.

If I understand it correctly, in OhNoes, foo is just short for:

```<code>var foo: String {
  get {
    return self._foo.wrappedValue
  }
  set {
    self._foo.wrappedValue = newValue
  }
}
</code>```

So there is no way this could work in any other way.

I was facing the same issue you had and I actually think that it is some sort of bug/unwanted behavior.

Anyway the best I could go out with is this:

@propertyWrapper
struct Box<Value> {
  private var box: Value

  init(wrappedValue: Value) {
    box = wrappedValue
  }

  var wrappedValue: Value {
    get { box }
    set { box = newValue }
  }
}

class OhNoes {
  @Box var foo : String
  let upperCased: String

  init() {
    let box = Box(wrappedValue: "ABC")
    _foo = box
    self.upperCased = box.wrappedValue.uppercased()
  }
}
```
<p>That is quite good (I mean, it works with no side effects, but is ugly).</p>
<p>The problem of this solution is that it doesn't really work (without side effects) in case your property wrapper has an empty initializer <code>init()</code> or if the wrappedValue is <code>Optional</code>.</p>
<p>If, for example, you try with the code below, you will realize that Box is initialized twice: once at the definition of the member variable and once in the OhNoes' init, and will replace the former.</p>
```
@propertyWrapper
struct Box<Value> {
  private var box: Value?

  init(wrappedValue: Value?) { // Actually called twice in this case
    box = wrappedValue
  }

  var wrappedValue: Value? {
    get { box }
    set { box = newValue }
  }
}

class OhNoes {
  @Box var foo : String?
  let upperCased: String?

  init() {
    let box = Box(wrappedValue: "ABC")
    _foo = box
    self.upperCased = box.wrappedValue?.uppercased()
  }
}
```

I think this is definitely something we shouldn't have, (or at least we should be able to opt out of this behavior). Anyway I think it's related to what they say in this pitch:

When a property wrapper type has a no-parameter init(), properties
that use that wrapper type will be implicitly initialized via init().

PS: did you find some other way of doing this?

Body:
I am trying to use Swift 5.1 property wrappers but every time I think I have a cool use case for it, I eventually hit the problem where I can't use them inside of my View Model's initializer.

Take this extremely simple example.

class NoProblem {
  var foo = "ABC"
  let upperCased: String

  init(dependencies: AppDependencies) {
    self.upperCased = foo.uppercased()
  }
}

@propertyWrapper
struct Box<Value> {
  private var box: Value

  init(wrappedValue: Value) {
    box = wrappedValue
  }

  var wrappedValue: Value {
    get { box }
    set { box = newValue }
  }
}

class OhNoes {
  @Box var foo = "ABC"
  let upperCased: String

  init(dependencies: AppDependencies) {
    self.upperCased = foo.uppercased()
  }
}

In NoProblem, everything works as expected. However in OhNoes I get this error: 'self' used in property access 'foo' before all stored properties are initialized.

Of course this is an extremely simplified example, but I get the same problem when doing an @Property wrapper for observable properties, or an @Injected wrapper like in this article, etc.

And no, sadly making it a lay property won't work either: Property 'foo' with a wrapper cannot also be lazy.

This is also a pretty big problem in SwiftUI, see this example:

class AppStore: ObservableObject {
  let foo = "foo"
}

struct ContentView: View {
  @EnvironmentObject private var store: AppStore
  private let foo: String

  init() {
    foo = store.foo // error: 'self' used before all stored properties are initialized
  }

  var body: some View {
    Text("Hello world")
  }
}

Body:
EDIT:

Actually a better workaround would be to directly use _foo.wrappedValue.uppercased() instead of foo.uppercased().

This solves also the other issue with the double initialization.

Thinking deeper about this, that's definitely the intended behavior.

If I understand it correctly, in OhNoes, foo is just short for:

var foo: String {
  get {
    return self._foo.wrappedValue
  }
  set {
    self._foo.wrappedValue = newValue
  }
}

So there is no way this could work in any other way.

I was facing the same issue you had and I actually think that it is some sort of bug/unwanted behavior.

Anyway the best I could go out with is this:

@propertyWrapper
struct Box<Value> {
  private var box: Value

  init(wrappedValue: Value) {
    box = wrappedValue
  }

  var wrappedValue: Value {
    get { box }
    set { box = newValue }
  }
}

class OhNoes {
  @Box var foo : String
  let upperCased: String

  init() {
    let box = Box(wrappedValue: "ABC")
    _foo = box
    self.upperCased = box.wrappedValue.uppercased()
  }
}

That is quite good (I mean, it works with no side effects, but is ugly).

The problem of this solution is that it doesn't really work (without side effects) in case your property wrapper has an empty initializer init() or if the wrappedValue is Optional.

If, for example, you try with the code below, you will realize that Box is initialized twice: once at the definition of the member variable and once in the OhNoes' init, and will replace the former.

@propertyWrapper
struct Box<Value> {
  private var box: Value?

  init(wrappedValue: Value?) { // Actually called twice in this case
    box = wrappedValue
  }

  var wrappedValue: Value? {
    get { box }
    set { box = newValue }
  }
}

class OhNoes {
  @Box var foo : String?
  let upperCased: String?

  init() {
    let box = Box(wrappedValue: "ABC")
    _foo = box
    self.upperCased = box.wrappedValue?.uppercased()
  }
}

I think this is definitely something we shouldn't have, (or at least we should be able to opt out of this behavior). Anyway I think it's related to what they say in this pitch:

When a property wrapper type has a no-parameter init(), properties
that use that wrapper type will be implicitly initialized via init().

PS: did you find some other way of doing this?


问:
Gatsby.js image source issue
I just started learning Gatsby.js with Styled Components and the problem is that the browser doesn't show images. store.js is in pages folder and images are in images folder. Both in src folder. The only thing which appears is the value of alt attribute.

```<code>class Store extends React.Component {
  formatPrice(price) {
    return (price * 0.01).toFixed(2)
  }
  render() {
    return (
      <Main>
        <StoreContent>
          {products.map(product => {
            return (
              <Product key={product.key}>
                <img
                  width={100}
                  src={`../images/${product.sku}.jpg`}
                  alt="macbook"
                />
                <h2>{product.name}</h2>
                <p>{this.formatPrice(product.price)}</p>
              </Product>
            )
          })}
        </StoreContent>
      </Main>
    )
  }
}

export default Store

</code>```

Does anyone know what's wrong?

答:
You have to put the images folder into static/ folder.

Here's what Gatsby documentation says about static/ folder:

You can create a folder named static at the root of your project. Every file you put into that folder will be copied into the public folder. E.g. if you add a file named sun.jpg to the static folder, it’ll be copied to public/sun.jpg

Later reference the images from the web root directory, e.g. src={`/images/${product.sku}.jpg`}

Title: Gatsby.js image source issue

Body:
I just started learning Gatsby.js with Styled Components and the problem is that the browser doesn't show images. store.js is in pages folder and images are in images folder. Both in src folder. The only thing which appears is the value of alt attribute.

class Store extends React.Component {
  formatPrice(price) {
    return (price * 0.01).toFixed(2)
  }
  render() {
    return (

        <StoreContent>
          {products.map(product => {
            return (
              <Product key={product.key}>
                <img
                  width={100}
                  src={`../images/${product.sku}.jpg`}
                  alt="macbook"
                />

{product.name}

{this.formatPrice(product.price)}

              </Product>
            )
          })}
        </StoreContent>

    )
  }
}

export default Store

Does anyone know what's wrong?


问:
Prevent form submitting when pressing enter from a text input, using Vue.js
I am using Vue.js in my app and have a text input within a form

```<code><div id="myVueForm">
<form>
   <input type="text" v-on="keyup:addCategory | key 'enter'">

   <!-- more form fields -->
   <button type="submit">Submit Form</button>
</form>
</div>
</code>```

In my Vue instance I have the following

```<code>new Vue({
    el: '#myVueForm',

    methods: {
        addCategory: function(e)
        {
           if(e) e.preventDefault();
           console.log("Added a new category, thanks!");
        }
    }
});
</code>```

Despite the preventDefault() call, when a user presses enter whilst on the text input the form still submits (although the addCategory() method does fire). This behaviour can be demonstrated in this fiddle.

I know I can use jQuery to catch the event and prevent the submit, but I'd like to see if it's possible in Vue to do this as it seems quite a common usage.

答:
For those simply looking to prevent a form submitting on enter, but not wanting to trigger any method on the input, you can simply do:

```<code><input type="text" @keypress.enter.prevent />
</code>```

Or on a custom component include the native modifier:

```<code><custom-input type="text" @keypress.enter.native.prevent />
</code>```

Beautifully readable and succinct.

Body:
I am using Vue.js in my app and have a text input within a form

<form>
   <input type="text" v-on="keyup:addCategory | key 'enter'">

   <button type="submit">Submit Form</button>
</form>

In my Vue instance I have the following

new Vue({
    el: '#myVueForm',

    methods: {
        addCategory: function(e)
        {
           if(e) e.preventDefault();
           console.log("Added a new category, thanks!");
        }
    }
});

Despite the preventDefault() call, when a user presses enter whilst on the text input the form still submits (although the addCategory() method does fire). This behaviour can be demonstrated in this fiddle.

I know I can use jQuery to catch the event and prevent the submit, but I'd like to see if it's possible in Vue to do this as it seems quite a common usage.

Body:
For those simply looking to prevent a form submitting on enter, but not wanting to trigger any method on the input, you can simply do:

<input type="text" @keypress.enter.prevent />

Or on a custom component include the native modifier:

<custom-input type="text" @keypress.enter.native.prevent />

Beautifully readable and succinct.


问:
Android NFC: Reading tag does not work
I want to create an application that can read a tag. I copied the NFCDemo code, but that did not work. I also added

```<code><intent-filter>
  <action android:name="android.nfc.action.NDEF_DISCOVERED" />
  <data android:mimeType="mime/type" />
</intent-filter>
<intent-filter>
  <action android:name="android.nfc.action.TECH_DISCOVERED" />
  <meta-data android:name="android.nfc.action.TECH_DISCOVERED"
    android:resource="@xml/nfc_tech_filter" />
</intent-filter>
<intent-filter>
  <action android:name="android.nfc.action.TAG_DISCOVERED" />
  <category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</code>```

to my manifest file.

But the application is never called / opened when I hold the tag at my Nexus S.

Thanks for any help!!

答: To make it easy at the beginning, remove all the intent filters but the TAG_DISCOVERED one. This is the most basic one. Once the NFC chip will discover a NFC tag, it will send out and event with TAG_DISCOVERED. If you have registered teh intent filter to an activity you should then see the intent chooser with your app in it. </p>

Title: Android NFC: Reading tag does not work

Body:
I want to create an application that can read a tag. I copied the NFCDemo code, but that did not work. I also added

<intent-filter>
  <action android:name="android.nfc.action.NDEF_DISCOVERED" />
  <data android:mimeType="mime/type" />
</intent-filter>
<intent-filter>
  <action android:name="android.nfc.action.TECH_DISCOVERED" />
  <meta-data android:name="android.nfc.action.TECH_DISCOVERED"
    android:resource="@xml/nfc_tech_filter" />
</intent-filter>
<intent-filter>
  <action android:name="android.nfc.action.TAG_DISCOVERED" />
  <category android:name="android.intent.category.DEFAULT"/>
</intent-filter>

to my manifest file.

But the application is never called / opened when I hold the tag at my Nexus S.

Thanks for any help!!


问:
How can I use the apply() function for a single column?
I have a pandas dataframe with two columns. I need to change the values of the first column without affecting the second one and get back the whole dataframe with just first column values changed. How can I do that using apply() in pandas?

答:
Let me try a complex computation using datetime and considering nulls or empty spaces. I am reducing 30 years on a datetime column and using apply method as well as lambda and converting datetime format. Line if x != '' else x will take care of all empty spaces or nulls accordingly.

```<code>df['Date'] = df['Date'].fillna('')
df['Date'] = df['Date'].apply(lambda x : ((datetime.datetime.strptime(str(x), '%m/%d/%Y') - datetime.timedelta(days=30*365)).strftime('%Y%m%d')) if x != '' else x)
</code>```

Body:
Let me try a complex computation using datetime and considering nulls or empty spaces. I am reducing 30 years on a datetime column and using apply method as well as lambda and converting datetime format. Line if x != '' else x will take care of all empty spaces or nulls accordingly.

df['Date'] = df['Date'].fillna('')
df['Date'] = df['Date'].apply(lambda x : ((datetime.datetime.strptime(str(x), '%m/%d/%Y') - datetime.timedelta(days=30*365)).strftime('%Y%m%d')) if x != '' else x)


问:
When I connect to a remote database from a Docker container, what IP address does the remote see?
I have Docker containers which use a bridge network with subnet 172.16.238.0/24 and I'm connecting to external databases.  (Successfully.)

What I'd like to know, though, is:  what IP address does the remote database see the connection as coming from?  Does it see an address in the subnet address range on any of the packets that it receives?

答:
Okay, thank you Husein ... I'll call it "answered."

The reason for my question is that I'm getting an unexpected security-error from an AS/400 DB2 database when I think I'm giving it the right password.  I just wanted to make sure that a 172.16.238.xxx IP-address wasn't showing up in any of the internal fields of the packet that the remote database might be examining.  (Naturally, this database is well-protected.)  I'll follow up with the friendly DBA's now ... and if they say anything interesting I'll add it to this or another ticket.


问:
Unable to record sound with sounddevice
I am unable to record audio using sounddevice in python. This code worked before on an older version of Mac OS.

The python3 code is as follows:

```<code>import sounddevice as sd
import numpy as np
fs = 48000
duration=5
rec = sd.rec(int(duration * fs), samplerate=fs, channels=1, blocking=True)
print(rec)
</code>```

The output is

```<code>array([[0.],
       [0.],
       [0.],
       ...,
       [0.],
       [0.],
       [0.]], dtype=float32)
</code>```

Although not all values are shown here, I have confirmed that they are all zero. When the sound records correctly, most of the these values are non-zero.

I have confirmed that the devices are set correctly:

```<code>sd.default.device # Output is [2, 3]

python3 -m sounddevice
  0 DisplayPort, Core Audio (0 in, 2 out)
  1 DisplayPort, Core Audio (0 in, 2 out)
> 2 MacBook Pro Microphone, Core Audio (1 in, 0 out)
< 3 MacBook Pro Speakers, Core Audio (0 in, 2 out)
</code>```

Is this something to do with permissions in Mac OS? I'm using Mojave.

Thank you.

答:
try this code</p>

```<code>import sounddevice as sd
from scipy.io.wavfile import write

fs=44100
duration=5
print("recording...............")

record_voice=sd.rec(int(duration * fs),samplerate=fs,channels=2)
sd.wait()
write("sound.wav",fs,record_voice)

</code>```

Title: Unable to record sound with sounddevice

Body:
I am unable to record audio using sounddevice in python. This code worked before on an older version of Mac OS.

The python3 code is as follows:

import sounddevice as sd
import numpy as np
fs = 48000
duration=5
rec = sd.rec(int(duration * fs), samplerate=fs, channels=1, blocking=True)
print(rec)

The output is

array([[0.],
       [0.],
       [0.],
       ...,
       [0.],
       [0.],
       [0.]], dtype=float32)

Although not all values are shown here, I have confirmed that they are all zero. When the sound records correctly, most of the these values are non-zero.

I have confirmed that the devices are set correctly:

sd.default.device # Output is [2, 3]

python3 -m sounddevice
  0 DisplayPort, Core Audio (0 in, 2 out)
  1 DisplayPort, Core Audio (0 in, 2 out)
> 2 MacBook Pro Microphone, Core Audio (1 in, 0 out)
< 3 MacBook Pro Speakers, Core Audio (0 in, 2 out)

Is this something to do with permissions in Mac OS? I'm using Mojave.

Thank you.

Body:
try this code

import sounddevice as sd
from scipy.io.wavfile import write

fs=44100
duration=5
print("recording...............")

record_voice=sd.rec(int(duration * fs),samplerate=fs,channels=2)
sd.wait()
write("sound.wav",fs,record_voice)


问:
DropDownListFor without a List type
I am currently working with the Salesforce API to basically pull data from Salesforce and push it back.

There is this one section where I need to pull the Data and Deserialize it so I have model access to it.

This certain property in the model, called Subject, is not of type list because there aren't multiple of them, BUT there are multiple Subjects from different objects coming in, and thats what I want to put in the dropdown.

How would I go about this?

My GetAllEvents() method in my Services.

```<code>        public async Task<SFEventModel> GetAllEvents()
        {
            HttpClient queryClient = new HttpClient();
            var tm = await GetToken();
            List<SelectListItem> events = new List<SelectListItem>();

            string restQuery = tm.ServiceUrl + "/services/data/v25.0/query?q=SELECT+Subject+from+Event";

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, restQuery);

            // Adding the token to the header
            request.Headers.Add("Authorization", "Bearer " + tm.AccessToken);
            // Return JSON to the caller
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Call Endpoint Async
            HttpResponseMessage response = await queryClient.SendAsync(request);

            string responseString = await response.Content.ReadAsStringAsync();
            var model = JsonConvert.DeserializeObject<SFEventModel>(responseString);

            return model;
        }
</code>```

My half-assed attempt of putting these inbound objects into a list

```<code>    <div class="text-center">
        <div>
            @Html.LabelFor(x => Model.Subject)
            <div class="col-md-5">
                @Html.DropDownListFor(x => Model.Subject, new SelectList(Model.Subject))
            </div>
        </div>
    </div>
</code>```

I am going to filter out all the other properties as they have no context to this question and there are lots of properties. I have the data pulling correctly from this model in my controller to actually pull "PicklistValues", but the problem is, it is considered a type.

```<code>public partial class Field
{
[JsonProperty("picklistValues")
public PicklistValue[] PicklistValues { get; set; }
}
</code>```

PicklistValue partial class in model -->

```<code>public partial class PicklistValue
        {
            [JsonProperty("active")]
            public bool Active { get; set; }

            [JsonProperty("defaultValue")]
            public bool DefaultValue { get; set; }

            [JsonProperty("label")]
            public string Label { get; set; }

            [JsonProperty("validFor")]
            public object ValidFor { get; set; }

            [JsonProperty("value")]
            public string Value { get; set; }
        }

</code>```

method in controller to pull these values coming in from the API call.

```<code>var allEvents = await _api.GetAllEvents();
var subjectList = allEvents.Fields.Where(x => x.Name == "Subject").Select(x => x.PicklistValues).FirstOrDefault();
</code>```

答:
EDIT: SOLVED

Might have just worded the question wrong but I did it.

My Index action in my HomeController had to have this method ->

ViewData["Picklist1"] = new SelectLit(await GetSubject(), "Value", "Label")

and my view had to have this

<select asp-items="ViewBag.Picklist1"> </select>

for the curious, my GetSubject method was tailored to the fact that Salesforce API is terrible.

```<code>private async Task<List<PicklistValue>> GetSubject()
 {
    var allEvents = await _api.GetAllEvents();
    var subjectList = allEvents.Fields.Where(x => x.Name == "Subject").Select(x =>
           x.PicklistValues).FirstOrDefault().ToList();

    return subjectList;
 }
</code>```

Title: DropDownListFor without a List type

Body:
I am currently working with the Salesforce API to basically pull data from Salesforce and push it back.

There is this one section where I need to pull the Data and Deserialize it so I have model access to it.

This certain property in the model, called Subject, is not of type list because there aren't multiple of them, BUT there are multiple Subjects from different objects coming in, and thats what I want to put in the dropdown.

How would I go about this?

My GetAllEvents() method in my Services.

        public async Task<SFEventModel> GetAllEvents()
        {
            HttpClient queryClient = new HttpClient();
            var tm = await GetToken();
            List<SelectListItem> events = new List<SelectListItem>();

            string restQuery = tm.ServiceUrl + "/services/data/v25.0/query?q=SELECT+Subject+from+Event";

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, restQuery);

            // Adding the token to the header
            request.Headers.Add("Authorization", "Bearer " + tm.AccessToken);
            // Return JSON to the caller
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Call Endpoint Async
            HttpResponseMessage response = await queryClient.SendAsync(request);

            string responseString = await response.Content.ReadAsStringAsync();
            var model = JsonConvert.DeserializeObject<SFEventModel>(responseString);

            return model;
        }

My half-assed attempt of putting these inbound objects into a list

            @Html.LabelFor(x => Model.Subject)

                @Html.DropDownListFor(x => Model.Subject, new SelectList(Model.Subject))

I am going to filter out all the other properties as they have no context to this question and there are lots of properties. I have the data pulling correctly from this model in my controller to actually pull "PicklistValues", but the problem is, it is considered a type.

public partial class Field
{
[JsonProperty("picklistValues")
public PicklistValue[] PicklistValues { get; set; }
}

PicklistValue partial class in model -->

public partial class PicklistValue
        {
            [JsonProperty("active")]
            public bool Active { get; set; }

            [JsonProperty("defaultValue")]
            public bool DefaultValue { get; set; }

            [JsonProperty("label")]
            public string Label { get; set; }

            [JsonProperty("validFor")]
            public object ValidFor { get; set; }

            [JsonProperty("value")]
            public string Value { get; set; }
        }

method in controller to pull these values coming in from the API call.

var allEvents = await _api.GetAllEvents();
var subjectList = allEvents.Fields.Where(x => x.Name == "Subject").Select(x => x.PicklistValues).FirstOrDefault();

Body:
EDIT: SOLVED

Might have just worded the question wrong but I did it.

My Index action in my HomeController had to have this method ->

ViewData["Picklist1"] = new SelectLit(await GetSubject(), "Value", "Label")

and my view had to have this

<select asp-items="ViewBag.Picklist1"> </select>

for the curious, my GetSubject method was tailored to the fact that Salesforce API is terrible.

private async Task<List<PicklistValue>> GetSubject()
 {
    var allEvents = await _api.GetAllEvents();
    var subjectList = allEvents.Fields.Where(x => x.Name == "Subject").Select(x =>
           x.PicklistValues).FirstOrDefault().ToList();

    return subjectList;
 }


问:
Generate token for multiple realms with Keyclock
Is there a way to generate the same token for several realms in keycloak?

So that an authentication URL would look like this, for example:

http://localhost:8888/auth/"multiple realm"/glide/protocol/openid-connect/token

Thanks

答:
No, that's not possible:

A realm manages a set of users, credentials, roles, and groups. A user belongs to and logs into a realm. Realms are isolated from one another and can only manage and authenticate the users that they control.

https://www.keycloak.org/docs/latest/server_admin/#core-concepts-and-terms (definition of "realms")

If you could explain why you want to do this, I (or someone else) could maybe suggest a better alternative.


问:
How to read in Wed Oct 02 09:37:43 BST 2019 to datetime format using pandas?
So I have an excel sheet which is Wed Oct 02 09:37:43 BST 2019  and Wed Oct 02 09:37:43 GMT 2019,
I want to read it in via the format 2019-10-02 09:37:43 (with the time being GMT) in pandas.

Thanks

答:
If I understood well, you can use parser.parse
Here what it gives you:

```<code>date=('Wed Oct 02 09:37:43 BST 2019')
print(parser.parse(date))
out 2019-10-02 09:37:43
</code>```

Body:
If I understood well, you can use parser.parse
Here what it gives you:

date=('Wed Oct 02 09:37:43 BST 2019')
print(parser.parse(date))
out 2019-10-02 09:37:43


问:
Zend Dojo Filtering Select only returning one value
Hi can anyone please tell me why the following code is only returning the single value 2,bath

The autocomplete action from my controller

```<code>  public function groomappointserviceAction()
   {

    $this->_helper->layout->disableLayout();
    $this->getHelper('viewRenderer')->setNoRender(true);

    // get a list of all grooming services IDs and related procedures
   $gqry= Doctrine_Query::create()
   ->select('g.groomServicesID AS iden , p.groomprocedure AS name')
   ->from('PetManager_Model_Groomservices g')
   ->leftJoin('g.PetManager_Model_Groomprocedures p');
   $result = $gqry->fetchArray();

   //generate and return JSON string
    $data = new Zend_Dojo_Data('iden',$result);
    echo $data->toJson();
  }
</code>```

The filteringselect of my form

```<code>  // Create a autocomplete select input for the grooming
    $gservice = new Zend_Dojo_Form_Element_FilteringSelect('gapmtService');
    $gservice->setLabel('Proceedure');
            $gservice->setOptions(array(
            'autocomplete' => true,
            'storeID'   => 'groomappointserviceStore',
            'storeType' => 'dojo.data.ItemFileReadStore',
            'storeParams' => array('url' => "/groomappointments/appointment/groomappointservice"),
      'dijitParams' => array('searchAttr' => 'name')))
        ->setRequired(true)
        ->addValidator('NotEmpty', true)
        ->addFilter('HTMLEntities')
        ->addFilter('StringToLower')
        ->addFilter('StringTrim');
</code>```

When the same (I Believe) query in MySQL returns

```<code>mysql> select g.groomservicesid AS iden , p.groomprocedure as name
     -> from groomservices AS g LEFT JOIN groomProcedures AS p
     -> on g.groomProcedure = p.groomProceduresID;
 +------+--------------------------+
 | iden | name                     |
 +------+--------------------------+
 |    2 | Bath                     |
 |    7 | Bath                     |
 |    8 | Bath                     |
 |    9 | Bath                     |
 |    1 | Nail Clip                |
 |    4 | Nail Clip                |
 |    5 | Nail Clip                |
 |    6 | Nail Clip                |
 |   19 | Shed Less                |
 |   20 | Shed Less                |
 |   21 | Shed Less                |
 |   22 | Shed Less                |
 |   13 | Dematting/Hand Stripping |
 |   14 | Dematting/Hand Stripping |
 |   15 | Dematting/Hand Stripping |
 |   16 | Dematting/Hand Stripping |
 |   17 | Dematting/Hand Stripping |
 |   18 | Dematting/Hand Stripping |
 |    3 | Bath Brush               |
 |   10 | Bath Brush               |
 |   11 | Bath Brush               |
 |   12 | Bath Brush               |
 +------+--------------------------+
 22 rows in set (0.00 sec)
</code>```

答:
Ok I've actually sorted this by changing the code to that below. Not sure why it is now working as I tried this earlier but it didn't work.

My autocomplete action

```<code>public function groomappointserviceAction()
{

    $this->_helper->layout->disableLayout();
    $this->getHelper('viewRenderer')->setNoRender(true);

   // get a list of all grooming services IDs and related procedures
   $gqry= Doctrine_Query::create()
       ->select('g.groomServicesID, p.groomprocedure AS name')
       ->from('PetManager_Model_Groomservices g')
      ->leftJoin('g.PetManager_Model_Groomprocedures');
   $result = $gqry->fetchArray();

  //generate and return JSON string
  $data = new Zend_Dojo_Data('groomServicesID',$result);
  echo $data->toJson();
}
</code>```

The FilteringSelect on my form

```<code>  // Create a autocomplete select input for the grooming
    $gservice = new Zend_Dojo_Form_Element_FilteringSelect('gapmtService');
    $gservice->setLabel('Proceedure');
    $gservice->setOptions(array(
      'autocomplete' => true,
      'storeID'   => 'groomappointserviceStore',
      'storeType' => 'dojo.data.ItemFileReadStore',
      'storeParams' => array('url' => "/groomappointments/appointment/groomappointservice"),
      'dijitParams' => array('searchAttr' => 'name')))
        ->setRequired(true)
        ->addValidator('NotEmpty', true)
        ->addFilter('HTMLEntities')
        ->addFilter('StringToLower')
        ->addFilter('StringTrim');
</code>```

Body:
Hi can anyone please tell me why the following code is only returning the single value 2,bath

The autocomplete action from my controller

  public function groomappointserviceAction()
   {

    $this->_helper->layout->disableLayout();
    $this->getHelper('viewRenderer')->setNoRender(true);

    // get a list of all grooming services IDs and related procedures
   $gqry= Doctrine_Query::create()
   ->select('g.groomServicesID AS iden , p.groomprocedure AS name')
   ->from('PetManager_Model_Groomservices g')
   ->leftJoin('g.PetManager_Model_Groomprocedures p');
   $result = $gqry->fetchArray();

   //generate and return JSON string
    $data = new Zend_Dojo_Data('iden',$result);
    echo $data->toJson();
  }

The filteringselect of my form

  // Create a autocomplete select input for the grooming
    $gservice = new Zend_Dojo_Form_Element_FilteringSelect('gapmtService');
    $gservice->setLabel('Proceedure');
            $gservice->setOptions(array(
            'autocomplete' => true,
            'storeID'   => 'groomappointserviceStore',
            'storeType' => 'dojo.data.ItemFileReadStore',
            'storeParams' => array('url' => "/groomappointments/appointment/groomappointservice"),
      'dijitParams' => array('searchAttr' => 'name')))
        ->setRequired(true)
        ->addValidator('NotEmpty', true)
        ->addFilter('HTMLEntities')
        ->addFilter('StringToLower')
        ->addFilter('StringTrim');

When the same (I Believe) query in MySQL returns

mysql> select g.groomservicesid AS iden , p.groomprocedure as name
     -> from groomservices AS g LEFT JOIN groomProcedures AS p
     -> on g.groomProcedure = p.groomProceduresID;
 +------+--------------------------+
 | iden | name                     |
 +------+--------------------------+
 |    2 | Bath                     |
 |    7 | Bath                     |
 |    8 | Bath                     |
 |    9 | Bath                     |
 |    1 | Nail Clip                |
 |    4 | Nail Clip                |
 |    5 | Nail Clip                |
 |    6 | Nail Clip                |
 |   19 | Shed Less                |
 |   20 | Shed Less                |
 |   21 | Shed Less                |
 |   22 | Shed Less                |
 |   13 | Dematting/Hand Stripping |
 |   14 | Dematting/Hand Stripping |
 |   15 | Dematting/Hand Stripping |
 |   16 | Dematting/Hand Stripping |
 |   17 | Dematting/Hand Stripping |
 |   18 | Dematting/Hand Stripping |
 |    3 | Bath Brush               |
 |   10 | Bath Brush               |
 |   11 | Bath Brush               |
 |   12 | Bath Brush               |
 +------+--------------------------+
 22 rows in set (0.00 sec)

Body:
Ok I've actually sorted this by changing the code to that below. Not sure why it is now working as I tried this earlier but it didn't work.

My autocomplete action

public function groomappointserviceAction()
{

    $this->_helper->layout->disableLayout();
    $this->getHelper('viewRenderer')->setNoRender(true);

   // get a list of all grooming services IDs and related procedures
   $gqry= Doctrine_Query::create()
       ->select('g.groomServicesID, p.groomprocedure AS name')
       ->from('PetManager_Model_Groomservices g')
      ->leftJoin('g.PetManager_Model_Groomprocedures');
   $result = $gqry->fetchArray();

  //generate and return JSON string
  $data = new Zend_Dojo_Data('groomServicesID',$result);
  echo $data->toJson();
}

The FilteringSelect on my form

  // Create a autocomplete select input for the grooming
    $gservice = new Zend_Dojo_Form_Element_FilteringSelect('gapmtService');
    $gservice->setLabel('Proceedure');
    $gservice->setOptions(array(
      'autocomplete' => true,
      'storeID'   => 'groomappointserviceStore',
      'storeType' => 'dojo.data.ItemFileReadStore',
      'storeParams' => array('url' => "/groomappointments/appointment/groomappointservice"),
      'dijitParams' => array('searchAttr' => 'name')))
        ->setRequired(true)
        ->addValidator('NotEmpty', true)
        ->addFilter('HTMLEntities')
        ->addFilter('StringToLower')
        ->addFilter('StringTrim');


问:
Programmatically loop a section of JSX within an output
I would like to programmatically repeat a section of JSX within an output.
Below I would like to get the same effect as below without repeating the PageLeft id="Diary" component 3 times. I'd like to use a loop or something.

```<code>const DiaryPages = {

}

  return (
    <Fragment>
     <PageLeftDivider
      />
      <PageRight
  header={bookData[0].pageHeader}
  pageNumber={bookData[0].id}
  htmlContent={bookData[0].htmlContent}
  bookSection={bookData[0].bookSection}
      />

      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />
      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />

      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />

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

答:
If you want to render 3 times exactly the same component then I guess you can use .map() for that purpose as the following:

```<code>return <Fragment>
    {/* your other components */}

    {
       [1,2,3].map(e => <PageLeft id="Diary"
            pageHeader={bookData[1].pageHeader}
            pageNumber={bookData[1].id}
            htmlContent={bookData[1].htmlContent}
       />)
    }
</Fragment>
</code>```

As the documentation states for .map():

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

So technically we are taking each elements from the array - in this case 3 elements, does not matter what they are for now - and returning the created JSX for each. That's how you can render elements.

Usually this is used to pick up data from an array, e.g.: id, name fields from an object and create a render format for elements of an array.

Suggested read from React documentation: Lists and Keys

I hope that helps!

Body:
I would like to programmatically repeat a section of JSX within an output.
Below I would like to get the same effect as below without repeating the PageLeft id="Diary" component 3 times. I'd like to use a loop or something.

const DiaryPages = {

}

  return (
    <Fragment>
     <PageLeftDivider
      />
      <PageRight
  header={bookData[0].pageHeader}
  pageNumber={bookData[0].id}
  htmlContent={bookData[0].htmlContent}
  bookSection={bookData[0].bookSection}
      />

      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />
      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />

      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />

    </Fragment>
  );
}

Body:
If you want to render 3 times exactly the same component then I guess you can use .map() for that purpose as the following:

return <Fragment>
    {/* your other components */}

    {
       [1,2,3].map(e => <PageLeft id="Diary"
            pageHeader={bookData[1].pageHeader}
            pageNumber={bookData[1].id}
            htmlContent={bookData[1].htmlContent}
       />)
    }
</Fragment>

As the documentation states for .map():

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

So technically we are taking each elements from the array - in this case 3 elements, does not matter what they are for now - and returning the created JSX for each. That's how you can render elements.

Usually this is used to pick up data from an array, e.g.: id, name fields from an object and create a render format for elements of an array.

Suggested read from React documentation: Lists and Keys

I hope that helps!


问:
Is there a way to check how many messages are in a MSMQ Queue?
I was wondering if there is a way to programmatically check how many messages are in a private or public MSMQ using C#? I have code that checks if a queue is empty or not using the peek method wrapped in a try/catch, but I've never seen anything about showing the number of messages in the queue. This would be very helpful for monitoring if a queue is getting backed up.</p>

答:
If you want a Count of a private queue, you can do this using WMI.
This is the code for this:

```<code>// You can change this query to a more specific queue name or to get all queues
private const string WmiQuery = @"SELECT Name,MessagesinQueue FROM Win32_PerfRawdata_MSMQ_MSMQQueue WHERE Name LIKE 'private%myqueue'";

public int GetCount()
{
    using (ManagementObjectSearcher wmiSearch = new ManagementObjectSearcher(WmiQuery))
    {
        ManagementObjectCollection wmiCollection = wmiSearch.Get();

        foreach (ManagementBaseObject wmiObject in wmiCollection)
        {
            foreach (PropertyData wmiProperty in wmiObject.Properties)
            {
                if (wmiProperty.Name.Equals("MessagesinQueue", StringComparison.InvariantCultureIgnoreCase))
                {
                    return int.Parse(wmiProperty.Value.ToString());
                }
            }
        }
    }
}
</code>```

Thanks to the Microsoft.Windows.Compatibility package this also works in netcore/netstandard.

ContentLicense: CC BY-SA 2.5

Body:
If you want a Count of a private queue, you can do this using WMI.
This is the code for this:

// You can change this query to a more specific queue name or to get all queues
private const string WmiQuery = @"SELECT Name,MessagesinQueue FROM Win32_PerfRawdata_MSMQ_MSMQQueue WHERE Name LIKE 'private%myqueue'";

public int GetCount()
{
    using (ManagementObjectSearcher wmiSearch = new ManagementObjectSearcher(WmiQuery))
    {
        ManagementObjectCollection wmiCollection = wmiSearch.Get();

        foreach (ManagementBaseObject wmiObject in wmiCollection)
        {
            foreach (PropertyData wmiProperty in wmiObject.Properties)
            {
                if (wmiProperty.Name.Equals("MessagesinQueue", StringComparison.InvariantCultureIgnoreCase))
                {
                    return int.Parse(wmiProperty.Value.ToString());
                }
            }
        }
    }
}

Thanks to the Microsoft.Windows.Compatibility package this also works in netcore/netstandard.


问:
can't upload a image to express api with Multer from react
I want to upload a image from my react app to my express API.
i made something like this in vainla js and it work ed with same endpoint but in react project doesn't work .
I created a react component like this:

```<code>import React, { useState } from "react";
import BackupIcon from "@material-ui/icons/Backup";
import url from "../url";
import Preview from "./Preview";

const AdaugaImg = props => {
  const [file, setFile] = useState(null);
  const [ales, setAles] = useState(false);
  const [imgUrl, setImgUrl] = useState("");

  const modificare = e => {
    //console.log(e.target.value);
    setFile(e.target.files[0]);
    setAles(true);

    const urlImg = URL.createObjectURL(e.target.files[0]);
    //console.log(urlImg);
    //reader.onloadend = e => setImgUrl(reader.result);
    setImgUrl(urlImg);
  };

  const upload = async e => {
    e.preventDefault();
    setAles(false);
    console.log("incarcare");
    console.log(file);
    try {
      const data = new FormData();
      data.append("img", file);
      const res = await fetch(`${url}/add`, {
        method: "POST",
        data: data
      });
      console.log(await res.json());
    } catch (error) {
      console.log(error);
    }
  };
  const closePreview = () => setAles(false);
  const preview = ales ? (
    <Preview imgUrl={imgUrl} closePreview={closePreview} />
  ) : null;
  return (
    <div className="upload">
      {preview}
      <form method="POST" onSubmit={upload}>
        <input
          type="file"
          name="img"
          id="poza"
          style={{ width: 0.1, height: 0.1 }}
          onChange={modificare}
        />
        {!ales ? (
          <label for="poza" className="upload-label">
            <p>Selecteaza o poza</p>
          </label>
        ) : null}
        <button className="upload-btn" type="submit">
          <BackupIcon />
          <p>Incarca poza</p>
        </button>
      </form>
    </div>
  );
};
export default AdaugaImg;
</code>```

them I wrote code. for api using multer

```<code>const router = require("express").Router();
const multer = require("multer");
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, "img-biserici/");
  },
  filename: function(req, file, cb) {
    cb(null, file.fieldname + "_" + Date.now() + "_.jpg");
  }
});

const upload = multer({
  storage: storage
});

router.post("/add", upload.array("img", 1), (req, res) => {
  console.log(req.files[0]);
  res.json({ ok: true });
});
</code>```

when I upload image in console it shows me this error:TypeError: Cannot read property '0' of undefined .what I missed?and how to fix this?

答:
You are missing content type in headers.</p>

```<code>  const res = await fetch(`${url}/add`, {
    method: "POST",
    data: data,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
</code>```

Body:
I want to upload a image from my react app to my express API.
i made something like this in vainla js and it work ed with same endpoint but in react project doesn't work .
I created a react component like this:

import React, { useState } from "react";
import BackupIcon from "@material-ui/icons/Backup";
import url from "../url";
import Preview from "./Preview";

const AdaugaImg = props => {
  const [file, setFile] = useState(null);
  const [ales, setAles] = useState(false);
  const [imgUrl, setImgUrl] = useState("");

  const modificare = e => {
    //console.log(e.target.value);
    setFile(e.target.files[0]);
    setAles(true);

    const urlImg = URL.createObjectURL(e.target.files[0]);
    //console.log(urlImg);
    //reader.onloadend = e => setImgUrl(reader.result);
    setImgUrl(urlImg);
  };

  const upload = async e => {
    e.preventDefault();
    setAles(false);
    console.log("incarcare");
    console.log(file);
    try {
      const data = new FormData();
      data.append("img", file);
      const res = await fetch(`${url}/add`, {
        method: "POST",
        data: data
      });
      console.log(await res.json());
    } catch (error) {
      console.log(error);
    }
  };
  const closePreview = () => setAles(false);
  const preview = ales ? (
    <Preview imgUrl={imgUrl} closePreview={closePreview} />
  ) : null;
  return (

      {preview}
      <form method="POST" onSubmit={upload}>
        <input
          type="file"
          name="img"
          id="poza"
          style={{ width: 0.1, height: 0.1 }}
          onChange={modificare}
        />
        {!ales ? (

Selecteaza o poza

        ) : null}
        <button className="upload-btn" type="submit">
          <BackupIcon />

Incarca poza

        </button>
      </form>

  );
};
export default AdaugaImg;

them I wrote code. for api using multer

const router = require("express").Router();
const multer = require("multer");
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, "img-biserici/");
  },
  filename: function(req, file, cb) {
    cb(null, file.fieldname + "_" + Date.now() + "_.jpg");
  }
});

const upload = multer({
  storage: storage
});

router.post("/add", upload.array("img", 1), (req, res) => {
  console.log(req.files[0]);
  res.json({ ok: true });
});

when I upload image in console it shows me this error:TypeError: Cannot read property '0' of undefined .what I missed?and how to fix this?

Body:
You are missing content type in headers.

  const res = await fetch(`${url}/add`, {
    method: "POST",
    data: data,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });


问:
Compare only two rows in dataframe with each other
I have a dataframe with a column focus_duration and I want to compare this data pair wise, meaning row zero and one, row two and three, row four and five, etc. If the first integer is bigger than the second, write a 1 in a new column. If it is less, write -1 and if it is equal then 0. I tried by creating a list and comparing one element with the next. But this way it compares element two with element three and element three with element four, what I don't want. </p>

```<code>a = df['focus_duration'].tolist()
b = []

for i in range(0, (len(a)-1)):
    if a[i] < a[i+1]:
        b.append(0)
    elif a[i] > a[i+1]:
        b.append(1)
</code>```

答:
You need to check the condition if the number of your row is odd or even.
I'm adding a condition to your own code.
Also, for example, when you use range(3) it iterates from 0 to 2.

```<code>a = df['focus_duration'].tolist()
b = []

for i in range(len(a)):
    if i%2 == 0:
        if a[i] < a[i+1]:
            b.append(0)
        elif a[i] > a[i+1]:
            b.append(1)
    else:
        if a[i] < a[i-1]:
            b.append(0)
        elif a[i] > a[i-1]:
            b.append(1)
</code>```

This code compares zero with one, one with zero, two with three and three with two, so on.

Body:
I have a dataframe with a column focus_duration and I want to compare this data pair wise, meaning row zero and one, row two and three, row four and five, etc. If the first integer is bigger than the second, write a 1 in a new column. If it is less, write -1 and if it is equal then 0. I tried by creating a list and comparing one element with the next. But this way it compares element two with element three and element three with element four, what I don't want.

a = df['focus_duration'].tolist()
b = []

for i in range(0, (len(a)-1)):
    if a[i]  a[i+1]:
        b.append(1)

Body:
You need to check the condition if the number of your row is odd or even.
I'm adding a condition to your own code.
Also, for example, when you use range(3) it iterates from 0 to 2.

a = df['focus_duration'].tolist()
b = []

for i in range(len(a)):
    if i%2 == 0:
        if a[i] < a[i+1]:
            b.append(0)
        elif a[i] > a[i+1]:
            b.append(1)
    else:
        if a[i] < a[i-1]:
            b.append(0)
        elif a[i] > a[i-1]:
            b.append(1)

This code compares zero with one, one with zero, two with three and three with two, so on.


问:
How to assign a type of string or nil in Active Interaction?
Example

```<code>array :names do
  string
end
</code>```

how to determine the type of elements as a string and nil.

答:
Looking at Active Interaction's source code, it seems you can't have multiple types neither nil values inside an array:

```<code>raise InvalidFilterError, 'multiple filters in array block'
raise InvalidDefaultError, 'default values in array block'
</code>```

You could remove unwanted nil values from the array before calling the interaction though. This would work unless you're expecting exact indices in the array (in which case named indexes e.g. objects should be used instead).

Example:

```<code>SampleInteraction.run!(names: ['a', 'b', nil, 'd'].compact)
</code>```

Body:
Example

array :names do
  string
end

how to determine the type of elements as a string and nil.

Body:
Looking at Active Interaction's source code, it seems you can't have multiple types neither nil values inside an array:

raise InvalidFilterError, 'multiple filters in array block'
raise InvalidDefaultError, 'default values in array block'

You could remove unwanted nil values from the array before calling the interaction though. This would work unless you're expecting exact indices in the array (in which case named indexes e.g. objects should be used instead).

Example:

SampleInteraction.run!(names: ['a', 'b', nil, 'd'].compact)


问:
Need help for writing query for a marketplace in postgres
I have database for a marketplace which looks like this:

I have different suppliers selling the same product at different price points, also some products are more popular than others in a given location. For example we have product A and product B, and product A is more popular that product B based on how many has already been sold in that location, and for product A we have 3 suppliers. I want my query to show product A from the cheapest seller, then product B from the cheapest seller. I can achieve that with this code:

```<code>WITH tem_1 AS (SELECT product_id, MIN(price) AS price FROM product_supplier GROUP BY product_id) ,
     tem_2 AS (SELECT product_id, SUM(quantity) AS n_orders FROM orders Group by product_id)
SELECT products.product_id, suppliers.supplier_id, products.name, tem_1.price,
COALESCE(tem_2.n_orders,0) AS quant FROM products
  INNER JOIN product_supplier ON product_supplier.product_id = products.product_id
  INNER JOIN suppliers ON suppliers.supplier_id = product_supplier.supplier_id
  INNER JOIN product_code ON product_code.code_id = products.code_id
  INNER JOIN product_crop ON product_crop.product_id = products.product_id
  INNER JOIN crops ON crops.crops_id = product_crop.crop_id
  INNER JOIN product_tags ON product_tags.product_id = products.product_id
  INNER JOIN tags ON tags.tag_id = product_tags.tag_id
  INNER JOIN tem_1 ON tem_1.price = product_supplier.price AND tem_1.product_id = products.product_id
  LEFT JOIN tem_2 ON tem_2.product_id = products.product_id
WHERE crops.crops_id = 1 AND product_supplier.quantity >= 3 AND tags.tag = 'علف کش'
ORDER BY quant DESC
LIMIT 10;
</code>```

The problem is, if i have two different suppliers from different locations, selling the same product with the same price, the results show that product twice, but i only want the results from the closest supplier to the user, in this case product 101 from supplier 3 and not the supplier 1.

I think i have to use MIN(ST_Distance("geopoint from user", "geopoint from suppliers")) and LATERAL to have a distance filed, but because i'm using aggregate functions, in order to do a GROUP BY to remove the duplicate results, i have to add all the fields product_id, supplier_id, name, price, ... to the GROUP BY and that won't result in removing the duplicates.

Any suggestion on how to achieve that?

答:
Your query is rather hard to follow.  But, distinct on solves your problem.  I'm not 100% sure what you want to be distinct, but something like this:

```<code>select distinct on (product_id, price) . . .
from . . .
where . . .
order by product_id, price, ST_Distance("geopoint from user", "geopoint from suppliers");
</code>```

This returns one row per product and price, based on the smallest distance.

If you want the data ordered in a different way, then use this as a subquery or CTE and order by again in the outer query.

Body:
I have database for a marketplace which looks like this:

I have different suppliers selling the same product at different price points, also some products are more popular than others in a given location. For example we have product A and product B, and product A is more popular that product B based on how many has already been sold in that location, and for product A we have 3 suppliers. I want my query to show product A from the cheapest seller, then product B from the cheapest seller. I can achieve that with this code:

WITH tem_1 AS (SELECT product_id, MIN(price) AS price FROM product_supplier GROUP BY product_id) ,
     tem_2 AS (SELECT product_id, SUM(quantity) AS n_orders FROM orders Group by product_id)
SELECT products.product_id, suppliers.supplier_id, products.name, tem_1.price,
COALESCE(tem_2.n_orders,0) AS quant FROM products
  INNER JOIN product_supplier ON product_supplier.product_id = products.product_id
  INNER JOIN suppliers ON suppliers.supplier_id = product_supplier.supplier_id
  INNER JOIN product_code ON product_code.code_id = products.code_id
  INNER JOIN product_crop ON product_crop.product_id = products.product_id
  INNER JOIN crops ON crops.crops_id = product_crop.crop_id
  INNER JOIN product_tags ON product_tags.product_id = products.product_id
  INNER JOIN tags ON tags.tag_id = product_tags.tag_id
  INNER JOIN tem_1 ON tem_1.price = product_supplier.price AND tem_1.product_id = products.product_id
  LEFT JOIN tem_2 ON tem_2.product_id = products.product_id
WHERE crops.crops_id = 1 AND product_supplier.quantity >= 3 AND tags.tag = 'علف کش'
ORDER BY quant DESC
LIMIT 10;

The problem is, if i have two different suppliers from different locations, selling the same product with the same price, the results show that product twice, but i only want the results from the closest supplier to the user, in this case product 101 from supplier 3 and not the supplier 1.

I think i have to use MIN(ST_Distance("geopoint from user", "geopoint from suppliers")) and LATERAL to have a distance filed, but because i'm using aggregate functions, in order to do a GROUP BY to remove the duplicate results, i have to add all the fields product_id, supplier_id, name, price, ... to the GROUP BY and that won't result in removing the duplicates.

Any suggestion on how to achieve that?

Body:
Your query is rather hard to follow.  But, distinct on solves your problem.  I'm not 100% sure what you want to be distinct, but something like this:

select distinct on (product_id, price) . . .
from . . .
where . . .
order by product_id, price, ST_Distance("geopoint from user", "geopoint from suppliers");

This returns one row per product and price, based on the smallest distance.

If you want the data ordered in a different way, then use this as a subquery or CTE and order by again in the outer query.


问:
Python: Removing list element while iterating over list
I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

```<code>for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list
</code>```

What should I use in place of remove_element?
I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

答:
You can make a generator that returns everything that isn't removed:</p>

```<code>def newlist(somelist):
    for element in somelist:
        do_action(element)
        if not check(element):
            yield element
</code>```

Body:
I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list

What should I use in place of remove_element?
I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

Body:
You can make a generator that returns everything that isn't removed:

def newlist(somelist):
    for element in somelist:
        do_action(element)
        if not check(element):
            yield element


问:
How do I properly use strcat for char array?
I'm trying to concatenate another string onto arg[0].

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

int main() {

    char* arg[] = {
        "Hello",
        NULL,
        NULL,
        NULL
    };

    strcat(arg[0], " World");

}
</code>```

This returns abort trap.

What am I doing wrong?

答:
One of the shortcomings of C strings is that you need to know how big they will be ahead of time.

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

int main() {
    char arg[1024] = "Hello";
    strcat(arg, " World");
    printf("%s\n", arg);
}
</code>```

In this case, the size of the concatenated string must be less than 1024 characters. This is why it is safer to use something like C++, where you have std::string to prevent these types of issues.

Body:
I'm trying to concatenate another string onto arg[0].

#include <stdio.h>
#include <string.h>

int main() {

    char* arg[] = {
        "Hello",
        NULL,
        NULL,
        NULL
    };

    strcat(arg[0], " World");

}

This returns abort trap.

What am I doing wrong?

Body:
One of the shortcomings of C strings is that you need to know how big they will be ahead of time.

#include <stdio.h>
#include <string.h>

int main() {
    char arg[1024] = "Hello";
    strcat(arg, " World");
    printf("%s\n", arg);
}

In this case, the size of the concatenated string must be less than 1024 characters. This is why it is safer to use something like C++, where you have std::string to prevent these types of issues.


问:
How to update multiple rows using more than one CASE statement in SQL Server?
How can I use more than one CASE to update my rows in my table? I've been trying to write the script in different ways, but I'm sure the syntax is wrong. Any idea where the error is?

```<code>UPDATE NameToSplit
SET Aliases = CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 4 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 5, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 5 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 6, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 6 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 7, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 7 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 8, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 8 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 9, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 9 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 10, 0, '-')END;
</code>```

The results must be like:

```<code>        Names                              Alias                  Aliases
    -------------------------------------------------------------------------
    idealink.core.usergroup            core.usergroup         core.user-group
    idealink.core.userloginhistory     core.userloginhistory  core.user-loginhistory
   idealink.core.challengecategories   core.challengecategories core.challenge-categories
   idealink.core.activitydetails       core.activitydetails    core.activity-details
</code>```

The length of the words after (core.) are different that's why I needed to create different cases to get all of them.

答:
Don't think you will be able to produce the result you want with a case.
Since the length off the world is not enough how will you know when to split with just the length better to use a string comparaison.

```<code> UPDATE NameToSplit
    SET Aliases = CASE
                     WHEN  ALIAS LIKE 'core.user%'
                        THEN STUFF(Alias, CHARINDEX('.', Alias) + 5, 0, '-')
                    WHEN ALIAS LIKE 'core.challenge%'
                        THEN STUFF(Alias, CHARINDEX('.', Alias) + 10, 0, '-')
                WHEN  ALIAS LIKE 'core.idea%'
                        THEN STUFF(Alias, CHARINDEX('.', Alias) + 5, 0, '-')
                 -- .....
                 WHEN ALIAS LIKE 'core.%'
                 THEN ALIAS --keep it at the end
                 END
</code>```

If the Alias is only "core.user" then the ELSE will do is work and Aliases = alias

Body:
How can I use more than one CASE to update my rows in my table? I've been trying to write the script in different ways, but I'm sure the syntax is wrong. Any idea where the error is?

UPDATE NameToSplit
SET Aliases = CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 4 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 5, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 5 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 6, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 6 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 7, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 7 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 8, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 8 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 9, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 9 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 10, 0, '-')END;

The results must be like:

        Names                              Alias                  Aliases
    -------------------------------------------------------------------------
    idealink.core.usergroup            core.usergroup         core.user-group
    idealink.core.userloginhistory     core.userloginhistory  core.user-loginhistory
   idealink.core.challengecategories   core.challengecategories core.challenge-categories
   idealink.core.activitydetails       core.activitydetails    core.activity-details

The length of the words after (core.) are different that's why I needed to create different cases to get all of them.

Body:
Don't think you will be able to produce the result you want with a case.
Since the length off the world is not enough how will you know when to split with just the length better to use a string comparaison.

 UPDATE NameToSplit
    SET Aliases = CASE
                     WHEN  ALIAS LIKE 'core.user%'
                        THEN STUFF(Alias, CHARINDEX('.', Alias) + 5, 0, '-')
                    WHEN ALIAS LIKE 'core.challenge%'
                        THEN STUFF(Alias, CHARINDEX('.', Alias) + 10, 0, '-')
                WHEN  ALIAS LIKE 'core.idea%'
                        THEN STUFF(Alias, CHARINDEX('.', Alias) + 5, 0, '-')
                 -- .....
                 WHEN ALIAS LIKE 'core.%'
                 THEN ALIAS --keep it at the end
                 END

If the Alias is only "core.user" then the ELSE will do is work and Aliases = alias