问:
Get the rank of each string extracted from split_string
I have a TABLE with STR DNA DATA the following Table [DYS]

Id
DYS385

3
10-19

4
13-16

5
13-18

6
13-19

7
13-17

8
13-18

9
13-18

10
14-19

11
13-19

12
13-18

I am USING the following script to split the values of [DYS385]

```<code>select top 10 id,[DYS385],t.Value
from dys
OUTER APPLY(select * from string_split([DYS385],'-')) t
where dys385 is not null
</code>```

Output

Id
DYS385
VALUE

3
10-19
10

3
10-19
19

4
13-16
13

4
13-16
16

5
13-18
13

5
13-18
18

6
13-19
13

6
13-19
19

7
13-17
13

7
13-17
17

I want to get for each Value, the Rank
example
10-19 => 10: Rank 1, 19: Rank 2

Desired results:

Id
DYS385
VALUE
RANK

3
10-19
10
1

3
10-19
19
2

4
13-16
13
1

4
13-16
16
2

5
13-18
13
1

5
13-18
18
2

6
13-19
13
1

6
13-19
19
2

7
13-17
13
1

7
13-17
17
2

答:
We can also make recursive split_string function which returns the rank of each item as follows
Link dbfiddle

```<code>Create function Split_Recursive(@string nvarchar(max),@delimiter as varchar(1)) returns Table
as
return(
with cte as(
select 1 N,
case when charindex(@delimiter,@string,1) =0 then @string else
substring(@string,1,-1+charindex(@delimiter,@string,1)) end [Found],
case when charindex(@delimiter,@string,1)=0 then @string else substring(@string,1+charindex(@delimiter,@string,1) ,len(@string))
end [MYSTRING]
union all
select 1+n,
case when charindex(@delimiter,[MYSTRING],1)=0 then [MYSTRING] else
substring([MYSTRING],1,-1+charindex(@delimiter,[MYSTRING],1)) end,substring([MYSTRING],1+charindex(@delimiter,[MYSTRING]),len([MYSTRING])) from cte
where charindex(@delimiter,[MYSTRING],1)>0),
cte2 as (select N,Found from cte
union select 1+t.N,Mystring from cte OUTER APPLY(select top 1 N from cte order by n desc)t where t.n=cte.n
)
select N Rank,Found from cte2
)

go

select * from dbo.Split_Recursive('12-16','-')
</code>```

Output

Rank
Found

1
12

2
16

Body:
I have a TABLE with STR DNA DATA the following Table [DYS]

Id
DYS385

3
10-19

4
13-16

5
13-18

6
13-19

7
13-17

8
13-18

9
13-18

10
14-19

11
13-19

12
13-18

I am USING the following script to split the values of [DYS385]

select top 10 id,[DYS385],t.Value
from dys
OUTER APPLY(select * from string_split([DYS385],'-')) t
where dys385 is not null

Output

Id
DYS385
VALUE

3
10-19
10

3
10-19
19

4
13-16
13

4
13-16
16

5
13-18
13

5
13-18
18

6
13-19
13

6
13-19
19

7
13-17
13

7
13-17
17

I want to get for each Value, the Rank
example
10-19 => 10: Rank 1, 19: Rank 2

Desired results:

Id
DYS385
VALUE
RANK

3
10-19
10
1

3
10-19
19
2

4
13-16
13
1

4
13-16
16
2

5
13-18
13
1

5
13-18
18
2

6
13-19
13
1

6
13-19
19
2

7
13-17
13
1

7
13-17
17
2

Body:
We can also make recursive split_string function which returns the rank of each item as follows
Link dbfiddle

Create function Split_Recursive(@string nvarchar(max),@delimiter as varchar(1)) returns Table
as
return(
with cte as(
select 1 N,
case when charindex(@delimiter,@string,1) =0 then @string else
substring(@string,1,-1+charindex(@delimiter,@string,1)) end [Found],
case when charindex(@delimiter,@string,1)=0 then @string else substring(@string,1+charindex(@delimiter,@string,1) ,len(@string))
end [MYSTRING]
union all
select 1+n,
case when charindex(@delimiter,[MYSTRING],1)=0 then [MYSTRING] else
substring([MYSTRING],1,-1+charindex(@delimiter,[MYSTRING],1)) end,substring([MYSTRING],1+charindex(@delimiter,[MYSTRING]),len([MYSTRING])) from cte
where charindex(@delimiter,[MYSTRING],1)>0),
cte2 as (select N,Found from cte
union select 1+t.N,Mystring from cte OUTER APPLY(select top 1 N from cte order by n desc)t where t.n=cte.n
)
select N Rank,Found from cte2
)

go

select * from dbo.Split_Recursive('12-16','-')

Output

Rank
Found

1
12

2
16


来源: stackexchange

问:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure ,about mybatis
I'm using java's mybatis,I've implemented interface IBaseBusinessQuery, maping file set method -> T findOne(K var1).

I suspect the reason for the name of the variable,so,I rewrote this method -> @Override T_Permission findOne(String key);,but,the result is so.

implemented interface

```<code>public interface IBaseBusinessQuery<T, K> {
    T findOne(K var1);

    List<T> findAll();
}
</code>```

dao layer

```<code>@Repository("permissionDao")
public interface PermissionDao extends IBaseDao<T_Permission, String>, IBaseBusinessQuery<T_Permission,String> {
}
</code>```

dao layer After modification

```<code>
@Repository("permissionDao")
public interface PermissionDao extends IBaseDao<T_Permission, String>, IBaseBusinessQuery<T_Permission,String> {

    @Override
    T_Permission findOne(String key);
}

</code>```

mybatis mapping file

```<code>  <select id="findOne" resultType="T_Permission">
        select * from t_permission where `ps_id` = #{key}
    </select>
</code>```

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 6,464 milliseconds ago.  The last packet sent successfully to the server was 22 milliseconds ago.

答: The database version maybe have the influence. For me, when mysql version is 5.1.14, the error is like yours. But I change the mysql verison to 8.0.17, and all the problems solved!</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm using java's mybatis,I've implemented interface IBaseBusinessQuery, maping file set method -> T findOne(K var1).

I suspect the reason for the name of the variable,so,I rewrote this method -> @Override T_Permission findOne(String key);,but,the result is so.

implemented interface

public interface IBaseBusinessQuery<T, K> {
    T findOne(K var1);

    List<T> findAll();
}

dao layer

@Repository("permissionDao")
public interface PermissionDao extends IBaseDao<T_Permission, String>, IBaseBusinessQuery<T_Permission,String> {
}

dao layer After modification

@Repository("permissionDao")
public interface PermissionDao extends IBaseDao<T_Permission, String>, IBaseBusinessQuery<T_Permission,String> {

    @Override
    T_Permission findOne(String key);
}

mybatis mapping file

  <select id="findOne" resultType="T_Permission">
        select * from t_permission where `ps_id` = #{key}
    </select>

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 6,464 milliseconds ago.  The last packet sent successfully to the server was 22 milliseconds ago.


问:
Trying to compile a .h file without understanding something
I'm trying to compile Opengazer (Open source gaze tracker) code with visual studio on windows, while  the code was originally written for linux and should be compile with cmake.

Anyway, I can't compile few files.

The code won't compile is this:

Containers.h:

```<code>#pragma once

#define xforeachactive(iter,container) \
    for(typeof(container.begin()) iter = container.begin(); \
    iter != container.end(); iter++)            \
    if ((*iter)->parent == this)

template <class ParentType, class ChildType> class Container;

template <class ParentType, class ChildType>
class  Containee {
 protected:
    void detach() { parent = 0; }
 public:
    ParentType *parent;     /* set to null to request removal */
    Containee(): parent(0) {}
    virtual ~Containee() {}
};

template <class ParentType, class ChildType>
class Container {
    typedef ChildType *ChildPtr;
    static bool isFinished(const ChildPtr &object) {
    return !(object && object->parent);
    }
 protected:
    std::vector<ChildPtr> objects;

    void removeFinished() {
    objects.erase(remove_if(objects.begin(), objects.end(), isFinished),
              objects.end());
    }

 public:
    void clear() {
    xforeachactive(iter, objects)
        (*iter)->parent = 0;
    removeFinished();
    }

    static void addchild(ParentType *parent, const ChildPtr &child) {
    parent->objects.push_back(child);
    child->parent = parent;
    parent->removeFinished();
    }

    virtual ~Container() {
    clear();
    }
};

template <class ParentPtr, class ChildPtr>
class ProcessContainer: public Container<ParentPtr, ChildPtr> {
 public:
    virtual void process() {
    xforeachactive(iter, this->objects)
        (*iter)->process();
    this->removeFinished();
    }
    virtual ~ProcessContainer() {};
};
</code>```

btw Containers.cpp is empty

ad the code uses the above class is:

```<code>#pragma once

class FrameProcessing;

class FrameFunction:
public Containee<FrameProcessing, FrameFunction>
{
    const int &frameno;
    int startframe;
 protected:
    int getFrame() { return frameno - startframe; }
public:
    FrameFunction(const int &frameno): frameno(frameno), startframe(frameno) {}
    virtual void process()=0;
    virtual ~FrameFunction();
};

class FrameProcessing:
public ProcessContainer<FrameProcessing,FrameFunction> {};

class MovingTarget: public FrameFunction {
    WindowPointer *pointer;
 public:
    MovingTarget(const int &frameno,
         const vector<Point>& points,
         WindowPointer *&pointer,
         int dwelltime=20);
    virtual ~MovingTarget();
    virtual void process();
 protected:
    vector<Point> points;
    const int dwelltime;
    int getPointNo();
    int getPointFrame();
    bool active();
};

class CalibrationHandler
{
public:
    CalibrationHandler(void);
    ~CalibrationHandler(void);
};
</code>```

the error I get is :

```<code>visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2146: syntax error : missing ';' before identifier 'iter'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2146: syntax error : missing ')' before identifier 'iter'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2059: syntax error : ';'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2059: syntax error : ')'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2143: syntax error : missing ';' before 'if'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2227: left of '->parent' must point to class/struct/union/generic type
        type is ''unknown-type''
visual studio 2008\projects\eyemouse\eyemouse\containers.h(59) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(59) : error C2227: left of '->process' must point to class/struct/union/generic type
        type is ''unknown-type''
</code>```

I understand why I'm getting an error.
'iter' is not defined anywhere. anyway, this isnt my code and it should work.
I tried to copy and past the define part to the function, but still get the same error.
I'm stuck with this and trying to solve it for hours, but can't understand what to do to make it work.

I'll really be grateful for any help.

答:
typeof is a gcc extension and equivalent to C++0x decltype there is no VS version that actually supports it.

You would need to use C++0x and decltype or try to use Boost.TypeOf, which comes with its own caveats.

Change the macro to this:

```<code>#include <boost/typeof/typeof.hpp>

#define xforeachactive(iter,container) \
    for(BOOST_TYPEOF(container.begin()) iter = container.begin(); \
    iter != container.end(); iter++)            \
    if ((*iter)->parent == this)
</code>```

You could also use BOOST_AUTO if you think this is clearer.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to compile Opengazer (Open source gaze tracker) code with visual studio on windows, while  the code was originally written for linux and should be compile with cmake.

Anyway, I can't compile few files.

The code won't compile is this:

Containers.h:

#pragma once

#define xforeachactive(iter,container) \
    for(typeof(container.begin()) iter = container.begin(); \
    iter != container.end(); iter++)            \
    if ((*iter)->parent == this)

template <class ParentType, class ChildType> class Container;

template <class ParentType, class ChildType>
class  Containee {
 protected:
    void detach() { parent = 0; }
 public:
    ParentType *parent;     /* set to null to request removal */
    Containee(): parent(0) {}
    virtual ~Containee() {}
};

template <class ParentType, class ChildType>
class Container {
    typedef ChildType *ChildPtr;
    static bool isFinished(const ChildPtr &object) {
    return !(object && object->parent);
    }
 protected:
    std::vector<ChildPtr> objects;

    void removeFinished() {
    objects.erase(remove_if(objects.begin(), objects.end(), isFinished),
              objects.end());
    }

 public:
    void clear() {
    xforeachactive(iter, objects)
        (*iter)->parent = 0;
    removeFinished();
    }

    static void addchild(ParentType *parent, const ChildPtr &child) {
    parent->objects.push_back(child);
    child->parent = parent;
    parent->removeFinished();
    }

    virtual ~Container() {
    clear();
    }
};

template <class ParentPtr, class ChildPtr>
class ProcessContainer: public Container<ParentPtr, ChildPtr> {
 public:
    virtual void process() {
    xforeachactive(iter, this->objects)
        (*iter)->process();
    this->removeFinished();
    }
    virtual ~ProcessContainer() {};
};

btw Containers.cpp is empty

ad the code uses the above class is:

#pragma once

class FrameProcessing;

class FrameFunction:
public Containee<FrameProcessing, FrameFunction>
{
    const int &frameno;
    int startframe;
 protected:
    int getFrame() { return frameno - startframe; }
public:
    FrameFunction(const int &frameno): frameno(frameno), startframe(frameno) {}
    virtual void process()=0;
    virtual ~FrameFunction();
};

class FrameProcessing:
public ProcessContainer<FrameProcessing,FrameFunction> {};

class MovingTarget: public FrameFunction {
    WindowPointer *pointer;
 public:
    MovingTarget(const int &frameno,
         const vector<Point>& points,
         WindowPointer *&pointer,
         int dwelltime=20);
    virtual ~MovingTarget();
    virtual void process();
 protected:
    vector<Point> points;
    const int dwelltime;
    int getPointNo();
    int getPointFrame();
    bool active();
};

class CalibrationHandler
{
public:
    CalibrationHandler(void);
    ~CalibrationHandler(void);
};

the error I get is :

visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2146: syntax error : missing ';' before identifier 'iter'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2146: syntax error : missing ')' before identifier 'iter'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2059: syntax error : ';'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2059: syntax error : ')'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2143: syntax error : missing ';' before 'if'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2227: left of '->parent' must point to class/struct/union/generic type
        type is ''unknown-type''
visual studio 2008\projects\eyemouse\eyemouse\containers.h(59) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(59) : error C2227: left of '->process' must point to class/struct/union/generic type
        type is ''unknown-type''

I understand why I'm getting an error.
'iter' is not defined anywhere. anyway, this isnt my code and it should work.
I tried to copy and past the define part to the function, but still get the same error.
I'm stuck with this and trying to solve it for hours, but can't understand what to do to make it work.

I'll really be grateful for any help.

Body:
typeof is a gcc extension and equivalent to C++0x decltype there is no VS version that actually supports it.

You would need to use C++0x and decltype or try to use Boost.TypeOf, which comes with its own caveats.

Change the macro to this:

#include <boost/typeof/typeof.hpp>

#define xforeachactive(iter,container) \
    for(BOOST_TYPEOF(container.begin()) iter = container.begin(); \
    iter != container.end(); iter++)            \
    if ((*iter)->parent == this)

You could also use BOOST_AUTO if you think this is clearer.


问:
Split cells themselves (not the data in them) into several columns
Suppose I have numbers from 1 to 1000 in column A. How do I split this column into 10 different columns ?
Column A would be 1 to 100, column B would be 101 to 200; etc.
Thanks in advance and sorry about my rusty english, not my native language.</p>

答:
Assuming that what you actually want to do is take everything in A1:A1000 and break it into 10 columns, you can do it with an INDEX and multiplexed indexation to reshape it, but, as a lazy alternative, here is a general purpose reshaper that I made. It has a lot of overhead as a protection for error handling as well as some hooks for re-ordering, but it will do what you want.

With Office 365:

```<code>=LET( Matrix, A1:A1000,
      newRows, ,
      newCols, 10,

       rdR, ROWS( Matrix ),
       rdC, COLUMNS( Matrix ),
       rdCells, rdR * rdC,
       rdIR, SEQUENCE( 1, rdCells, 0 ),
       wrR, IF( newRows > 0, newRows,
                      IF( newCols > 0, ROUNDUP( rdCells/newCols, 0), rdR ) ),
       wrC, IF( newCols = 0, ROUNDUP( rdCells/wrR, 0), newCols ),
       wrCells, wrR * wrC,
       wrIR, SEQUENCE( wrR, wrC, 0 ),
       mux, INDEX( Matrix, rdIR/rdC + 1, MOD( rdIR, rdC ) + 1 ),
       demux, INDEX( mux, wrIR/wrCells +  1, wrIR + MOD( wrIR, wrC)*(wrR - 1) - INT( wrIR/wrC ) * (wrC - 1) ),
       demux
     )
</code>```

I put in the wrong write order - fixed now

12 Feb : I found one more error and it is fixed now

You can enter whatever number of rows you want in newRows and whatever number of columns you want in newCols. If you leave either blank, it calculates the other.

Body:
Assuming that what you actually want to do is take everything in A1:A1000 and break it into 10 columns, you can do it with an INDEX and multiplexed indexation to reshape it, but, as a lazy alternative, here is a general purpose reshaper that I made. It has a lot of overhead as a protection for error handling as well as some hooks for re-ordering, but it will do what you want.

With Office 365:

=LET( Matrix, A1:A1000,
      newRows, ,
      newCols, 10,

       rdR, ROWS( Matrix ),
       rdC, COLUMNS( Matrix ),
       rdCells, rdR * rdC,
       rdIR, SEQUENCE( 1, rdCells, 0 ),
       wrR, IF( newRows > 0, newRows,
                      IF( newCols > 0, ROUNDUP( rdCells/newCols, 0), rdR ) ),
       wrC, IF( newCols = 0, ROUNDUP( rdCells/wrR, 0), newCols ),
       wrCells, wrR * wrC,
       wrIR, SEQUENCE( wrR, wrC, 0 ),
       mux, INDEX( Matrix, rdIR/rdC + 1, MOD( rdIR, rdC ) + 1 ),
       demux, INDEX( mux, wrIR/wrCells +  1, wrIR + MOD( wrIR, wrC)*(wrR - 1) - INT( wrIR/wrC ) * (wrC - 1) ),
       demux
     )

I put in the wrong write order - fixed now

12 Feb : I found one more error and it is fixed now

You can enter whatever number of rows you want in newRows and whatever number of columns you want in newCols. If you leave either blank, it calculates the other.


问:
How can I create a task function can delay and output in different order in JavaScript
Define a task function and the output after execution is as follows

```<code>task('james')
// james starts work
task('james').waitFirst(5).do('push')
// wait 5s, james do push, james starts work
task('james').wait(5).do('commit')
// james starts work, wait 5s, james do commit
</code>```

I have no idea how to create such a wait function, does anyone can help me about that or give me some ideas.

答:
Here is my solution with a little annoying .end() call after every task() call.

function task(name) {
  const register = {};

  const preventCallAfter = (methodName) => {
    if (methodName in register)
      throw new Error(`You cannot use "wait" and "waitFirst" together.`);
  };

  return {
    wait(seconds) {
      preventCallAfter("waitFirst");
      register.wait = seconds;
      return this;
    },
    waitFirst(seconds) {
      preventCallAfter("wait");
      register.waitFirst = seconds;
      return this;
    },
    do(workName) {
      if ("workName" in register)
        throw new Error(`The .do() method is already called.`);

      register.workName = workName;
      return this;
    },
    end() {
      if ("wait" in register) {
        console.log(`${name} starts work.`);
        console.log(`wait ${register.wait} seconds.`);
        setTimeout(
          () => console.log(`${name} do ${register.workName}`),
          register.wait * 1000
        );
      } else if ("waitFirst" in register) {
        console.log(`wait ${register.waitFirst} seconds.`);

        setTimeout(() => {
          console.log(`${name} do ${register.workName}`);
          console.log(`${name} starts work.`);
        }, register.waitFirst * 1000);
      } else console.log(`${name} starts work.`);
    },
  };
}

// task("james").end();
// james starts work
// task("james").waitFirst(5).do("push").end();
// wait 5s, chenlee do push, james starts work
task("james").wait(5).do("commit").end();
// james starts work, wait 5s, james do commit```

Body:
Define a task function and the output after execution is as follows

task('james')
// james starts work
task('james').waitFirst(5).do('push')
// wait 5s, james do push, james starts work
task('james').wait(5).do('commit')
// james starts work, wait 5s, james do commit

I have no idea how to create such a wait function, does anyone can help me about that or give me some ideas.


问:
Merging PHP Arrays
I have multiple associative arrays that I want to merge if all values except startdate are the same. If two arrays are indeed the same, I want to merge them and create a new element enddate so that startdate and enddate show the date range. All dates within the range must be represented in the original arrays, i.e. if a date is missing, the dates on either side of it must not be merged.

```<code>Array('color'=>'red','size'=>'large','shape'=>'circle','startdate'=>'2011-08-17')
Array('color'=>'red','size'=>'large','shape'=>'circle','startdate'=>'2011-08-18')
Array('color'=>'red','size'=>'large','shape'=>'square','startdate'=>'2011-08-20')
</code>```

should become:

```<code>Array('color'=>'red','size'=>'large','shape'=>'circle','startdate'=>'2011-08-17','enddate'=>'2011-08-18')
Array('color'=>'red','size'=>'large','shape'=>'square','startdate'=>'2011-08-20')
</code>```

So far I have tried looping through each array and creating a multidimensional array:

```<code>foreach($arrays as $id => $array){
    $mergearray[$array['red']][$array['large']][$array['circle']] = $id;
};
</code>```

in order to check whether another array has the same values. I'm trying to use those arrays to reconstruct arrays in the original structure.

答:
Something like this should do the trick:</p>

```<code>$newArray = array();
$newLine = false;
$prev_day = false;
foreach ($array as $line) {
    $this_day = strtotime($line['startdate']);
    if (($newLine) && ($prev_day == strtotime('-1 day', $this_day))) {
        $newLine['enddate'] = $line['startdate'];
        $newArray[] = $newLine;
        $newLine = false;
    } elseif (!$newLine) {
        $newLine = $line;
    }
    if ($newLine) {
        $newLine['enddate'] = $line['startdate'];
    }
    $prev_day = $this_day;
}
$newArray[] = $newLine;
</code>```

Title: Merging PHP Arrays

Body:
I have multiple associative arrays that I want to merge if all values except startdate are the same. If two arrays are indeed the same, I want to merge them and create a new element enddate so that startdate and enddate show the date range. All dates within the range must be represented in the original arrays, i.e. if a date is missing, the dates on either side of it must not be merged.

Array('color'=>'red','size'=>'large','shape'=>'circle','startdate'=>'2011-08-17')
Array('color'=>'red','size'=>'large','shape'=>'circle','startdate'=>'2011-08-18')
Array('color'=>'red','size'=>'large','shape'=>'square','startdate'=>'2011-08-20')

should become:

Array('color'=>'red','size'=>'large','shape'=>'circle','startdate'=>'2011-08-17','enddate'=>'2011-08-18')
Array('color'=>'red','size'=>'large','shape'=>'square','startdate'=>'2011-08-20')

So far I have tried looping through each array and creating a multidimensional array:

foreach($arrays as $id => $array){
    $mergearray[$array['red']][$array['large']][$array['circle']] = $id;
};

in order to check whether another array has the same values. I'm trying to use those arrays to reconstruct arrays in the original structure.

Body:
Something like this should do the trick:

$newArray = array();
$newLine = false;
$prev_day = false;
foreach ($array as $line) {
    $this_day = strtotime($line['startdate']);
    if (($newLine) && ($prev_day == strtotime('-1 day', $this_day))) {
        $newLine['enddate'] = $line['startdate'];
        $newArray[] = $newLine;
        $newLine = false;
    } elseif (!$newLine) {
        $newLine = $line;
    }
    if ($newLine) {
        $newLine['enddate'] = $line['startdate'];
    }
    $prev_day = $this_day;
}
$newArray[] = $newLine;


问:
I have problem with deploying Sanity studio on Netlify
it maybe silly questions to someone here but I have nowhere to ask so I came here.
I deployed my portfolio page with Sanity & Gatsby Starter.
It works okay → https://lovethis.one.
deploy status
The website is deployed perfectly but Studio keeps failing when I try to deploy.

On netlify it says it's failing because

```<code>$ npm run build-studio && cp studio/netlify.toml studio/dist
12:52:01 AM: > sanity-gatsby-portfolio@0.0.0 build-studio
12:52:01 AM: > (cd studio && npm run build)
12:52:01 AM: > sanity-gatsby-portfolio-studio@1.0.6 build
12:52:01 AM: > sanity build
12:52:01 AM: sh: 1: sanity: not found
12:52:01 AM:
12:52:01 AM: ────────────────────────────────────────────────────────────────
12:52:01 AM:   "build.command" failed
12:52:01 AM: ────────────────────────────────────────────────────────────────
12:52:01 AM:
12:52:01 AM:   Error message
12:52:01 AM:   Command failed with exit code 127: npm run build-studio && cp studio/netlify.toml studio/dist
12:52:01 AM:
12:52:01 AM:   Error location
12:52:01 AM:   In Build command from Netlify app:
12:52:01 AM:   npm run build-studio && cp studio/netlify.toml studio/dist
12:52:01 AM:
12:52:01 AM:   Resolved config
12:52:01 AM:   build:
12:52:01 AM:     base: /opt/build/repo
12:52:01 AM:     command: npm run build-studio && cp studio/netlify.toml studio/dist
12:52:01 AM:     commandOrigin: ui
12:52:01 AM:     environment:
12:52:01 AM:       - INCOMING_HOOK_BODY
12:52:01 AM:       - INCOMING_HOOK_TITLE
12:52:01 AM:       - INCOMING_HOOK_URL
12:52:01 AM:     publish: /opt/build/repo/studio/dist
12:52:01 AM:     publishOrigin: ui
</code>```

I am quite newbie here and hope I can find answer.
Also I am wondering why my studio shows the blank area like this.
blank area on dashboard
On the content side, it the name of the project is sample project I also wish to change.
sample project not project
Thank you in advance for your help!
If I broke any rules here, I will try to edit or fix the content.
Thank you for understanding.

答: It looks like the Sanity CLI isn't installed so when the script tries to run the sanity build command, it fails. Could you run npm install @sanity/cli (note—not globally) in your studio folder, then try pushing/deploying once again?

Body:
it maybe silly questions to someone here but I have nowhere to ask so I came here.
I deployed my portfolio page with Sanity & Gatsby Starter.
It works okay → https://lovethis.one.
deploy status
The website is deployed perfectly but Studio keeps failing when I try to deploy.

On netlify it says it's failing because

$ npm run build-studio && cp studio/netlify.toml studio/dist
12:52:01 AM: > sanity-gatsby-portfolio@0.0.0 build-studio
12:52:01 AM: > (cd studio && npm run build)
12:52:01 AM: > sanity-gatsby-portfolio-studio@1.0.6 build
12:52:01 AM: > sanity build
12:52:01 AM: sh: 1: sanity: not found
12:52:01 AM:
12:52:01 AM: ────────────────────────────────────────────────────────────────
12:52:01 AM:   "build.command" failed
12:52:01 AM: ────────────────────────────────────────────────────────────────
12:52:01 AM:
12:52:01 AM:   Error message
12:52:01 AM:   Command failed with exit code 127: npm run build-studio && cp studio/netlify.toml studio/dist
12:52:01 AM:
12:52:01 AM:   Error location
12:52:01 AM:   In Build command from Netlify app:
12:52:01 AM:   npm run build-studio && cp studio/netlify.toml studio/dist
12:52:01 AM:
12:52:01 AM:   Resolved config
12:52:01 AM:   build:
12:52:01 AM:     base: /opt/build/repo
12:52:01 AM:     command: npm run build-studio && cp studio/netlify.toml studio/dist
12:52:01 AM:     commandOrigin: ui
12:52:01 AM:     environment:
12:52:01 AM:       - INCOMING_HOOK_BODY
12:52:01 AM:       - INCOMING_HOOK_TITLE
12:52:01 AM:       - INCOMING_HOOK_URL
12:52:01 AM:     publish: /opt/build/repo/studio/dist
12:52:01 AM:     publishOrigin: ui

I am quite newbie here and hope I can find answer.
Also I am wondering why my studio shows the blank area like this.
blank area on dashboard
On the content side, it the name of the project is sample project I also wish to change.
sample project not project
Thank you in advance for your help!
If I broke any rules here, I will try to edit or fix the content.
Thank you for understanding.


问:
Compare headers of dataframes and add the columns to the delta table
There are two  dataframes

df1 ---> OrgID, location, Address, State -- which is delta table

df2 ---> OrgID, location, Address, State, Active, Seq_Number -- which is createOrReplaceTempViewtable

In df2 there are two additional columns Active, Seq_Number.

How to get the datatypes of the new columns

How to add the new columns to the existing Delta table and update the values

tried the below:

converted the dataframes to pandaDF and used this, which got new columns in the Index object.

```<code>df_new_columns = df1.columns.difference(df2.columns)
</code>```
```<code>new = [ ]

if len(df_new_columns.tolist()) != 0:

for column in df_new_columns.tolist():
    column_name = column
    new.append(column)
</code>```

答:
If you do not want to name any of the duplicate tables when join the missing one from your original table, you can do the following thing:

```<code>import pandas as pd

a = [{'A': 3, 'B': 5, 'C': 3, 'D': 2},{'A': 2,  'B': 4, 'C': 3, 'D': 9}]
df1 = pd.DataFrame(a)
b = [{'F': 0,  'M': 4,  'B': 2,  'C': 8 },{'F': 2,  'M': 4, 'B': 3, 'C': 9}]
df2 = pd.DataFrame(b)

df_delta = df2.columns.difference(df1.columns)

print(pd.concat([df1,df2]).T.drop_duplicates().T)
</code>```

which gives:

```<code> A    B    C    D    F    M
0  3.0  5.0  3.0  2.0  NaN  NaN
1  2.0  4.0  3.0  9.0  NaN  NaN
0  NaN  2.0  8.0  NaN  0.0  4.0
1  NaN  3.0  9.0  NaN  2.0  4.0
</code>```

and

```<code>Index(['F', 'M'], dtype='object')
</code>```

Body:
There are two  dataframes

df1 ---> OrgID, location, Address, State -- which is delta table

df2 ---> OrgID, location, Address, State, Active, Seq_Number -- which is createOrReplaceTempViewtable

In df2 there are two additional columns Active, Seq_Number.

How to get the datatypes of the new columns

How to add the new columns to the existing Delta table and update the values

tried the below:

converted the dataframes to pandaDF and used this, which got new columns in the Index object.

df_new_columns = df1.columns.difference(df2.columns)

new = [ ]

if len(df_new_columns.tolist()) != 0:

for column in df_new_columns.tolist():
    column_name = column
    new.append(column)

Body:
If you do not want to name any of the duplicate tables when join the missing one from your original table, you can do the following thing:

import pandas as pd

a = [{'A': 3, 'B': 5, 'C': 3, 'D': 2},{'A': 2,  'B': 4, 'C': 3, 'D': 9}]
df1 = pd.DataFrame(a)
b = [{'F': 0,  'M': 4,  'B': 2,  'C': 8 },{'F': 2,  'M': 4, 'B': 3, 'C': 9}]
df2 = pd.DataFrame(b)

df_delta = df2.columns.difference(df1.columns)

print(pd.concat([df1,df2]).T.drop_duplicates().T)

which gives:

 A    B    C    D    F    M
0  3.0  5.0  3.0  2.0  NaN  NaN
1  2.0  4.0  3.0  9.0  NaN  NaN
0  NaN  2.0  8.0  NaN  0.0  4.0
1  NaN  3.0  9.0  NaN  2.0  4.0

and

Index(['F', 'M'], dtype='object')


Title: Create new column using tidy evaluation on the left and right of mutate in R

Body:
I know there are many questions regarding tidy evaluation in R. However, I couldn't figure out a solution to this seemingly easily problem.

I have this data.frame

structure(list(Date = c("25.02.2020", "26.02.2020", "27.02.2020",
"28.02.2020", "02.03.2020", "03.03.2020", "04.03.2020", "05.03.2020",
"06.03.2020", "09.03.2020", "10.03.2020", "11.03.2020", "12.03.2020",
"13.03.2020", "16.03.2020", "17.03.2020", "18.03.2020", "19.03.2020",
"20.03.2020", "23.03.2020", "24.03.2020", "25.03.2020", "26.03.2020",
"27.03.2020", "30.03.2020", "31.03.2020", "01.04.2020", "02.04.2020",
"03.04.2020", "06.04.2020"), change_AAPL_stocks = c("1", "0,95",
"0,93", "0,85", "0,94", "1,01", "0,99", "0,98", "0,94", "0,88",
"0,92", "0,92", "0,85", "0,88", "0,8", "0,82", "0,8", "0,82",
"0,82", "0,76", "0,79", "0,83", "0,82", "0,84", "0,83", "0,85",
"0,82", "0,8", "0,81", "0,83"), change_AMZN_stocks = c("1", "0,97",
"0,95", "0,9", "0,94", "0,97", "0,96", "0,95", "0,93", "0,88",
"0,92", "0,92", "0,85", "0,87", "0,81", "0,88", "0,86", "0,92",
"0,95", "0,9", "0,96", "0,95", "0,94", "0,95", "0,95", "0,97",
"0,95", "0,94", "0,94", "0,96")), row.names = c(NA, -30L), class = c("tbl_df",
"tbl", "data.frame"))

And I have these variables

date_col = "Date"
date_format = "%d.%m.%Y"
value_col = "change_AAPL_stocks"

And I'd like to write a function that can take arbitrary date_col and date_format values.

The code at the moment looks like this:

  df %>%
    select(date_col, value_col) %>%
    mutate(
      {{date_col}} := as.Date({date_col}, format=date_format)
    )

Which creates (overwrites) the column names Date. However, the as.Date(...) function does not work. I am not entirely sure what to do about that.

Body:
Use sym and unsplice it on the rhs.

df %>%
    select(all_of(date_col)) %>%
    mutate(
        {{date_col}} := as.Date(!!sym(date_col), format=date_format)
    )
# A tibble: 30 x 1
   Date
   <date>
 1 2020-02-25
 2 2020-02-26
 3 2020-02-27
 4 2020-02-28
 5 2020-03-02
 6 2020-03-03
 7 2020-03-04
 8 2020-03-05
 9 2020-03-06
10 2020-03-09
# ... with 20 more rows

You can generalize the function to take symbol or character as input as follows:

f <- function(data, date_col){
    if(rlang::is_symbol(date_col)){
        rhs <- enquo(date_col)
        date_col <- as.character(date_col)
    }else{
        rhs <- sym(date_col)
    }
    data %>%
        select(date_col) %>%
        mutate(
            {{date_col}} := as.Date(!!rhs, format=date_format)
        )
}
df %>%
    f('Date')
# A tibble: 30 x 1
   Date
   <date>
 1 2020-02-25
 2 2020-02-26
 3 2020-02-27
 4 2020-02-28
 5 2020-03-02
 6 2020-03-03
 7 2020-03-04
 8 2020-03-05
 9 2020-03-06
10 2020-03-09
# ... with 20 more rows
df %>%
    f(date_col)
# A tibble: 30 x 1
   Date
   <date>
 1 2020-02-25
 2 2020-02-26
 3 2020-02-27
 4 2020-02-28
 5 2020-03-02
 6 2020-03-03
 7 2020-03-04
 8 2020-03-05
 9 2020-03-06
10 2020-03-09
# ... with 20 more rows


问:
Python encoding issue, Network adapter not recognised
Here is my piece of python code scratch.

```<code> import os
 print 'netsh interface ip set address name="' + adapter + '" static '+ staticaddr +' 255.255.255.0 192.168.1.1'
</code>```

Until this point all is fine the adapter is included within my drivers.

Now when i run this (as an administrator)

```<code> os.system('netsh interface ipv4 set address name="' + adapter + '" static '+ staticaddr +' 255.255.255.0 192.168.1.1')
</code>```

It fires this error:

```<code>La syntaxe du nom de fichier, de répertoire ou de volume est incorrecte.
</code>```

Which means the command's syntax isn't correct.

I tried os.system('netsh interface ipv4 set address name="' + adapter.encode('ascii','ignore') + '" static '+ staticaddr +' 255.255.255.0 192.168.1.1')

Now this kind of exception occurs:

```<code>'ascii' codec can't decode byte 0x82 in position 11: ordinal not in range(128)
</code>```

Where is the problem exactly ?

My network adapter's name is : Connexion réseau sans fil

答:
I've encountered a similar problem in my end.
I have a script that lists all the previously connected wi-fi networks and their passwords. One network specifically ("Gestão TI") was giving me a headache, beacuse when I ran the command, the name came back as "GestÆo TI", and the following command couldn't run, because the name changed.
I tried a few different encodings, such as UTF-8, Latin-1 and others, with no success.
A frind of mine pointed out to me that maybe the problem was with the netsh encoding when it was exporting the names. As the netsh is fairly old, he suggested I tried using the old latin encoding (CP850) and it finally worked...</p>

Body:
Here is my piece of python code scratch.

 import os
 print 'netsh interface ip set address name="' + adapter + '" static '+ staticaddr +' 255.255.255.0 192.168.1.1'

Until this point all is fine the adapter is included within my drivers.

Now when i run this (as an administrator)

 os.system('netsh interface ipv4 set address name="' + adapter + '" static '+ staticaddr +' 255.255.255.0 192.168.1.1')

It fires this error:

La syntaxe du nom de fichier, de répertoire ou de volume est incorrecte.

Which means the command's syntax isn't correct.

I tried os.system('netsh interface ipv4 set address name="' + adapter.encode('ascii','ignore') + '" static '+ staticaddr +' 255.255.255.0 192.168.1.1')

Now this kind of exception occurs:

'ascii' codec can't decode byte 0x82 in position 11: ordinal not in range(128)

Where is the problem exactly ?

My network adapter's name is : Connexion réseau sans fil


问:
Create Pandas dataframe from list which contains dictionary of dictionary
I have a list of dictionaries that each contain dictionary key:value pairs as the value - see below:

```<code>d = [{'line': {'Area Boundary Must Be Covered By Boundary Of': '10', 'Must Be Inside': '55', 'Must Not Have Gaps': '2', 'Must Not Self-Intersect': '2', 'Must Not Self-Overlap': '2'}},
     {'point': {'Must Not Self-Intersect': '3'}},
     {'poly': {'Must Not Overlap': '2'}}]
</code>```

The desired dataframe form would be:

I've been creating test dataframes for a bit, and can't seem to wrangle it to the form above.

Some notes - these errors will be dynamic. Meaning, this script will run at a weekly interval, and as the source data changes, so will the errors. The only constants will be the type geometry (i.e 'line' 'point' and 'poly').

edit:

```<code>d = [{'line': {'Area Boundary Must Be Covered By Boundary Of': '10', 'Must Be Inside': '55', 'Must Not Have Gaps': '2', 'Must Not Self-Intersect': '2', 'Must Not Self-Overlap': '2'}},
         {'point': {'Must Not Self-Intersect': '3'}},
         {'poly': {'Must Not Overlap': '2'}}]
df = pandas.concat([pandas.DataFrame(x) for x in d])
print(df)
</code>```

Produces:

```<code>                                             line point poly
Area Boundary Must Be Covered By Boundary Of   10   NaN  NaN
Must Be Inside                                 55   NaN  NaN
Must Not Have Gaps                              2   NaN  NaN
Must Not Self-Intersect                         2   NaN  NaN
Must Not Self-Overlap                           2   NaN  NaN
Must Not Self-Intersect                       NaN     3  NaN
Must Not Overlap                              NaN   NaN    2
</code>```

This will suffice.

答:
You can create a dataframe for each sub-object, concat them, and then compress the duplicates together with groupby(level=0) (for 0th index level) + sum:

```<code>df = pd.concat([pd.DataFrame(o) for o in objects]).groupby(level=0).sum().T
</code>```

Output:

```<code>>>> df
      Area Boundary Must Be Covered By Boundary Of Must Be Inside Must Not Have Gaps Must Not Overlap Must Not Self-Intersect Must Not Self-Overlap
line                                            10             55                  2                0                       2                     2
point                                            0              0                  0                0                       3                     0
poly                                             0              0                  0                2                       0                     0
</code>```

Body:
I have a list of dictionaries that each contain dictionary key:value pairs as the value - see below:

d = [{'line': {'Area Boundary Must Be Covered By Boundary Of': '10', 'Must Be Inside': '55', 'Must Not Have Gaps': '2', 'Must Not Self-Intersect': '2', 'Must Not Self-Overlap': '2'}},
     {'point': {'Must Not Self-Intersect': '3'}},
     {'poly': {'Must Not Overlap': '2'}}]

The desired dataframe form would be:

I've been creating test dataframes for a bit, and can't seem to wrangle it to the form above.

Some notes - these errors will be dynamic. Meaning, this script will run at a weekly interval, and as the source data changes, so will the errors. The only constants will be the type geometry (i.e 'line' 'point' and 'poly').

edit:

d = [{'line': {'Area Boundary Must Be Covered By Boundary Of': '10', 'Must Be Inside': '55', 'Must Not Have Gaps': '2', 'Must Not Self-Intersect': '2', 'Must Not Self-Overlap': '2'}},
         {'point': {'Must Not Self-Intersect': '3'}},
         {'poly': {'Must Not Overlap': '2'}}]
df = pandas.concat([pandas.DataFrame(x) for x in d])
print(df)

Produces:

                                             line point poly
Area Boundary Must Be Covered By Boundary Of   10   NaN  NaN
Must Be Inside                                 55   NaN  NaN
Must Not Have Gaps                              2   NaN  NaN
Must Not Self-Intersect                         2   NaN  NaN
Must Not Self-Overlap                           2   NaN  NaN
Must Not Self-Intersect                       NaN     3  NaN
Must Not Overlap                              NaN   NaN    2

This will suffice.

Body:
You can create a dataframe for each sub-object, concat them, and then compress the duplicates together with groupby(level=0) (for 0th index level) + sum:

df = pd.concat([pd.DataFrame(o) for o in objects]).groupby(level=0).sum().T

Output:

>>> df
      Area Boundary Must Be Covered By Boundary Of Must Be Inside Must Not Have Gaps Must Not Overlap Must Not Self-Intersect Must Not Self-Overlap
line                                            10             55                  2                0                       2                     2
point                                            0              0                  0                0                       3                     0
poly                                             0              0                  0                2                       0                     0


问:
How to convert a Bitmap to Drawable in android?
How can I convert a Bitmap image to Drawable ?</p>

答:
For Kotlin users:

Kotlin has a function for converting Bitmap to BitmapDrawable:

Bitmap.toDrawable(resources)


问:
python optional caching of function
What's the best way to cache a function in python with an optional caching parameter?

I've a function which performs a database request and does not take any arguments.
Most of the times it's okay if the function uses the cached result but sometimes I want to send a new database request.

from functools import lru_cache

@lru_cache
def my_database_request_function(use_cache: bool = False):

    if use_cache:
    # takes response from cache
    else:
    # makes database request

    return response

```

The implementation above won't work because the second time the functions gets called with the use_cache=False parameter it will not make a new request.

答:
Here's a straightforward approach with helper functions:</p>
```<code>from functools import lru_cache

def my_database_request_function(use_cache: bool = False):
    if use_cache:
        return _my_database_request_function_cached()
    else:
        return _my_database_request_function_fresh()

@lru_cache
def _my_database_request_function_cached():
    return _my_database_request_function_fresh()

def _my_database_request_function_fresh():
    # do actual database request
</code>```

Title: python optional caching of function

Body:
What's the best way to cache a function in python with an optional caching parameter?

I've a function which performs a database request and does not take any arguments.
Most of the times it's okay if the function uses the cached result but sometimes I want to send a new database request.

from functools import lru_cache

@lru_cache
def my_database_request_function(use_cache: bool = False):

    if use_cache:
    # takes response from cache
    else:
    # makes database request

    return response

The implementation above won't work because the second time the functions gets called with the use_cache=False parameter it will not make a new request.

Body:
Here's a straightforward approach with helper functions:

from functools import lru_cache

def my_database_request_function(use_cache: bool = False):
    if use_cache:
        return _my_database_request_function_cached()
    else:
        return _my_database_request_function_fresh()

@lru_cache
def _my_database_request_function_cached():
    return _my_database_request_function_fresh()

def _my_database_request_function_fresh():
    # do actual database request


问:
Trying to relaod api inside command but getting some errors in debug
```<code>@client.command()
async def eth(ctx):
  while True:
    r = requests.request("GET", eth_api, headers=headers)
    data2 = r.json()
    eth_price = data2['data']['rates']['USD']
    await ctx.message.delete()
    await ctx.send(f"The price of ETH is {eth_price}$")
    sleep(0.2)
</code>```
```<code>Ignoring exception in command eth:
Traceback (most recent call last):
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 35, in eth
    await ctx.message.delete()
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/message.py", line 1023, in delete
    await self._state.http.delete_message(self.channel.id, self.id)
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/http.py", line 250, in request
    raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message

</code>```

I am getting this error in debug whenever i use the command but the command is working fine, i think it's because it's trying to delete in a loop that's why, any better way to refresh API's and do it?

答: Your issue is the await ctx.message.delete() line - during the first iteration of the while loop, the original command message will be deleted. This means that it won't be available any longer, and from the second iteration on, trying to delete it again will cause the error you're seeing because the message no longer exists. You can fix this by simply moving the await ctx.message.delete() line outside of the while loop

Body:
@client.command()
async def eth(ctx):
  while True:
    r = requests.request("GET", eth_api, headers=headers)
    data2 = r.json()
    eth_price = data2['data']['rates']['USD']
    await ctx.message.delete()
    await ctx.send(f"The price of ETH is {eth_price}$")
    sleep(0.2)

Ignoring exception in command eth:
Traceback (most recent call last):
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 35, in eth
    await ctx.message.delete()
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/message.py", line 1023, in delete
    await self._state.http.delete_message(self.channel.id, self.id)
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/http.py", line 250, in request
    raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/Elon-Musk/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message

I am getting this error in debug whenever i use the command but the command is working fine, i think it's because it's trying to delete in a loop that's why, any better way to refresh API's and do it?


问:
Select price record if record for a customer exists, otherwise select general price record
Suppose i have the following MySQL prices table:

ID
item
from_date
to_date
customer
price

1
1
2021-10-10
2021-12-14
NULL
103.25

2
1
2021-12-15
NULL
NULL
100.25

3
5
2022-01-01
NULL
NULL
201.50

4
1
2022-01-05
NULL
3
80.75

The idea is that for there will be a price record for each item and if there are special price deals for a customer, also a record for that item with a different price. Looking for the price, the price should be taken from the record that is for the item and that specific customer. if there is none, it should return the default price which is valid for all customers.

So, I am trying to get the price that is valid at today's date (2022-02-02). Having those records selected, if there is a most recent record for my specific customer (3) it takes precedence, return that (record ID 4). If there is none for this customer, return the most recent price (record ID 2)

So, today = 2022-02-02, my item is 1 AND my customer is 3. Using the table above the result should be:

ID
item
from_date
to_date
customer
price

4
1
2022-01-05
NULL
3
80.75

If the record with ID = 4 is not there the result should be:

ID
item
from_date
to_date
customer
price

2
1
2021-12-15
NULL
NULL
100.25

I tried several select queries but still don’t see what i should do and google didn’t help me much.

Any help would be appreciated greatly!

答:
Assuming that there is no record for the same item with the same from_date, then this could do it.

```<code>SELECT * FROM YourTable WHERE item = '1' AND ((from_date = '2022-02-02' AND customer = '3') OR (from_date < '2022-02-02' AND (customer <> '3' OR customer IS NULL))) ORDER BY from_date DESC, ID DESC LIMIT 1
</code>```

The query selects all records for item = 1, with either the requested from_date from the customer you wish, or from other customer (or null) from previous dates.
The order by DESC will sort the records by the latest from_date and ID (if there is the same date) and the LIMIT 1 will show only the first record of the query.

If you wish to show the latest price with no customer (if the requested record for the customer is not found), omit the customer <> '3'

```<code>SELECT * FROM YourTable WHERE item = '1' AND ((from_date = '2022-02-02' AND customer = '3') OR (from_date < '2022-02-02' AND customer IS NULL)) ORDER BY from_date DESC, ID DESC LIMIT 1
</code>```

Body:
Assuming that there is no record for the same item with the same from_date, then this could do it.

SELECT * FROM YourTable WHERE item = '1' AND ((from_date = '2022-02-02' AND customer = '3') OR (from_date < '2022-02-02' AND (customer <> '3' OR customer IS NULL))) ORDER BY from_date DESC, ID DESC LIMIT 1

The query selects all records for item = 1, with either the requested from_date from the customer you wish, or from other customer (or null) from previous dates.
The order by DESC will sort the records by the latest from_date and ID (if there is the same date) and the LIMIT 1 will show only the first record of the query.

If you wish to show the latest price with no customer (if the requested record for the customer is not found), omit the customer <> '3'

SELECT * FROM YourTable WHERE item = '1' AND ((from_date = '2022-02-02' AND customer = '3') OR (from_date < '2022-02-02' AND customer IS NULL)) ORDER BY from_date DESC, ID DESC LIMIT 1


问:
adding textarea to wordpress options-general.php
I don't know exactly how to define my question, im working on my custom Wordpress theme, and I've added custom input field in General Settings in Wordpress admin, by editing general.php and adding a new array in general list, then i created a new tablerow in options-general.php:

```<code><tr valign="top">
<th scope="row"><label for="siteupdates"><?php _e('Site Updates') ?></label></th>
<td><input name="siteupdates" type="text" id="content"
"value="<?php  form_option('siteupdates'); ?>" class="regular-text" ></>
<span class="description"><?php _e('Site news,updates,etc.') ?></span></td>
</tr>
</code>```

and also added a div in header.php where i wanted it to be shown:

```<code><div id="siteInfo">
<?php form_option('siteupdates'); ?>
</div><!--siteInfo end-->
</code>```

then i added new Query in wordpress database in phpmyadmin ('siteupdates') and everything works great,since im very new in php, i have watched lots of tutorials and found that way was the easiest for me.
Now i want to change this input to a textarea field, but when i changed html to:

```<code><tr valign="top">
<th scope="row"><label for="siteupdates"><?php _e('Site updates') ?></label></th>
<td><textarea name="siteupdates" type="text" id="content"
cols="50" rows="6" value="<?php form_option('siteupdates'); ?>" class="regular-text">
</textarea>
<span class="description"><?php _e('Site news,updates,etc.') ?></span></td>
</tr>
</code>```

Its looks fine, i see textfield instead of input, but i cant store data in it. Where am i wrong?

答:
Change your <textarea> into this one:

```<code><textarea name="siteupdates" type="text" id="content"
cols="50" rows="6" class="regular-text"><?php form_option('siteupdates'); ?></textarea>
</code>```

Bascially get rid of the value attribute and use the content inside the textarea tag.

Body:
I don't know exactly how to define my question, im working on my custom Wordpress theme, and I've added custom input field in General Settings in Wordpress admin, by editing general.php and adding a new array in general list, then i created a new tablerow in options-general.php:

<?php _e('Site Updates') ?>
<input name="siteupdates" type="text" id="content"
"value="<?php  form_option('siteupdates'); ?>" class="regular-text" ></>
<?php _e('Site news,updates,etc.') ?>

and also added a div in header.php where i wanted it to be shown:

<?php form_option('siteupdates'); ?>

then i added new Query in wordpress database in phpmyadmin ('siteupdates') and everything works great,since im very new in php, i have watched lots of tutorials and found that way was the easiest for me.
Now i want to change this input to a textarea field, but when i changed html to:

<?php _e('Site updates') ?>
<textarea name="siteupdates" type="text" id="content"
cols="50" rows="6" value="<?php form_option('siteupdates'); ?>" class="regular-text">
</textarea>
<?php _e('Site news,updates,etc.') ?>

Its looks fine, i see textfield instead of input, but i cant store data in it. Where am i wrong?

Body:
Change your <textarea> into this one:

<textarea name="siteupdates" type="text" id="content"
cols="50" rows="6" class="regular-text"><?php form_option('siteupdates'); ?></textarea>

Bascially get rid of the value attribute and use the content inside the textarea tag.


问:
Tweeter Oauth:You are authenticated as XXX, but are not authorized to access this page. Would you like to login to a different account?
I have created just a simple django app to login using tweeter, but when i try to login from my app I get this message
"You are authenticated as xxx, but are not authorized to access this page. Would you like to login to a different account?"

I have tried to login with account I used to create the app and different account, but the result is the same. What could be the solution to this?

I am using django and django-allauth library

答:
If using a custom user model (which the Django docs recommend), Django will throw an error: "AttributeError: Manager isn't available...", which is the problem @elizandro-sparcbr had in 2021.

The steps are a bit different than the answer by @Paolo. When I ran into the "Manager isn't available" problem, the steps below worked for me in Feb 2022, on Django 3.2.

settings.py

```<code>ACCOUNT_EMAIL_VERIFICATION = 'none'
</code>```

(Or if using cookiecutter, then in settings folder, modify base.py as above.)

In the terminal:

```<code>$ python manage.py shell
$ from django.contrib.auth import get_user_model
$ User = get_user_model()
$ u = User.objects.get(username='testmyap')
$ u.is_staff = True  # required to access admin panel
$ u.is_superuser = True  # optional
$ u.save()
$ quit()
</code>```

The key steps that are different are the 2nd and 3rd lines above.

For more background on why this is required and what these steps are doing, see:

Django ticket #21616 about "Manager isn't available."

Django docs for "Customizing authentication."

Will Vincent's post "Django Best Practices: Referencing the User Model."

Body:
If using a custom user model (which the Django docs recommend), Django will throw an error: "AttributeError: Manager isn't available...", which is the problem @elizandro-sparcbr had in 2021.

The steps are a bit different than the answer by @Paolo. When I ran into the "Manager isn't available" problem, the steps below worked for me in Feb 2022, on Django 3.2.

settings.py

ACCOUNT_EMAIL_VERIFICATION = 'none'

(Or if using cookiecutter, then in settings folder, modify base.py as above.)

In the terminal:

$ python manage.py shell
$ from django.contrib.auth import get_user_model
$ User = get_user_model()
$ u = User.objects.get(username='testmyap')
$ u.is_staff = True  # required to access admin panel
$ u.is_superuser = True  # optional
$ u.save()
$ quit()

The key steps that are different are the 2nd and 3rd lines above.

For more background on why this is required and what these steps are doing, see:

Django ticket #21616 about "Manager isn't available."

Django docs for "Customizing authentication."

Will Vincent's post "Django Best Practices: Referencing the User Model."


问:
Connect postman from an RDP windows 10 client back to a node web restapi running on the macbook pro host?
I am trying to run postman in a windows 10 RDP client, and I want to test a node application running on the host computer.  The host is a macbook pro and the application is running on localhost:3000 there.  I can't simply use https://localhost:3000 in postman, because localhost there is for that machine.  Is there a way?</p>

答: I am thinking that it might be a big security hole.  The more I think about it, the more I see a problem with it.  I mean, I can share folders - as you do - but that is pretty controlled.  I could well be wrong though</p>


问:
Why release fences added to Scala collections in 2.13 are enough in absence of matching acquire fences?
The process of creation of some of Scala immutable collections, most notably List, is mutable. In 2.13 the concurrency issues were addressed by adding a release fence basically to every builder. A release fence prevents memory writes coming after the fence from being reordered before the fence - so, if you have a 'final write' (such as 'payload_ready' in many examples), it means that anything you wrote (and read) before is commited to shared memory (or at least visible to other threads). When I was reading on fences, I came under impression that a release fence needs a matching acquire fence in the code reading the data commited by the other thread. I accepted it as it coincided with an old adage that no synchronisation will work if it happens only at one site (vide the famous 'double-check locking/singleton pattern is broken' warning). I know that Java's (and C++) memory model is more abstract than any contemporary physical architecture, so some aspects of it are irrelevant.

I freely admit that I have no experience with such low-level control as memory barriers, so I do not feel comfortable with using them. In particular, I can't see how writes being reordered after a release fence (which, as I understand, is still possible) is any different from writes from after the fence actually happening before it, the latter being forbidden. The fence location is irrelevant, what matters is the happens-before relationship. I would like to understand why the lone release fence is enough, or ''when'' it is enough, and when in that case an acquire fence will still be needed.

答:
It looks like the releaseFence appeared in List code as a result of these discussions: 1 and 2.

To be fair with you, I didn't find there clear explanations why only releaseFence was added (without accompanying acquireFence).

So I don't know the real answer, but I have a version.

As I understand, releaseFence alone could be enough.

As I've read every CPU supported by Java preserves a so called load dependency.

It looks like load dependency was used to implement final JMM guarantees (see this article), so I guess, Scala might have used the same trick.

Example of load dependency:

class Obj {
  int a = 0;
}

Obj obj = null;

void thread1() {
  var o = new Obj();
  o.a = 1;
  VarHandle.releaseFence();
  obj = o;
}

void thread2() {
  Obj o;
  do {
    o = obj;
  } while (o == null)
  var r1 = o.a;
}
```
<ul>
<li><p>In <code>thread1()</code>: releaseFence guarantees that <code>o.a = 1</code> and <code>obj = o</code> aren't reordered.</p>
</li>
<li><p>In <code>thread2()</code>
Read <code>var r1 = o.a</code> means that we compute memory address for loading as <code>[memory address of object o] + [offset of field a inside Obj]</code>.<br />
This is a <em>load dependency</em>: memory address for load <code>o.a</code> is computed from memory address of <code>o</code> loaded by <code>o = obj</code>.<br />
CPU preserving <em>load dependency</em> means that <code>o = obj</code> and <code>var r1 = o.a</code> aren't reordered.<br />
Since in <code>thread1()</code> <code>o.a = 1</code> and <code>obj = o</code> aren't reordered either, then read <code>var r1 = o.a</code> in <code>thread2()</code> is guaranteed to see <code>1</code>.</p>
<p>Note that this works because it's one object:</p>
<ul>
<li>when the value of <code>obj</code> changes => we know that <code>thread1()</code> is done</li>
<li>when we read inner fields of <code>obj</code> we get <em>load dependency</em> => we are guaranteed to see all the writes from <code>thread1()</code> which are before <code>obj = o</code></li>
</ul>
</li>
</ul>
<p>Here is an example when we need <code>acquireFence</code>:</p>
<pre class="lang-java prettyprint-override"><code>int a = 0;
int ready = false;

void thread1() {
  a = 1;
  VarHandle.releaseFence();
  ready = true;
}

void thread2() {
  while (!ready) {;}
  VarHandle.acquireFence(); // required in this case
  var r1 = a;
}
</code>```

Here there is no load dependency between the reads of a and ready in thread2().

As a result acquireFence is required to prevent reordering of the reads of a and ready.

Keep in mind that this is just a version.

As you correctly noted, this all is very low level. I don't know Java on such a deep level.
(BTW as I understand fences are outside the JMM + JMM is defined only for Java (not Scala or JVM) - so I'm not sure that happens-before can be applied here, at least as it's defined in the JMM)

Body:
It looks like the releaseFence appeared in List code as a result of these discussions: 1 and 2.

To be fair with you, I didn't find there clear explanations why only releaseFence was added (without accompanying acquireFence).

So I don't know the real answer, but I have a version.

As I understand, releaseFence alone could be enough.

As I've read every CPU supported by Java preserves a so called load dependency.

It looks like load dependency was used to implement final JMM guarantees (see this article), so I guess, Scala might have used the same trick.

Example of load dependency:

class Obj {
  int a = 0;
}

Obj obj = null;

void thread1() {
  var o = new Obj();
  o.a = 1;
  VarHandle.releaseFence();
  obj = o;
}

void thread2() {
  Obj o;
  do {
    o = obj;
  } while (o == null)
  var r1 = o.a;
}

In thread1(): releaseFence guarantees that o.a = 1 and obj = o aren't reordered.

In thread2()
Read var r1 = o.a means that we compute memory address for loading as [memory address of object o] + [offset of field a inside Obj].

This is a load dependency: memory address for load o.a is computed from memory address of o loaded by o = obj.

CPU preserving load dependency means that o = obj and var r1 = o.a aren't reordered.

Since in thread1() o.a = 1 and obj = o aren't reordered either, then read var r1 = o.a in thread2() is guaranteed to see 1.

Note that this works because it's one object:

when the value of obj changes => we know that thread1() is done

when we read inner fields of obj we get load dependency => we are guaranteed to see all the writes from thread1() which are before obj = o

Here is an example when we need acquireFence:

int a = 0;
int ready = false;

void thread1() {
  a = 1;
  VarHandle.releaseFence();
  ready = true;
}

void thread2() {
  while (!ready) {;}
  VarHandle.acquireFence(); // required in this case
  var r1 = a;
}

Here there is no load dependency between the reads of a and ready in thread2().

As a result acquireFence is required to prevent reordering of the reads of a and ready.

Keep in mind that this is just a version.

As you correctly noted, this all is very low level. I don't know Java on such a deep level.
(BTW as I understand fences are outside the JMM + JMM is defined only for Java (not Scala or JVM) - so I'm not sure that happens-before can be applied here, at least as it's defined in the JMM)


问:
How to invoke an already running instance of an application
I am developing a BHO with c++ for identifying the phone numbers on any webpage, highlighting the phone numbers and invoking an utility when click on the phone number.

I am using IHtmlTxtRange::findtext for finding the phone numbers and for  highlighting the phone numbers I am injecting HTML's span tag to the web page using IHtmlTxtRange::pastetext().

I want to invoke the same instance of an already running application, when click on the phone number on web page . How to achieve this with onclick() of HTML span tag.

Below I have given the code snippet which I am using for finding and highlighting the phone number.

```<code>lpBody->createTextRange(&lpTxtRange);

lpBody->Release();

CComBSTR html;

CComBSTR newhtml;

long t;

VARIANT_BOOL bFound;

int i=0;

int size= findText.size();

for(int i=0;i<size;i++)

{

    while(1)

    {

        CComBSTR str1= findText[i].c_str();

        lpTxtRange->findText(str1,0,lFlags,&bFound);

        if(bFound==-1)

        {

            newhtml.Empty();

            lpTxtRange->get_htmlText(&html);

            newhtml.Append("<span id='");

            newhtml.Append(L"begin_highlight");

            newhtml.Append("' title='");

            newhtml.Append(L"call this phone number ");

            newhtml.Append(str1);

            newhtml.Append("' style='");

            newhtml.Append(L"color: white; background-color: grey");

            newhtml.Append("'>");

            newhtml.AppendBSTR(html);

            newhtml.Append("</span>");

            lpTxtRange->pasteHTML(newhtml);

            lpTxtRange->moveStart((BSTR)CComBSTR("Character"),1,&t);

            lpTxtRange->moveEnd((BSTR)CComBSTR("Textedit"),1,&t);

        }

        else

             break;

    }

}

lpTxtRange->Release();

findText.clear();
</code>```

Thanks a lot.

答:
This may help with half of your problem..

You can use EnumWindows to find the window of your running application.  To identify the window as being your application, you can use the class name of the window (which you could use a GUID for).  GetClassNameA should get this from your HWND.

In the app that you are sending the data to, be sure to set this class name up when the main window is created.

To actually send the data to it, you can send it a WM_COPYDATA command using SendMessage and a COPYDATASTRUCT.  The receiving application then need to receive this via its message loop.

All that is left then is getting a callback in the BHO when you item is clicked to do all of this!

Edit: this could be of use for that:
Is it possible to use a BHO (IE8) to track which links a user clicks

Body:
I am developing a BHO with c++ for identifying the phone numbers on any webpage, highlighting the phone numbers and invoking an utility when click on the phone number.

I am using IHtmlTxtRange::findtext for finding the phone numbers and for  highlighting the phone numbers I am injecting HTML's span tag to the web page using IHtmlTxtRange::pastetext().

I want to invoke the same instance of an already running application, when click on the phone number on web page . How to achieve this with onclick() of HTML span tag.

Below I have given the code snippet which I am using for finding and highlighting the phone number.

lpBody->createTextRange(&lpTxtRange);

lpBody->Release();

CComBSTR html;

CComBSTR newhtml;

long t;

VARIANT_BOOL bFound;

int i=0;

int size= findText.size();

for(int i=0;i<size;i++)

{

    while(1)

    {

        CComBSTR str1= findText[i].c_str();

        lpTxtRange->findText(str1,0,lFlags,&bFound);

        if(bFound==-1)

        {

            newhtml.Empty();

            lpTxtRange->get_htmlText(&html);

            newhtml.Append("");

            newhtml.AppendBSTR(html);

            newhtml.Append("");

            lpTxtRange->pasteHTML(newhtml);

            lpTxtRange->moveStart((BSTR)CComBSTR("Character"),1,&t);

            lpTxtRange->moveEnd((BSTR)CComBSTR("Textedit"),1,&t);

        }

        else

             break;

    }

}

lpTxtRange->Release();

findText.clear();

Thanks a lot.


问:
Read data from multiple sub-collections in Firestore?
I'm stuck on obtaining data from sub-collection from Firestore. I'm attaching my code script below for reference.

Right now I get the data from a specific sub-collection. Using this Query line:

```<code> Query query = db.collection("Users").document("Group").collection("Group_1);
</code>```

It works fine and returns the data also.

But I want to get all data from the Group document.

Below link attached to my database image.

Firestore Database Image

```<code>  Query query = db.collection("Users");

    FirestoreRecyclerOptions<PatientRegister> response = new FirestoreRecyclerOptions.Builder<PatientRegister>()
            .setQuery(query, PatientRegister.class)
            .build();

    adapter = new FirestoreRecyclerAdapter<PatientRegister, RegisterHolder>(response) {
        @Override
        public void onBindViewHolder(RegisterHolder holder, int position, PatientRegister model) {

            holder.text_1.setText(model.getPatient_name());
            holder.text_2.setText(model.getGender());
            holder.text_3.setText(model.getDatetime());

        @Override
        public RegisterHolder onCreateViewHolder(ViewGroup group, int i) {
            View view = LayoutInflater.from(group.getContext())
                    .inflate(R.layout.registration_list, group, false);

            return new RegisterHolder(view);
        }

        @Override
        public void onError(FirebaseFirestoreException e) {
            Log.d("000147", e.getMessage());
        }
    };
</code>```

答:
I had a similar problem, and the problem I think is that you can't get all data from a document, .get() method just work for collections.

In my case i just solve the problem adding a data in my documents to specify the group:

```<code>Map<String,Double> User = new HashMap<>();
User.put("name","MyUserName");
User.put("group",1);
</code>```

Now to get all:

```<code>db.collection("Users").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
   @Override
   public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
       postList.clear();
       for (DocumentSnapshot dc:queryDocumentSnapshots.getDocuments()) {
          //dc get each document
    }
}
</code>```

Body:
I'm stuck on obtaining data from sub-collection from Firestore. I'm attaching my code script below for reference.

Right now I get the data from a specific sub-collection. Using this Query line:

 Query query = db.collection("Users").document("Group").collection("Group_1);

It works fine and returns the data also.

But I want to get all data from the Group document.

Below link attached to my database image.

Firestore Database Image

  Query query = db.collection("Users");

    FirestoreRecyclerOptions<PatientRegister> response = new FirestoreRecyclerOptions.Builder<PatientRegister>()
            .setQuery(query, PatientRegister.class)
            .build();

    adapter = new FirestoreRecyclerAdapter<PatientRegister, RegisterHolder>(response) {
        @Override
        public void onBindViewHolder(RegisterHolder holder, int position, PatientRegister model) {

            holder.text_1.setText(model.getPatient_name());
            holder.text_2.setText(model.getGender());
            holder.text_3.setText(model.getDatetime());

        @Override
        public RegisterHolder onCreateViewHolder(ViewGroup group, int i) {
            View view = LayoutInflater.from(group.getContext())
                    .inflate(R.layout.registration_list, group, false);

            return new RegisterHolder(view);
        }

        @Override
        public void onError(FirebaseFirestoreException e) {
            Log.d("000147", e.getMessage());
        }
    };

Body:
I had a similar problem, and the problem I think is that you can't get all data from a document, .get() method just work for collections.

In my case i just solve the problem adding a data in my documents to specify the group:

Map<String,Double> User = new HashMap<>();
User.put("name","MyUserName");
User.put("group",1);

Now to get all:

db.collection("Users").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
   @Override
   public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
       postList.clear();
       for (DocumentSnapshot dc:queryDocumentSnapshots.getDocuments()) {
          //dc get each document
    }
}


问:
How make steps calendar diagram in Vue.js?
The data is for the moment registered in raw I still have to make it dynamic but I would like to make a kind of diagram with the data present. Like in this picture:

I don't really know where to start I tried to look for diagrams but nothing really matches...

Here is my code:

<template>
    <v-row>
        <v-col cols="5" lg="8" md="6" sm="5" class="months">

{{month.month}}

        </v-col>
        <v-container style="max-width: 100%; height: 420px;" class="overflow-y-auto scrollbar-hidden card-association">

Sowing : {{s.start[0] === 1 ? "January" : ""}} to {{s.end[0] === 5 ? "May" : ""}}

Planting : {{p.start[0] === 3 ? "March" : ""}} to {{p.end[0] === 8 ? "August" : ""}}

Harvesting : {{h.start[0] === 7 ? "July" : ""}} to {{h.end[0] === 11 ? "November" : ""}}

        </v-container>
    </v-row>
</template>

```
</div>
</div>
</p>
<p>And what it looks like now:</p>
<p><img src="https://i.stack.imgur.com/FZfoM.png" alt="enter image description here" /></p>
<p>And here is an example of what I get in response with the API:</p>
```    [
  {
    "id": 9,
    "plant_id": {
      "id": 136,
      "name": "Basilic"
    },
    "start": [
      7
    ],
    "end": [
      11
    ],
    "step_title": "Harvesting",
    "step_order": 3,
    "step_subtitle": "Récolte",
    "help": ""
  }
]
```

答:
I'm assuming you're using Vuetify? There is a range slider component that looks exactly like what you need. Make it readonly and style accordingly.

Alternatively, you can use timeline charts. Here is an example from Apex Charts that looks pretty close to what you need.

Body:
The data is for the moment registered in raw I still have to make it dynamic but I would like to make a kind of diagram with the data present. Like in this picture:

I don't really know where to start I tried to look for diagrams but nothing really matches...

Here is my code:

<template>
    <v-row>
        <v-col cols="5" lg="8" md="6" sm="5" class="months">

{{month.month}}

        </v-col>
        <v-container style="max-width: 100%; height: 420px;" class="overflow-y-auto scrollbar-hidden card-association">

Sowing : {{s.start[0] === 1 ? "January" : ""}} to {{s.end[0] === 5 ? "May" : ""}}

Planting : {{p.start[0] === 3 ? "March" : ""}} to {{p.end[0] === 8 ? "August" : ""}}

Harvesting : {{h.start[0] === 7 ? "July" : ""}} to {{h.end[0] === 11 ? "November" : ""}}

        </v-container>
    </v-row>
</template>

And what it looks like now:

And here is an example of what I get in response with the API:

    [
  {
    "id": 9,
    "plant_id": {
      "id": 136,
      "name": "Basilic"
    },
    "start": [
      7
    ],
    "end": [
      11
    ],
    "step_title": "Harvesting",
    "step_order": 3,
    "step_subtitle": "Récolte",
    "help": ""
  }
]


问:
How does one get AVX512_FP16 flag support?
My CPU supports all sorts of things

```<code>  -march=CPU[,+EXTENSION...]
                          generate code for CPU and EXTENSION, CPU is one of:
                           generic32, generic64, i386, i486, i586, i686,
                           pentium, pentiumpro, pentiumii, pentiumiii, pentium4,
                           prescott, nocona, core, core2, corei7, l1om, k1om,
                           iamcu, k6, k6_2, athlon, opteron, k8, amdfam10,
                           bdver1, bdver2, bdver3, bdver4, znver1, btver1,
                           btver2
                          EXTENSION is combination of:
                           8087, 287, 387, 687, mmx, sse, sse2, sse3, ssse3,
                           sse4.1, sse4.2, sse4, avx, avx2, avx512f, avx512cd,
                           avx512er, avx512pf, avx512dq, avx512bw, avx512vl,
                           vmx, vmfunc, smx, xsave, xsaveopt, xsavec, xsaves,
                           aes, pclmul, fsgsbase, rdrnd, f16c, bmi2, fma, fma4,
                           xop, lwp, movbe, cx16, ept, lzcnt, hle, rtm, invpcid,
                           clflush, nop, syscall, rdtscp, 3dnow, 3dnowa,
                           padlock, svme, sse4a, abm, bmi, tbm, adx, rdseed,
                           prfchw, smap, mpx, sha, clflushopt, prefetchwt1, se1,
                           clwb, avx512ifma, avx512vbmi, avx512_4fmaps,
                           avx512_4vnniw, avx512_vpopcntdq, clzero, mwaitx,
                           ospke, rdpid, ptwrite, cet, no87, no287, no387,
                           no687, nommx, nosse, nosse2, nosse3, nossse3,
                           nosse4.1, nosse4.2, nosse4, noavx, noavx2, noavx512f,
                           noavx512cd, noavx512er, noavx512pf, noavx512dq,
                           noavx512bw, noavx512vl, noavx512ifma, noavx512vbmi,
                           noavx512_4fmaps, noavx512_4vnniw, noavx512_vpopcntdq
</code>```

Yet, something as simple as __m256h inter; yields an error: '__m256h' was not declared in this scope. Which makes sense hense CPU requirement is a CPUID Flags: AVX512_FP16 + AVX512VL where AVX512_FP16 is not on the list.

How does one get AVX512_FP16 support? Is it CPU version dependent or can it be fixed with a patch?

Update: intel mentions that AVX512_FP16 is only supported alongside AVX512BW [check]. I am compiling using -march=skylake-avx512 which compiles regular __m512 but fails speficically on these FP16 based ops.

答:
Main Answer

Because AVX512FP16 is an extension to the AVX512 ISA, it must either:

A) Have explicit hardware support built in.

B) Be emulated in software by promoting the type to another suitable alternative such as fp32 with specific rounding/conformance code.

As of the time of your posting there were no systems in the market that had AVX 512 FP16 support available.

As of this posting (Feb 10 2022) the only in market support is the AVX512 P(erformance)-core workaround for Intel 12th generation K series AlderLake CPU's*.

These P-cores, based on the Golden Cove architecture, support AVX512FP16*.

To use the instruction in C or C++ a very recent compiler must be used. My own testing shows that GCC-12, Clang-14 and ICX 2022.0 are all capable of utilizing the instruction.

If you'd like to use an officially supported platform, the option is to wait for Intel Xeon Sapphire Rapids, which are based on only Golden Cove cores and will have the full AVX512 ISA enabled.

A snippet of code that will compile to utilize the FMA instructions from the AVX512FP16 ISA extension is at the end with instructions on it's usage.

Note on using Alder Lake

*NB: This capability can only be enabled once Gracemont E-cores are disabled, on specific vendors motherboards with specific BIOS/Microcode revisions. This is not Sanctioned or supported by Intel

The reason for this is mainly to do with different ISA's between the Gracemont and Golden Cove core's and Process pinning (but that is beyond the scope of this question)

Code example

Use gcc-12 fp16_FMA_avx512.c -O3 -march=sapphirerapids -mavx512fp16 -o avx512example.bin
To generate an executable if your platform supports the instruction

Use gcc-12 fp16_FMA_avx512.c -O3 -march=sapphirerapids -mavx512fp16 -o avx512example.S -S
To generate an assembly file that shows the usage of the instructions themselves.

```<code>    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    /*
    Simple example of FP16 arithmetic with it's declaration

    NB: This uses Clang/GCC convention FP16 declarations due to near universal platform support.
    Any compiler that has yet to formally adopt ISO/IEC TS 18661-3:2015 (“Floating-point extensions for C”) will not support the type.
    Known working x86_64 compilers as of Feb 08 2022 are:
    Clang/LLVM-14+
    GCC-12+
    Intel ICX Version 2022.0.0

    Known working architectures:
        Intel Alder-Lake [        *under certain conditions]
        Intel Sapphire Rapids
*/

int main(){

float seed = 1;
srand((time(0)));
int count = 31;
_Float16 factor = seed;

//primaries
_Float16 a=1.436;
_Float16 b=0.83546;

//arrays to be used for FMA
_Float16 alpha[32];
_Float16 delta[32];
_Float16 omega[32];

while (count>=0)
{
//fill the arrays with differing values
alpha[count]=(_Float16) (a*factor);
delta[count]=(_Float16) (b*factor);
omega[count]=(_Float16) (factor+(a*b));

factor = factor+b;
count--;
}

printf("Print the FMA of 3  _Float16's that are cast as Float\n");

while (count < 32){

omega[count]=(omega[count]*alpha[count])+delta[count];

count++;
}
printf("\n"); //clear last line

while (count>=0)
{
printf("%i %f \n", count, (float) omega[count]);
count--;
}

// 32 entry variable can be used: 512bit/16bits per variable = 32 variables
//c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae af ag ah
}
</code>```

Body:
My CPU supports all sorts of things

  -march=CPU[,+EXTENSION...]
                          generate code for CPU and EXTENSION, CPU is one of:
                           generic32, generic64, i386, i486, i586, i686,
                           pentium, pentiumpro, pentiumii, pentiumiii, pentium4,
                           prescott, nocona, core, core2, corei7, l1om, k1om,
                           iamcu, k6, k6_2, athlon, opteron, k8, amdfam10,
                           bdver1, bdver2, bdver3, bdver4, znver1, btver1,
                           btver2
                          EXTENSION is combination of:
                           8087, 287, 387, 687, mmx, sse, sse2, sse3, ssse3,
                           sse4.1, sse4.2, sse4, avx, avx2, avx512f, avx512cd,
                           avx512er, avx512pf, avx512dq, avx512bw, avx512vl,
                           vmx, vmfunc, smx, xsave, xsaveopt, xsavec, xsaves,
                           aes, pclmul, fsgsbase, rdrnd, f16c, bmi2, fma, fma4,
                           xop, lwp, movbe, cx16, ept, lzcnt, hle, rtm, invpcid,
                           clflush, nop, syscall, rdtscp, 3dnow, 3dnowa,
                           padlock, svme, sse4a, abm, bmi, tbm, adx, rdseed,
                           prfchw, smap, mpx, sha, clflushopt, prefetchwt1, se1,
                           clwb, avx512ifma, avx512vbmi, avx512_4fmaps,
                           avx512_4vnniw, avx512_vpopcntdq, clzero, mwaitx,
                           ospke, rdpid, ptwrite, cet, no87, no287, no387,
                           no687, nommx, nosse, nosse2, nosse3, nossse3,
                           nosse4.1, nosse4.2, nosse4, noavx, noavx2, noavx512f,
                           noavx512cd, noavx512er, noavx512pf, noavx512dq,
                           noavx512bw, noavx512vl, noavx512ifma, noavx512vbmi,
                           noavx512_4fmaps, noavx512_4vnniw, noavx512_vpopcntdq

Yet, something as simple as __m256h inter; yields an error: '__m256h' was not declared in this scope. Which makes sense hense CPU requirement is a CPUID Flags: AVX512_FP16 + AVX512VL where AVX512_FP16 is not on the list.

How does one get AVX512_FP16 support? Is it CPU version dependent or can it be fixed with a patch?

Update: intel mentions that AVX512_FP16 is only supported alongside AVX512BW [check]. I am compiling using -march=skylake-avx512 which compiles regular __m512 but fails speficically on these FP16 based ops.

Body:
Main Answer

Because AVX512FP16 is an extension to the AVX512 ISA, it must either:

A) Have explicit hardware support built in.

B) Be emulated in software by promoting the type to another suitable alternative such as fp32 with specific rounding/conformance code.

As of the time of your posting there were no systems in the market that had AVX 512 FP16 support available.

As of this posting (Feb 10 2022) the only in market support is the AVX512 P(erformance)-core workaround for Intel 12th generation K series AlderLake CPU's*.

These P-cores, based on the Golden Cove architecture, support AVX512FP16*.

To use the instruction in C or C++ a very recent compiler must be used. My own testing shows that GCC-12, Clang-14 and ICX 2022.0 are all capable of utilizing the instruction.

If you'd like to use an officially supported platform, the option is to wait for Intel Xeon Sapphire Rapids, which are based on only Golden Cove cores and will have the full AVX512 ISA enabled.

A snippet of code that will compile to utilize the FMA instructions from the AVX512FP16 ISA extension is at the end with instructions on it's usage.

Note on using Alder Lake

*NB: This capability can only be enabled once Gracemont E-cores are disabled, on specific vendors motherboards with specific BIOS/Microcode revisions. This is not Sanctioned or supported by Intel

The reason for this is mainly to do with different ISA's between the Gracemont and Golden Cove core's and Process pinning (but that is beyond the scope of this question)

Code example

Use gcc-12 fp16_FMA_avx512.c -O3 -march=sapphirerapids -mavx512fp16 -o avx512example.bin
To generate an executable if your platform supports the instruction

Use gcc-12 fp16_FMA_avx512.c -O3 -march=sapphirerapids -mavx512fp16 -o avx512example.S -S
To generate an assembly file that shows the usage of the instructions themselves.

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    /*
    Simple example of FP16 arithmetic with it's declaration

    NB: This uses Clang/GCC convention FP16 declarations due to near universal platform support.
    Any compiler that has yet to formally adopt ISO/IEC TS 18661-3:2015 (“Floating-point extensions for C”) will not support the type.
    Known working x86_64 compilers as of Feb 08 2022 are:
    Clang/LLVM-14+
    GCC-12+
    Intel ICX Version 2022.0.0

    Known working architectures:
        Intel Alder-Lake [        *under certain conditions]
        Intel Sapphire Rapids
*/

int main(){

float seed = 1;
srand((time(0)));
int count = 31;
_Float16 factor = seed;

//primaries
_Float16 a=1.436;
_Float16 b=0.83546;

//arrays to be used for FMA
_Float16 alpha[32];
_Float16 delta[32];
_Float16 omega[32];

while (count>=0)
{
//fill the arrays with differing values
alpha[count]=(_Float16) (a*factor);
delta[count]=(_Float16) (b*factor);
omega[count]=(_Float16) (factor+(a*b));

factor = factor+b;
count--;
}

printf("Print the FMA of 3  _Float16's that are cast as Float\n");

while (count < 32){

omega[count]=(omega[count]*alpha[count])+delta[count];

count++;
}
printf("\n"); //clear last line

while (count>=0)
{
printf("%i %f \n", count, (float) omega[count]);
count--;
}

// 32 entry variable can be used: 512bit/16bits per variable = 32 variables
//c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae af ag ah
}


问:
Randomize control visibility (asp.net)
I have been searching for a solution to this but haven't come across one yet and i'm not too good at randomizing with c#.

I have three asp.net controls and I would like to make visible one of those controls at any one time.

The controls may be like this

panel 1

panel 2

panel 3

So I guess all of these controls would be set to visible='false' by default. Then the randomize method would choose one of those controls and make it visible='true'.

I think the hardest part here would be to put the controls into an array to randomize? Again, i'm not sure how to do that so any help would be great.

Thank you in advance.

答:
How about this:

```<code>Panel[] array1 = new Panel[3];
array1[0] = panel1;
array1[1] = panel2;
array1[2] = panel3;

foreach(Panel p in array1) {
  p.Visible = False;
}

Random rand = new Random();
int toshow = rand.next(0, 3);
array1[toshow].Visible = true;
</code>```

This was conveiced from my head without any IDE to support if it works correctly. The Class name for random might be wrong (isn't it in the Math Namespace?)

Title: Randomize control visibility (asp.net)

Body:
How about this:

Panel[] array1 = new Panel[3];
array1[0] = panel1;
array1[1] = panel2;
array1[2] = panel3;

foreach(Panel p in array1) {
  p.Visible = False;
}

Random rand = new Random();
int toshow = rand.next(0, 3);
array1[toshow].Visible = true;

This was conveiced from my head without any IDE to support if it works correctly. The Class name for random might be wrong (isn't it in the Math Namespace?)


问:
Generate all combinations of vector with consecutive occurrences is considered as single occurrence
I want to generate vectors with all possible combinations of vector elements where a consecutive multiple occurrences of an element is considered as single occurrence of that element.

Simple cases

For n = 2,

```<code>original <- c("a","a","a","b","b","b")
      v1 <- c("b","b","b","a","a","a")
</code>```

So all unique occurrences of a swap with b.

For n = 3, we get

```<code>original<-c("a","a","a","b","b","b","c","c","c")
    ver1<-c("a","a","a","c","c","c","b","b","b")
    ver2<-c("b","b","b","a","a","a","c","c","c")
    ver3<-c("b","b","b","c","c","c","a","a","a")
    ver4<-c("c","c","c","b","b","b","a","a","a")
    ver5<-c("c","c","c","a","a","a","b","b","b")
</code>```

So all unique occurrences of a swap with b and c, all unique occurrences of b swap with a and c AND all unique occurrences of c swap with b and a.

The cases go up to n = 10. (I believe the possible vectors with different combinations are 10!)

Also, there can be more than a single chunk of a, b, c...

Complex case

For n = 2;

```<code>original<-c("a","a","a","b","b","b","a","a","b","b")
    ver1<-c("b","b","b","a","a","a","b","b","a","a")
</code>```

But if we swap the elements correctly the complex case and simple case should not matter.

What I am trying: (for n=2)

```<code>original<-c("a","a","a","b","b","b","a","a","b","b")
ver1<-replace(original,which(original=='a'),'b')
ver1<-replace(ver1,which(original=='b'),'a')
gives ver1<-c("b","b","b","a","a","a","b","b","a","a")
</code>```

But not sure how to automate this.

答:
Using chartr, you can do (although this might crash for larger vectors):

f <- function(vec){
  uni <- unique(vec)
  size <- length(uni)
  pVec <- paste(uni, collapse = "")
  grid <- expand.grid(rep(list(uni), size))
  expanded <- grid[apply(grid, 1, function(x) length(unique(x))) == size,]
  p <- unname(apply(ex, 1, paste0, collapse = ""))

  lapply(p, function(x) chartr(pVec, x, vec))
}
```
<p>output:</p>
<pre class="lang-r prettyprint-override"><code>original<-c("a","a","a","b","b","b","c","c","c")
f(original)

# [[1]]
# [1] "c" "c" "c" "b" "b" "b" "a" "a" "a"
#
# [[2]]
# [1] "b" "b" "b" "c" "c" "c" "a" "a" "a"
#
# [[3]]
# [1] "c" "c" "c" "a" "a" "a" "b" "b" "b"
#
# [[4]]
# [1] "a" "a" "a" "c" "c" "c" "b" "b" "b"
#
# [[5]]
# [1] "b" "b" "b" "a" "a" "a" "c" "c" "c"
#
# [[6]]
# [1] "a" "a" "a" "b" "b" "b" "c" "c" "c"
</code>```

Previous answer (do not work for n > 2).

Using gtools::permutations. Results are each columns of the matrix. The idea is to get the permutations from unique values, and the repeat the values to match the desired group length.

f <- function(x){
  r <- rle(x)
  l <- length(r$values)
  apply(gtools::permutations(n=l, r=l, v=r$values), 1, function(x) rep(x, each = unique(r$l)))
}
```

Body:
I want to generate vectors with all possible combinations of vector elements where a consecutive multiple occurrences of an element is considered as single occurrence of that element.

Simple cases

For n = 2,

original <- c("a","a","a","b","b","b")
      v1 <- c("b","b","b","a","a","a")

So all unique occurrences of a swap with b.

For n = 3, we get

original<-c("a","a","a","b","b","b","c","c","c")
    ver1<-c("a","a","a","c","c","c","b","b","b")
    ver2<-c("b","b","b","a","a","a","c","c","c")
    ver3<-c("b","b","b","c","c","c","a","a","a")
    ver4<-c("c","c","c","b","b","b","a","a","a")
    ver5<-c("c","c","c","a","a","a","b","b","b")

So all unique occurrences of a swap with b and c, all unique occurrences of b swap with a and c AND all unique occurrences of c swap with b and a.

The cases go up to n = 10. (I believe the possible vectors with different combinations are 10!)

Also, there can be more than a single chunk of a, b, c...

Complex case

For n = 2;

original<-c("a","a","a","b","b","b","a","a","b","b")
    ver1<-c("b","b","b","a","a","a","b","b","a","a")

But if we swap the elements correctly the complex case and simple case should not matter.

What I am trying: (for n=2)

original<-c("a","a","a","b","b","b","a","a","b","b")
ver1<-replace(original,which(original=='a'),'b')
ver1<-replace(ver1,which(original=='b'),'a')
gives ver1<-c("b","b","b","a","a","a","b","b","a","a")

But not sure how to automate this.

Body:
Using chartr, you can do (although this might crash for larger vectors):

f <- function(vec){
  uni <- unique(vec)
  size <- length(uni)
  pVec <- paste(uni, collapse = "")
  grid <- expand.grid(rep(list(uni), size))
  expanded <- grid[apply(grid, 1, function(x) length(unique(x))) == size,]
  p <- unname(apply(ex, 1, paste0, collapse = ""))

  lapply(p, function(x) chartr(pVec, x, vec))
}

output:

original<-c("a","a","a","b","b","b","c","c","c")
f(original)

# [[1]]
# [1] "c" "c" "c" "b" "b" "b" "a" "a" "a"
#
# [[2]]
# [1] "b" "b" "b" "c" "c" "c" "a" "a" "a"
#
# [[3]]
# [1] "c" "c" "c" "a" "a" "a" "b" "b" "b"
#
# [[4]]
# [1] "a" "a" "a" "c" "c" "c" "b" "b" "b"
#
# [[5]]
# [1] "b" "b" "b" "a" "a" "a" "c" "c" "c"
#
# [[6]]
# [1] "a" "a" "a" "b" "b" "b" "c" "c" "c"

Previous answer (do not work for n > 2).

Using gtools::permutations. Results are each columns of the matrix. The idea is to get the permutations from unique values, and the repeat the values to match the desired group length.

f <- function(x){
  r <- rle(x)
  l <- length(r$values)
  apply(gtools::permutations(n=l, r=l, v=r$values), 1, function(x) rep(x, each = unique(r$l)))
}