问:
Change checkbox tick color and icon - sapui5
I need to change the color of the tick on a UI5 checkbox.
I've looked at the CSS and found out that this is in the ::before selector:

I've added a class to the checkbox, called .accept and defined like this on the CSS file:

.accept.sapMCbBg.sapMCbMarkChecked::before{
    content: "\e05b";
    font-family: "SAP-icons";
    color: #00a600;
}```
</div>
</div>
</p>

<p>This is not working. Do you have any suggestion?
Thank you.</p>

<p>EDIT: Here's the code for the checkbox:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var oCheckBox = new sap.m.CheckBox({
  text: "test",
  selected: false,
  select: function(oEvent){
    if (oEvent.getSource().getSelected() == true){
      oEvent.getSource().addStyleClass("accept");
    }else{
      oEvent.getSource().removeStyleClass("accept");
    }
  }
});</code>```

答:
Since UI5 1.38, a valueState can be assigned to sap.m.CheckBox:

<CheckBox valueState="Success" />
```

Currently, four value states / semantic colors are supported:

From: https://ui5.sap.com/#/entity/sap.m.CheckBox/sample/sap.m.sample.CheckBox

Body:
I need to change the color of the tick on a UI5 checkbox.
I've looked at the CSS and found out that this is in the ::before selector:

I've added a class to the checkbox, called .accept and defined like this on the CSS file:

.accept.sapMCbBg.sapMCbMarkChecked::before{
    content: "\e05b";
    font-family: "SAP-icons";
    color: #00a600;
}

This is not working. Do you have any suggestion?
Thank you.

EDIT: Here's the code for the checkbox:

var oCheckBox = new sap.m.CheckBox({
  text: "test",
  selected: false,
  select: function(oEvent){
    if (oEvent.getSource().getSelected() == true){
      oEvent.getSource().addStyleClass("accept");
    }else{
      oEvent.getSource().removeStyleClass("accept");
    }
  }
});

Body:
Since UI5 1.38, a valueState can be assigned to sap.m.CheckBox:

<CheckBox valueState="Success" />

Currently, four value states / semantic colors are supported:

From: https://ui5.sap.com/#/entity/sap.m.CheckBox/sample/sap.m.sample.CheckBox


来源: stackexchange

问:
Disabling assert macro in C++
I'm trying to disable the assert macro in C++ in this way:

```<code>#include <stdio.h>      /* printf */
#include <assert.h>     /* assert */

#define NDEBUG

void print_number(int* myInt) {
  assert (myInt != NULL);
  printf ("%d\n", *myInt);
}

int main ()
{
  int a = 10;
  int * b = NULL;
  int * c = NULL;

  b = &a;

  print_number (b);
  print_number (c);

  return 0;
}
</code>```

The official website says that if I define NDEBUG, all the assert macro will be disable. This way doesn't work. Can you tell me how fix it?

答:
The NDEBUG define controls the definition of the assert macro, not its expansion.  In order for it to be effective, you need to define it before the macro itself is defined, which happens in assert.h.

There are two ways to achieve that:

put the #define NDEBUG before the line that says #include <assert.h>; or

define NDEBUG on the command line, by doing something like:

```<code>cc -DNDEBUG main.c
</code>```

Perhaps you should also take a step back and consider why you are trying to disable assertions.  After all, the assertions are there for a reason, so unless you are running on a 40MHz SPARCstation, you should probably not be disabling them.

ContentLicense: CC BY-SA 4.0

Title: Disabling assert macro in C++

Body:
I'm trying to disable the assert macro in C++ in this way:

#include <stdio.h>      /* printf */
#include <assert.h>     /* assert */

#define NDEBUG

void print_number(int* myInt) {
  assert (myInt != NULL);
  printf ("%d\n", *myInt);
}

int main ()
{
  int a = 10;
  int * b = NULL;
  int * c = NULL;

  b = &a;

  print_number (b);
  print_number (c);

  return 0;
}

The official website says that if I define NDEBUG, all the assert macro will be disable. This way doesn't work. Can you tell me how fix it?

Body:
The NDEBUG define controls the definition of the assert macro, not its expansion.  In order for it to be effective, you need to define it before the macro itself is defined, which happens in assert.h.

There are two ways to achieve that:

put the #define NDEBUG before the line that says #include <assert.h>; or

define NDEBUG on the command line, by doing something like:

cc -DNDEBUG main.c

Perhaps you should also take a step back and consider why you are trying to disable assertions.  After all, the assertions are there for a reason, so unless you are running on a 40MHz SPARCstation, you should probably not be disabling them.


问:
Malloc using more memory than specified?
I'm allocating memory for a string using malloc: s=(char*) malloc(sizeof(char)*4)
Why can I store more than 4 characters to the string? If I allocated 4 bytes of memory and each character requires 1 byte, why can I store 8 characters before the program crashes?

答:
you can do it i(in some cases) but this results in 'Undefined Behavior'. UB can produce many results, including seeming to work most of the time until your biggest customer tries to run your app on their busiest day.

You must not do this. There are various tools that you can use to detect it (electric fence, valgrind, for example)


问:
Oracle 10: Using HEXTORAW to fill in blob data
We have a table in Oracle with a BLOB column that needs to be filled with a small amount of arbitrary byte data--we will never put in more than 4000 bytes of data.

I am working with an existing C++ OCI-based infrastructure that makes it extremely difficult to use bind variables in certain contexts, so I need to populate this BLOB column using only a simple query. (We are working to modernize it but that's not an option today,)

We had some luck with a query like this:

```<code>UPDATE MyTable
   SET blobData = HEXTORAW('0EC1D7FA6B411DA5814...lots of hex data...0EC1D7FA6B411DA5814')
 WHERE ID = 123;
</code>```

At first, this was working great. However, recently we encountered a case where we need to put in more than 2000 bytes of data. At this point, we hit an Oracle error, ORA-01704: string literal too long because the string being passed to HEXTORAW was over 4000 characters. I tried splitting up the string and then concatenating with ||, but this didn't dodge the error.

So, I need a way to update this column and fill it with more than 2000 bytes' worth of data using a simple query. Is it possible?

(I know if I had bind variables at my disposal it would be trivial--and in fact other apps which interact with this table use that exact technique--but unfortunately I am not in a position to refactor the DB guts here. Just need to get data into the table.)

EDIT:

One promising approach that didn't work was concatenating RAWs:

```<code>UTL_RAW.CONCAT(HEXTORAW('...'), HEXTORAW('...'), HEXTORAW('...'))
</code>```

This dodges the string-length limit, but it appears that Oracle also has a matching internal 2000 byte limit on the length of a RAW. So I can't populate the blob with a RAW. Maybe there is a function that concatenates multiple RAWs into a BLOB.

答:
Another alternative since Oracle 12c is to use ALTER SYSTEM SET max_string_size=extended SCOPE=SPFILE; as documented in https://docs.oracle.com/database/121/REFRN/GUID-D424D23B-0933-425F-BC69-9C0E6724693C.htm#REFRN10321.

This would extend VARCHAR2 and RAW max size from 2000 to 32767.

Note that this requires sys permissions, DB restart and involves some gotchas: Oracle 12c extended to support varchar2 > 4000 bytes doesn't work for user who is not sysdba.

ContentLicense: CC BY-SA 3.0

Body:
We have a table in Oracle with a BLOB column that needs to be filled with a small amount of arbitrary byte data--we will never put in more than 4000 bytes of data.

I am working with an existing C++ OCI-based infrastructure that makes it extremely difficult to use bind variables in certain contexts, so I need to populate this BLOB column using only a simple query. (We are working to modernize it but that's not an option today,)

We had some luck with a query like this:

UPDATE MyTable
   SET blobData = HEXTORAW('0EC1D7FA6B411DA5814...lots of hex data...0EC1D7FA6B411DA5814')
 WHERE ID = 123;

At first, this was working great. However, recently we encountered a case where we need to put in more than 2000 bytes of data. At this point, we hit an Oracle error, ORA-01704: string literal too long because the string being passed to HEXTORAW was over 4000 characters. I tried splitting up the string and then concatenating with ||, but this didn't dodge the error.

So, I need a way to update this column and fill it with more than 2000 bytes' worth of data using a simple query. Is it possible?

(I know if I had bind variables at my disposal it would be trivial--and in fact other apps which interact with this table use that exact technique--but unfortunately I am not in a position to refactor the DB guts here. Just need to get data into the table.)

EDIT:

One promising approach that didn't work was concatenating RAWs:

UTL_RAW.CONCAT(HEXTORAW('...'), HEXTORAW('...'), HEXTORAW('...'))

This dodges the string-length limit, but it appears that Oracle also has a matching internal 2000 byte limit on the length of a RAW. So I can't populate the blob with a RAW. Maybe there is a function that concatenates multiple RAWs into a BLOB.


问:
UIBarButtonItem: How can I find its frame?
I have a button in a toolbar. How can I grab its frame? Do UIBarButtonItems not have a frame property?

答:
I used a view on the bar button item with a tag on the view:

```<code>for view in bottomToolbar.subviews {
   if let stackView = view.subviews.filter({$0 is UIStackView}).first {
       //target view has tag = 88
       if let targetView = stackView.subviews.filter({$0.viewWithTag(88) != nil}).first {
          //do something with target view
   }
}
</code>```

}

Body:
I used a view on the bar button item with a tag on the view:

for view in bottomToolbar.subviews {
   if let stackView = view.subviews.filter({$0 is UIStackView}).first {
       //target view has tag = 88
       if let targetView = stackView.subviews.filter({$0.viewWithTag(88) != nil}).first {
          //do something with target view
   }
}

}


问:
perform event-sourcing projections over table storage
I'm creating a tiny event-sourcing-style function app, where every invocation of a function will write an event to table storage. An example of such an event would be:

```<code>+------------+---------------+-----------------+
|   Event    |   Timestamp   |   Destination   |
+------------+---------------+-----------------+
| Connect    | 7/1/2019 4:52 | sftp.alex.com   |
| Disconnect | 7/1/2019 4:53 | sftp.liza.com   |
| Connect    | 7/1/2019 4:54 | sftp.yomama.com |
| Connect    | 7/1/2019 4:54 | sftp.alex.com   |
| Connect    | 7/1/2019 4:59 | sftp.liza.com   |
| Disconnect | 7/1/2019 4:59 | sftp.alex.com   |
| Disconnect | 7/1/2019 4:59 | sftp.yomama.com |
| Connect    | 7/1/2019 5:03 | sftp.alex.com   |
+------------+---------------+-----------------+
</code>```

How do I create a projection over this table?

The main question that I would need to answer is:

How many connections does each destination currently have?

答:
Projections should be decoupled from the Event Stream because they are business driven while the Event Stream is purely a technical aspect.

I assume you are going to use SQL for persisting the projections to simplify the answer, but any Key/Value data store will do.

You can create a DestinationEvents table with the following structure:

```<code>+------------------+-----------------+-------------------+
|   Destination    |   Connections   |   Disconnections  |
+------------------+-----------------+-------------------+
| sftp.alex.com    |        3        |        1          |
| sftp.liza.com    |        1        |        1          |
+------------------+-----------------+-------------------+
</code>```

With proper indexing this should give both fast reads and writes. For extra speed consider something like Redis to cache your projections.

The tricky bit is in solution design, you want it to scale.
A naive approach may be to set up a SQL trigger for each write into the Event Stream, but this will slow you down if you have loads of writes.

If you want scalability, you need to start thinking about budget(time and money) and business requirements. Do the projections need to be available in real time?

if Not, you can have a scheduled process that computes/updates projections at a certain interval: daily, hourly, weekly, etc.

if Yes, you need to start looking into Queues/Message Brokers (RabbitMQ, Kafka, etc). Now you are entering in Producer/Consumer logic. Your App is the Producer, it publishes events. The EventStream and Projections storage are Consumers, they listen, transform and persist the incoming events. It is possible for the Queue/MessageBroker itself to replace your Event Stream table, it is easy with Kafka.

If you just want to learn, start with defining an in memory projection storage using a Dictionary<string, (int Connections, int Disconnections)> where Destination acts as Key and (int Connections, int Disconnections) is a tuple/class.

If you want to support other Projections, the in memory storage can be a Dictionary<string, Dictionary<string, (int Connections, int Disconnections)>> where the outer dictionary Key is the Projection name.

Body:
I'm creating a tiny event-sourcing-style function app, where every invocation of a function will write an event to table storage. An example of such an event would be:

+------------+---------------+-----------------+
|   Event    |   Timestamp   |   Destination   |
+------------+---------------+-----------------+
| Connect    | 7/1/2019 4:52 | sftp.alex.com   |
| Disconnect | 7/1/2019 4:53 | sftp.liza.com   |
| Connect    | 7/1/2019 4:54 | sftp.yomama.com |
| Connect    | 7/1/2019 4:54 | sftp.alex.com   |
| Connect    | 7/1/2019 4:59 | sftp.liza.com   |
| Disconnect | 7/1/2019 4:59 | sftp.alex.com   |
| Disconnect | 7/1/2019 4:59 | sftp.yomama.com |
| Connect    | 7/1/2019 5:03 | sftp.alex.com   |
+------------+---------------+-----------------+

How do I create a projection over this table?

The main question that I would need to answer is:

How many connections does each destination currently have?

Body:
Projections should be decoupled from the Event Stream because they are business driven while the Event Stream is purely a technical aspect.

I assume you are going to use SQL for persisting the projections to simplify the answer, but any Key/Value data store will do.

You can create a DestinationEvents table with the following structure:

+------------------+-----------------+-------------------+
|   Destination    |   Connections   |   Disconnections  |
+------------------+-----------------+-------------------+
| sftp.alex.com    |        3        |        1          |
| sftp.liza.com    |        1        |        1          |
+------------------+-----------------+-------------------+

With proper indexing this should give both fast reads and writes. For extra speed consider something like Redis to cache your projections.

The tricky bit is in solution design, you want it to scale.
A naive approach may be to set up a SQL trigger for each write into the Event Stream, but this will slow you down if you have loads of writes.

If you want scalability, you need to start thinking about budget(time and money) and business requirements. Do the projections need to be available in real time?

if Not, you can have a scheduled process that computes/updates projections at a certain interval: daily, hourly, weekly, etc.

if Yes, you need to start looking into Queues/Message Brokers (RabbitMQ, Kafka, etc). Now you are entering in Producer/Consumer logic. Your App is the Producer, it publishes events. The EventStream and Projections storage are Consumers, they listen, transform and persist the incoming events. It is possible for the Queue/MessageBroker itself to replace your Event Stream table, it is easy with Kafka.

If you just want to learn, start with defining an in memory projection storage using a Dictionary<string, (int Connections, int Disconnections)> where Destination acts as Key and (int Connections, int Disconnections) is a tuple/class.

If you want to support other Projections, the in memory storage can be a Dictionary<string, Dictionary<string, (int Connections, int Disconnections)>> where the outer dictionary Key is the Projection name.


问:
Having trouble installing PubNub and using it with PyCharm
I've been trying to install pubnub on my mac and then use it in PyCharm. When I run the install command on terminal, it says that all the requirements are satisfied, leading me to believe it is installed on my machine. However, when I try to install it on PyCharm, it gives me the error that the packages are not found and I am unable to use it.

pip3 install pubnub==4.5.2
Requirement already satisfied: pubnub==4.5.2 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (4.5.2)
Requirement already satisfied: pycryptodomex>=3.3 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from pubnub==4.5.2) (3.9.7)
Requirement already satisfied: requests>=2.4 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from pubnub==4.5.2) (2.23.0)
```

答:
I consulted with the PubNub Engineering team. It seems to have more to do with PyCharm than PubNub, specifically. It is likely that your PyCharm is not using the same python environment as when you run from your terminal. Here are some links that should assist with getting everything configured the way you need it:

Install, uninstall, and upgrade packages

Create a virtual environment

Configure a Python interpreter

Not implying to do all of the above, but read through all of them and decide what actions you may need to take based on your environment. For further issues, you may need to hit up a PyCharm forum.

If there is something specific to PubNub, you can send your inquiry with as much detail as possible to PubNub Support. But again, probably just environment configuration issues that you would have with any third party Python library, similar to PubNub.


问:
Kotlin - Interface with two functions and one of the functions is not working
I have an interface with one function and it was working properly. Then I added a second function, which I want to use to send the same array but to a different activity, but in the main activity I'm getting the following error: No value passed for parameter 'PatDischargeBtnDelegate'. Here is my code:

Interface

```<code>interface PatDataCommentDelegate {
    fun patDataCommentBtnClicked(ptdata: PatData)
    fun dischargePatientBtnClicked(ptdata: PatData)
}
</code>```

Adapter

```<code>class PatDataAdapter(val ptdata: ArrayList<PatData>, val patDataBtnDelegate: PatDataCommentDelegate,
                     val patDischargeBtnDelegate: PatDataCommentDelegate) :
RecyclerView.Adapter<PatDataAdapter.ViewHolder>() {
......

       commentImage?.setOnClickListener {
            patDataBtnDelegate.patDataCommentBtnClicked(ptdata)
        }

        dischargePatImg?.setOnClickListener{
            patDischargeBtnDelegate.dischargePatientBtnClicked(ptdata)
        }
</code>```

Main Activity

```<code>class PatDataActivity : AppCompatActivity(), PatDataCommentDelegate {
....

patDataFromAdapter = PatDataAdapter(ptdatas, this) //I get the error here

 override fun patDataCommentBtnClicked(ptdata: PatData) {
        val commentDataActivity = Intent(this, CommentsActivity::class.java)
        commentDataActivity.putExtra(DOCUMENT_ID, ptdata.documentId)
        commentDataActivity.putExtra(USER_ID, userId)
        commentDataActivity.putExtra(PTNAME, ptdata.ptName)
        commentDataActivity.putExtra(FIN, ptdata.fin)
        commentDataActivity.putExtra(ROOM, ptdata.room)
        commentDataActivity.putExtra(HOSP, ptdata.hosp)
        startActivity(commentDataActivity)
    }

    override fun dischargePatientBtnClicked(ptdata: PatData) {
        val dischargePatientActivity = Intent(this, DischargeActivity::class.java)
        dischargePatientActivity.putExtra(DOCUMENT_ID, ptdata.documentId)
        dischargePatientActivity.putExtra(USER_ID, userId)
        dischargePatientActivity.putExtra(PTNAME, ptdata.ptName)
        dischargePatientActivity.putExtra(FIN, ptdata.fin)
        dischargePatientActivity.putExtra(ROOM, ptdata.room)
        dischargePatientActivity.putExtra(HOSP, ptdata.hosp)
        startActivity(dischargePatientActivity)
    }
</code>```

I'm not sure what I'm missing, please any help is greatly appreciated. Thank you!

答:
The problem is here in 3rd argument.

```<code>class PatDataAdapter(
    val ptdata: ArrayList<PatData>,
    val patDataBtnDelegate: PatDataCommentDelegate,
    val patDischargeBtnDelegate: PatDataCommentDelegate // you don't need this one.
) : RecyclerView.Adapter<PatDataAdapter.ViewHolder>() {
</code>```

This should work:

```<code>class PatDataAdapter(val ptdata: ArrayList<PatData>, val patDataBtnDelegate: PatDataCommentDelegate) :
RecyclerView.Adapter<PatDataAdapter.ViewHolder>() {

   commentImage?.setOnClickListener {
        patDataBtnDelegate.patDataCommentBtnClicked(ptdata)
    }

    dischargePatImg?.setOnClickListener{
        patDataBtnDelegate.dischargePatientBtnClicked(ptdata)
    }
</code>```

You only need a reference to interface PatDataCommentDelegate itself NOT to each method separately.

Body:
I have an interface with one function and it was working properly. Then I added a second function, which I want to use to send the same array but to a different activity, but in the main activity I'm getting the following error: No value passed for parameter 'PatDischargeBtnDelegate'. Here is my code:

Interface

interface PatDataCommentDelegate {
    fun patDataCommentBtnClicked(ptdata: PatData)
    fun dischargePatientBtnClicked(ptdata: PatData)
}

Adapter

class PatDataAdapter(val ptdata: ArrayList<PatData>, val patDataBtnDelegate: PatDataCommentDelegate,
                     val patDischargeBtnDelegate: PatDataCommentDelegate) :
RecyclerView.Adapter<PatDataAdapter.ViewHolder>() {
......

       commentImage?.setOnClickListener {
            patDataBtnDelegate.patDataCommentBtnClicked(ptdata)
        }

        dischargePatImg?.setOnClickListener{
            patDischargeBtnDelegate.dischargePatientBtnClicked(ptdata)
        }

Main Activity

class PatDataActivity : AppCompatActivity(), PatDataCommentDelegate {
....

patDataFromAdapter = PatDataAdapter(ptdatas, this) //I get the error here

 override fun patDataCommentBtnClicked(ptdata: PatData) {
        val commentDataActivity = Intent(this, CommentsActivity::class.java)
        commentDataActivity.putExtra(DOCUMENT_ID, ptdata.documentId)
        commentDataActivity.putExtra(USER_ID, userId)
        commentDataActivity.putExtra(PTNAME, ptdata.ptName)
        commentDataActivity.putExtra(FIN, ptdata.fin)
        commentDataActivity.putExtra(ROOM, ptdata.room)
        commentDataActivity.putExtra(HOSP, ptdata.hosp)
        startActivity(commentDataActivity)
    }

    override fun dischargePatientBtnClicked(ptdata: PatData) {
        val dischargePatientActivity = Intent(this, DischargeActivity::class.java)
        dischargePatientActivity.putExtra(DOCUMENT_ID, ptdata.documentId)
        dischargePatientActivity.putExtra(USER_ID, userId)
        dischargePatientActivity.putExtra(PTNAME, ptdata.ptName)
        dischargePatientActivity.putExtra(FIN, ptdata.fin)
        dischargePatientActivity.putExtra(ROOM, ptdata.room)
        dischargePatientActivity.putExtra(HOSP, ptdata.hosp)
        startActivity(dischargePatientActivity)
    }

I'm not sure what I'm missing, please any help is greatly appreciated. Thank you!

Body:
The problem is here in 3rd argument.

class PatDataAdapter(
    val ptdata: ArrayList<PatData>,
    val patDataBtnDelegate: PatDataCommentDelegate,
    val patDischargeBtnDelegate: PatDataCommentDelegate // you don't need this one.
) : RecyclerView.Adapter<PatDataAdapter.ViewHolder>() {

This should work:

class PatDataAdapter(val ptdata: ArrayList<PatData>, val patDataBtnDelegate: PatDataCommentDelegate) :
RecyclerView.Adapter<PatDataAdapter.ViewHolder>() {

   commentImage?.setOnClickListener {
        patDataBtnDelegate.patDataCommentBtnClicked(ptdata)
    }

    dischargePatImg?.setOnClickListener{
        patDataBtnDelegate.dischargePatientBtnClicked(ptdata)
    }

You only need a reference to interface PatDataCommentDelegate itself NOT to each method separately.


问:
how to show data from two database tables in vue with vuetify
I have a list of clients wiht a salesman field which is bound to a user id in the database, ¿how do i show in the table the user name that corresponds to its id?

```<code><v-data-table :headers="headers" :items="arrayClientes">
  <template v-slot:item.user_id="{ item }" :items="userLists">
          <span>{{item.user_id}}</span>
  </template>
</code>```

Script:

```<code>computed: {
      userLists() {
        return this.$store.state.user.users;
      },
    },
    created(){
        this.$store.dispatch('user/getUsers')
    },
</code>```

答:
you can try it this way

```<code>getUser(id) {
     return this.userLists.filter(user => user.id === id).map(user => user.name)[0];
},
</code>```

I hope it works for you, regards!

Body:
I have a list of clients wiht a salesman field which is bound to a user id in the database, ¿how do i show in the table the user name that corresponds to its id?

<v-data-table :headers="headers" :items="arrayClientes">
  <template v-slot:item.user_id="{ item }" :items="userLists">
          {{item.user_id}}
  </template>

Script:

computed: {
      userLists() {
        return this.$store.state.user.users;
      },
    },
    created(){
        this.$store.dispatch('user/getUsers')
    },

Body:
you can try it this way

getUser(id) {
     return this.userLists.filter(user => user.id === id).map(user => user.name)[0];
},

I hope it works for you, regards!


问:
How can I count the unique values from all columns and display them in a separate dataframe w.r.t. their unique name?
```<code>| 1st Most Common Value | 2nd Most Common Value | 3rd Most Common Value | 4th Most Common Value | 5th Most Common Value |
|-----------------------|-----------------------|-----------------------|-----------------------|-----------------------|
| Grocery Store         | Pub                   | Coffee Shop           | Clothing Store        | Park                  |
| Pub                   | Grocery Store         | Clothing Store        | Park                  | Coffee Shop           |
| Hotel                 | Theatre               | Bookstore             | Plaza                 | Park                  |
| Supermarket           | Coffee Shop           | Pub                   | Park                  | Cafe                  |
| Pub                   | Supermarket           | Coffee Shop           | Cafe                  | Park                  |
</code>```

The name of the dataframe is df0. As you can see there are many values repeating in all the columns. So I want to create a dataframe which has all the unique values with their frequencies from all the columns. Can someone please help with the code since I want to create a Bar plot of it?

The Output should be as follows:

```<code>| Venues         | Count |
|----------------|-------|
| Bookstore      | 1     |
| Cafe           | 2     |
| Coffee Shop    | 4     |
| Clothing Store | 2     |
| Grocery Store  | 2     |
| Hotel          | 1     |
| Park           | 5     |
| Plaza          | 1     |
| Pub            | 4     |
| Supermarket    | 2     |
| Theatre        | 1     |
</code>```

答:
EDIT: I got ahead of myself in my original answer (also thanks OP for adding the edit/expected output).  You want this post, I think the simplest answer:

```<code>new_df = pd.DataFrame(df0.stack().value_counts())
</code>```

If you don't care about which column the values are coming from, and you just want their counts, then use value_counts() (as @Celius Stingher said in the comments), following this post.

If you do want to report the frequency of each value for each column, you can use value_counts() for each column, but you may end up with uneven entries (to get back into a DataFrame, you could do some sort of join).

I instead made a little function to count the occurrences of values in a df, and return a new one:

```<code>import pandas as pd
import numpy as np

def counted_entries(df, array):
    output = pd.DataFrame(columns=df.columns, index=array)
    for i in array:
        output.loc[i] = (df==i).sum()
    return output
</code>```

This works for a df filled with random animal value names.  You just have to pass the unique entries in the df by getting the set of its values:

```<code>columns = ['Column ' + str(i+1) for i in range(10)]
index = ['Row ' + str(i+1) for i in range(5)]

df = pd.DataFrame(np.random.choice(['pig','cow','sheep','horse','dog'],size=(5,10)), columns=columns, index=index)

unique_vals = list(set(df.stack())) #this is all the possible entries in the df

df2 = counted_entries(df, unique_vals)
</code>```

df before:

```<code>      Column 1 Column 2 Column 3 Column 4  ... Column 7 Column 8 Column 9 Column 10
Row 1      pig      pig      cow      cow  ...      cow      pig      dog       pig
Row 2    sheep      cow      pig    sheep  ...      dog      pig      pig       cow
Row 3      cow      cow      cow    sheep  ...    horse      dog    sheep     sheep
Row 4    sheep      cow    sheep      cow  ...      cow    horse      pig       pig
Row 5      dog      pig    sheep    sheep  ...    sheep    sheep    horse     horse
</code>```

output of counted_entries()

```<code>       Column 1  Column 2  Column 3  ...  Column 8  Column 9  Column 10
pig           1         2         1  ...         2         2          2
horse         0         0         0  ...         1         1          1
sheep         2         0         2  ...         1         1          1
dog           1         0         0  ...         1         1          0
cow           1         3         2  ...         0         0          1
</code>```

Body:
| 1st Most Common Value | 2nd Most Common Value | 3rd Most Common Value | 4th Most Common Value | 5th Most Common Value |
|-----------------------|-----------------------|-----------------------|-----------------------|-----------------------|
| Grocery Store         | Pub                   | Coffee Shop           | Clothing Store        | Park                  |
| Pub                   | Grocery Store         | Clothing Store        | Park                  | Coffee Shop           |
| Hotel                 | Theatre               | Bookstore             | Plaza                 | Park                  |
| Supermarket           | Coffee Shop           | Pub                   | Park                  | Cafe                  |
| Pub                   | Supermarket           | Coffee Shop           | Cafe                  | Park                  |

The name of the dataframe is df0. As you can see there are many values repeating in all the columns. So I want to create a dataframe which has all the unique values with their frequencies from all the columns. Can someone please help with the code since I want to create a Bar plot of it?

The Output should be as follows:

| Venues         | Count |
|----------------|-------|
| Bookstore      | 1     |
| Cafe           | 2     |
| Coffee Shop    | 4     |
| Clothing Store | 2     |
| Grocery Store  | 2     |
| Hotel          | 1     |
| Park           | 5     |
| Plaza          | 1     |
| Pub            | 4     |
| Supermarket    | 2     |
| Theatre        | 1     |

Body:
EDIT: I got ahead of myself in my original answer (also thanks OP for adding the edit/expected output).  You want this post, I think the simplest answer:

new_df = pd.DataFrame(df0.stack().value_counts())

If you don't care about which column the values are coming from, and you just want their counts, then use value_counts() (as @Celius Stingher said in the comments), following this post.

If you do want to report the frequency of each value for each column, you can use value_counts() for each column, but you may end up with uneven entries (to get back into a DataFrame, you could do some sort of join).

I instead made a little function to count the occurrences of values in a df, and return a new one:

import pandas as pd
import numpy as np

def counted_entries(df, array):
    output = pd.DataFrame(columns=df.columns, index=array)
    for i in array:
        output.loc[i] = (df==i).sum()
    return output

This works for a df filled with random animal value names.  You just have to pass the unique entries in the df by getting the set of its values:

columns = ['Column ' + str(i+1) for i in range(10)]
index = ['Row ' + str(i+1) for i in range(5)]

df = pd.DataFrame(np.random.choice(['pig','cow','sheep','horse','dog'],size=(5,10)), columns=columns, index=index)

unique_vals = list(set(df.stack())) #this is all the possible entries in the df

df2 = counted_entries(df, unique_vals)

df before:

      Column 1 Column 2 Column 3 Column 4  ... Column 7 Column 8 Column 9 Column 10
Row 1      pig      pig      cow      cow  ...      cow      pig      dog       pig
Row 2    sheep      cow      pig    sheep  ...      dog      pig      pig       cow
Row 3      cow      cow      cow    sheep  ...    horse      dog    sheep     sheep
Row 4    sheep      cow    sheep      cow  ...      cow    horse      pig       pig
Row 5      dog      pig    sheep    sheep  ...    sheep    sheep    horse     horse

output of counted_entries()

       Column 1  Column 2  Column 3  ...  Column 8  Column 9  Column 10
pig           1         2         1  ...         2         2          2
horse         0         0         0  ...         1         1          1
sheep         2         0         2  ...         1         1          1
dog           1         0         0  ...         1         1          0
cow           1         3         2  ...         0         0          1


问:
kinesis video streams webrtc 403 forbidden on presigned websocket wss url
I'm using SigV4RequestSigner to presign a WebSocket url in aws lambda, using Amazon Kinesis Video Streams WebRTC SDK for JavaScript

In the client when attempting to call new SignalingClient() with a requestSigner that returns the presigned url from the server I'm getting the following error:

```<code>Error during WebSocket handshake: Unexpected response code: 403
</code>```

What could be the reason?

Could this be a CORS issue?

Maybe the url is missing a token or a header?

答: Solved when adding the kinesisvideo:ConnectAsMaster permission to the lambda function which signs the url.

Body:
I'm using SigV4RequestSigner to presign a WebSocket url in aws lambda, using Amazon Kinesis Video Streams WebRTC SDK for JavaScript

In the client when attempting to call new SignalingClient() with a requestSigner that returns the presigned url from the server I'm getting the following error:

Error during WebSocket handshake: Unexpected response code: 403

What could be the reason?

Could this be a CORS issue?

Maybe the url is missing a token or a header?


问:
Return to Main, but with free format
I'm writing a Virtual Time Machine
I want to go back to the beginning when a year is evaluated, but with free format I can't just say "GO TO MAIN"
I basically want the program say: do you want to evaluate other years?"
IF yes GO TO "MAIN" (that there isn't, because for writing long text I use free format)
IF NO stop run.

```<code>ACCEPT INPUT1
           IF INPUT1 = 1900
                  DISPLAY"London reaches 4,300,000 inhabitants"
                  DISPLAY"Paris reaches 2,000,000 inhabitants"
                  DISPLAY"From 14 May to 28 October, the 2nd Olympics will take place in Paris."
                  DISPLAY"In Great Britain, on 28 February, the Labour representation committee was founded, under the leadership of Ramsay McDonald (1866-1937), which united, within the new party, associations and unions of socialist orientation."
                  DISPLAY"Bernhard von Bülow succeeded the Prince of Hohenlohe, Chlodwig, as the new Chancellor of the German Reich (1900 - 1909)."
                  DISPLAY"The American Schools of Oriental Research is founded."
               END-IF
               DISPLAY "Do you want to analyze the events of other years??"
               ACCEPT Q
               IF Q = "Y" OR "YES" OR "y" OR "yes" OR "Yes" GO TO
                   ELSE DISPLAY "OK, GOOD JOB :)"
                       DISPLAY "I EXIT IN 3 SECONDS..."
                       CALL "CBL_OC_NANOSLEEP" USING "1000000000"
                   END-CALL
                   DISPLAY "I EXIT IN 2 SECONDS.."
                   CALL "CBL_OC_NANOSLEEP" USING "1000000000"
                   END-CALL
                   DISPLAY "I EXIT IN 1 SECOND."
                   CALL "CBL_OC_NANOSLEEP" USING "300000000"
                   END-CALL
               STOP RUN.
</code>```

Have you any ideas? Thanks a lot:)

答:
Free-form reference-format did not drop paragraphs or GO TO, therefore you could simply add those and are fine.
But I'd suggest to have a main logic including the loop as a loop and structure the code a bit, in this case:

```<code>  MAIN SECTION.
     PERFORM TIME-MACHINE UNTIL NOT (Q = "Y" OR "YES")
     PERFORM ENDING-CINEMA
     GOBACK.
  *>
  TIME-MACHINE SECTION.
     ACCEPT INPUT1
     IF INPUT1 = 1900
        DISPLAY"London reaches 4,300,000 inhabitants"
        DISPLAY"Paris reaches 2,000,000 inhabitants"
        DISPLAY"From 14 May to 28 October, the 2nd Olympics will take place in Paris."
        DISPLAY"In Great Britain, on 28 February, the Labour representation committee was founded, under the leadership of Ramsay McDonald (1866-1937), which united, within the new party, associations and unions of socialist orientation."
        DISPLAY"Bernhard von Bülow succeeded the Prince of Hohenlohe, Chlodwig, as the new Chancellor of the German Reich (1900 - 1909)."
        DISPLAY"The American Schools of Oriental Research is founded."
     END-IF
     DISPLAY "Do you want to analyze the events of other years??"
     ACCEPT Q
     INSPECT Q (1:3) CONVERTING "yes" to "YES"
     CONTINUE.
  *>
  ENDING-CINEMA SECTION.
     DISPLAY "OK, GOOD JOB :)"
     DISPLAY "I EXIT IN 3 SECONDS..."
     CONTINUE AFTER 1 SECOND  *> for "old" GnuCOBOL use a call to "C$SLEEP" USING "1"
     DISPLAY "I EXIT IN 2 SECONDS.."
     CONTINUE AFTER 1 SECOND
     DISPLAY "I EXIT IN 1 SECOND."
     CONTINUE AFTER 1 SECOND
     CONTINUE.
</code>```

Title: Return to Main, but with free format

Body:
I'm writing a Virtual Time Machine
I want to go back to the beginning when a year is evaluated, but with free format I can't just say "GO TO MAIN"
I basically want the program say: do you want to evaluate other years?"
IF yes GO TO "MAIN" (that there isn't, because for writing long text I use free format)
IF NO stop run.

ACCEPT INPUT1
           IF INPUT1 = 1900
                  DISPLAY"London reaches 4,300,000 inhabitants"
                  DISPLAY"Paris reaches 2,000,000 inhabitants"
                  DISPLAY"From 14 May to 28 October, the 2nd Olympics will take place in Paris."
                  DISPLAY"In Great Britain, on 28 February, the Labour representation committee was founded, under the leadership of Ramsay McDonald (1866-1937), which united, within the new party, associations and unions of socialist orientation."
                  DISPLAY"Bernhard von Bülow succeeded the Prince of Hohenlohe, Chlodwig, as the new Chancellor of the German Reich (1900 - 1909)."
                  DISPLAY"The American Schools of Oriental Research is founded."
               END-IF
               DISPLAY "Do you want to analyze the events of other years??"
               ACCEPT Q
               IF Q = "Y" OR "YES" OR "y" OR "yes" OR "Yes" GO TO
                   ELSE DISPLAY "OK, GOOD JOB :)"
                       DISPLAY "I EXIT IN 3 SECONDS..."
                       CALL "CBL_OC_NANOSLEEP" USING "1000000000"
                   END-CALL
                   DISPLAY "I EXIT IN 2 SECONDS.."
                   CALL "CBL_OC_NANOSLEEP" USING "1000000000"
                   END-CALL
                   DISPLAY "I EXIT IN 1 SECOND."
                   CALL "CBL_OC_NANOSLEEP" USING "300000000"
                   END-CALL
               STOP RUN.

Have you any ideas? Thanks a lot:)

Body:
Free-form reference-format did not drop paragraphs or GO TO, therefore you could simply add those and are fine.
But I'd suggest to have a main logic including the loop as a loop and structure the code a bit, in this case:

  MAIN SECTION.
     PERFORM TIME-MACHINE UNTIL NOT (Q = "Y" OR "YES")
     PERFORM ENDING-CINEMA
     GOBACK.
  *>
  TIME-MACHINE SECTION.
     ACCEPT INPUT1
     IF INPUT1 = 1900
        DISPLAY"London reaches 4,300,000 inhabitants"
        DISPLAY"Paris reaches 2,000,000 inhabitants"
        DISPLAY"From 14 May to 28 October, the 2nd Olympics will take place in Paris."
        DISPLAY"In Great Britain, on 28 February, the Labour representation committee was founded, under the leadership of Ramsay McDonald (1866-1937), which united, within the new party, associations and unions of socialist orientation."
        DISPLAY"Bernhard von Bülow succeeded the Prince of Hohenlohe, Chlodwig, as the new Chancellor of the German Reich (1900 - 1909)."
        DISPLAY"The American Schools of Oriental Research is founded."
     END-IF
     DISPLAY "Do you want to analyze the events of other years??"
     ACCEPT Q
     INSPECT Q (1:3) CONVERTING "yes" to "YES"
     CONTINUE.
  *>
  ENDING-CINEMA SECTION.
     DISPLAY "OK, GOOD JOB :)"
     DISPLAY "I EXIT IN 3 SECONDS..."
     CONTINUE AFTER 1 SECOND  *> for "old" GnuCOBOL use a call to "C$SLEEP" USING "1"
     DISPLAY "I EXIT IN 2 SECONDS.."
     CONTINUE AFTER 1 SECOND
     DISPLAY "I EXIT IN 1 SECOND."
     CONTINUE AFTER 1 SECOND
     CONTINUE.


问:
Can't set Guzzle Content Type
I'm trying to request this way:

```<code>$body = [];
$body['holder_name'] = $full_name;
$body['bank_code'] = $bank_number;
$body['routing_number'] = $branch_number;
$body['account_number'] = $account_number;
$body['type'] = 'checking';

$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'headers'  => ['content-type' => 'application/json', 'Accept' => 'application/json'],
    'defaults' => [
         'auth' => [$publishable_key, ''],
],
    'body' => json_encode($body),
]);
</code>```

The problem is that this request is being set without Content-Type.
What am I doing wrong?

答:
I was encountering the same issue with the Hubspot API that requires to set application/json as Content-Type for POST requests.

I fixed it this way

```<code>$client = new Client([
    'base_uri' => 'https://api.hubapi.com/',
    'timeout'  => 5,
    'headers' => ['Content-Type' => 'application/json']
]);
</code>```

And then performing my requests the regular way

```<code>try
{
    $response = $client->request('POST', '/contacts/v1/contact/email/test@test.com/profile',
    ['query' => MY_HUBSPOT_API_KEY, 'body' => $body]);
}
catch (RequestException $e) { print_r($e); }
</code>```

I hope this helps.

Title: Can't set Guzzle Content Type

Body:
I'm trying to request this way:

$body = [];
$body['holder_name'] = $full_name;
$body['bank_code'] = $bank_number;
$body['routing_number'] = $branch_number;
$body['account_number'] = $account_number;
$body['type'] = 'checking';

$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'headers'  => ['content-type' => 'application/json', 'Accept' => 'application/json'],
    'defaults' => [
         'auth' => [$publishable_key, ''],
],
    'body' => json_encode($body),
]);

The problem is that this request is being set without Content-Type.
What am I doing wrong?

Body:
I was encountering the same issue with the Hubspot API that requires to set application/json as Content-Type for POST requests.

I fixed it this way

$client = new Client([
    'base_uri' => 'https://api.hubapi.com/',
    'timeout'  => 5,
    'headers' => ['Content-Type' => 'application/json']
]);

And then performing my requests the regular way

try
{
    $response = $client->request('POST', '/contacts/v1/contact/email/test@test.com/profile',
    ['query' => MY_HUBSPOT_API_KEY, 'body' => $body]);
}
catch (RequestException $e) { print_r($e); }

I hope this helps.


问:
Xamarin Forms Center CollectionView content
I have a problem. I created a page that looks like this:

Now I want the content of the CollectionView to be centered. I already tried things to set on HorizontalOptions=Center, but no luck!

Here is the code of that part:

```<code><StackLayout HorizontalOptions="CenterAndExpand">
    <CollectionView ItemsSource="{Binding coinDataList}" ItemsLayout="HorizontalList" Margin="0" HorizontalOptions="CenterAndExpand" BackgroundColor="Red">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <Grid RowSpacing="0" Margin="20,0,20,0" HorizontalOptions="CenterAndExpand" Padding="0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="20" />
                        <RowDefinition Height="5" />
                        <RowDefinition Height="20" />
                        <RowDefinition Height="10" />
                        <RowDefinition Height="20" />
                    </Grid.RowDefinitions>

                    <Label Grid.Row="0" VerticalOptions="CenterAndExpand" HorizontalOptions="Center" Text="{Binding Coin}" FontAttributes="Bold" TextColor="#00D8FF" FontSize="18"/>
                    <Label Grid.Row="2" VerticalOptions="CenterAndExpand" HorizontalOptions="Center" Text="{Binding Price, StringFormat='{0:F2}'}" TextColor="White" FontSize="18"/>
                </Grid>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</StackLayout>
</code>```

How can I do that?

答:
You can achieve this by using BindableLayout in conjunction with the StackLayout with horizontal orientation. This will not be as performant as CollectionView, but from your UI, it looks like you will not be having a lot of items in your ItemSource collection, but you your need UI to be dynamic and evenly spaced and centered when there are fewer items. As the item list grows, the UI will look more like the horizontal list view.

So here is the minimal working XAML which you can modify to fit into your project. For sake of simplicity, I have added everything in the XAML (no code behind), so you can plug this XAML right into the content page and test it out!

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:generic="clr-namespace:System.Collections.Generic;assembly=netstandard"
             mc:Ignorable="d"
             x:Class="Playground.MainPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <generic:List x:Key="SymbolNames" x:TypeArguments="x:String">
                <x:String>BTC</x:String>
                <x:String>LTC</x:String>
                <x:String>ETH</x:String>
                <x:String>OT1</x:String>
                <x:String>OT2</x:String>
                <x:String>OT3</x:String>
                <x:String>OT4</x:String>
                <x:String>OT5</x:String>
                <x:String>OT6</x:String>
            </generic:List>
        </ResourceDictionary>
    </ContentPage.Resources>

    <ScrollView Orientation="Horizontal" HeightRequest="60" VerticalOptions="Start">
        <StackLayout BindableLayout.ItemsSource="{Binding Source={StaticResource SymbolNames}}" Orientation="Horizontal">
            <BindableLayout.ItemTemplate>
                <DataTemplate>
                    <Label Text="{Binding}" HorizontalOptions="CenterAndExpand" VerticalOptions="Center" Margin="10"/>
                </DataTemplate>
            </BindableLayout.ItemTemplate>
        </StackLayout>
    </ScrollView>
</ContentPage>
</code>```

UI when 3 Items:

UI When multiple overflowing items:

Body:
I have a problem. I created a page that looks like this:

Now I want the content of the CollectionView to be centered. I already tried things to set on HorizontalOptions=Center, but no luck!

Here is the code of that part:

<StackLayout HorizontalOptions="CenterAndExpand">
    <CollectionView ItemsSource="{Binding coinDataList}" ItemsLayout="HorizontalList" Margin="0" HorizontalOptions="CenterAndExpand" BackgroundColor="Red">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <Grid RowSpacing="0" Margin="20,0,20,0" HorizontalOptions="CenterAndExpand" Padding="0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="20" />
                        <RowDefinition Height="5" />
                        <RowDefinition Height="20" />
                        <RowDefinition Height="10" />
                        <RowDefinition Height="20" />
                    </Grid.RowDefinitions>

                </Grid>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</StackLayout>

How can I do that?

Body:
You can achieve this by using BindableLayout in conjunction with the StackLayout with horizontal orientation. This will not be as performant as CollectionView, but from your UI, it looks like you will not be having a lot of items in your ItemSource collection, but you your need UI to be dynamic and evenly spaced and centered when there are fewer items. As the item list grows, the UI will look more like the horizontal list view.

So here is the minimal working XAML which you can modify to fit into your project. For sake of simplicity, I have added everything in the XAML (no code behind), so you can plug this XAML right into the content page and test it out!

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:generic="clr-namespace:System.Collections.Generic;assembly=netstandard"
             mc:Ignorable="d"
             x:Class="Playground.MainPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <generic:List x:Key="SymbolNames" x:TypeArguments="x:String">
                <x:String>BTC</x:String>
                <x:String>LTC</x:String>
                <x:String>ETH</x:String>
                <x:String>OT1</x:String>
                <x:String>OT2</x:String>
                <x:String>OT3</x:String>
                <x:String>OT4</x:String>
                <x:String>OT5</x:String>
                <x:String>OT6</x:String>
            </generic:List>
        </ResourceDictionary>
    </ContentPage.Resources>

    <ScrollView Orientation="Horizontal" HeightRequest="60" VerticalOptions="Start">
        <StackLayout BindableLayout.ItemsSource="{Binding Source={StaticResource SymbolNames}}" Orientation="Horizontal">
            <BindableLayout.ItemTemplate>
                <DataTemplate>
                    <Label Text="{Binding}" HorizontalOptions="CenterAndExpand" VerticalOptions="Center" Margin="10"/>
                </DataTemplate>
            </BindableLayout.ItemTemplate>
        </StackLayout>
    </ScrollView>
</ContentPage>

UI when 3 Items:

UI When multiple overflowing items:


问:
How to rebuild Lustre Properly for MOFED
I've been struggling lately in how to get o2ib to function properly with a particular MOFED version. What I've tried so far is to install the Lustre kernel, rebuild MOFED for that Lustre kernel (which appears to be working) and then observe that ib0 is listed upon a reboot, and install the generic Lustre kmod-lustre kmod-lustre-osd-ldiskfs lustre-osd-ldiskfs-mount lustre lustre-resource-agents. However just because ib0 is there, does not  mean that o2ib presents itself in Lustre. Even running "lnetctl net add --net o2ib --if ib0" gives nothing but errors that the interface cannot be found.

I have tried rebuilding Lustre serveral times to try and get the o2ib interface, but to no avail. The rpms are built, but when I install them the situation is no better. My process is as follows (for Lustre 2.12):

git clone git://git.whamcloud.com/fs/lustre-release.git
cd lustre-release
git checkout 2.12.0
sh autogen.sh
./configure --with-o2ib=/usr/src/ofa_kernel/default/
make rpms

Would anyone have any suggestons?

Thanks!

答:
Actually you should do the other way around: you should compile Lustre to properly use your MOFED and your kernel. This is the order of dependencies:

Your kernel (e.g: 3.10.0-1127.8.2.el7.x86_64)

Your MOFED has to be compiled for your kernel. If your kernel is one of the ones available from Mellanox you just need to install the rpms or let the MOFED installer do it for you:

```<code># ./mlnxofedinstall
</code>```

If you're using a different kernel you need to recompile MOFED (you need to install kernel-devel for this) with support for your kernel:

```<code># ./mlnxofedinstall --add-kernel-support
</code>```

Last, you'll have to rebuild Lustre against your kernel (kernel-devel) AND your MOFED (mlnx-ofa_kernel-devel):

```<code># ./configure --with-linux=/usr/src/kernels/3.10.0-1127.8.2.el7.x86_64/ --with-o2ib=/usr/src/ofa_kernel/default/
</code>```

Now your MOFED is ready to run on top of your kernel and your Lustre RPMs are ready to run on top of your kernel and the o2ib driver will use the symbols compiled for your MOFED.

Body:
Actually you should do the other way around: you should compile Lustre to properly use your MOFED and your kernel. This is the order of dependencies:

Your kernel (e.g: 3.10.0-1127.8.2.el7.x86_64)

Your MOFED has to be compiled for your kernel. If your kernel is one of the ones available from Mellanox you just need to install the rpms or let the MOFED installer do it for you:

# ./mlnxofedinstall

If you're using a different kernel you need to recompile MOFED (you need to install kernel-devel for this) with support for your kernel:

# ./mlnxofedinstall --add-kernel-support

Last, you'll have to rebuild Lustre against your kernel (kernel-devel) AND your MOFED (mlnx-ofa_kernel-devel):

# ./configure --with-linux=/usr/src/kernels/3.10.0-1127.8.2.el7.x86_64/ --with-o2ib=/usr/src/ofa_kernel/default/

Now your MOFED is ready to run on top of your kernel and your Lustre RPMs are ready to run on top of your kernel and the o2ib driver will use the symbols compiled for your MOFED.


问:
how to NVDA screen reader read the tool-tip?
I had also tried this but it not work

here i have attache the code of simple tooltip , i want the tool-tip read by the  screen reader i had also tried tabindex for focus but it not working```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div></code>```

`

答:
You have to use aria-describedby attribute</p>

```<code><a href="#" aria-describedby="myinfo">Texto de el Link</a>
<div role="tooltip" id="myinfo">Contenido de el tooltip]</div>
</code>```

Body:
I had also tried this but it not work

here i have attache the code of simple tooltip , i want the tool-tip read by the  screen reader i had also tried tabindex for focus but it not working

Hover over me
  Tooltip text

`

Body:
You have to use aria-describedby attribute

<a href="#" aria-describedby="myinfo">Texto de el Link</a>
<div role="tooltip" id="myinfo">Contenido de el tooltip]</div>


问:
revert GIT HEAD to older commit
I have realized that I have committed stuff into my branch that's bad and I want to revert to an earlier commit. I have confirmed that git checkout 8dd018c brings me to an earlier commit to which I want to revert HEAD to now, I  tried the following:

```<code>git checkout 8dd018c
git status
HEAD detached at 8dd018c
nothing to commit, working directory clean
git reset --hard  8dd018c
git push origin HEAD:<my_branch>
</code>```

but got:

```<code> ! [rejected]        HEAD -> my_branch (non-fast-forward)
error: failed to push some refs to 'https://github.com/my/repository.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

How do I do this correctly? I'm not the only one working on this repository so I think push -f is out of the question, is it?

答:
The way you could do it with minimum hassle is:

```<code>git checkout old-commit
git reset --soft the-branch
git commit -m "Going back in time"
# now you are one revision on top of the-branch but content is like old-revision
# if you like the result
git branch -f the-branch # set branch where you are now
git checkout the-branch
</code>```

And now you can push and stuff.

Title: revert GIT HEAD to older commit

Body:
I have realized that I have committed stuff into my branch that's bad and I want to revert to an earlier commit. I have confirmed that git checkout 8dd018c brings me to an earlier commit to which I want to revert HEAD to now, I  tried the following:

git checkout 8dd018c
git status
HEAD detached at 8dd018c
nothing to commit, working directory clean
git reset --hard  8dd018c
git push origin HEAD:<my_branch>

but got:

 ! [rejected]        HEAD -> my_branch (non-fast-forward)
error: failed to push some refs to 'https://github.com/my/repository.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

How do I do this correctly? I'm not the only one working on this repository so I think push -f is out of the question, is it?

Body:
The way you could do it with minimum hassle is:

git checkout old-commit
git reset --soft the-branch
git commit -m "Going back in time"
# now you are one revision on top of the-branch but content is like old-revision
# if you like the result
git branch -f the-branch # set branch where you are now
git checkout the-branch

And now you can push and stuff.


问:
How to make this method more generic
i am having some trouble figuring something regarding inheritance in Java. I thought it would be straightforward but it has stumped me.

I have this superclass..

```<code>public class MyItem {

    private String barCode;
    private String price;

    public String getBarCode() {
        return barCode;
    }

    public void setBarCode(String barCode) {
        this.barCode = barCode;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

}
</code>```

And i have these 2 subclasses

```<code>public class PromotionalItem extends MyItem {

    private String promotion;

    public String setPromotion(String promotion) {
        this.promotion = promotion;
    }

    public void getPromotion() {
        this.promotion = promotion;
    }

}

public class SellableItem extends MyItem {

    private String quantity;

    public String setQuantity(String quantity) {
        this.quantity = quantity;
    }

    public void getQuantity() {
        this.quantity = quantity;
    }

}
</code>```

Now i have a method that i want to make generic, i thought something like this could work...

```<code>public void processItem(MyItem item){
    if(item.getClass().isAssignableFrom(PromotionalItem.class)){
        processPromotionalItem((PromotionalItem)item);
    }
    else{
        processSellableItem((SellableItem)item);
    }
}
</code>```

But I am getting a ClassCastException when i try to cast these items as their respective subclasses. I thought something like this would be do-able. Am i missing something? What is the alternative do something like this?

答:
I‘ll only address the issue, as there are enough solutions (I think @Major Ben s one is nice)

```<code>item.getClass().isAssignableFrom(PromotionalItem.class)
</code>```

What this line means is:
„Can I assign to the dynamic class of item  an instance of PromotionalItem.“

But now consider this - is it legal?

```<code>MyItem item = new PromotionalItem();
</code>```

Yes, it is. So this will always be true. Hence, you then try to cast to PromotionalItem, even when it is actually not ok.

Also have a look at this. https://stackoverflow.com/a/3657960/2995907

Title: How to make this method more generic

Body:
i am having some trouble figuring something regarding inheritance in Java. I thought it would be straightforward but it has stumped me.

I have this superclass..

public class MyItem {

    private String barCode;
    private String price;

    public String getBarCode() {
        return barCode;
    }

    public void setBarCode(String barCode) {
        this.barCode = barCode;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

}

And i have these 2 subclasses

public class PromotionalItem extends MyItem {

    private String promotion;

    public String setPromotion(String promotion) {
        this.promotion = promotion;
    }

    public void getPromotion() {
        this.promotion = promotion;
    }

}

public class SellableItem extends MyItem {

    private String quantity;

    public String setQuantity(String quantity) {
        this.quantity = quantity;
    }

    public void getQuantity() {
        this.quantity = quantity;
    }

}

Now i have a method that i want to make generic, i thought something like this could work...

public void processItem(MyItem item){
    if(item.getClass().isAssignableFrom(PromotionalItem.class)){
        processPromotionalItem((PromotionalItem)item);
    }
    else{
        processSellableItem((SellableItem)item);
    }
}

But I am getting a ClassCastException when i try to cast these items as their respective subclasses. I thought something like this would be do-able. Am i missing something? What is the alternative do something like this?

Body:
I‘ll only address the issue, as there are enough solutions (I think @Major Ben s one is nice)

item.getClass().isAssignableFrom(PromotionalItem.class)

What this line means is:
„Can I assign to the dynamic class of item  an instance of PromotionalItem.“

But now consider this - is it legal?

MyItem item = new PromotionalItem();

Yes, it is. So this will always be true. Hence, you then try to cast to PromotionalItem, even when it is actually not ok.

Also have a look at this. https://stackoverflow.com/a/3657960/2995907


问:
How I can get the expiry date from a gpg key?
I have created a gpg key with an expiry date (it has to expire in 1m), and when I want to display it in my python script, I get this :

```<code>Key expiry date :  1593681565
</code>```

With this value, how I can know when the key will expire ?

答:
I don't know what Python command you used but this looks like a Unix timestamp and this is very easy to convert.

The result from www.epochconverter.com is: GMT: Thursday, July 2, 2020 9:19:25 AM

Converting from Python:

```<code>from datetime import datetime
timestamp = 1593681565
datetime.fromtimestamp(timestamp)
</code>```

Output:

```datetime.datetime(2020, 7, 2, 11, 19, 25)```

Body:
I have created a gpg key with an expiry date (it has to expire in 1m), and when I want to display it in my python script, I get this :

Key expiry date :  1593681565

With this value, how I can know when the key will expire ?

Body:
I don't know what Python command you used but this looks like a Unix timestamp and this is very easy to convert.

The result from www.epochconverter.com is: GMT: Thursday, July 2, 2020 9:19:25 AM

Converting from Python:

from datetime import datetime
timestamp = 1593681565
datetime.fromtimestamp(timestamp)

Output:

datetime.datetime(2020, 7, 2, 11, 19, 25)


问:
Can the HWND from CreateWindow/CreateDialog be GetMessage'd from another thread?
Using the Win32 APIs, is it possible to create a Window or Dialog in one thread then collect events for it from another thread?

Are HWNDs tied to threads?

Trying the contrived example below I never see GetMessage() fire.

```
HWND g_hWnd;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}
```

But here, I do.

```
HWND g_hWnd;
HINSTANCE g_hInstance;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);

    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    g_hInstance = hInstance;
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}
```

Can somebody explain what I'm seeing?

答:
Of course you can !

Just use remote code injection ! (very classic !)

OwnerDisplayName: Joby Taffey

ContentLicense: CC BY-SA 2.5

Body:
Using the Win32 APIs, is it possible to create a Window or Dialog in one thread then collect events for it from another thread?

Are HWNDs tied to threads?

Trying the contrived example below I never see GetMessage() fire.

HWND g_hWnd;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}

But here, I do.

HWND g_hWnd;
HINSTANCE g_hInstance;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);

    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    g_hInstance = hInstance;
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}

Can somebody explain what I'm seeing?

LastEditorDisplayName: Joby Taffey


问:
Import strings from .txt and searching for first numeric character - python
I am a total noob with python (programming in fact) but I hope you can help :)

I have a .txt file with a list of strings containing addresses.

I want to import it to Python and then search for the first numberic character and then create a new column for it...like

input

```<code>'Elm Street 12'
'Baker Street 143'
</code>```

and output

```<code>'Elm Street 12' , 12
'Baker Street 143' , 14
</code>```

and save it to .txt.

I am trying to do if from the windows cmd.

Thank you in advance.

答:
This might be what you are looking for</p>

```<code>import re

input = '''Elm Street 12
Baker Street 143'''
output = ""

rows = input.split("\n")
for row in rows:
    m = re.search(r'\d+', row)
    output += "{0} {1}\n".format(row, m.group())

print output
</code>```

Body:
I am a total noob with python (programming in fact) but I hope you can help :)

I have a .txt file with a list of strings containing addresses.

I want to import it to Python and then search for the first numberic character and then create a new column for it...like

input

'Elm Street 12'
'Baker Street 143'

and output

'Elm Street 12' , 12
'Baker Street 143' , 14

and save it to .txt.

I am trying to do if from the windows cmd.

Thank you in advance.

Body:
This might be what you are looking for

import re

input = '''Elm Street 12
Baker Street 143'''
output = ""

rows = input.split("\n")
for row in rows:
    m = re.search(r'\d+', row)
    output += "{0} {1}\n".format(row, m.group())

print output


问:
Write values to a text file with scientific notation
I have an Excel file with a large amount of data in scientific notation, sorted in columns like this:

I have some VB code that extracts each column of data from Excel and writes each individual column to a text file:

```<code>    Sub ExportToNotepad()
    Dim wsData As Variant
    Dim myFileName As String
    Dim FN As Integer
    Dim p As Integer, q As Integer
    Dim path As String
    Dim myString As String
    Dim lastrow As Long, lastcolumn As Long

    lastrow = Sheets("flux2018").Range("B" & Rows.Count).End(xlUp).Row
    lastcolumn = ActiveSheet.Cells(29, Columns.Count).End(xlToLeft).Column
    path = "C:\Users\bloughj\Documents\NFluxes\"

    For p = 1 To lastcolumn
    wsData = ActiveSheet.Cells(28, p).Value
    If wsData = "" Then Exit Sub
    myFileName = wsData
    myFileName = myFileName & ".txt"
    myFileName = path & myFileName
    For q = 29 To lastrow
    myString = myString & vbCrLf & Cells(q, p)

    FN = FreeFile
    Open myFileName For Output As #FN
    Print #FN, myString
    Close #FN
    Next q
    myString = ""
    Next p

    End Sub
</code>```

It seems to extract the data, but it doesn't put it in scientific notation with 4 decimal places like the source data.  Also, each resulting text file starts with a blank line:

Example:

```<code>    24
    20000000
    10000000
    5000000
    2000000
    1000000
    100000
    10000
    1000
    100
    10
    1
    0.625
    0.5
    0.4
    0.3
    0.2
    0.1
    0.08
    0.06
    0.04
    0.03
    0.02
    0.01
    0.0002
    0.00001
    1.0515639915552E-05
    3.63926199086599E-04
    1.9676665491577E-03
    1.42654567203907E-03
    5.81606017515438E-03
    1.00247561028745E-02
    1.32534668446465E-02
    1.54728811746672E-02
    1.69472358325774E-02
    1.87875054958548E-02
    4.40254611566843E-03
    2.24021737838812E-03
    2.37656211009138E-03
    3.40419784285222E-03
    7.97308912593133E-03
    9.15215298875479E-02
    7.52308259032017E-02
    0.12439644621192
    0.192207571010406
    0.120888605459018
    0.126903744311048
    0.112336857282057
    5.20321789727604E-02
    1.37510447075413E-05
    56
    20000000
    6430000
    4300000
    3000000
    1850000
    1500000
    1200000
    861000
    750000
    600000
    470000
    330000
    270000
    200000
    50000
    20000
    17000
    3740
    2250
    192
    188
    118
    116
    105
    101
    67.5
    65
    37.1
    36
    21.8
    21.2
    20.5
    7
    6.88
    6.5
    6.25
    5
    1.13
    1.08
    1.01
    0.625
    0.45
    0.375
    0.35
    0.325
    0.25
    0.2
    0.15
    0.1
    0.08
    0.06
    0.05
    0.04
    0.0253
    0.01
    0.004
    0.00001
</code>```

How can I get it to format the output in scientific notation with 4 decimal places, like the original data?  And how do I get rid of the blank line at the beginning of each .txt file?

答:
You don't need VBA to do this. If you want a macro you can use the macro recorder to record yourself performing these steps. Then edit the resultant VBA in to a reusable function that performs the operation.

First, format the cells so that the data conforms to the display you want.

Right click the column

Select Format Cells

Choose "Scientific", and "4" decimal places

Click File > Save As

Choose File Type: Unicode Text (*.txt)

Enter the name of the file

Click Save

Body:
I have an Excel file with a large amount of data in scientific notation, sorted in columns like this:

I have some VB code that extracts each column of data from Excel and writes each individual column to a text file:

    Sub ExportToNotepad()
    Dim wsData As Variant
    Dim myFileName As String
    Dim FN As Integer
    Dim p As Integer, q As Integer
    Dim path As String
    Dim myString As String
    Dim lastrow As Long, lastcolumn As Long

    lastrow = Sheets("flux2018").Range("B" & Rows.Count).End(xlUp).Row
    lastcolumn = ActiveSheet.Cells(29, Columns.Count).End(xlToLeft).Column
    path = "C:\Users\bloughj\Documents\NFluxes\"

    For p = 1 To lastcolumn
    wsData = ActiveSheet.Cells(28, p).Value
    If wsData = "" Then Exit Sub
    myFileName = wsData
    myFileName = myFileName & ".txt"
    myFileName = path & myFileName
    For q = 29 To lastrow
    myString = myString & vbCrLf & Cells(q, p)

    FN = FreeFile
    Open myFileName For Output As #FN
    Print #FN, myString
    Close #FN
    Next q
    myString = ""
    Next p

    End Sub

It seems to extract the data, but it doesn't put it in scientific notation with 4 decimal places like the source data.  Also, each resulting text file starts with a blank line:

Example:

    24
    20000000
    10000000
    5000000
    2000000
    1000000
    100000
    10000
    1000
    100
    10
    1
    0.625
    0.5
    0.4
    0.3
    0.2
    0.1
    0.08
    0.06
    0.04
    0.03
    0.02
    0.01
    0.0002
    0.00001
    1.0515639915552E-05
    3.63926199086599E-04
    1.9676665491577E-03
    1.42654567203907E-03
    5.81606017515438E-03
    1.00247561028745E-02
    1.32534668446465E-02
    1.54728811746672E-02
    1.69472358325774E-02
    1.87875054958548E-02
    4.40254611566843E-03
    2.24021737838812E-03
    2.37656211009138E-03
    3.40419784285222E-03
    7.97308912593133E-03
    9.15215298875479E-02
    7.52308259032017E-02
    0.12439644621192
    0.192207571010406
    0.120888605459018
    0.126903744311048
    0.112336857282057
    5.20321789727604E-02
    1.37510447075413E-05
    56
    20000000
    6430000
    4300000
    3000000
    1850000
    1500000
    1200000
    861000
    750000
    600000
    470000
    330000
    270000
    200000
    50000
    20000
    17000
    3740
    2250
    192
    188
    118
    116
    105
    101
    67.5
    65
    37.1
    36
    21.8
    21.2
    20.5
    7
    6.88
    6.5
    6.25
    5
    1.13
    1.08
    1.01
    0.625
    0.45
    0.375
    0.35
    0.325
    0.25
    0.2
    0.15
    0.1
    0.08
    0.06
    0.05
    0.04
    0.0253
    0.01
    0.004
    0.00001

How can I get it to format the output in scientific notation with 4 decimal places, like the original data?  And how do I get rid of the blank line at the beginning of each .txt file?


问:
classifying multiple observations within one variable so then i can categorise them in new column . how can i make the code shorter? in R
i'm looking for a shortcut or less labour intensive way of grouping certain observations within the same variable, then output in a new column depending.

```<code>axa$type[axa$instrument_type == "CORPORATE BONDS" | axa$instrument_type == "GOVERNMENT BONDS"] <- 'BONDS'
axa$type[axa$instrument_type == "FOREIGN CURRENCY"] <- 'Cash'
axa$type[axa$instrument_type == "FUT-FIXED INCOME"] <- 'Derivatives'
axa$type[axa$instrument_type  ==  "INTEREST RATE SWAP"] <- 'Derivatives'
axa$type[axa$instrument_type == "MUTUAL FUNDS"] <- 'Funds'
axa$type[axa$instrument_type == "SHORT TERMS"] <- 'Cash Equivalent'
axa$type[axa$instrument_type == "CMO"] <- 'Other Fi'
axa$type[axa$instrument_type == "NON-SECY ASSET STOCK"] <- 'Other'
</code>```

the code searches for certain observations,then will output in column axa$type, with the desired output: "cash", "derivatives".

is there any way of making this code shorter/compact.
preferably using the Data table Package

答:
An easier option is to create a key/value dataset pair and then do a join.  This is extensible and it requires only a single join instead of doing the == multiple times and assignments

```<code>library(data.table)
keydat <- data.table(instrument_type = c("CORPORATE_BONDS", "FOREIGN_CURRENCY",
    ...), type = c("GOVERNMENT", "Cash",...))

setDT(axa)[keydat, type := i.type, on = .(instrument_type)]
</code>```

NOTE: ... is the remaining values  in 'instrument_type' and the corresponding 'type' values

Body:
i'm looking for a shortcut or less labour intensive way of grouping certain observations within the same variable, then output in a new column depending.

axa$type[axa$instrument_type == "CORPORATE BONDS" | axa$instrument_type == "GOVERNMENT BONDS"] <- 'BONDS'
axa$type[axa$instrument_type == "FOREIGN CURRENCY"] <- 'Cash'
axa$type[axa$instrument_type == "FUT-FIXED INCOME"] <- 'Derivatives'
axa$type[axa$instrument_type  ==  "INTEREST RATE SWAP"] <- 'Derivatives'
axa$type[axa$instrument_type == "MUTUAL FUNDS"] <- 'Funds'
axa$type[axa$instrument_type == "SHORT TERMS"] <- 'Cash Equivalent'
axa$type[axa$instrument_type == "CMO"] <- 'Other Fi'
axa$type[axa$instrument_type == "NON-SECY ASSET STOCK"] <- 'Other'

the code searches for certain observations,then will output in column axa$type, with the desired output: "cash", "derivatives".

is there any way of making this code shorter/compact.
preferably using the Data table Package

Body:
An easier option is to create a key/value dataset pair and then do a join.  This is extensible and it requires only a single join instead of doing the == multiple times and assignments

library(data.table)
keydat <- data.table(instrument_type = c("CORPORATE_BONDS", "FOREIGN_CURRENCY",
    ...), type = c("GOVERNMENT", "Cash",...))

setDT(axa)[keydat, type := i.type, on = .(instrument_type)]

NOTE: ... is the remaining values  in 'instrument_type' and the corresponding 'type' values


问:
Using WriteConsoleOutput on '/u263a' always prints incorrectly
Having looked at this question and modifying the code to print characters like '☺', '☻' or '█', I can't see how to get these characters to actually draw properly with WriteConsoleOutput. (There is no problem when using a stream or Console.Write but I can't individually control the character colour with these solutions so they're unsuitable.)

It seems there was a solution here for C++ but the "L" macro they talk about down the bottom does not apply to C#.

Finally, having checked the suggestions here, I can't see anything wrong with the code I ended up with:

```<code>class Program
{
    [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    static extern SafeFileHandle CreateFile(
        string fileName,
        [MarshalAs(UnmanagedType.U4)] uint fileAccess,
        [MarshalAs(UnmanagedType.U4)] uint fileShare,
        IntPtr securityAttributes,
        [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
        [MarshalAs(UnmanagedType.U4)] int flags,
        IntPtr template
    );

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool WriteConsoleOutputW(
        SafeFileHandle hConsoleOutput,
        CharInfo[] lpBuffer,
        Coord dwBufferSize,
        Coord dwBufferCoord,
        ref SmallRect lpWriteRegion
    );

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleOutputCP(uint wCodePageID);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCP(uint wCodePageID);

    [StructLayout(LayoutKind.Sequential)]
    public struct Coord
    {
        public short X;
        public short Y;

        public Coord(short X, short Y)
        {
            this.X = X;
            this.Y = Y;
        }
    };

    [StructLayout(LayoutKind.Explicit)]
    public struct CharUnion
    {
        [FieldOffset(0)] public char UnicodeChar;
        [FieldOffset(0)] public byte AsciiChar;
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct CharInfo
    {
        [FieldOffset(0)] public CharUnion Char;
        [FieldOffset(2)] public short Attributes;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct SmallRect
    {
        public short Left;
        public short Top;
        public short Right;
        public short Bottom;
    }

    static void Main(string[] args)
    {
        //SetConsoleOutputCP(65001);
        //SetConsoleCP(65001);
        SafeFileHandle fileHandle = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
        Console.TreatControlCAsInput = true;
        //Console.OutputEncoding = Encoding.UTF8;
        Console.OutputEncoding = System.Text.Encoding.Unicode;
        Console.CursorVisible = false;
        short screenWidth = 40;
        short screenHeight = 20;
        Console.SetWindowSize(screenWidth + 1, screenHeight + 1);
        Console.SetBufferSize(screenWidth + 1, screenHeight + 1);
        bool running = true;
        while (running)
        {
            CharInfo[] buf = new CharInfo[screenWidth * screenHeight];
            SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = screenWidth, Bottom = screenHeight };
            for (int i = 0; i < buf.Length; ++i)
            {
                buf[i].Attributes = 6;
                buf[i].Char.UnicodeChar = '☺';
            }
            bool b = WriteConsoleOutputW(
                fileHandle,
                buf,
                new Coord() { X = screenWidth, Y = screenHeight },
                new Coord() { X = 0, Y = 0 },
                ref rect
            );
            Console.SetCursorPosition(0, 0);
        }
    }
}
</code>```

I seem to have ruled out all combinations of CharSet, A/W DLLImport suffixes, code pages, Console properties & source-file encoding.

(Surely it can't be impossible to fast-print coloured smiley-face characters to a C# console. Somebody tell me I've missed something silly here; I've spent about 2 hours Googling & trying to emulate something Castle Adventure managed in 1984 with ease.)

How can I get the aforementioned '☺' to print anything other than a '?' or a ':'?

答:
This seems to be a duplicate of Using WriteConsoleOutput to write Unicode with c#

The solution to that was to add the CharSet = CharSet.Unicode attribute to both the CharInfo and CharUnion structs.

Body:
Having looked at this question and modifying the code to print characters like '☺', '☻' or '█', I can't see how to get these characters to actually draw properly with WriteConsoleOutput. (There is no problem when using a stream or Console.Write but I can't individually control the character colour with these solutions so they're unsuitable.)

It seems there was a solution here for C++ but the "L" macro they talk about down the bottom does not apply to C#.

Finally, having checked the suggestions here, I can't see anything wrong with the code I ended up with:

class Program
{
    [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    static extern SafeFileHandle CreateFile(
        string fileName,
        [MarshalAs(UnmanagedType.U4)] uint fileAccess,
        [MarshalAs(UnmanagedType.U4)] uint fileShare,
        IntPtr securityAttributes,
        [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
        [MarshalAs(UnmanagedType.U4)] int flags,
        IntPtr template
    );

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool WriteConsoleOutputW(
        SafeFileHandle hConsoleOutput,
        CharInfo[] lpBuffer,
        Coord dwBufferSize,
        Coord dwBufferCoord,
        ref SmallRect lpWriteRegion
    );

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleOutputCP(uint wCodePageID);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCP(uint wCodePageID);

    [StructLayout(LayoutKind.Sequential)]
    public struct Coord
    {
        public short X;
        public short Y;

        public Coord(short X, short Y)
        {
            this.X = X;
            this.Y = Y;
        }
    };

    [StructLayout(LayoutKind.Explicit)]
    public struct CharUnion
    {
        [FieldOffset(0)] public char UnicodeChar;
        [FieldOffset(0)] public byte AsciiChar;
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct CharInfo
    {
        [FieldOffset(0)] public CharUnion Char;
        [FieldOffset(2)] public short Attributes;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct SmallRect
    {
        public short Left;
        public short Top;
        public short Right;
        public short Bottom;
    }

    static void Main(string[] args)
    {
        //SetConsoleOutputCP(65001);
        //SetConsoleCP(65001);
        SafeFileHandle fileHandle = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
        Console.TreatControlCAsInput = true;
        //Console.OutputEncoding = Encoding.UTF8;
        Console.OutputEncoding = System.Text.Encoding.Unicode;
        Console.CursorVisible = false;
        short screenWidth = 40;
        short screenHeight = 20;
        Console.SetWindowSize(screenWidth + 1, screenHeight + 1);
        Console.SetBufferSize(screenWidth + 1, screenHeight + 1);
        bool running = true;
        while (running)
        {
            CharInfo[] buf = new CharInfo[screenWidth * screenHeight];
            SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = screenWidth, Bottom = screenHeight };
            for (int i = 0; i < buf.Length; ++i)
            {
                buf[i].Attributes = 6;
                buf[i].Char.UnicodeChar = '☺';
            }
            bool b = WriteConsoleOutputW(
                fileHandle,
                buf,
                new Coord() { X = screenWidth, Y = screenHeight },
                new Coord() { X = 0, Y = 0 },
                ref rect
            );
            Console.SetCursorPosition(0, 0);
        }
    }
}

I seem to have ruled out all combinations of CharSet, A/W DLLImport suffixes, code pages, Console properties & source-file encoding.

(Surely it can't be impossible to fast-print coloured smiley-face characters to a C# console. Somebody tell me I've missed something silly here; I've spent about 2 hours Googling & trying to emulate something Castle Adventure managed in 1984 with ease.)

How can I get the aforementioned '☺' to print anything other than a '?' or a ':'?


问:
I get a syntax error when trying to translate into broken english using Googletrans API (Python 3.8.1)?
This is very much a dumb thing to ask, however I'm new to Python. I just installed googletrans from PyPI and I wanted to make a program that runs a phrase through a set of translations to make the phrase come out as broken English. However, I get a Syntax error! I can't figure it out and I've Googled everywhere. Please help!</p>

```<code>from googletrans import Translator
import os

translator = Translator()

def addToClipBoard(text):
    command = 'echo ' + text.strip() + '| clip'
    os.system(command)

one = (translator.translate(input("ENTER PHRASE"))
two = (translator.translate(one, dest='sp'))
three = (translator.translate(two, dest='ch'))
four = (translator.translate(three, dest='fi'))
five = (translator.translate(four, dest='ja'))

result = (translator.translate(five))

addToClipBoard(result.text)

print("Copied succesfully. Closing now...")

exit()
</code>```

答:
You're missing a bracket at the end here:

```<code>one = (translator.translate(input("ENTER PHRASE")) # <- missing bracket
# should be
one = (translator.translate(input("ENTER PHRASE"))) # <- see the extra bracket
</code>```

I recommend using a linter, like pylint. Linters catch syntax/style errors for you. If you use a text editor like vscode or pycharm, it's really easy to have it work in the background while you code so you can fix your syntax errors while coding.

Body:
This is very much a dumb thing to ask, however I'm new to Python. I just installed googletrans from PyPI and I wanted to make a program that runs a phrase through a set of translations to make the phrase come out as broken English. However, I get a Syntax error! I can't figure it out and I've Googled everywhere. Please help!

from googletrans import Translator
import os

translator = Translator()

def addToClipBoard(text):
    command = 'echo ' + text.strip() + '| clip'
    os.system(command)

one = (translator.translate(input("ENTER PHRASE"))
two = (translator.translate(one, dest='sp'))
three = (translator.translate(two, dest='ch'))
four = (translator.translate(three, dest='fi'))
five = (translator.translate(four, dest='ja'))

result = (translator.translate(five))

addToClipBoard(result.text)

print("Copied succesfully. Closing now...")

exit()

Body:
You're missing a bracket at the end here:

one = (translator.translate(input("ENTER PHRASE")) # <- missing bracket
# should be
one = (translator.translate(input("ENTER PHRASE"))) # <- see the extra bracket

I recommend using a linter, like pylint. Linters catch syntax/style errors for you. If you use a text editor like vscode or pycharm, it's really easy to have it work in the background while you code so you can fix your syntax errors while coding.


问:
Copying result from pgAdmin to a spreadsheet
I am copying every result of Query (application pgAdmin) into Google Docs Sheet.

I am wonder if it is possible to set Postgres to output tabs instead of semicolon ; to separate values in columns - I would like to simply copy and paste from Postgres to Google Docs sheet.

If it is not possible, is there any way to write a macro in Google Docs sheet?

I would like to ask one more question - how can I divide two values which I get by using select command (and how to demand from Postgres SQL to store values as for example double)?

答:
Maybe something like this could be usefull :)</p>

```<code>select relname || chr(9) || reltype || chr(9) || relam from pg_class
</code>```

Body:
Maybe something like this could be usefull :)

select relname || chr(9) || reltype || chr(9) || relam from pg_class


问:
QML module not found when using KDE Kirigami
So I decided to use KDE Kirigami UI framework in my app so I followed the instructions here. I cloned the repo in my app directory and then added it with a simple include(kirigami/kirigami.pri) in my project file.

Now this works, however the problem I encountered is that in QML there is always the error: QML module not found when I import the plugin (import org.kde.kirigami 2.9). The project still compiles and runs just fine and I am able to use the UI components I need, however the major issue is that code completion and syntax highlighting for the Kirigami plugin do not work.

A similar question has been asked before here, I have tried all the suggestions in the answers of that thread but none of them worked:

I imported QQmlEngine::addImportPath the kirigami/src/controls folders using absolute and relative paths. I also tried with qrc:/.

I added a QML_IMPORT_PATH += $$PWD/kirigami/src/controls $$PWD/kirigami line to my project file.

答:
When you mouse over the "module org.kde.kirigami not found" error marker in a QML file, the popup tells you that Qt Creator is looking in QML_IMPORT_PATH for these files. It also tells you how to set this.

By adding QML_IMPORT_PATH += … to your project file, you have set it for a qmake based build process. However, Kirigami projects usually use CMake, and that might be the reason why your previous attempts did not work out.

To set QML_IMPORT_PATH for a CMake based build system, you would open the CMakeLists.txt file from the root of your project tree and add the following section on top:

```<code># ------------------------- BEGIN: lists to maintain manually -------------------------

# Directories where Qt Creator can find QML files of Kirigami etc. on your system.
#   (This setting is cached in variable QML_IMPORT_DIR, see below. Delete
#   ${BUIL_DIR}/CMakeCache.txt to make make changes here effective.)
list(APPEND QML_DIRS "/usr/lib/x86_64-linux-gnu/qt5/qml")

# ------------------------- END: lists to maintain manually -------------------------

# Tell Qt Creator where to find QML files.
#   (The build process will work without this, but no code completion etc..)
set(
    QML_IMPORT_PATH "${QML_DIRS}"
    CACHE STRING "Qt Creator 4.1 extra qml import paths"
)
</code>```

Of course, adapt it to the correct directory for your system. On a Debian / Ubuntu based system, the following will determine the directory containing Kirigami QML files installed from the repositories:

```<code>dpkg -L qml-module-org-kde-kirigami2 | grep "\.qml"
</code>```

Source: another answer on StackOverflow

Body:
When you mouse over the "module org.kde.kirigami not found" error marker in a QML file, the popup tells you that Qt Creator is looking in QML_IMPORT_PATH for these files. It also tells you how to set this.

By adding QML_IMPORT_PATH += … to your project file, you have set it for a qmake based build process. However, Kirigami projects usually use CMake, and that might be the reason why your previous attempts did not work out.

To set QML_IMPORT_PATH for a CMake based build system, you would open the CMakeLists.txt file from the root of your project tree and add the following section on top:

# ------------------------- BEGIN: lists to maintain manually -------------------------

# Directories where Qt Creator can find QML files of Kirigami etc. on your system.
#   (This setting is cached in variable QML_IMPORT_DIR, see below. Delete
#   ${BUIL_DIR}/CMakeCache.txt to make make changes here effective.)
list(APPEND QML_DIRS "/usr/lib/x86_64-linux-gnu/qt5/qml")

# ------------------------- END: lists to maintain manually -------------------------

# Tell Qt Creator where to find QML files.
#   (The build process will work without this, but no code completion etc..)
set(
    QML_IMPORT_PATH "${QML_DIRS}"
    CACHE STRING "Qt Creator 4.1 extra qml import paths"
)

Of course, adapt it to the correct directory for your system. On a Debian / Ubuntu based system, the following will determine the directory containing Kirigami QML files installed from the repositories:

dpkg -L qml-module-org-kde-kirigami2 | grep "\.qml"

Source: another answer on StackOverflow