问:
How to 'convert' amount of Hz to appropriate byte/bit format?
I am programming an IR camera. But the internal register for storing the refreshrate (bits 9, 8 and 7 of 16 in total) only accepts 1's and 0's of course. For example, a value of 0b110 means 32Hz and 0b111, 64Hz. How can I best convert a given integer (refresh_rate) value between 0.5Hz and 64Hz to 0b000 - 0b111 when looking at the Refresh rate control picture?

To be honest, I haven't tried anything yet because I think it requires a weird hack. However I have been thinking of a lookuptable, I think that is possible but requires more memory and it has to be memory efficient since it is programmed on an Arduino Due.

Note: You can see that the refresh_rate is an uint16_t which does not accept floating point values such as 0.5Hz, however, I am probably not going to use the 0.5Hz setting.

// the end-user currently has to pass a value between 7 and 0
void mlx90650::set_refresh_rate(uint16_t refresh_rate) {
    // So the refresh rate may not be higher than 7 (0b111) since this register only
accepts 3 bits. The memory map is:
/*
    | decimal | bits  |
    (decimal 0) 0 0 0 IR refresh rate = 0.5Hz
    (decimal 1) 0 0 1 IR refresh rate = 1Hz
    (decimal 2) 0 1 0 IR refresh rate = 2Hz (default)
    (decimal 3) 0 1 1 IR refresh rate = 4Hz
    (decimal 4) 1 0 0 IR refresh rate = 8Hz
    (decimal 5) 1 0 1 IR refresh rate = 16Hz
    (decimal 6) 1 1 0 IR refresh rate = 32Hz
    (decimal 7) 1 1 1 IR refresh rate = 64H
*/
}
```

I want that this function converts for example 64Hz to 0b111.

答:
How can I best convert a given integer (refresh_rate) value between 0.5Hz and 64Hz to 0b000 - 0b111

One approach is to see that the target value increases by one every time the input doubles, meaning it is log2(Hz) + 1.

So, you can write

```<code>uint16_t hz_bits(float hz) {
    return static_cast<uint16_t>(round(1.0f + log2(hz)));
}
</code>```

which admittedly requires floating-point and isn't highly-optimized. Conversely,

```<code>float hz_from_bits(uint16_t hzB) {
    return 0.5f * (1 << hzB);
}
</code>```

Both of those have the three bits you care about as the least significant bits of the uint16_t.

If you want to use an integral Hz number, and ignore the 0.5 case, then log2 is just the number of the highest set bit: eg, 64 = 0b1000000, with highest set bit 6 (you still need to add 1 to get 7 = 0b111).

Then you can combine them with something like

```<code>static const uint16_t HZ_START = 7;
static const uint16_t HZ_LEN = 3;
static const uint16_t HZ_MASK = ((1 << HZ_LEN)-1) << HZ_START;

uint16_t set_hz_bits(uint16_t control, uint16_t hzB) {
    return (control & ~HZ_MASK) | (hzB << HZ_START);
}
uint16_t get_hz_bits(uint16_t control) {
    return (control & HZ_MASK) >> HZ_START;
}
</code>```

into

```<code>uint16_t set_hz(uint16_t control, float hz) {
    return set_hz_bits(control, hz_bits(hz));
}
float get_hz(uint16_t control) {
    return hz_from_bits(get_hz_bits(control));
}
</code>```

Note that the actual bit masking and shifting is pretty mechanical - you can automate this stuff for your various fields quite easily, using something like the below, and pass around HzField objects instead of having to remember which uint16_t contain zero-based encoded Hz values, and which contain correctly layed-out control registers.

```<code>template <size_t Bstart, size_t Blen, typename T = uint16_t>
struct BitField
{
    T value; // zero-based, not shifted

    static constexpr T mask() { return ((1 << Blen)-1) << Bstart; }

    static T clear(T r) { return r & ~mask(); }

    void decode(T r) { value = (r & mask()) >> Bstart; }
    T encode(T r) { return clear(r) | ((value << Bstart) & mask()); }
    // etc.
};
using HzField = BitField<7, 3>;
</code>```

Body:
I am programming an IR camera. But the internal register for storing the refreshrate (bits 9, 8 and 7 of 16 in total) only accepts 1's and 0's of course. For example, a value of 0b110 means 32Hz and 0b111, 64Hz. How can I best convert a given integer (refresh_rate) value between 0.5Hz and 64Hz to 0b000 - 0b111 when looking at the Refresh rate control picture?

To be honest, I haven't tried anything yet because I think it requires a weird hack. However I have been thinking of a lookuptable, I think that is possible but requires more memory and it has to be memory efficient since it is programmed on an Arduino Due.

Note: You can see that the refresh_rate is an uint16_t which does not accept floating point values such as 0.5Hz, however, I am probably not going to use the 0.5Hz setting.

// the end-user currently has to pass a value between 7 and 0
void mlx90650::set_refresh_rate(uint16_t refresh_rate) {
    // So the refresh rate may not be higher than 7 (0b111) since this register only
accepts 3 bits. The memory map is:
/*
    | decimal | bits  |
    (decimal 0) 0 0 0 IR refresh rate = 0.5Hz
    (decimal 1) 0 0 1 IR refresh rate = 1Hz
    (decimal 2) 0 1 0 IR refresh rate = 2Hz (default)
    (decimal 3) 0 1 1 IR refresh rate = 4Hz
    (decimal 4) 1 0 0 IR refresh rate = 8Hz
    (decimal 5) 1 0 1 IR refresh rate = 16Hz
    (decimal 6) 1 1 0 IR refresh rate = 32Hz
    (decimal 7) 1 1 1 IR refresh rate = 64H
*/
}

I want that this function converts for example 64Hz to 0b111.

Body:
How can I best convert a given integer (refresh_rate) value between 0.5Hz and 64Hz to 0b000 - 0b111

One approach is to see that the target value increases by one every time the input doubles, meaning it is log2(Hz) + 1.

So, you can write

uint16_t hz_bits(float hz) {
    return static_cast<uint16_t>(round(1.0f + log2(hz)));
}

which admittedly requires floating-point and isn't highly-optimized. Conversely,

float hz_from_bits(uint16_t hzB) {
    return 0.5f * (1 << hzB);
}

Both of those have the three bits you care about as the least significant bits of the uint16_t.

If you want to use an integral Hz number, and ignore the 0.5 case, then log2 is just the number of the highest set bit: eg, 64 = 0b1000000, with highest set bit 6 (you still need to add 1 to get 7 = 0b111).

Then you can combine them with something like

static const uint16_t HZ_START = 7;
static const uint16_t HZ_LEN = 3;
static const uint16_t HZ_MASK = ((1 << HZ_LEN)-1) << HZ_START;

uint16_t set_hz_bits(uint16_t control, uint16_t hzB) {
    return (control & ~HZ_MASK) | (hzB << HZ_START);
}
uint16_t get_hz_bits(uint16_t control) {
    return (control & HZ_MASK) >> HZ_START;
}

into

uint16_t set_hz(uint16_t control, float hz) {
    return set_hz_bits(control, hz_bits(hz));
}
float get_hz(uint16_t control) {
    return hz_from_bits(get_hz_bits(control));
}

Note that the actual bit masking and shifting is pretty mechanical - you can automate this stuff for your various fields quite easily, using something like the below, and pass around HzField objects instead of having to remember which uint16_t contain zero-based encoded Hz values, and which contain correctly layed-out control registers.

template <size_t Bstart, size_t Blen, typename T = uint16_t>
struct BitField
{
    T value; // zero-based, not shifted

    static constexpr T mask() { return ((1 << Blen)-1) << Bstart; }

    static T clear(T r) { return r & ~mask(); }

    void decode(T r) { value = (r & mask()) >> Bstart; }
    T encode(T r) { return clear(r) | ((value << Bstart) & mask()); }
    // etc.
};
using HzField = BitField<7, 3>;


来源: stackexchange

问:
How to align second line in a bullet-ed un-ordered list
I have a bullet-ed un-ordered list of ingredients on my recipe site.  I have some padding around the list so that it is displayed in the center of the page.  However, when I go to view the page on an iphone or a tablet (a device with a narrower screen), my bullet points are pushed to 2 lines and the second line is not in line with the first.

I believe this is due to the padding code I have around the list so that on a narrow screen, the bullets are still in the center of the page.  When the bullet point is too long that it has to go to 2 lines, the second line is pushed all the way to the left while the bullet is still centered.  I am looking to align the second line with the first (still centered on the page)

I have tried positioning it 'outside' the bullet point, however, because I have made my own bullet point with code this doesn't seem to work.

The code below is the code I have for the cellular device display of this issue.

```<code>    @media only screen and (max-width : 480px)
    { ul[data-rte-list] li>*:first-child::before  {
        content: "•";
        position: outside;
        line-height: 1.5em !important;
        top: 2px;
        padding-right: 10px;
        font-size: 22px;
        padding-left: 100px;
        color: #373737;
        opacity: .4;
    }

}
</code>```

This is exactly what the page looks like:

答:
You are applying the padding to the ::before selector of each
 element.
Remove it from there and add it to the
 element.

```<code>@media only screen and (max-width : 480px)
{
    ul[data-rte-list] {
        padding-left: 100px;
    }

    ul[data-rte-list] li>*:first-child::before  {
        content: "•";
        position: outside;
        line-height: 1.5em !important;
        top: 2px;
        padding-right: 10px;
        font-size: 22px;
        color: #373737;
        opacity: .4;
   }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a bullet-ed un-ordered list of ingredients on my recipe site.  I have some padding around the list so that it is displayed in the center of the page.  However, when I go to view the page on an iphone or a tablet (a device with a narrower screen), my bullet points are pushed to 2 lines and the second line is not in line with the first.

I believe this is due to the padding code I have around the list so that on a narrow screen, the bullets are still in the center of the page.  When the bullet point is too long that it has to go to 2 lines, the second line is pushed all the way to the left while the bullet is still centered.  I am looking to align the second line with the first (still centered on the page)

I have tried positioning it 'outside' the bullet point, however, because I have made my own bullet point with code this doesn't seem to work.

The code below is the code I have for the cellular device display of this issue.

    @media only screen and (max-width : 480px)
    { ul[data-rte-list] li>*:first-child::before  {
        content: "•";
        position: outside;
        line-height: 1.5em !important;
        top: 2px;
        padding-right: 10px;
        font-size: 22px;
        padding-left: 100px;
        color: #373737;
        opacity: .4;
    }

}

This is exactly what the page looks like:

Body:
You are applying the padding to the ::before selector of each <li> element.
Remove it from there and add it to the <ul> element.

@media only screen and (max-width : 480px)
{
    ul[data-rte-list] {
        padding-left: 100px;
    }

    ul[data-rte-list] li>*:first-child::before  {
        content: "•";
        position: outside;
        line-height: 1.5em !important;
        top: 2px;
        padding-right: 10px;
        font-size: 22px;
        color: #373737;
        opacity: .4;
   }
}


问:
Is there a way to conditionally validate a model based on the http verb used?

I'm writing an API and have a very simple model

public class CategoryModel
{
    public int ID { get; set; }

    [Required]
    [StringLength(30)]
    public string Name { get; set; }

    public string Description { get; set; }
}
```

I don't want to enforce that the ID property is required if the model is coming in via a post action, but I do if it's a put action. Are there any validation attributes that allow for this or do I need to create a separate model for post and put?

I'm just learning this so I could be doing it wrong altogether so a point in the right direction would be appreciated!

Thanks!

答: We can do by use fluentvalidation library or create customer attribute </p>

Body:
I'm writing an API and have a very simple model

public class CategoryModel
{
    public int ID { get; set; }

    [Required]
    [StringLength(30)]
    public string Name { get; set; }

    public string Description { get; set; }
}

I don't want to enforce that the ID property is required if the model is coming in via a post action, but I do if it's a put action. Are there any validation attributes that allow for this or do I need to create a separate model for post and put?

I'm just learning this so I could be doing it wrong altogether so a point in the right direction would be appreciated!

Thanks!


问:
How to set background image only for a part of the textView
I have a multiline textview and i want to set a background image only at the last three characters of the textview -> from tv.length() - 3 to tv.lenght()</p>

答:
You should use buildSpannedString :</p>

```<code>buildSpannedString {
            append("str1")
            append(' ')
            color(ContextCompat.getColor(context, R.color.red)) {
                append("red text")
            }
</code>```

Body:
You should use buildSpannedString :

buildSpannedString {
            append("str1")
            append(' ')
            color(ContextCompat.getColor(context, R.color.red)) {
                append("red text")
            }


问:
How does a queryset knows what records are in the database if it doesn't hit the database
Django querysets are lazy

```<code>person_set = Person.objects.all()
</code>```

In the documentation it says the above code doesn’t run any database queries.
But with the above command it generates a queryset in this case person_set and this object contains all the person objects.

```<code> person_set = Person.objects.all()

 print(person_set)
</code>```

This is the output.

```<code> <QuerySet [<Person: Person object (7)>, <Person: Person object (8)>, <Person: Person object (9)>]>
</code>```

If it didn't hit the database then how does it know that what records are in the database? As it is supposed to run queries only when it is evaluated using a loop or others methods.

答: Printing the queryset is evaluating it, to build the string representation of the object.</p>

Body:
Django querysets are lazy

person_set = Person.objects.all()

In the documentation it says the above code doesn’t run any database queries.
But with the above command it generates a queryset in this case person_set and this object contains all the person objects.

 person_set = Person.objects.all()

 print(person_set)

This is the output.

 <QuerySet [<Person: Person object (7)>, <Person: Person object (8)>, <Person: Person object (9)>]>

If it didn't hit the database then how does it know that what records are in the database? As it is supposed to run queries only when it is evaluated using a loop or others methods.


问:
How to update ListView entries and let the user continue and scrolling the listview values?
I am trying to  update the list of listView while the user is scrolling the list and give the user the option to continue and scrolling the new entries but with no success and i need an help.

In my application, i have a chat and i am saving history of the chat at SQLite. when the user is entered to the chat, the application is reading only the last 25 message and present the newest message at the bottom of the list.
In order that do that i am using the following options at the XML:

```<code>    android:transcriptMode="alwaysScroll"
    android:stackFromBottom="true"
</code>```

and it is working fine.
Now , when the user is starting to scroll up and checking the history of the chat, when he is arriving to the top of the list, i am accessing the database and retrieving another 25 messages and add them to the top of the list and i am calling to:
        chatAdaptor.notifyDataSetChanged();

but when the user is trying to scroll up, nothing is presented, only after scrolling down and up again the new entries are presented.

I have try to set the position of the list view using setSelection and smoothScrollToPosition but it is not really work.

how can it update the list with new entries and give the user the option to continue and scroll up?

here is the relevant code:

```<code><ListView
    android:id="@+id/chatList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    android:layout_margin="2dp"
    android:layout_weight="1"
    android:transcriptMode="alwaysScroll"
    android:stackFromBottom="true"
    android:background="@drawable/frame_tab"></ListView>

public void showChatLines() {

    chatLinesView = chatTextDialog.findViewById(R.id.chatList);

    chatAdaptor = new GenericAdapter<ChatLine>(activity, chatLines) {
        @Override
        public View getMyView(int position, View convertView, ViewGroup parent, ChatLine chatLine) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.chat_line, null);

            TextView chatLineText = view.findViewById(R.id.chatLine);
            chatLineText.setText(chatLine.messageText);
            TextView chatLineTime = view.findViewById(R.id.chatLineTime);
            chatLineTime.setText(chatLine.displayDateTime);
            TextView chatLineUserName = view.findViewById(R.id.userName);
            chatLineUserName.setText(chatLine.userDisplayName);
            chatLineUserName.setTextColor(activity.getColor(Constants.colors[getColorBy(chatLine.userName)]));

            LinearLayout chatLineLayout = view.findViewById(R.id.chatLineLayout);
            LinearLayout.LayoutParams chatLineLayoutParams = (LinearLayout.LayoutParams) chatLineLayout.getLayoutParams();
            CardView chatLineBackground = view.findViewById(R.id.chatLineBackground);
            LinearLayout.LayoutParams chatLineBackgroundParams = (LinearLayout.LayoutParams) chatLineBackground.getLayoutParams();
            LinearLayout chatLineSubLayout = view.findViewById(R.id.chatLineSubLayout);
            FrameLayout.LayoutParams chatLineSubLayoutParams = (FrameLayout.LayoutParams) chatLineSubLayout.getLayoutParams();

            if (chatLine.userName.equals(logonUserName)) {
                CardView charLineCard = view.findViewById(R.id.chatLineBackground);
                charLineCard.setCardBackgroundColor(activity.getColor(R.color.focusedColor));
                ((ViewGroup) chatLineUserName.getParent()).removeView(chatLineUserName);
            } else {
                chatLineLayoutParams.gravity = Gravity.RIGHT;
                chatLineLayout.setLayoutParams(chatLineLayoutParams);
                chatLineSubLayoutParams.gravity = Gravity.RIGHT;
                chatLineSubLayout.setLayoutParams(chatLineSubLayoutParams);
                chatLineBackgroundParams.gravity = Gravity.RIGHT;
                chatLineBackground.setLayoutParams(chatLineBackgroundParams);
            }

            if (position==0 & fromLine!=0) {
                getNextChatLinesFromDb(position);
            }
            return view;
        }
    };

    chatLinesView.setAdapter(chatAdaptor);

}

private void getNextChatLinesFromDb(int position) {
    toLine = fromLine - 1;
    fromLine -= pageSize;
    if (fromLine < 0) {
        fromLine = 0;
    }
    ArrayList<ChatLine> newChatLines = db.getChatLines(chatRoomId, fromLine, toLine);
    chatLines.addAll(0, newChatLines);
    chatAdaptor.notifyDataSetChanged();
}
</code>```

答:
i think this code will help you :

```<code>// get position of listview
int index = chatLinesView.getFirstVisiblePosition();
View v = chatLinesView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();

// notify dataset changed or re-assign adapter here

//re-assign the position of listview after setting the adapter again
chatLinesView.setSelectionFromTop(index, top);
</code>```

edit

```<code>int h1 = chatLinesView.getHeight();
int h2 = chatLinesViewRow.getHeight();

chatLinesView.smoothScrollToPositionFromTop(position, h1/2 - h2/2, duration);
</code>```

Parameters
  position -> Position to scroll to

offset ---->Desired distance in pixels of position from the top of the
  view when scrolling is finished

duration-> Number of milliseconds to use for the scroll

Body:
I am trying to  update the list of listView while the user is scrolling the list and give the user the option to continue and scrolling the new entries but with no success and i need an help.

In my application, i have a chat and i am saving history of the chat at SQLite. when the user is entered to the chat, the application is reading only the last 25 message and present the newest message at the bottom of the list.
In order that do that i am using the following options at the XML:

    android:transcriptMode="alwaysScroll"
    android:stackFromBottom="true"

and it is working fine.
Now , when the user is starting to scroll up and checking the history of the chat, when he is arriving to the top of the list, i am accessing the database and retrieving another 25 messages and add them to the top of the list and i am calling to:
        chatAdaptor.notifyDataSetChanged();

but when the user is trying to scroll up, nothing is presented, only after scrolling down and up again the new entries are presented.

I have try to set the position of the list view using setSelection and smoothScrollToPosition but it is not really work.

how can it update the list with new entries and give the user the option to continue and scroll up?

here is the relevant code:

<ListView
    android:id="@+id/chatList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    android:layout_margin="2dp"
    android:layout_weight="1"
    android:transcriptMode="alwaysScroll"
    android:stackFromBottom="true"
    android:background="@drawable/frame_tab"></ListView>

public void showChatLines() {

    chatLinesView = chatTextDialog.findViewById(R.id.chatList);

    chatAdaptor = new GenericAdapter<ChatLine>(activity, chatLines) {
        @Override
        public View getMyView(int position, View convertView, ViewGroup parent, ChatLine chatLine) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.chat_line, null);

            TextView chatLineText = view.findViewById(R.id.chatLine);
            chatLineText.setText(chatLine.messageText);
            TextView chatLineTime = view.findViewById(R.id.chatLineTime);
            chatLineTime.setText(chatLine.displayDateTime);
            TextView chatLineUserName = view.findViewById(R.id.userName);
            chatLineUserName.setText(chatLine.userDisplayName);
            chatLineUserName.setTextColor(activity.getColor(Constants.colors[getColorBy(chatLine.userName)]));

            LinearLayout chatLineLayout = view.findViewById(R.id.chatLineLayout);
            LinearLayout.LayoutParams chatLineLayoutParams = (LinearLayout.LayoutParams) chatLineLayout.getLayoutParams();
            CardView chatLineBackground = view.findViewById(R.id.chatLineBackground);
            LinearLayout.LayoutParams chatLineBackgroundParams = (LinearLayout.LayoutParams) chatLineBackground.getLayoutParams();
            LinearLayout chatLineSubLayout = view.findViewById(R.id.chatLineSubLayout);
            FrameLayout.LayoutParams chatLineSubLayoutParams = (FrameLayout.LayoutParams) chatLineSubLayout.getLayoutParams();

            if (chatLine.userName.equals(logonUserName)) {
                CardView charLineCard = view.findViewById(R.id.chatLineBackground);
                charLineCard.setCardBackgroundColor(activity.getColor(R.color.focusedColor));
                ((ViewGroup) chatLineUserName.getParent()).removeView(chatLineUserName);
            } else {
                chatLineLayoutParams.gravity = Gravity.RIGHT;
                chatLineLayout.setLayoutParams(chatLineLayoutParams);
                chatLineSubLayoutParams.gravity = Gravity.RIGHT;
                chatLineSubLayout.setLayoutParams(chatLineSubLayoutParams);
                chatLineBackgroundParams.gravity = Gravity.RIGHT;
                chatLineBackground.setLayoutParams(chatLineBackgroundParams);
            }

            if (position==0 & fromLine!=0) {
                getNextChatLinesFromDb(position);
            }
            return view;
        }
    };

    chatLinesView.setAdapter(chatAdaptor);

}

private void getNextChatLinesFromDb(int position) {
    toLine = fromLine - 1;
    fromLine -= pageSize;
    if (fromLine < 0) {
        fromLine = 0;
    }
    ArrayList<ChatLine> newChatLines = db.getChatLines(chatRoomId, fromLine, toLine);
    chatLines.addAll(0, newChatLines);
    chatAdaptor.notifyDataSetChanged();
}

Body:
i think this code will help you :

// get position of listview
int index = chatLinesView.getFirstVisiblePosition();
View v = chatLinesView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();

// notify dataset changed or re-assign adapter here

//re-assign the position of listview after setting the adapter again
chatLinesView.setSelectionFromTop(index, top);

edit

int h1 = chatLinesView.getHeight();
int h2 = chatLinesViewRow.getHeight();

chatLinesView.smoothScrollToPositionFromTop(position, h1/2 - h2/2, duration);

Parameters
  position -> Position to scroll to

offset ---->Desired distance in pixels of position from the top of the
  view when scrolling is finished

duration-> Number of milliseconds to use for the scroll


问:
MARS Simulator has PC-relative addressing refer to the number of bytes instead of words?
I'm currently reading the book of David Patterson and John Hennesy titled: "Computer Organisation and Design - 4th Edition". In some point the book says:

Since all MIPS instructions are 4 bytes long, MIPS stretches the distance of the branch by having PC-relative addressing refer to the number of
  words to the next instruction instead of the number of bytes.

As soon as I read that, I went over to the MARS Simulator to see that in practise. To my surprise, I observed that the $pc register doesn't follow that rule and has always the byte memory address stored.

Shouldn't the $pc register be something like this before the execution of the below instructions located in the instruction addresses?

```<code>Instruction Address |    $pc Content
                    |
    0x00400000      |     0x00100000
    0x00400004      |     0x00100001
    0x00400008      |     0x00100002
      ....          |         ....
</code>```

答:
Another way to look at this: the low 2 bits of PC are fixed at 0.

Under your proposal, the high 2 bits would be fixed at 0.  And jr $ra or other jump-to-register instructions would also have to left-shift the register instead of simply setting $pc = function-pointer.

(Or else the difference would be architecturally visible and accessing code as data or vice versa would have to be shift to convert from data address to code address for the same word.)

As Jester points out, $pc is a normal pointer to an instruction word, like MIPS is used to dealing with.  MIPS uses byte-addressable memory, but word loads have to be aligned (until MIPS32r6).  So $pc increments by 4 instead of being scaled by 4 every time it's used.

The only scaling needed with the actual design is of immediates for branch (I-type) and jump (J-type).  See How to Calculate Jump Target Address and Branch Target Address? for how that works.  That's just a matter of what position you wire the immediate bits into an adder, leaving the lower bits zero.  And it only happens in the decoding of those instructions; everything else just works with normal byte addresses.

Body:
I'm currently reading the book of David Patterson and John Hennesy titled: "Computer Organisation and Design - 4th Edition". In some point the book says:

Since all MIPS instructions are 4 bytes long, MIPS stretches the distance of the branch by having PC-relative addressing refer to the number of
  words to the next instruction instead of the number of bytes.

As soon as I read that, I went over to the MARS Simulator to see that in practise. To my surprise, I observed that the $pc register doesn't follow that rule and has always the byte memory address stored.

Shouldn't the $pc register be something like this before the execution of the below instructions located in the instruction addresses?

Instruction Address |    $pc Content
                    |
    0x00400000      |     0x00100000
    0x00400004      |     0x00100001
    0x00400008      |     0x00100002
      ....          |         ....


问:
Jest getReversedNavigationSections of null
I have a handle on scroll like so:

```<code>handleOnScroll = () => {
    const {form, navigationSections} = this.props;

    const reversedSections = this.getReversedNavigationSections();

    const OFFSET_TOP = form === 'createIdentity' ? 34 : 140;
    const st = window.pageYOffset || document.documentElement.scrollTop;

    if (st > window.lastScrollTop) {
        for (let i = 0; i < navigationSections.length; i += 1) {
            if (document.getElementById(navigationSections[i].id).getBoundingClientRect().top <= OFFSET_TOP) {
                this.setNavigationActiveWithDebounce(navigationSections[i].id);
            }
        }

    }

    if (st < window.lastScrollTop) {
        for (let y = 0; y < reversedSections.length; y += 1) {
            if (document.getElementById(navigationSections[y].id).getBoundingClientRect().top <= OFFSET_TOP) {
                this.setNavigationActiveWithDebounce(navigationSections[y].id);
            }
        }
    }

    window.lastScrollTop = st <= 0 ? 0 : st;

}
</code>```

and a test for it like so:

```<code>    it('should handle handleOnScroll', () => {
        window.lastScrollTop = 200;
        window.pageYOffset = 50;

        instance.handleOnScroll();

        expect(instance.getReversedNavigationSections).toHaveBeenCalled();
    });
</code>```

I would expect this test to pass (at least for 'getReversedNavigationSections') however I am getting:

答:
First, have you tried debugging this test yet?

The fact that you are getting that error implies that something is wrong here.

```<code>document.getElementById(navigationSections[i].id)
</code>```

Which means you aren't getting the element at all.

Without being able to see the rest of your implementation, my initial guess would be that you are splicing Virtual DOM manipulation with direct DOM manipulation and something is getting lost in the mix but I can't tell based on the code snippet.

Body:
I have a handle on scroll like so:

handleOnScroll = () => {
    const {form, navigationSections} = this.props;

    const reversedSections = this.getReversedNavigationSections();

    const OFFSET_TOP = form === 'createIdentity' ? 34 : 140;
    const st = window.pageYOffset || document.documentElement.scrollTop;

    if (st > window.lastScrollTop) {
        for (let i = 0; i < navigationSections.length; i += 1) {
            if (document.getElementById(navigationSections[i].id).getBoundingClientRect().top <= OFFSET_TOP) {
                this.setNavigationActiveWithDebounce(navigationSections[i].id);
            }
        }

    }

    if (st < window.lastScrollTop) {
        for (let y = 0; y < reversedSections.length; y += 1) {
            if (document.getElementById(navigationSections[y].id).getBoundingClientRect().top <= OFFSET_TOP) {
                this.setNavigationActiveWithDebounce(navigationSections[y].id);
            }
        }
    }

    window.lastScrollTop = st <= 0 ? 0 : st;

}

and a test for it like so:

    it('should handle handleOnScroll', () => {
        window.lastScrollTop = 200;
        window.pageYOffset = 50;

        instance.handleOnScroll();

        expect(instance.getReversedNavigationSections).toHaveBeenCalled();
    });

I would expect this test to pass (at least for 'getReversedNavigationSections') however I am getting:

Body:
First, have you tried debugging this test yet?

The fact that you are getting that error implies that something is wrong here.

document.getElementById(navigationSections[i].id)

Which means you aren't getting the element at all.

Without being able to see the rest of your implementation, my initial guess would be that you are splicing Virtual DOM manipulation with direct DOM manipulation and something is getting lost in the mix but I can't tell based on the code snippet.


问:
socketio inter server communication with redis and haproxy
I'm working on a project which uses SocketIO and should be Horizontally scalable. Im using

A Load Balancer using HAProxy

Multiple Node Servers (2-4)

Database server(Redis and MongoDB)

I'm able to redirect my incoming Socket connections to Node servers using roundrobin method. Socket connection is stable and if I use socket.emit() I'm receiving the data. I'm also able to emit to the Other socket connection connected to the same Node server.

I'm facing issue in the following scenario:

User A connected to Node server 1 and User B connected to Node Server 2

My intention is to store the Socket data in redis

If User A wants to send some data to User B, how can I tell the Node server 2 to emit the data to User B from Node server 1

Please let me know how can I achieve this (with ref if possible).

Thanks in advance.

答:
This scenario is a match for the case Pub/Sub of Redis.

If you haven't already, you should try Pub/Sub.

ContentLicense: CC BY-SA 3.0


问:
Any Bazel document to help migrate from an older version to newer version?
I am using Bazel 19 and I want to migrate to latest version 26. Looks like lot of things have changed and it is hard to figure out all changes from the release notes. Is there any document/tools that can help with migrating from older version to newer version</p>

答:
Bazelisk provides a --strict and --migrate flag that can help you:

```<code>USE_BAZEL_VERSION=0.26.1 bazelisk --strict build //...
</code>```

--strict enables all incompatible flags and helps you to identify upgrade problems.

If --strict fails you should try --migrate. It sets enables incompatible flags step by step and gives you a report of the incompatible flags that lead to a build problem:

```<code>USE_BAZEL_VERSION=0.26.1 bazelisk --migrate build //...
</code>```

Take also a look at the documentation about Backward Compatibility:

When we introduce an incompatible change, we try to make it easier for
  Bazel users to update their code. We do this by means of migration
  windows and migration recipes.

Migration window is one or more release of Bazel during which a
  migration from old functionality to new functionality is possible,
  according to a migration recipe.

During the migration window, both the old functionality and the new
  functionality are available in the Bazel release. For every
  incompatible change, we provide a migration recipe that allows
  updating the user code (BUILD and .bzl files, as well as any Bazel
  usage in scripts, usage of Bazel API and so on) in such a way that it
  works simultaneously without any flags with old and new functionality.

Body:
Bazelisk provides a --strict and --migrate flag that can help you:

USE_BAZEL_VERSION=0.26.1 bazelisk --strict build //...

--strict enables all incompatible flags and helps you to identify upgrade problems.

If --strict fails you should try --migrate. It sets enables incompatible flags step by step and gives you a report of the incompatible flags that lead to a build problem:

USE_BAZEL_VERSION=0.26.1 bazelisk --migrate build //...

Take also a look at the documentation about Backward Compatibility:

When we introduce an incompatible change, we try to make it easier for
  Bazel users to update their code. We do this by means of migration
  windows and migration recipes.

Migration window is one or more release of Bazel during which a
  migration from old functionality to new functionality is possible,
  according to a migration recipe.

During the migration window, both the old functionality and the new
  functionality are available in the Bazel release. For every
  incompatible change, we provide a migration recipe that allows
  updating the user code (BUILD and .bzl files, as well as any Bazel
  usage in scripts, usage of Bazel API and so on) in such a way that it
  works simultaneously without any flags with old and new functionality.


问:
Override the existing Css in Vaadin
I need to override the existing css of ValoTheme, i added the new css rules in mytheme.scss ,i compile the theme , and run the application but still it is not update on UI.

```<code>  @mixin mytheme {
      @include valo;
      // Insert your own theme rules here

      .v-widget {
        box-sizing: border-box;
        vertical-align: top;
        text-align: right;
    }

    .v-slot, .v-spacing {
        display: -webkit-inline-box;
        white-space: nowrap;
        vertical-align: top;
    }
}
</code>```

i tried to clean and refresh the project. how to update the UserInterface by Override of the existing css of valoTheme

答:
Did you include the mixin in your scss ?

In your example code, I saw that you declared a mixin by @mixin mytheme. But did you wrote @incude mytheme in your code ?

Sass mixin and include:
https://sass-lang.com/documentation/at-rules/mixin

Title: Override the existing Css in Vaadin

Body:
I need to override the existing css of ValoTheme, i added the new css rules in mytheme.scss ,i compile the theme , and run the application but still it is not update on UI.

  @mixin mytheme {
      @include valo;
      // Insert your own theme rules here

      .v-widget {
        box-sizing: border-box;
        vertical-align: top;
        text-align: right;
    }

    .v-slot, .v-spacing {
        display: -webkit-inline-box;
        white-space: nowrap;
        vertical-align: top;
    }
}

i tried to clean and refresh the project. how to update the UserInterface by Override of the existing css of valoTheme


问:
Why can't I connect to my USB Composite Device with HIDSharp?
I'm working on a project that emulates a USB Composite Device consisting of a HID keyboard and HID Mouse using a microprocessor.  I have the device properly enumerating and functioning with both my Windows 7 x64 and Raspbian hosts and it all looks good, but where I'm running into a problem is getting my winforms application (using HidSharp) to open the connected composite device so I can get at the raw data in the keyboard endpoint.

The problem seems to be with the TryOpen() function, in that I can find the connected device by matching VID and PID, I assign the device information and report descriptor, but when I try to open a datastream via TryOpen() it fails, and I don't know why.  Unfortunately the function only returns a bool, so I don't know why it's failing, just that it can't open the datastream.  I'm wondering if maybe there's something funny with opening a composite device that I'm not aware of?  My code for finding the device and opening the datastream is below:

```<code>/*These vars are part of the class*/
byte[] keyboardBuffer;  //EP1
HidSharp.Reports.Input.HidDeviceInputReceiver InputReceiver;
HidSharp.Reports.ReportDescriptor KeyboardRptDescriptor;
HidStream KeyboardStream;
HidDevice KeyboardDevice;

private void FindDevice()
{
    var list = DeviceList.Local;
    var stopwatch = Stopwatch.StartNew();
    var hidDeviceList = list.GetHidDevices().ToArray();

    foreach (HidDevice d in hidDeviceList)
    {

        if (d.VendorID == 0x0000 && d.ProductID == 0xA0A0)
        {
            /*Proper VID and PID Found*/
            if (d.GetProductName() == "Keyboard")
            {
                KeyboardDevice = d;
                KeyboardRptDescriptor = KeyboardDevice.GetReportDescriptor();

            }

        }

    }

    if (KeyboardDevice != null)
    {
        /*Device Found, open the datastream*/
        if (KeyboardDevice.TryOpen(out KeyboardStream))    //PROBLEM LINE - Always False?
        {
            KeyboardReport = KeyboardRptDescriptor.InputReports.FirstOrDefault();
            keyboardBuffer = new byte[KeyboardDevice.GetMaxInputReportLength()];
            InputParser = KeyboardReport.DeviceItem.CreateDeviceItemInputParser();
            InputReceiver = KeyboardRptDescriptor.CreateHidDeviceInputReceiver();
            InputReceiver.Received -= new EventHandler(HidInputReceived);
            InputReceiver.Received += new EventHandler(HidInputReceived);
            InputReceiver.Start(KeyboardStream);
        } else {
            rtb_hidLog.AppendText("Unable to connect to device\r\n");
        }

    }
    else
    {
        rtb_hidLog.AppendText("No Device Found\r\n");
    }

}
</code>```

Right now I'm only attempting to read from the HID Keyboard, and will add the mouse once I sort the keyboard out.  There are seemingly no issues finding the device, but why is opening it giving me such an issue?  My HIDSharp library appears to be v2.0.2.0 (according to the file properties).

Thanks in advance for any suggestions!

答:
So I asked around on the HIDSharp forum about this, and I got an answer from the dev:

Turns out Windows does not allow you to open HID Keyboard devices as a security "feature", so HIDSharp will always fail to open the datastream of a HID Keyboard device.

Body:
I'm working on a project that emulates a USB Composite Device consisting of a HID keyboard and HID Mouse using a microprocessor.  I have the device properly enumerating and functioning with both my Windows 7 x64 and Raspbian hosts and it all looks good, but where I'm running into a problem is getting my winforms application (using HidSharp) to open the connected composite device so I can get at the raw data in the keyboard endpoint.

The problem seems to be with the TryOpen() function, in that I can find the connected device by matching VID and PID, I assign the device information and report descriptor, but when I try to open a datastream via TryOpen() it fails, and I don't know why.  Unfortunately the function only returns a bool, so I don't know why it's failing, just that it can't open the datastream.  I'm wondering if maybe there's something funny with opening a composite device that I'm not aware of?  My code for finding the device and opening the datastream is below:

/*These vars are part of the class*/
byte[] keyboardBuffer;  //EP1
HidSharp.Reports.Input.HidDeviceInputReceiver InputReceiver;
HidSharp.Reports.ReportDescriptor KeyboardRptDescriptor;
HidStream KeyboardStream;
HidDevice KeyboardDevice;

private void FindDevice()
{
    var list = DeviceList.Local;
    var stopwatch = Stopwatch.StartNew();
    var hidDeviceList = list.GetHidDevices().ToArray();

    foreach (HidDevice d in hidDeviceList)
    {

        if (d.VendorID == 0x0000 && d.ProductID == 0xA0A0)
        {
            /*Proper VID and PID Found*/
            if (d.GetProductName() == "Keyboard")
            {
                KeyboardDevice = d;
                KeyboardRptDescriptor = KeyboardDevice.GetReportDescriptor();

            }

        }

    }

    if (KeyboardDevice != null)
    {
        /*Device Found, open the datastream*/
        if (KeyboardDevice.TryOpen(out KeyboardStream))    //PROBLEM LINE - Always False?
        {
            KeyboardReport = KeyboardRptDescriptor.InputReports.FirstOrDefault();
            keyboardBuffer = new byte[KeyboardDevice.GetMaxInputReportLength()];
            InputParser = KeyboardReport.DeviceItem.CreateDeviceItemInputParser();
            InputReceiver = KeyboardRptDescriptor.CreateHidDeviceInputReceiver();
            InputReceiver.Received -= new EventHandler(HidInputReceived);
            InputReceiver.Received += new EventHandler(HidInputReceived);
            InputReceiver.Start(KeyboardStream);
        } else {
            rtb_hidLog.AppendText("Unable to connect to device\r\n");
        }

    }
    else
    {
        rtb_hidLog.AppendText("No Device Found\r\n");
    }

}

Right now I'm only attempting to read from the HID Keyboard, and will add the mouse once I sort the keyboard out.  There are seemingly no issues finding the device, but why is opening it giving me such an issue?  My HIDSharp library appears to be v2.0.2.0 (according to the file properties).

Thanks in advance for any suggestions!


问:
How to call a method in .Net DLL in a Java program
I was trying to use a .NET DLL from Java code, the tsMemberFunctions.DLL is loaded successfully, but the code fails to call the actual function.

See the snippet below:

```<code>public class tsMemberFunctions {
    public native void GetMemberJSONSample();

    static {
        System.loadLibrary("tsMemberFunctions");
        System.out.println("Loaded");
    }

    public static void main(String[] args) {
        new tsMemberFunctions().GetMemberJSONSample();

    }
}
</code>```

On executing above method I am getting below error:

```<code>Loaded
Exception in thread "main" java.lang.UnsatisfiedLinkError: tsMemberFunctions.GetMemberJSONSample()V
    at tsMemberFunctions.GetMemberJSONSample(Native Method)
    at tsMemberFunctions.main(tsMemberFunctions.java:12)
</code>```

Can someone please tell me if I missed anything or anything is incorrect in the code or suggest better alternative for this use case. TIA.

答:
You have to be very careful with the names and exports.

Let's say you have this super simple lib

```<code>// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include "jni.h"
#include <stdio.h>

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

extern "C" JNIEXPORT void JNICALL Java_recipeNo001_HelloWorld_displayMessage

(JNIEnv* env, jclass obj) {

    printf("Hello world!\n");

}
</code>```

You have to make sure to build your DLL for proper architecture (it will depend on Java version you have - 32/64 bit).

Let's say you have x64 DLL and x64 JDK, you can call your lib like this

```<code>package recipeNo001;

public class HelloWorld {

    public static native void displayMessage();

    static {
        System.load("C:\\Users\\your_name\\Source\\Repos\\HelloWorld\\x64\\Debug\\HelloWorld.dll");
    }

    public static void main(String[] args) {
      HelloWorld.displayMessage();
    }
}
</code>```

In your case, I bet you don't have extern "C" in your code - this is why your symbol can't be found by JVM.

When it comes to tools, I suggest Visual Studio 2019 (when it comes to creating DLL) and IntelliJ for Java code.

You can find lots of samples here:   http://jnicookbook.owsiak.org/ and here: https://github.com/mkowsiak/jnicookbook

Body:
I was trying to use a .NET DLL from Java code, the tsMemberFunctions.DLL is loaded successfully, but the code fails to call the actual function.

See the snippet below:

public class tsMemberFunctions {
    public native void GetMemberJSONSample();

    static {
        System.loadLibrary("tsMemberFunctions");
        System.out.println("Loaded");
    }

    public static void main(String[] args) {
        new tsMemberFunctions().GetMemberJSONSample();

    }
}

On executing above method I am getting below error:

Loaded
Exception in thread "main" java.lang.UnsatisfiedLinkError: tsMemberFunctions.GetMemberJSONSample()V
    at tsMemberFunctions.GetMemberJSONSample(Native Method)
    at tsMemberFunctions.main(tsMemberFunctions.java:12)

Can someone please tell me if I missed anything or anything is incorrect in the code or suggest better alternative for this use case. TIA.

Body:
You have to be very careful with the names and exports.

Let's say you have this super simple lib

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include "jni.h"
#include <stdio.h>

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

extern "C" JNIEXPORT void JNICALL Java_recipeNo001_HelloWorld_displayMessage

(JNIEnv* env, jclass obj) {

    printf("Hello world!\n");

}

You have to make sure to build your DLL for proper architecture (it will depend on Java version you have - 32/64 bit).

Let's say you have x64 DLL and x64 JDK, you can call your lib like this

package recipeNo001;

public class HelloWorld {

    public static native void displayMessage();

    static {
        System.load("C:\\Users\\your_name\\Source\\Repos\\HelloWorld\\x64\\Debug\\HelloWorld.dll");
    }

    public static void main(String[] args) {
      HelloWorld.displayMessage();
    }
}

In your case, I bet you don't have extern "C" in your code - this is why your symbol can't be found by JVM.

When it comes to tools, I suggest Visual Studio 2019 (when it comes to creating DLL) and IntelliJ for Java code.

You can find lots of samples here:   http://jnicookbook.owsiak.org/ and here: https://github.com/mkowsiak/jnicookbook


问:
how to write a regular expression to match pronouns in a text file?
I am trying to write a program to calculate the pronoun/proper nouns ratio.

I've tried to look for the nouns starting with capital letters to match de proper nouns and pronouns using regular expession. However, my RE to match pronouns does not work well, because it matches not only the pronouns but also words containing the charaters of the pronouns . See code below:

```<code>def pron_propn():

    while True:
        try:
            file_to_open =Path(input("\nPlease, insert your file path: "))
            dic_to_open=Path(input('\nPlease, insert your dictionary path: '))
            with open(file_to_open,'r', encoding="utf-8") as f:
                words = wordpunct_tokenize(f.read())
            with open(dic_to_open,'r', encoding="utf-8") as d:
                dic = wordpunct_tokenize(d.read())
                break
        except FileNotFoundError:
            print("\nFile not found. Better try again")

    patt=re.compile(r"^[A-Z][a-z]+\b|^[A-Z]+\b")
    c_n= list(filter(patt.match, words))

    patt2=re.compile(r"\bhe|she|it+\b")
    pronouns= list(filter(patt2.match, words))

    propn_new=[]
    propn=[]
    other=[]
    pron=[]

    for i in words:
        if i in c_n:
            propn.append(i)
        elif i in pronouns:
            pron.append(i)

        else:
            continue

    for j in propn:
        if j not in dic:
           propn_new.append(j)
        else:
            other.append(j)

    print(propn_new)
    print(pron)
    print(len(pron)/len(propn))

pron_propn()
</code>```

When I print the list of pronouns, I get:  ['he', 'he', 'he', 'he', 'hearing', 'he', 'it', 'hear', 'it', 'he', 'it']

But I want a list like: ['he', 'he', 'he', 'he', 'he', 'it', 'it', 'he', 'it']

I also want to get the result of division: the number of pronouns found by the number of proper nouns

Can anyone help to capture pronouns only?

答:
We can have one capturing group, with word boundary, and add our desired pronouns to it, with an expression similar to:

```<code>(\b(s?he|it)\b)
</code>```

If we wish, we can add more constraints.

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(\b(s?he|it)\b)"

test_str = "Anything she wish before it. Anything he wish after it. Then, we repeat. Anything she wish before it. Anything he wish after it. Then, we repeat. Anything she wish before it. Anything he wish after it. Then, we repeat. Anything she wish before it. Anything he wish after it. Then, we repeat. Anything she wish before it. Anything he wish after it. Then, we repeat. "

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

Then, we can script the rest and count pronouns, count all words, and we would simply divide those to get the ratio.

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I am trying to write a program to calculate the pronoun/proper nouns ratio.

I've tried to look for the nouns starting with capital letters to match de proper nouns and pronouns using regular expession. However, my RE to match pronouns does not work well, because it matches not only the pronouns but also words containing the charaters of the pronouns . See code below:

def pron_propn():

    while True:
        try:
            file_to_open =Path(input("\nPlease, insert your file path: "))
            dic_to_open=Path(input('\nPlease, insert your dictionary path: '))
            with open(file_to_open,'r', encoding="utf-8") as f:
                words = wordpunct_tokenize(f.read())
            with open(dic_to_open,'r', encoding="utf-8") as d:
                dic = wordpunct_tokenize(d.read())
                break
        except FileNotFoundError:
            print("\nFile not found. Better try again")

    patt=re.compile(r"^[A-Z][a-z]+\b|^[A-Z]+\b")
    c_n= list(filter(patt.match, words))

    patt2=re.compile(r"\bhe|she|it+\b")
    pronouns= list(filter(patt2.match, words))

    propn_new=[]
    propn=[]
    other=[]
    pron=[]

    for i in words:
        if i in c_n:
            propn.append(i)
        elif i in pronouns:
            pron.append(i)

        else:
            continue

    for j in propn:
        if j not in dic:
           propn_new.append(j)
        else:
            other.append(j)

    print(propn_new)
    print(pron)
    print(len(pron)/len(propn))

pron_propn()

When I print the list of pronouns, I get:  ['he', 'he', 'he', 'he', 'hearing', 'he', 'it', 'hear', 'it', 'he', 'it']

But I want a list like: ['he', 'he', 'he', 'he', 'he', 'it', 'it', 'he', 'it']

I also want to get the result of division: the number of pronouns found by the number of proper nouns

Can anyone help to capture pronouns only?

Body:
We can have one capturing group, with word boundary, and add our desired pronouns to it, with an expression similar to:

(\b(s?he|it)\b)

If we wish, we can add more constraints.

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(\b(s?he|it)\b)"

test_str = "Anything she wish before it. Anything he wish after it. Then, we repeat. Anything she wish before it. Anything he wish after it. Then, we repeat. Anything she wish before it. Anything he wish after it. Then, we repeat. Anything she wish before it. Anything he wish after it. Then, we repeat. Anything she wish before it. Anything he wish after it. Then, we repeat. "

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

Then, we can script the rest and count pronouns, count all words, and we would simply divide those to get the ratio.

DEMO

RegEx Circuit

jex.im visualizes regular expressions:


答:
You can see all of the situations where a QuerySet hits the database here: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#when-querysets-are-evaluated

One of them is repr(), which is called when you print the queryset.

Title: How does a queryset knows what records are in the database if it doesn't hit the database


问:
YuiCompressorTask: "Can't find bundle for base name org.mozilla.javascript.resources.Messages, locale en_US"
I have been using YuiCompressorTask (latest version) on my project for a very long time with no issues. After upgrading to Oracle's Java 1.7 package on OSX, hwoever, it breaks with the following exception (this is for a javascript file; it works fine with a css file):

```<code>[yuiCompress] java.lang.reflect.InvocationTargetException
[yuiCompress]   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[yuiCompress]   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
[yuiCompress]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[yuiCompress]   at java.lang.reflect.Method.invoke(Method.java:601)
[yuiCompress]   at com.yahoo.platform.yui.compressor.Bootstrap.main(Bootstrap.java:21)
[yuiCompress]   at ww.ant.YuiCompressorTask.execute(YuiCompressorTask.java:40)
[yuiCompress]   at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
[yuiCompress]   at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
[yuiCompress]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[yuiCompress]   at java.lang.reflect.Method.invoke(Method.java:601)
[yuiCompress]   at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
[yuiCompress]   at org.apache.tools.ant.Task.perform(Task.java:348)
[yuiCompress]   at org.apache.tools.ant.Target.execute(Target.java:390)
[yuiCompress]   at org.apache.tools.ant.Target.performTasks(Target.java:411)
[yuiCompress]   at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
[yuiCompress]   at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
[yuiCompress]   at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
[yuiCompress]   at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
[yuiCompress]   at org.apache.tools.ant.Main.runBuild(Main.java:809)
[yuiCompress]   at org.apache.tools.ant.Main.startAnt(Main.java:217)
[yuiCompress]   at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
[yuiCompress]   at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
[yuiCompress] Caused by: java.util.MissingResourceException: Can't find bundle for base name org.mozilla.javascript.resources.Messages, locale en_US
[yuiCompress]   at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1499)
[yuiCompress]   at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1322)
[yuiCompress]   at java.util.ResourceBundle.getBundle(ResourceBundle.java:796)
[yuiCompress]   at org.mozilla.javascript.ScriptRuntime.getMessage(ScriptRuntime.java:3316)
[yuiCompress]   at org.mozilla.javascript.ScriptRuntime.getMessage0(ScriptRuntime.java:3273)
[yuiCompress]   at org.mozilla.javascript.Parser.addError(Parser.java:121)
[yuiCompress]   at org.mozilla.javascript.TokenStream.getToken(TokenStream.java:773)
[yuiCompress]   at org.mozilla.javascript.Parser.peekToken(Parser.java:161)
[yuiCompress]   at org.mozilla.javascript.Parser.parse(Parser.java:361)
[yuiCompress]   at org.mozilla.javascript.Parser.parse(Parser.java:337)
[yuiCompress]   at com.yahoo.platform.yui.compressor.JavaScriptCompressor.parse(JavaScriptCompressor.java:312)
[yuiCompress]   at com.yahoo.platform.yui.compressor.JavaScriptCompressor.<init>(JavaScriptCompressor.java:533)
[yuiCompress]   at com.yahoo.platform.yui.compressor.YUICompressor.main(YUICompressor.java:131)
[yuiCompress]   ... 22 more
</code>```

I can switch back to Apple's Java 1.6 and it works fine. My question is, is there a way around this? I really can't continue on 1.6 any longer.

答:
old question but i had to put a comment with my other finds.

It doesnt support define variables with let.

And a new find today, it doesnt allow to define functions with params with a default value

In my case i had to change

function convertDate(inputFormat,type=1)

to

function convertDate(inputFormat,type) {

if(typeof(type)==="undefined")

    type=1;

As tip to find why it fails, the best way is to clone the javascript that you are using, and start a new empty, and add blocks until you find which one produces the error.

Body:
I have been using YuiCompressorTask (latest version) on my project for a very long time with no issues. After upgrading to Oracle's Java 1.7 package on OSX, hwoever, it breaks with the following exception (this is for a javascript file; it works fine with a css file):

[yuiCompress] java.lang.reflect.InvocationTargetException
[yuiCompress]   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[yuiCompress]   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
[yuiCompress]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[yuiCompress]   at java.lang.reflect.Method.invoke(Method.java:601)
[yuiCompress]   at com.yahoo.platform.yui.compressor.Bootstrap.main(Bootstrap.java:21)
[yuiCompress]   at ww.ant.YuiCompressorTask.execute(YuiCompressorTask.java:40)
[yuiCompress]   at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
[yuiCompress]   at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
[yuiCompress]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[yuiCompress]   at java.lang.reflect.Method.invoke(Method.java:601)
[yuiCompress]   at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
[yuiCompress]   at org.apache.tools.ant.Task.perform(Task.java:348)
[yuiCompress]   at org.apache.tools.ant.Target.execute(Target.java:390)
[yuiCompress]   at org.apache.tools.ant.Target.performTasks(Target.java:411)
[yuiCompress]   at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
[yuiCompress]   at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
[yuiCompress]   at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
[yuiCompress]   at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
[yuiCompress]   at org.apache.tools.ant.Main.runBuild(Main.java:809)
[yuiCompress]   at org.apache.tools.ant.Main.startAnt(Main.java:217)
[yuiCompress]   at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
[yuiCompress]   at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
[yuiCompress] Caused by: java.util.MissingResourceException: Can't find bundle for base name org.mozilla.javascript.resources.Messages, locale en_US
[yuiCompress]   at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1499)
[yuiCompress]   at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1322)
[yuiCompress]   at java.util.ResourceBundle.getBundle(ResourceBundle.java:796)
[yuiCompress]   at org.mozilla.javascript.ScriptRuntime.getMessage(ScriptRuntime.java:3316)
[yuiCompress]   at org.mozilla.javascript.ScriptRuntime.getMessage0(ScriptRuntime.java:3273)
[yuiCompress]   at org.mozilla.javascript.Parser.addError(Parser.java:121)
[yuiCompress]   at org.mozilla.javascript.TokenStream.getToken(TokenStream.java:773)
[yuiCompress]   at org.mozilla.javascript.Parser.peekToken(Parser.java:161)
[yuiCompress]   at org.mozilla.javascript.Parser.parse(Parser.java:361)
[yuiCompress]   at org.mozilla.javascript.Parser.parse(Parser.java:337)
[yuiCompress]   at com.yahoo.platform.yui.compressor.JavaScriptCompressor.parse(JavaScriptCompressor.java:312)
[yuiCompress]   at com.yahoo.platform.yui.compressor.JavaScriptCompressor.<init>(JavaScriptCompressor.java:533)
[yuiCompress]   at com.yahoo.platform.yui.compressor.YUICompressor.main(YUICompressor.java:131)
[yuiCompress]   ... 22 more

I can switch back to Apple's Java 1.6 and it works fine. My question is, is there a way around this? I really can't continue on 1.6 any longer.


问:
Date object SimpleDateFormat not parsing timestamp string correctly in Java (Android) environment
I'm using the SimpleDateFormat object with the Date object as shown below. The problem lis that the Date object shows the wrong date, which is a few minutes off from the original string. The Date object appears to store the time in  total milliseconds in the debugger.

Any ideas on the problem?

```<code>import java.text.SimpleDateFormat;

import java.util.Date;

Date played_at_local;

dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSSZ");

played_at_local = dateFormat.parse("2011-04-11T22:27:18.491726-05:00");

//played_at_local shows "Mon Apr 11 22:35:29 America/Chicago 2011" in debugger
</code>```

答:
05:00 -->> 0500

and

hh --> HH  // error not because of this ,but date is in 24hr format.

```<code>played_at_local = dateFormat.parse("2011-04-11T22:27:18.491726-05:00");
</code>```

should be

```<code>played_at_local = dateFormat.parse("2011-04-11T22:27:18.491726-0500");
</code>```

Body:
I'm using the SimpleDateFormat object with the Date object as shown below. The problem lis that the Date object shows the wrong date, which is a few minutes off from the original string. The Date object appears to store the time in  total milliseconds in the debugger.

Any ideas on the problem?

import java.text.SimpleDateFormat;

import java.util.Date;

Date played_at_local;

dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSSZ");

played_at_local = dateFormat.parse("2011-04-11T22:27:18.491726-05:00");

//played_at_local shows "Mon Apr 11 22:35:29 America/Chicago 2011" in debugger

Body:
05:00 -->> 0500

and

hh --> HH  // error not because of this ,but date is in 24hr format.

played_at_local = dateFormat.parse("2011-04-11T22:27:18.491726-05:00");

should be

played_at_local = dateFormat.parse("2011-04-11T22:27:18.491726-0500");


问:
Variables passed to url_for within an email link not working
I am setting up a registration feature for my flask application. When a user requests to register, I send an email to my admin account and would like to approve or deny their request.

When I send the email, the username, email and password given by the registration form are passed into the html and can be displayed. However when I try to move these variables along in a link created with 'url_for' they are unobtainable.

This is the email my admin account receives:

```<code><p>{{ form.username.data }} has requested registration authorization.</p>
<p> Their information is as follows,</p>
<p>Username: {{ form.username.data }}</p>
<p>Email: {{ form.email.data }}</p>
<p>Password: {{ form.password.data }}</p>
<p>
  To register this user:
  <a href="{{ url_for('auth.register_user', username=form.username.data,
             email=form.email.data, password=form.password.data, _external=True) }}">
    click here.
  </a>
</p>
<p>-ADCo Inventory</p>
</code>```

The username, email and password are all displayed correctly here.
And this is the auth.register_user html, where I am simply trying to show the username and password for the time being, which doesn't work.

```<code>{% extends 'base.html.j2' %}

{% block content %}
<h2> Register {{ username }}</h2>
<h2>pass: {{ password }}</h2>

{% endblock %}
</code>```

Here is the route for auth.register_user if it helps any:

```<code>@auth_bp.route('/register_user', methods=['GET', 'POST'])
def register_user():

    form = RegistrationForm()

    return render_template('register_user.html.j2', form=form)
</code>```

答:
You have passed the data via get request like below:

```<code><a href="{{ url_for('auth.register_user', username=form.username.data,
             email=form.email.data, password=form.password.data, _external=True) }}">
</code>```

So to access to username for example, you need to use request.args like below:

```<code>username = request.args.get('username', '')
</code>```

Body:
I am setting up a registration feature for my flask application. When a user requests to register, I send an email to my admin account and would like to approve or deny their request.

When I send the email, the username, email and password given by the registration form are passed into the html and can be displayed. However when I try to move these variables along in a link created with 'url_for' they are unobtainable.

This is the email my admin account receives:

{{ form.username.data }} has requested registration authorization.

 Their information is as follows,

Username: {{ form.username.data }}

Email: {{ form.email.data }}

Password: {{ form.password.data }}

  To register this user:

    click here.

-ADCo Inventory

The username, email and password are all displayed correctly here.
And this is the auth.register_user html, where I am simply trying to show the username and password for the time being, which doesn't work.

{% extends 'base.html.j2' %}

{% block content %}

 Register {{ username }}

pass: {{ password }}

{% endblock %}

Here is the route for auth.register_user if it helps any:

@auth_bp.route('/register_user', methods=['GET', 'POST'])
def register_user():

    form = RegistrationForm()

    return render_template('register_user.html.j2', form=form)

Body:
You have passed the data via get request like below:

<a href="{{ url_for('auth.register_user', username=form.username.data,
             email=form.email.data, password=form.password.data, _external=True) }}">

So to access to username for example, you need to use request.args like below:

username = request.args.get('username', '')