问:
Set Integers getItemViewType RecyclerView
I have an array list of integers[3,-3,7,9,8,1].

What I am trying to do is to get the same numbers that are positive and negative and make them type 1.
For example, The number "3" and "-3" will be type 1 and all the others will be type 2.

I did like the following:

override fun getItemViewType(position: Int): Int {

```<code>val positiveArray = ArrayList<Int>()
val negativeArray = ArrayList<Int>()

val currentNumber = numberList[position]

Log.e("getItemViewType","currentNumber= ${currentNumber.singleNumber}")

for (number in numberList){
    if (number.singleNumber > 0){
        positiveArray.add(number.singleNumber)
    }else{
        negativeArray.add(number.singleNumber)
    }
}

Log.e("positiveArray","Result: $positiveArray")
Log.e("negativeArray","Result: $negativeArray")

return if (positiveArray.contains(currentNumber.singleNumber) && negativeArray.contains(-currentNumber.singleNumber)) { // put your condition, according to your requirements
    Log.e("getItemViewType","Contains Both = ${currentNumber.singleNumber}")
    RED_ROW
} else{
    ORANGE_ROW
}
</code>```

}

So the problem here is that when I run the app with this code,its only mark "3" as type 1 but the "-3" is type 2.

Edit:

Full adapter class:

```<code>class MainRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val ORANGE_ROW = 1
        private const val RED_ROW = 2
    }

    private lateinit var numberList : List<SingleNumber>

    inner class RedRowViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){

        private lateinit var redTextView : TextView

        fun bindRedRow(singleNumber: Int) {
            redTextView = itemView.findViewById<TextView>(R.id.redNumberTextView)
            redTextView.text = singleNumber.toString()
        }

    }

    inner class OrangeRowViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){

        private lateinit var orangeTextView : TextView

        fun bindOrangeRow(singleNumber: Int) {
            orangeTextView = itemView.findViewById<TextView>(R.id.orangeNumberTextView)
            orangeTextView.text = singleNumber.toString()
        }

    }

override fun getItemViewType(position: Int): Int {

    val positiveArray = ArrayList<Int>()
    val negativeArray = ArrayList<Int>()

    val currentNumber = numberList[position]

    Log.e("getItemViewType","currentNumber= ${currentNumber.singleNumber}")

    for (number in numberList){
        if (number.singleNumber > 0){
            positiveArray.add(number.singleNumber)
        }else{
            negativeArray.add(number.singleNumber)
        }
    }

    Log.e("positiveArray","Result: $positiveArray")
    Log.e("negativeArray","Result: $negativeArray")

    return if (positiveArray.contains(currentNumber.singleNumber) && negativeArray.contains(-currentNumber.singleNumber)) { // put your condition, according to your requirements
        Log.e("getItemViewType","Contains Both = ${currentNumber.singleNumber}")
        RED_ROW
    } else{
        ORANGE_ROW
    }

}

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        return if (viewType == RED_ROW){
            val redRow = LayoutInflater.from(parent.context).inflate(R.layout.red_row,parent,false)
            RedRowViewHolder(redRow)
        }else{
            val orangeRow = LayoutInflater.from(parent.context).inflate(R.layout.orange_row,parent,false)
            OrangeRowViewHolder(orangeRow)
        }

    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (getItemViewType(position) == RED_ROW){
            (holder as RedRowViewHolder).bindRedRow(numberList[position].singleNumber)
        } else{
            (holder as OrangeRowViewHolder).bindOrangeRow(numberList[position].singleNumber)
        }
    }

    override fun getItemCount(): Int {
        return if (this::numberList.isInitialized){
            numberList.size
        } else 0
    }

    fun setList(newList : List<SingleNumber>){
        Log.e("ListSet","ListsET $newList")

        numberList = newList
        notifyDataSetChanged()
    }

}
</code>```

How can I overcome this ?
Do you think its build in the right way or you would do something different ? Thank you !

答:
This is wheat I have done:

```<code>override fun getItemViewType(position: Int): Int {

    val currentNumber = abs(numberList[position].singleNumber)

    val positiveArray = ArrayList<Int>()
    val negativeArray = ArrayList<Int>()

    for (number in numberList){
        if (number.singleNumber > 0){
            positiveArray.add(number.singleNumber)
        }else{
            negativeArray.add(abs(number.singleNumber))
        }
    }

    return if (positiveArray.contains(currentNumber) && negativeArray.contains(currentNumber)){
        1
    }else{
        2
    }

}
</code>```

Tnx to @GabeSechan I now know what is "abs",its making negative numbers positive.

I created 2 lists,1 for the negative and 1 for the positive(notice that when I adding the negative value,I use "abs".

After that I check the numbers in both lists,if its exist the type is 1,if not,the type is 2.

Body:
I have an array list of integers[3,-3,7,9,8,1].

What I am trying to do is to get the same numbers that are positive and negative and make them type 1.
For example, The number "3" and "-3" will be type 1 and all the others will be type 2.

I did like the following:

override fun getItemViewType(position: Int): Int {

val positiveArray = ArrayList<Int>()
val negativeArray = ArrayList<Int>()

val currentNumber = numberList[position]

Log.e("getItemViewType","currentNumber= ${currentNumber.singleNumber}")

for (number in numberList){
    if (number.singleNumber > 0){
        positiveArray.add(number.singleNumber)
    }else{
        negativeArray.add(number.singleNumber)
    }
}

Log.e("positiveArray","Result: $positiveArray")
Log.e("negativeArray","Result: $negativeArray")

return if (positiveArray.contains(currentNumber.singleNumber) && negativeArray.contains(-currentNumber.singleNumber)) { // put your condition, according to your requirements
    Log.e("getItemViewType","Contains Both = ${currentNumber.singleNumber}")
    RED_ROW
} else{
    ORANGE_ROW
}

}

So the problem here is that when I run the app with this code,its only mark "3" as type 1 but the "-3" is type 2.

Edit:

Full adapter class:

class MainRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val ORANGE_ROW = 1
        private const val RED_ROW = 2
    }

    private lateinit var numberList : List<SingleNumber>

    inner class RedRowViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){

        private lateinit var redTextView : TextView

        fun bindRedRow(singleNumber: Int) {
            redTextView = itemView.findViewById<TextView>(R.id.redNumberTextView)
            redTextView.text = singleNumber.toString()
        }

    }

    inner class OrangeRowViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){

        private lateinit var orangeTextView : TextView

        fun bindOrangeRow(singleNumber: Int) {
            orangeTextView = itemView.findViewById<TextView>(R.id.orangeNumberTextView)
            orangeTextView.text = singleNumber.toString()
        }

    }

override fun getItemViewType(position: Int): Int {

    val positiveArray = ArrayList<Int>()
    val negativeArray = ArrayList<Int>()

    val currentNumber = numberList[position]

    Log.e("getItemViewType","currentNumber= ${currentNumber.singleNumber}")

    for (number in numberList){
        if (number.singleNumber > 0){
            positiveArray.add(number.singleNumber)
        }else{
            negativeArray.add(number.singleNumber)
        }
    }

    Log.e("positiveArray","Result: $positiveArray")
    Log.e("negativeArray","Result: $negativeArray")

    return if (positiveArray.contains(currentNumber.singleNumber) && negativeArray.contains(-currentNumber.singleNumber)) { // put your condition, according to your requirements
        Log.e("getItemViewType","Contains Both = ${currentNumber.singleNumber}")
        RED_ROW
    } else{
        ORANGE_ROW
    }

}

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        return if (viewType == RED_ROW){
            val redRow = LayoutInflater.from(parent.context).inflate(R.layout.red_row,parent,false)
            RedRowViewHolder(redRow)
        }else{
            val orangeRow = LayoutInflater.from(parent.context).inflate(R.layout.orange_row,parent,false)
            OrangeRowViewHolder(orangeRow)
        }

    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (getItemViewType(position) == RED_ROW){
            (holder as RedRowViewHolder).bindRedRow(numberList[position].singleNumber)
        } else{
            (holder as OrangeRowViewHolder).bindOrangeRow(numberList[position].singleNumber)
        }
    }

    override fun getItemCount(): Int {
        return if (this::numberList.isInitialized){
            numberList.size
        } else 0
    }

    fun setList(newList : List<SingleNumber>){
        Log.e("ListSet","ListsET $newList")

        numberList = newList
        notifyDataSetChanged()
    }

}

How can I overcome this ?
Do you think its build in the right way or you would do something different ? Thank you !

Body:
This is wheat I have done:

override fun getItemViewType(position: Int): Int {

    val currentNumber = abs(numberList[position].singleNumber)

    val positiveArray = ArrayList<Int>()
    val negativeArray = ArrayList<Int>()

    for (number in numberList){
        if (number.singleNumber > 0){
            positiveArray.add(number.singleNumber)
        }else{
            negativeArray.add(abs(number.singleNumber))
        }
    }

    return if (positiveArray.contains(currentNumber) && negativeArray.contains(currentNumber)){
        1
    }else{
        2
    }

}

Tnx to @GabeSechan I now know what is "abs",its making negative numbers positive.

I created 2 lists,1 for the negative and 1 for the positive(notice that when I adding the negative value,I use "abs".

After that I check the numbers in both lists,if its exist the type is 1,if not,the type is 2.


来源: stackexchange

问:
How to change the background color of the Chakra UI Progress component?
The same question as this, but for Progress instead of Toast. Extending the theme's Progress component does nothing, so I thought this component also uses another component, like how the Toast uses Alert, but I couldn't find anything about this.
This doesn't work for Progress: (but it works for other components, like Button or Alert)</p>
```<code>const customTheme = extendTheme({
  components: {
    Progress: {
      baseStyle: {
        bg: '#d4f3e7'
      }
    }
  }
})
</code>```

答:
You need to specifically target filledTrack (or just track if you'd like to style the background of the progress bar), because <Progress> is a multipart component.

```<code>const customTheme = extendTheme({
  components: {
    Progress: {
      baseStyle: {
        filledTrack: {
          bg: '#d4f3e7'
        }
      }
    }
  }
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The same question as this, but for Progress instead of Toast. Extending the theme's Progress component does nothing, so I thought this component also uses another component, like how the Toast uses Alert, but I couldn't find anything about this.
This doesn't work for Progress: (but it works for other components, like Button or Alert)

const customTheme = extendTheme({
  components: {
    Progress: {
      baseStyle: {
        bg: '#d4f3e7'
      }
    }
  }
})

Body:
You need to specifically target filledTrack (or just track if you'd like to style the background of the progress bar), because <Progress> is a multipart component.

const customTheme = extendTheme({
  components: {
    Progress: {
      baseStyle: {
        filledTrack: {
          bg: '#d4f3e7'
        }
      }
    }
  }
})


问:
raise "pytesseract.pytesseract.TesseractError: (3221225477, '')"
I got the following error when I tried to find out the Chinese words in a picture by python: (By the way, I had already had "chi_sim.traineddata" training file in tessdata directory and got a successful try to find out English sentences in a picture, so this error really confused me.)</p>

```<code>*C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\python.exe E:/PKU1.3/python_math/set_for_recognition.py
Traceback (most recent call last):
  File "E:/PKU1.3/python_math/set_for_recognition.py", line 5, in <module>
    text=pytesseract.image_to_string(Image.open('climb_high.jpeg'),lang='chi_sim')
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytesseract\pytesseract.py", line 295, in image_to_string
    return run_and_get_output(*args)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytesseract\pytesseract.py", line 203, in run_and_get_output
    run_tesseract(**kwargs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytesseract\pytesseract.py", line 179, in run_tesseract
    raise TesseractError(status_code, get_errors(error_string))
pytesseract.pytesseract.TesseractError: (3221225477, '')*
</code>```

答:
Please try the below code :</p>
```<code>import pytesseract

from PIL import Image
pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe'
tessdata_dir_config = '--tessdata-dir "C:/Program Files/Tesseract-OCR/tessdata"'

img = Image.open('images\Capture2.JPG')

text = pytesseract.image_to_string(img, config=tessdata_dir_config)

print(text)
</code>```

Body:
I got the following error when I tried to find out the Chinese words in a picture by python: (By the way, I had already had "chi_sim.traineddata" training file in tessdata directory and got a successful try to find out English sentences in a picture, so this error really confused me.)

*C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\python.exe E:/PKU1.3/python_math/set_for_recognition.py
Traceback (most recent call last):
  File "E:/PKU1.3/python_math/set_for_recognition.py", line 5, in <module>
    text=pytesseract.image_to_string(Image.open('climb_high.jpeg'),lang='chi_sim')
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytesseract\pytesseract.py", line 295, in image_to_string
    return run_and_get_output(*args)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytesseract\pytesseract.py", line 203, in run_and_get_output
    run_tesseract(**kwargs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytesseract\pytesseract.py", line 179, in run_tesseract
    raise TesseractError(status_code, get_errors(error_string))
pytesseract.pytesseract.TesseractError: (3221225477, '')*

Body:
Please try the below code :

import pytesseract

from PIL import Image
pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe'
tessdata_dir_config = '--tessdata-dir "C:/Program Files/Tesseract-OCR/tessdata"'

img = Image.open('images\Capture2.JPG')

text = pytesseract.image_to_string(img, config=tessdata_dir_config)

print(text)


问:
Cypress: asserting elements within the same parent element
Suppose I have the following page:

```<code><div>
    <div class="item">
        <p data-testid=title>Item One Title</p>
        <p data-testid=subtitle>Item One Subtitle</p>
    </div>
    <div class="item">
        <p data-testid=title>Item Two Title</p>
        <p data-testid=subtitle>Item Two Subtitle</p>
    </div>
</div>
</code>```

I would like to test that Item One Title and Item One Subtitle are present within the same parent div.item. What would be the best way to do this in Cypress?

What I tried so far:

Test #1:

```<code>cy.get('[data-testid=title]').should('contain.text', 'Item One Title');
cy.get('[data-testid=subtitle]').should('contain.text', 'Item One Subtitle');
</code>```

These tests will pass, but does not check that Item One Title and Item One Subtitle are within the same parent div.

Test #2:

```<code>cy.get('[data-testid=title]').should('contain.text', 'Item One Title').then(($foo) => {
   cy.wrap($foo).next().should('contain.text', 'Item One Subtitle');
});
</code>```

Seems to be the same as Test #1, does not check that Item One Title and Item One Subtitle are within the same parent div.

答:
You can use siblings

cy.contains('[data-testid=title]', 'Item One Title')
  .siblings()
  .should('have.attr', 'data-testid', 'subtitle')
  .and('contain.text', 'Item One Subtitle')
```

Body:
Suppose I have the following page:

Item One Title

Item One Subtitle

Item Two Title

Item Two Subtitle

I would like to test that Item One Title and Item One Subtitle are present within the same parent div.item. What would be the best way to do this in Cypress?

What I tried so far:

Test #1:

cy.get('[data-testid=title]').should('contain.text', 'Item One Title');
cy.get('[data-testid=subtitle]').should('contain.text', 'Item One Subtitle');

These tests will pass, but does not check that Item One Title and Item One Subtitle are within the same parent div.

Test #2:

cy.get('[data-testid=title]').should('contain.text', 'Item One Title').then(($foo) => {
   cy.wrap($foo).next().should('contain.text', 'Item One Subtitle');
});

Seems to be the same as Test #1, does not check that Item One Title and Item One Subtitle are within the same parent div.


问:
weird jquery and IE issue
I found a weird problem with jQuery and IE and I was wondering if there is a fix or a work around. Basically, when the page initially loads, or if it is accessed directly from the url (eg. you copy paste the url and go to it), The page gives jQuery errors in IE (all other browsers are fine).

However, on the same page, if you refresh the page, everything runs and loads just fine. Has anybody encounter such problem?

答:
It sounds like you have a cache error. Usually it happens when you try to reference DOM objects that aren't loaded yet.

Make sure you wrap your jquery in

```<code>$(document).ready(function(){

});
</code>```

That way the DOM will be ready before you start messing with it.

ContentLicense: CC BY-SA 3.0

Title: weird jquery and IE issue

Body:
It sounds like you have a cache error. Usually it happens when you try to reference DOM objects that aren't loaded yet.

Make sure you wrap your jquery in

$(document).ready(function(){

});

That way the DOM will be ready before you start messing with it.


问:
Map result of query with filtered join back to entity with relation
I am trying to perform an SQL query with a join, where the join has an additional filter condition. Using plain SQL my data is modeled like this:

create table food_storage (
  name varchar primary key
);
create table food (
  name varchar primary key,
  expired bool,
  stored_in varchar references food_storage(name)
);

insert into food_storage (name) values ('drawer'), ('fridge'), ('cabinet');
insert into food
  (name,        expired, stored_in)
values
  ('teabags',   false,   'drawer'),
  ('beans',     true,    'drawer'),
  ('leftovers', true,    'fridge'),
  ('rice',      false,   'cabinet'),
  ('flour',     false,   'cabinet');
```
<p>And my query looks like this (only selecting a few fields for brevity):</p>
<pre class="lang-sql prettyprint-override"><code>select food_storage.name, food.name from food_storage
left outer join food on food.stored_in = food_storage.name and not food.expired;
</code>```

name
name

drawer
teabags

cabinet
rice

cabinet
flour

fridge
(null)

However, I am trying to perform this query using JPA, and have the result successfully map back to JPA entities. I modeled my JPA entities like this:

@Entity
@Table(name = "food_storage")
@Data
public class FoodStorage {
  @Id
  private String name;

  @OneToMany(mappedBy = "stored_in")
  private List<Food> foodContents;
}

@Entity
@Table(name = "food")
@Data
public class Food {
  @Id
  private String name;

  @Column
  private boolean expired;

  @Column(name = "stored_in")
  private String storedIn;
}
```
<p>For the raw SQL query result above, I need the result to be mapped back into entities like this:</p>
<pre class="lang-none prettyprint-override"><code>[
    FoodStorage(name=drawer, foodContents=[
        Food(name=teabags, expired=false, storedIn=drawer)
    ]),
    FoodStorage(name=fridge, foodContents=[]),
    FoodStorage(name=cabinet, foodContents=[
        Food(name=rice, expired=false, storedIn=cabinet),
        Food(name=flour, expired=false, storedIn=cabinet)
    ])
]
</code>```

I tried using this code:

String sql = """
select food_storage.*, food.* from food_storage
left outer join food on food.stored_in = food_storage.name and not food.expired;
""";
Query query = entityManager.createNativeQuery(sql, FoodStorage.class);
System.out.println(query.getResultList());
```
<p>But this is the result I get:</p>
<pre class="lang-none prettyprint-override"><code>[
    FoodStorage(name=drawer, foodContents=[
        Food(name=teabags, expired=false, storedIn=drawer),
        Food(name=beans, expired=true, storedIn=drawer)
    ]),
    FoodStorage(name=fridge, foodContents=[
        Food(name=leftovers, expired=true, storedIn=fridge)
    ]),
    FoodStorage(name=cabinet, foodContents=[
        Food(name=rice, expired=false, storedIn=cabinet),
        Food(name=flour, expired=false, storedIn=cabinet)
    ]),
    FoodStorage(name=cabinet, foodContents=[
        Food(name=rice, expired=false, storedIn=cabinet),
        Food(name=flour, expired=false, storedIn=cabinet)
    ])
]
</code>```

Hibernate appears to ignore my manual join, and instead just constructs one FoodStorage-instance per result row and subsequently fetches all Food per FoodStorage. How can I overcome this problem?

I have found Hibernate's @Where annotation. Unfortunately for my real-world case the join filter is dynamic, so I cannot use it.

答:
```<code>String sql = "select distinct food_storage.* from food_storage left outer join food on food.stored_in = food_storage.name and not food.expired; ";
</code>```

The food.* is useless.You can use spring.jpa.properties.hibernate.show_sql=true to print sql. Returning food.* does not reduce the number of queries.

Body:
I am trying to perform an SQL query with a join, where the join has an additional filter condition. Using plain SQL my data is modeled like this:

create table food_storage (
  name varchar primary key
);
create table food (
  name varchar primary key,
  expired bool,
  stored_in varchar references food_storage(name)
);

insert into food_storage (name) values ('drawer'), ('fridge'), ('cabinet');
insert into food
  (name,        expired, stored_in)
values
  ('teabags',   false,   'drawer'),
  ('beans',     true,    'drawer'),
  ('leftovers', true,    'fridge'),
  ('rice',      false,   'cabinet'),
  ('flour',     false,   'cabinet');

And my query looks like this (only selecting a few fields for brevity):

select food_storage.name, food.name from food_storage
left outer join food on food.stored_in = food_storage.name and not food.expired;

name
name

drawer
teabags

cabinet
rice

cabinet
flour

fridge
(null)

However, I am trying to perform this query using JPA, and have the result successfully map back to JPA entities. I modeled my JPA entities like this:

@Entity
@Table(name = "food_storage")
@Data
public class FoodStorage {
  @Id
  private String name;

  @OneToMany(mappedBy = "stored_in")
  private List<Food> foodContents;
}

@Entity
@Table(name = "food")
@Data
public class Food {
  @Id
  private String name;

  @Column
  private boolean expired;

  @Column(name = "stored_in")
  private String storedIn;
}

For the raw SQL query result above, I need the result to be mapped back into entities like this:

[
    FoodStorage(name=drawer, foodContents=[
        Food(name=teabags, expired=false, storedIn=drawer)
    ]),
    FoodStorage(name=fridge, foodContents=[]),
    FoodStorage(name=cabinet, foodContents=[
        Food(name=rice, expired=false, storedIn=cabinet),
        Food(name=flour, expired=false, storedIn=cabinet)
    ])
]

I tried using this code:

String sql = """
select food_storage.*, food.* from food_storage
left outer join food on food.stored_in = food_storage.name and not food.expired;
""";
Query query = entityManager.createNativeQuery(sql, FoodStorage.class);
System.out.println(query.getResultList());

But this is the result I get:

[
    FoodStorage(name=drawer, foodContents=[
        Food(name=teabags, expired=false, storedIn=drawer),
        Food(name=beans, expired=true, storedIn=drawer)
    ]),
    FoodStorage(name=fridge, foodContents=[
        Food(name=leftovers, expired=true, storedIn=fridge)
    ]),
    FoodStorage(name=cabinet, foodContents=[
        Food(name=rice, expired=false, storedIn=cabinet),
        Food(name=flour, expired=false, storedIn=cabinet)
    ]),
    FoodStorage(name=cabinet, foodContents=[
        Food(name=rice, expired=false, storedIn=cabinet),
        Food(name=flour, expired=false, storedIn=cabinet)
    ])
]

Hibernate appears to ignore my manual join, and instead just constructs one FoodStorage-instance per result row and subsequently fetches all Food per FoodStorage. How can I overcome this problem?

I have found Hibernate's @Where annotation. Unfortunately for my real-world case the join filter is dynamic, so I cannot use it.

Body:
String sql = "select distinct food_storage.* from food_storage left outer join food on food.stored_in = food_storage.name and not food.expired; ";

The food.* is useless.You can use spring.jpa.properties.hibernate.show_sql=true to print sql. Returning food.* does not reduce the number of queries.


问:
How to set pseudo selector on hover with styled-components
Using styled-components in React, I wonder how to set pseudo selectors like :before or :after when hovering an element.
This is css example:

So how to translate the css code in red rectangle with styled-components?

答:
If the styled component is the same as the target element. You can do the following:

const Link = styled.a`
  &:hover:before {
    width: 100%;
  }
`;
```
<p>If you are targeting an element nested inside the styled component:</p>
```const LinksWrapper = styled.div`
  a:hover:before {
    width: 100%;
  }
`;
```

Body:
If the styled component is the same as the target element. You can do the following:

const Link = styled.a`
  &:hover:before {
    width: 100%;
  }
`;

If you are targeting an element nested inside the styled component:

const LinksWrapper = styled.div`
  a:hover:before {
    width: 100%;
  }
`;


问:
Cheerio get method not working as expected
I am doing some web scraping in JS for the first time and already stuck.

I have a cheerio object that contains div tags I want to pull out. If I iterate through the cheerio using the each method, I can see they are all there

```<code>temp.each(function (i, e) {
    console.log($(e).text());
    console.log("...looping");
    console.log(i);
 });

...looping
0
“The square root of the amount of ducks I give"
...looping
1
Sweet Home, Alabama
...looping
2
FOOTER GOES HERE
...looping
3
</code>```

I see that quote I want is under the element indexed at 1, but if I try to grab it with temp.get(1).text(), I get TypeError: temp.get(...).text is not a function.

There is something big I am missing here.

答:
.get gives you the element, not the Cheerio object - elements don't have a .text method. Either use the proper property to extract text from an element:

```<code>console.log($(e).get(1).textContent)
</code>```

Or use .eq instead, which will give you a Cheerio object containing only the element at that index.

```<code>console.log($(e).eq(1).text())
</code>```

Body:
I am doing some web scraping in JS for the first time and already stuck.

I have a cheerio object that contains div tags I want to pull out. If I iterate through the cheerio using the each method, I can see they are all there

temp.each(function (i, e) {
    console.log($(e).text());
    console.log("...looping");
    console.log(i);
 });

...looping
0
“The square root of the amount of ducks I give"
...looping
1
Sweet Home, Alabama
...looping
2
FOOTER GOES HERE
...looping
3

I see that quote I want is under the element indexed at 1, but if I try to grab it with temp.get(1).text(), I get TypeError: temp.get(...).text is not a function.

There is something big I am missing here.

Body:
.get gives you the element, not the Cheerio object - elements don't have a .text method. Either use the proper property to extract text from an element:

console.log($(e).get(1).textContent)

Or use .eq instead, which will give you a Cheerio object containing only the element at that index.

console.log($(e).eq(1).text())


问:
React Antd not able to get value from custom date picker
I am currently using custom datepicker to enter date in the format 'MMDD' or 'MMDDYY' and setting the value in state and using in the datepicker component as controlled component. But on submit of form the datepicker value is undefined.

Please find the code in the codesandbox and correct me on what i am doing wrong in this one.

https://codesandbox.io/s/damp-haze-mmj80

答:
This is what works for me with React Hooks, hope it will help.

const initialInfo = {email: "", registrationDate: ""}
const [infoData, setInfoData] = useState(initialInfo);
```
<p>inside of the component...</p>
<pre class="lang-js prettyprint-override"><code><DatePicker defaultValue={moment(infoData?.dateDisplay, dateFormat)} />
</code>```

Body:
This is what works for me with React Hooks, hope it will help.

const initialInfo = {email: "", registrationDate: ""}
const [infoData, setInfoData] = useState(initialInfo);

inside of the component...

<DatePicker defaultValue={moment(infoData?.dateDisplay, dateFormat)} />


问:
How to Create a Java Quiz GUI?
I would like to create a quiz for my Java GUI.

I'd like it to display a question on one page, then have a next button which takes the user to another page telling them if that question was correct or not, and if it is correct they can move on to the next question (by clicking another next button) and if they got it wrong, have to go back and answer it again. However I have no clue how to do this!!

So far I have a simple GUI with a welcome page and tabs down the side, one of which includes a quiz. Would it be a better idea to create the quiz in Flash or something and then embed it into my Java application? Or just do the whole thing in Java? I'm really new to java so I'm not at all sure what to do, any help would be greatly appreciated!

Thanks

答:
For this type of app it would be best to use the language you are more familiar with.

Since this is just a simple display this  then do that there really is nothing very difficult about it.

Personal, I would lean towards Flash as the flash IDE is drag and drop and an experienced flash guru could make this in a few hours. Flash IDE is geared towards this.

Title: How to Create a Java Quiz GUI?


问:
Azure .NET SDK Documentation Missing
Azure REST APIs are well documented but I cannot find decent documentation for the Azure .NET SDK. Just as an example, I tried to delete and create a managed SQL database using the SDK. There is no documentation explaining the use of SqlManagementClient or even any info that I should be using SqlManagementClient for this purpose. I just found some samples here and there as a result of Google search.

Is it really that the .NET SDK for Azure is not properly documented or am I missing where it is? I would appreciate it if anyone could share a link to such documentation. (and I don't mean the API references.)

答:
Thanks, John, for raising this up, the reason is that for .net SDK we are in the process of upgrading to a new version which follows a new design principle, with the new design, it would be easy for us to create sample codes or documents. For your specific question, I'd suggest you can check Azure Resource Management with Azure .NET SDK, all SDK usage of managing azure resource follows the same principle.

Thanks again for letting us know your concerns about Azure SDK and we value all customer voices against Azure SDK.

Title: Azure .NET SDK Documentation Missing


问:
How to call or stub with same imported function with multiple ways
In controller I have imported config file for getting path for userId and secret  path location and auth file for getting the userId name and secret value based on that I have redirected to some endpoint. but when I write the testcases how to pass or get the all details using stub. can you please assist.

controller.ts

```<code>import { userConf } from './conf';
import {userSec} from './auth'

 export function userInfo(req: Request, res: Response) {
const path='test:path';
const path1='test:path1'
const userID = userConf(path); //user/Id
const userPass=userConf(path1); // user/pass
const secId=userSec(userID); // raj
const secPass=userSec(userPass) // Otersg
const url=`https://mapuser.com?userId=${secId}&usersec=${secPass}`;
res.redirect(302,url);
}
</code>```

details.json

```<code>{
"test":{
    "path":"user/Id",
    "path1":"user/pass"
 }
}
</code>```

conf.ts

```<code>export function userConf(path) {
  return 'implementation for getting path';
}
</code>```

auth.ts

```<code>export function usersec(path) {
  return 'implementation for getting values';
}
</code>```

test.spec.ts

```<code>import sinon from 'sinon';
import proxyquire from 'proxyquire';

 describe('should redirect', () => {
 it('should pass with all valid', () => {
  const getpath = sinon.stub().returns('test:path');
  const getsecId = sinon.stub().returns('ram');
  const urlctl = proxyquire('./controller', {
  './conf': {
    userConf: getpath,
  },
  './auth': {
    userSec: getsecId,
  },
});
const req = {};
const res = { redirect: sinon.stub() };
urlctl.getId(req, res);

sinon.assert.calledWithExactly(res.redirect, 302, 'https://mapuser.com?
userId=raj&usersec=Otersg');
 });
 });
</code>```

答:
It's not clear what you are trying to achieve. If you want to create stubs that can act differently in response to different arguments. You can use stub.withArgs(arg1[, arg2, ...]).

E.g.

controller.ts:

```<code>import { Request, Response } from 'express';
import { userConf } from './conf';
import { userSec } from './auth';

export function userInfo(req: Request, res: Response) {
  const path = 'test:path';
  const path1 = 'test:path1';
  const userID = userConf(path);
  const userPass = userConf(path1);
  const secId = userSec(userID);
  const secPass = userSec(userPass);
  const url = `https://mapuser.com?userId=${secId}&usersec=${secPass}`;
  res.redirect(302, url);
}
</code>```

controller.spec.ts:

```<code>import sinon from 'sinon';
import proxyquire from 'proxyquire';

describe('should redirect', () => {
  it('should pass with all valid', () => {
    const getpath = sinon.stub();
    getpath.withArgs('test:path').returns('fake user id');
    getpath.withArgs('test:path1').returns('fake user pass');

    const getsecId = sinon.stub();
    getsecId.withArgs('fake user id').returns('raj');
    getsecId.withArgs('fake user pass').returns('Otersg');

    const urlctl = proxyquire('./controller', {
      './conf': {
        userConf: getpath,
      },
      './auth': {
        userSec: getsecId,
      },
    });
    const req = {};
    const res = { redirect: sinon.stub() };
    urlctl.userInfo(req, res);

    sinon.assert.calledWithExactly(res.redirect, 302, 'https://mapuser.com?userId=raj&usersec=Otersg');
  });
});
</code>```

Test result:

  should redirect
    ✓ should pass with all valid (239ms)

  1 passing (243ms)

--------------------|---------|----------|---------|---------|-------------------
File                | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------------|---------|----------|---------|---------|-------------------
All files           |   93.33 |      100 |      60 |   93.33 |
 auth.ts            |      50 |      100 |       0 |      50 | 2
 conf.ts            |      50 |      100 |       0 |      50 | 2
 controller.spec.ts |     100 |      100 |     100 |     100 |
 controller.ts      |     100 |      100 |     100 |     100 |
--------------------|---------|----------|---------|---------|-------------------
```

Body:
In controller I have imported config file for getting path for userId and secret  path location and auth file for getting the userId name and secret value based on that I have redirected to some endpoint. but when I write the testcases how to pass or get the all details using stub. can you please assist.

controller.ts

import { userConf } from './conf';
import {userSec} from './auth'

 export function userInfo(req: Request, res: Response) {
const path='test:path';
const path1='test:path1'
const userID = userConf(path); //user/Id
const userPass=userConf(path1); // user/pass
const secId=userSec(userID); // raj
const secPass=userSec(userPass) // Otersg
const url=`https://mapuser.com?userId=${secId}&usersec=${secPass}`;
res.redirect(302,url);
}

details.json

{
"test":{
    "path":"user/Id",
    "path1":"user/pass"
 }
}

conf.ts

export function userConf(path) {
  return 'implementation for getting path';
}

auth.ts

export function usersec(path) {
  return 'implementation for getting values';
}

test.spec.ts

import sinon from 'sinon';
import proxyquire from 'proxyquire';

 describe('should redirect', () => {
 it('should pass with all valid', () => {
  const getpath = sinon.stub().returns('test:path');
  const getsecId = sinon.stub().returns('ram');
  const urlctl = proxyquire('./controller', {
  './conf': {
    userConf: getpath,
  },
  './auth': {
    userSec: getsecId,
  },
});
const req = {};
const res = { redirect: sinon.stub() };
urlctl.getId(req, res);

sinon.assert.calledWithExactly(res.redirect, 302, 'https://mapuser.com?
userId=raj&usersec=Otersg');
 });
 });

Body:
It's not clear what you are trying to achieve. If you want to create stubs that can act differently in response to different arguments. You can use stub.withArgs(arg1[, arg2, ...]).

E.g.

controller.ts:

import { Request, Response } from 'express';
import { userConf } from './conf';
import { userSec } from './auth';

export function userInfo(req: Request, res: Response) {
  const path = 'test:path';
  const path1 = 'test:path1';
  const userID = userConf(path);
  const userPass = userConf(path1);
  const secId = userSec(userID);
  const secPass = userSec(userPass);
  const url = `https://mapuser.com?userId=${secId}&usersec=${secPass}`;
  res.redirect(302, url);
}

controller.spec.ts:

import sinon from 'sinon';
import proxyquire from 'proxyquire';

describe('should redirect', () => {
  it('should pass with all valid', () => {
    const getpath = sinon.stub();
    getpath.withArgs('test:path').returns('fake user id');
    getpath.withArgs('test:path1').returns('fake user pass');

    const getsecId = sinon.stub();
    getsecId.withArgs('fake user id').returns('raj');
    getsecId.withArgs('fake user pass').returns('Otersg');

    const urlctl = proxyquire('./controller', {
      './conf': {
        userConf: getpath,
      },
      './auth': {
        userSec: getsecId,
      },
    });
    const req = {};
    const res = { redirect: sinon.stub() };
    urlctl.userInfo(req, res);

    sinon.assert.calledWithExactly(res.redirect, 302, 'https://mapuser.com?userId=raj&usersec=Otersg');
  });
});

Test result:

  should redirect
    ✓ should pass with all valid (239ms)

  1 passing (243ms)

--------------------|---------|----------|---------|---------|-------------------
File                | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------------|---------|----------|---------|---------|-------------------
All files           |   93.33 |      100 |      60 |   93.33 |
 auth.ts            |      50 |      100 |       0 |      50 | 2
 conf.ts            |      50 |      100 |       0 |      50 | 2
 controller.spec.ts |     100 |      100 |     100 |     100 |
 controller.ts      |     100 |      100 |     100 |     100 |
--------------------|---------|----------|---------|---------|-------------------


问:
what is the regex pattern for a regex pattern?
What is the regex pattern for a regex pattern? I am using Ruby version 1.8.7, and have a requirement to determine if a given string is a regex pattern. What is the best pattern to use to determine this?

Thanks,
Anand

答:
well any word can be a regex pattern.  The string "cat" could be compiled to a regex pattern. You could do something like:</p>

```<code>def is_regex?(str)
  Regexp.new(str) rescue false
end
</code>```

Body:
well any word can be a regex pattern.  The string "cat" could be compiled to a regex pattern. You could do something like:

def is_regex?(str)
  Regexp.new(str) rescue false
end


问:
how to convert a normal list to 2d list + changing the values to integers
I want to convert a normal list to 2d list and want to change the numbers to integers instead of str
I have somthing like this

```<code>my_list = ['00000000', '00000000', '00111000', '00101000', '00101000', '00000000', '00000000', '00000000']
</code>```

I want somthing like this using for loop:

```<code>my_list = [[00000000], [00000000], [00111000], [00101000], [00101000], [00000000], [00000000], [00000000]]
</code>```

Body:
I want to convert a normal list to 2d list and want to change the numbers to integers instead of str
I have somthing like this

my_list = ['00000000', '00000000', '00111000', '00101000', '00101000', '00000000', '00000000', '00000000']

I want somthing like this using for loop:

my_list = [[00000000], [00000000], [00111000], [00101000], [00101000], [00000000], [00000000], [00000000]]

Body:
You may use a list comprehension here:

my_list = ['00000000', '00000000', '00111000', '00101000', '00101000', '00000000', '00000000', '00000000']
output = [[int(x)] for x in my_list]
print(output)  # [[0], [0], [111000], [101000], [101000], [0], [0], [0]]

Note that there is no Python integer literal 00000000, which is really the same as 0.  If you need the leading zeroes, then you should leave your data as strings.

Edit:

To get a 2D list of single numbers from each string, use:

my_list = ['00000000', '00000000', '00111000', '00101000', '00101000', '00000000', '00000000', '00000000']
output = [[int(x) for x in list(y)] for y in my_list]
print(output)
# [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
#  [0, 0, 1, 1, 1, 0, 0, 0], ...


问:
Flutter TextFormField: The keyboard appeared and instantly disappeared
When I click the TextFormField, the keyboard appears, then it disappears instantly, just like blinking. I wonder that whether it is because the lacking of some parameters? Or some other problems? Thanks.
Here are my relative codes.</p>
```<code>final _formKey = GlobalKey<FormState>();
String? _account;
Widget _showAccountInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 0.0, 0.0),
      child: new TextFormField(
        maxLines: 1,
        obscureText: true,
        autofocus: false,
        style: TextStyle(fontSize: 15),
        decoration: new InputDecoration(
            border: InputBorder.none,
            hintText: 'input',
            icon: new Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        onSaved: (value) => _account = value?.trim(),
      ),
    );
  }
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: new AppBar(
        title: new Text("Second Screen"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _showAccountInput()

          ],
        ),
      ),
    );
  }
}
</code>```

答: if your build method is in a StatelessWidget, try to change it to a StatefulWidget

Body:
When I click the TextFormField, the keyboard appears, then it disappears instantly, just like blinking. I wonder that whether it is because the lacking of some parameters? Or some other problems? Thanks.
Here are my relative codes.

final _formKey = GlobalKey<FormState>();
String? _account;
Widget _showAccountInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 0.0, 0.0),
      child: new TextFormField(
        maxLines: 1,
        obscureText: true,
        autofocus: false,
        style: TextStyle(fontSize: 15),
        decoration: new InputDecoration(
            border: InputBorder.none,
            hintText: 'input',
            icon: new Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        onSaved: (value) => _account = value?.trim(),
      ),
    );
  }
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: new AppBar(
        title: new Text("Second Screen"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _showAccountInput()

          ],
        ),
      ),
    );
  }
}


问:
OSERROR: -1743 MESSAGE: The user has declined permission
I spent some time messing with openpyxl and had it doing more or less what I wanted until I introduced some real-world data (only as a test) and discovered it can't handle data validation in the Excel workbook (I think the data validation thing refers to a drop-down list):

```<code>UserWarning: Data Validation extension is not supported and will be removed
</code>```

My code carries on and opens the Excel file but because the validation is removed it breaks it.

Okay, so back to square one, I go away and do some more reading and discover that xlwings can probably handle this. I get xlwings and run the shortest test I can think of:

```<code>from pathlib import Path
import xlwings as xw

my_documents = Path('/users/chris/documents')

xw.Book()
wb = xw.Book(my_documents / 'Test.xlsx')
ws = wb.sheets['Sheet1']
</code>```

That gives a lot of errors for such a small piece of code!

```<code>Traceback (most recent call last):
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/aeosa/appscript/reference.py", line 482, in __call__
    return self.AS_appdata.target().event(self._code, params, atts, codecs=self.AS_appdata).send(timeout, sendflags)
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/aeosa/aem/aemsend.py", line 92, in send
    raise EventError(errornum, errormsg, eventresult)
aem.aemsend.EventError: Command failed: The user has declined permission. (-1743)

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

Traceback (most recent call last):
  File "/Users/chris/Documents/Python Projects/little_tests.py", line 6, in <module>
    xw.Book()
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/xlwings/main.py", line 540, in __init__
    app = App()
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/xlwings/main.py", line 210, in __init__
    self.impl = xlplatform.App(spec=spec, add_book=add_book)
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/xlwings/_xlmac.py", line 68, in __init__
    self.activate()  # Makes it behave like on Windows
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/xlwings/_xlmac.py", line 103, in activate
    appscript.app('System Events').processes[its.unix_id == self.pid].frontmost.set(True)
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/aeosa/appscript/reference.py", line 518, in __call__
    raise CommandError(self, (args, kargs), e, self.AS_appdata) from e
appscript.reference.CommandError: Command failed:
                OSERROR: -1743
                MESSAGE: The user has declined permission.
                COMMAND: app('/System/Library/CoreServices/System Events.app').processes[its.unix_id == 4976].frontmost.set(True)
(venv) chris@Chriss-MacBook-Pro Python Projects %
</code>```

Unusually for this site, there aren't many references to this here and a wider Google search also doesn't shed any light on it. There seem to be a few people with a similar problem but not so many and nobody I've yet seen seems to have a solution.

Does anybody have any ideas?

答:
I had the same problem on macOS. Launching Pycharm via terminal worked for me.

open /Applications/PyCharm\ CE.app/Contents/MacOS/pycharm

By launching via terminal the IDE will ask for Automation -> Excel Permission, once granted you will be able to execute the code.

Body:
I spent some time messing with openpyxl and had it doing more or less what I wanted until I introduced some real-world data (only as a test) and discovered it can't handle data validation in the Excel workbook (I think the data validation thing refers to a drop-down list):

UserWarning: Data Validation extension is not supported and will be removed

My code carries on and opens the Excel file but because the validation is removed it breaks it.

Okay, so back to square one, I go away and do some more reading and discover that xlwings can probably handle this. I get xlwings and run the shortest test I can think of:

from pathlib import Path
import xlwings as xw

my_documents = Path('/users/chris/documents')

xw.Book()
wb = xw.Book(my_documents / 'Test.xlsx')
ws = wb.sheets['Sheet1']

That gives a lot of errors for such a small piece of code!

Traceback (most recent call last):
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/aeosa/appscript/reference.py", line 482, in __call__
    return self.AS_appdata.target().event(self._code, params, atts, codecs=self.AS_appdata).send(timeout, sendflags)
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/aeosa/aem/aemsend.py", line 92, in send
    raise EventError(errornum, errormsg, eventresult)
aem.aemsend.EventError: Command failed: The user has declined permission. (-1743)

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

Traceback (most recent call last):
  File "/Users/chris/Documents/Python Projects/little_tests.py", line 6, in <module>
    xw.Book()
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/xlwings/main.py", line 540, in __init__
    app = App()
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/xlwings/main.py", line 210, in __init__
    self.impl = xlplatform.App(spec=spec, add_book=add_book)
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/xlwings/_xlmac.py", line 68, in __init__
    self.activate()  # Makes it behave like on Windows
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/xlwings/_xlmac.py", line 103, in activate
    appscript.app('System Events').processes[its.unix_id == self.pid].frontmost.set(True)
  File "/Users/chris/Documents/Python Projects/venv/lib/python3.8/site-packages/aeosa/appscript/reference.py", line 518, in __call__
    raise CommandError(self, (args, kargs), e, self.AS_appdata) from e
appscript.reference.CommandError: Command failed:
                OSERROR: -1743
                MESSAGE: The user has declined permission.
                COMMAND: app('/System/Library/CoreServices/System Events.app').processes[its.unix_id == 4976].frontmost.set(True)
(venv) chris@Chriss-MacBook-Pro Python Projects %

Unusually for this site, there aren't many references to this here and a wider Google search also doesn't shed any light on it. There seem to be a few people with a similar problem but not so many and nobody I've yet seen seems to have a solution.

Does anybody have any ideas?


问:
How do I replace the domain name in a Apache Rewrite rule?
I need to redirect a URL domain.com to domain.net in a Rewrite rule. I originally used redirect, but it lost the POST variables I was sending. Will a Rewrite carry them over and what is the best way to do this?</p>

答:
This should resolve your problem:</p>

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.domain.com$ [OR]
RewriteCond %{HTTP_HOST} ^domain.com$
RewriteRule ^(.*)$ http://www.thenewdomain.net/$1 [R=301,L]
</code>```

Body:
This should resolve your problem:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.domain.com$ [OR]
RewriteCond %{HTTP_HOST} ^domain.com$
RewriteRule ^(.*)$ http://www.thenewdomain.net/$1 [R=301,L]


问:
Python uppercase the entire string except letters which are within quotes but after colon
I have string in python like

```<code>INS_hdr:"To:abc.micky.com|From:xyz.micky.com",TRANSFERTARGET:"B_london"
</code>```

need to convert to like this

```<code>INS_HDR:"TO:abc.micky.com|FROM:xyz.micky.com",TRANSFERTARGET:"B_LONDON"
</code>```

I dont want to convert string to uppercase based on colon, as i use multiple colon in string, need to convert uppercase based on colon which appear inside quotes

答:
I would just brute force it, iterating and keeping track of the state
(in quote, in quote after colon, not in quote).

Any solution must treat : differently if : is in a quote or not.  I cannot see how to do this with regular expressions.

Body:
I have string in python like

INS_hdr:"To:abc.micky.com|From:xyz.micky.com",TRANSFERTARGET:"B_london"

need to convert to like this

INS_HDR:"TO:abc.micky.com|FROM:xyz.micky.com",TRANSFERTARGET:"B_LONDON"

I dont want to convert string to uppercase based on colon, as i use multiple colon in string, need to convert uppercase based on colon which appear inside quotes


问:
Is it possible to create a Bag of Words but word char or substrings?
Is it possible to create a BoW but instead of searching for words I do it for substrings?

I'm working on a python program were I input an array with various names (instead of full sentences) on it and try to apply BoW on it and the problem is that because BoW is for words in sentences the program treats them as sentences.

Example:
If I have the word Farahoka, Csanoha, April, Bas, Phrahonee and I'm looking for the substring aho

How could I do this?

Edit:
It seems that my question is not that clear, so I'll try to do my best to explain what is the task and what I need to do.

I have a list of various names on an array, and I'm trying to find a way to vectorize the letters or maybe find a way to separate into syllabes.

Example:

In BoW if I have The sky is blue today it will be separated into [The, sky, is, blue, today], in the problem I have I'm trying to do something similar, separate/find substrings for words.

Using the previous example, I want to take the word todayand search for the substring ay

Is it possible to do it without using things like if 'ay' in today or endswith('ay')?

In theory I need to use an unigram model for this in order to learn wights for a predictor but it seems all I can find online is focused on words and not substrings.

答:
You don't have much choice but to loop over the elements.

The exact output you expect is unclear, but you could do one of the following.

Searching for matches:

```<code>words = ['Farahoka', 'Csanoha', 'April', 'Bas', 'Phrahonee']

[w for w in words if 'aho' in w]
# ['Farahoka', 'Phrahonee']
</code>```

Testing is any word contains the substring:

```<code>any('aho' in w for w in words)
# True
</code>```

If you're looking for something a bit more generic, you could compute all three-grams of your words:

```<code>from nltk import ngrams
from collections import Counter

counts = sum((Counter(map(''.join, ngrams(w.lower(),3)))
              for w in words), Counter())
</code>```

Output:

```<code>Counter({'far': 1,
         'ara': 1,
         'rah': 2,
         'aho': 2,
         'hok': 1,
         'oka': 1,
         'csa': 1,
         'san': 1,
         'ano': 1,
         'noh': 1,
         'oha': 1,
         'apr': 1,
         'pri': 1,
         'ril': 1,
         'bas': 1,
         'phr': 1,
         'hra': 1,
         'hon': 1,
         'one': 1,
         'nee': 1})
</code>```

Body:
You don't have much choice but to loop over the elements.

The exact output you expect is unclear, but you could do one of the following.

Searching for matches:

words = ['Farahoka', 'Csanoha', 'April', 'Bas', 'Phrahonee']

[w for w in words if 'aho' in w]
# ['Farahoka', 'Phrahonee']

Testing is any word contains the substring:

any('aho' in w for w in words)
# True

If you're looking for something a bit more generic, you could compute all three-grams of your words:

from nltk import ngrams
from collections import Counter

counts = sum((Counter(map(''.join, ngrams(w.lower(),3)))
              for w in words), Counter())

Output:

Counter({'far': 1,
         'ara': 1,
         'rah': 2,
         'aho': 2,
         'hok': 1,
         'oka': 1,
         'csa': 1,
         'san': 1,
         'ano': 1,
         'noh': 1,
         'oha': 1,
         'apr': 1,
         'pri': 1,
         'ril': 1,
         'bas': 1,
         'phr': 1,
         'hra': 1,
         'hon': 1,
         'one': 1,
         'nee': 1})


问:
Using query strings in django GET
I've a GET request in django rest framework that fetches data using kwargs.

```<code>class FetchUser(APIView):

    def get(self, request, **kwargs):
        try:
            email = kwargs.get('email')
            user = User.objects.get(email=email)
            return Response(UserSerializer(user).data, status=status.HTTP_200_OK)
        except(KeyError, User.DoesNotExist) as e:
            return Response(str(e), status=status.HTTP_404_NOT_FOUND)
</code>```

Here's my url

```<code>path(r'fetch/<str:email>', FetchUser.as_view(), name='fetch_user'),
</code>```

However I want to fetch the data using a query string,

Something like http://base/fetch?email=something

How do I modify my urls and views to do this?

答:
You can do something like -

```<code>def get_queryset(self):
    cityId = self.request.GET.get('city')
    # this reads query param
    if cityId is None:
        queryset = branch.objects.all()
        # queryset = branch.objects.none()
    else:
        queryset = branch.objects.filter(city=cityId)
    return queryset
</code>```

and your query can be

```<code>http://base/?city=something
</code>```

Title: Using query strings in django GET

Body:
I've a GET request in django rest framework that fetches data using kwargs.

class FetchUser(APIView):

    def get(self, request, **kwargs):
        try:
            email = kwargs.get('email')
            user = User.objects.get(email=email)
            return Response(UserSerializer(user).data, status=status.HTTP_200_OK)
        except(KeyError, User.DoesNotExist) as e:
            return Response(str(e), status=status.HTTP_404_NOT_FOUND)

Here's my url

path(r'fetch/<str:email>', FetchUser.as_view(), name='fetch_user'),

However I want to fetch the data using a query string,

Something like http://base/fetch?email=something

How do I modify my urls and views to do this?

Body:
You can do something like -

def get_queryset(self):
    cityId = self.request.GET.get('city')
    # this reads query param
    if cityId is None:
        queryset = branch.objects.all()
        # queryset = branch.objects.none()
    else:
        queryset = branch.objects.filter(city=cityId)
    return queryset

and your query can be

http://base/?city=something


问:
With a NumPy Unicode array, why does dtype '|U5' become dtype '<U5'?
I learned from the comment in this answer Python: Numpy Data IO, how to save data by different dtype for each column?
that
< means byte order, U means unicode, and 5 means the number of characters.

Then what does '|' means in '|U5' and why did '|' change to '<' in the below example?
The example is from NumPy official documentation: https://numpy.org/devdocs/user/basics.io.genfromtxt.html

```<code>data = u"1, abc , 2\n 3, xxx, 4"
# Without autostrip
np.genfromtxt(StringIO(data), delimiter=",", dtype="|U5")

array([['1', ' abc ', ' 2'],
       ['3', ' xxx', ' 4']], dtype='<U5')
</code>```

答:
The U data type stores each Unicode character as a 32 bit integer (i.e. 4 bytes).  An integer with more than one byte must have an endianess, so the data type will show either < or >.  Arrays of type S store each character in a single byte, so endianess is irrelevant, and the endianess character will be |.

For example, here a1 and a2 contain a single Unicode character.  The arrays are created with opposite endianess.

```<code>In [248]: a1 = np.array(['π'], dtype='<U1')

In [249]: a2 = np.array(['π'], dtype='>U1')

In [250]: a1
Out[250]: array(['π'], dtype='<U1')

In [251]: a2
Out[251]: array(['π'], dtype='>U1')
</code>```

Inspect the actual bytes of the data in each array; you can see the different orders for each type:

```<code>In [252]: a1.view(np.uint8)
Out[252]: array([192,   3,   0,   0], dtype=uint8)

In [253]: a2.view(np.uint8)
Out[253]: array([  0,   0,   3, 192], dtype=uint8)
</code>```

When you specify | with a Unicode type when creating an array, apparently NumPy ignores it and uses the native byte order, e.g.

```<code>In [254]: np.dtype("|U5")
Out[254]: dtype('<U5')
</code>```

One might as well not include it at all:

```<code>In [255]: np.dtype("U5")
Out[255]: dtype('<U5')
</code>```

Body:
I learned from the comment in this answer Python: Numpy Data IO, how to save data by different dtype for each column?
that
< means byte order, U means unicode, and 5 means the number of characters.

Then what does '|' means in '|U5' and why did '|' change to '<' in the below example?
The example is from NumPy official documentation: https://numpy.org/devdocs/user/basics.io.genfromtxt.html

data = u"1, abc , 2\n 3, xxx, 4"
# Without autostrip
np.genfromtxt(StringIO(data), delimiter=",", dtype="|U5")

array([['1', ' abc ', ' 2'],
       ['3', ' xxx', ' 4']], dtype='<U5')

Body:
The U data type stores each Unicode character as a 32 bit integer (i.e. 4 bytes).  An integer with more than one byte must have an endianess, so the data type will show either < or >.  Arrays of type S store each character in a single byte, so endianess is irrelevant, and the endianess character will be |.

For example, here a1 and a2 contain a single Unicode character.  The arrays are created with opposite endianess.

In [248]: a1 = np.array(['π'], dtype='<U1')

In [249]: a2 = np.array(['π'], dtype='>U1')

In [250]: a1
Out[250]: array(['π'], dtype='<U1')

In [251]: a2
Out[251]: array(['π'], dtype='>U1')

Inspect the actual bytes of the data in each array; you can see the different orders for each type:

In [252]: a1.view(np.uint8)
Out[252]: array([192,   3,   0,   0], dtype=uint8)

In [253]: a2.view(np.uint8)
Out[253]: array([  0,   0,   3, 192], dtype=uint8)

When you specify | with a Unicode type when creating an array, apparently NumPy ignores it and uses the native byte order, e.g.

In [254]: np.dtype("|U5")
Out[254]: dtype('<U5')

One might as well not include it at all:

In [255]: np.dtype("U5")
Out[255]: dtype('<U5')


问:
Django Rest Framework testing with python queue
I have a DRF application with a python queue that I'm writing tests for. Somehow,

My queue thread cannot find an object that exists in the test database.

The main thread cannot destroy the db as it's in use by 1 other session.

To explain the usecase a bit further, I use Django's user model and have a table for metadata of files which you can upload. One of this fields is a created_by, which is a ForeignKey to django.conf.settings.AUTH_USER_MODEL. As shown below, I create a user in the TestCase's setUp(), which I then use to create an entry in the Files table. The creation of this entry happens in a queue however. During testing, this results in an error DETAIL:  Key (created_by_id)=(4) is not present in table "auth_user"..
When the tests are completed, and the tearDown tries to destroy the test DB, I get another error DETAIL:  There is 1 other session using the database.. The two seem related, and I'm probably handling the queue incorrectly.

The tests are written with Django's TestCase and run with python manage.py test.

from django.contrib.auth.models import User
from rest_framework.test import APIClient
from django.test import TestCase

class MyTest(TestCase):

    def setUp(self):
        self.client = APIClient()
        self.client.force_authenticate()
        user = User.objects.create_user('TestUser', 'test@test.test', 'testpass')
        self.client.force_authenticate(user)

    def test_failing(self):
        self.client.post('/totestapi', data={'files': [open('tmp.txt', 'rt')]})
```
<p>The queue is defined in separate file, <code>app/queue.py</code>.</p>
<pre class="lang-py prettyprint-override"><code>from app.models import FileMeta
from queue import Queue
from threading import Thread

def queue_handler():
    while True:
        user, files = queue.get()
        for file in files:
            upload(file)
            FileMeta(user=user, filename=file.name).save()
        queue.task_done()

queue = Queue()
thread = Thread(target=queue_handler, daemon=True)

def start_upload_thread():
    thread.start()

def put_upload_thread(*args):
    queue.put(args)
</code>```

Finally, the queue is started from app/views.py, which is always called when Django is started, and contains all the APIs.

from rest_framework import APIView
from app.queue import start_upload_thread, put_upload_thread

start_upload_thread()

class ToTestAPI(APIView):

    def post(self, request):
        put_upload_thread(request.user, request.FILES.getlist('files'))
```

答:
Apologies that this is not a "real" answer but it was getting longer than a comment would allow.

The new ticket looks good.  I did notice that there was no stoping of the background thread, as you did.  That is probably what is causing that issue with the db still being active.

You use TestCase, which runs a db transaction and undoes all database changes when the test function ends.  That means you won't be able to see data from the test case in another thread using a different connection to the database.  You can see it inside your tests and views, since they share a connection.

Celery and RQ are the standard job queues - Celery is more flexible, but RQ is simpler.  Start with RQ and keep things simple and isolated.

Some notes:

Pass in the PK of objects not the whole object

Read up on pickle if you do need to pass larger data.

Set the queues to async=False (run like normal code) in tests.

Queue consumers are a separate process running anywhere in the system, so data needs to get to them somehow.  If you use full objects those need to be pickled, or serialized, and saved in the queue itself (i.e. redis) to be retrieved and processed.  Just be careful and don't pass large objects this way - use the PK, store the file somewhere in S3 or another object storage, etc.

For Django-RQ I use this snippet to set the queues to sync mode when in testing, and then just run things as normal.

```<code>if IS_TESTING:
    for q in RQ_QUEUES.keys():
        RQ_QUEUES[q]['ASYNC'] = False
</code>```

Good luck!

Body:
I have a DRF application with a python queue that I'm writing tests for. Somehow,

My queue thread cannot find an object that exists in the test database.

The main thread cannot destroy the db as it's in use by 1 other session.

To explain the usecase a bit further, I use Django's user model and have a table for metadata of files which you can upload. One of this fields is a created_by, which is a ForeignKey to django.conf.settings.AUTH_USER_MODEL. As shown below, I create a user in the TestCase's setUp(), which I then use to create an entry in the Files table. The creation of this entry happens in a queue however. During testing, this results in an error DETAIL:  Key (created_by_id)=(4) is not present in table "auth_user"..
When the tests are completed, and the tearDown tries to destroy the test DB, I get another error DETAIL:  There is 1 other session using the database.. The two seem related, and I'm probably handling the queue incorrectly.

The tests are written with Django's TestCase and run with python manage.py test.

from django.contrib.auth.models import User
from rest_framework.test import APIClient
from django.test import TestCase

class MyTest(TestCase):

    def setUp(self):
        self.client = APIClient()
        self.client.force_authenticate()
        user = User.objects.create_user('TestUser', 'test@test.test', 'testpass')
        self.client.force_authenticate(user)

    def test_failing(self):
        self.client.post('/totestapi', data={'files': [open('tmp.txt', 'rt')]})

The queue is defined in separate file, app/queue.py.

from app.models import FileMeta
from queue import Queue
from threading import Thread

def queue_handler():
    while True:
        user, files = queue.get()
        for file in files:
            upload(file)
            FileMeta(user=user, filename=file.name).save()
        queue.task_done()

queue = Queue()
thread = Thread(target=queue_handler, daemon=True)

def start_upload_thread():
    thread.start()

def put_upload_thread(*args):
    queue.put(args)

Finally, the queue is started from app/views.py, which is always called when Django is started, and contains all the APIs.

from rest_framework import APIView
from app.queue import start_upload_thread, put_upload_thread

start_upload_thread()

class ToTestAPI(APIView):

    def post(self, request):
        put_upload_thread(request.user, request.FILES.getlist('files'))

Body:
Apologies that this is not a "real" answer but it was getting longer than a comment would allow.

The new ticket looks good.  I did notice that there was no stoping of the background thread, as you did.  That is probably what is causing that issue with the db still being active.

You use TestCase, which runs a db transaction and undoes all database changes when the test function ends.  That means you won't be able to see data from the test case in another thread using a different connection to the database.  You can see it inside your tests and views, since they share a connection.

Celery and RQ are the standard job queues - Celery is more flexible, but RQ is simpler.  Start with RQ and keep things simple and isolated.

Some notes:

Pass in the PK of objects not the whole object

Read up on pickle if you do need to pass larger data.

Set the queues to async=False (run like normal code) in tests.

Queue consumers are a separate process running anywhere in the system, so data needs to get to them somehow.  If you use full objects those need to be pickled, or serialized, and saved in the queue itself (i.e. redis) to be retrieved and processed.  Just be careful and don't pass large objects this way - use the PK, store the file somewhere in S3 or another object storage, etc.

For Django-RQ I use this snippet to set the queues to sync mode when in testing, and then just run things as normal.

if IS_TESTING:
    for q in RQ_QUEUES.keys():
        RQ_QUEUES[q]['ASYNC'] = False

Good luck!


问:
How to fix DatetimeIndex.union_many is deprecated warning in Python
I have the following code:

```<code>import datetime, pytz
import pandas_market_calendars as mcal

today_date = datetime.datetime.now(tz=pytz.timezone('US/Eastern'))
start_date = datetime.date(today_date.year - 5, today_date.month, today_date.day)

end_date = datetime.date(today_date.year + 2, today_date.month, today_date.day + 5)

nyse_calender = mcal.get_calendar('NYSE')
nyse_business_days = nyse_calender.schedule(start_date=start_date, end_date=end_date)
</code>```

When I run this, I get the following warning:

```<code> FutureWarning: DatetimeIndex.union_many is deprecated and will be removed in a future version. Use obj.union instead.
  nyse_business_days = nyse_calender.schedule(start_date=start_date, end_date=end_date)
</code>```

How am I supposed to solve this problem? The warning doesn't really help to take an action..

答: A PR for pandas_market_calendar was merged a couple of days ago which fixes this issue.

Body:
I have the following code:

import datetime, pytz
import pandas_market_calendars as mcal

today_date = datetime.datetime.now(tz=pytz.timezone('US/Eastern'))
start_date = datetime.date(today_date.year - 5, today_date.month, today_date.day)

end_date = datetime.date(today_date.year + 2, today_date.month, today_date.day + 5)

nyse_calender = mcal.get_calendar('NYSE')
nyse_business_days = nyse_calender.schedule(start_date=start_date, end_date=end_date)

When I run this, I get the following warning:

 FutureWarning: DatetimeIndex.union_many is deprecated and will be removed in a future version. Use obj.union instead.
  nyse_business_days = nyse_calender.schedule(start_date=start_date, end_date=end_date)

How am I supposed to solve this problem? The warning doesn't really help to take an action..


问:
Does update Cosmos DB TTL container settings will impact on old items?
I updated my cosmos db container with this code

```<code>var containerResponse = await _cosmosContainer.ReadContainerAsync();
            var containerProperties = containerResponse.Resource;
            if (containerProperties.DefaultTimeToLive == null)
            {
                containerProperties.DefaultTimeToLive = 60 * 60 * 24 * 180; // set 180 days default TTL
                await _cosmosContainer.ReplaceContainerAsync(containerProperties);
            }
</code>```

Does update Cosmos DB TTL container settings will impact on old items?

答:
From the docs,

After you set the TTL at a container or at an item level, Azure Cosmos
DB will automatically remove these items after the time period, since
the time they were last modified.

Yes it will impact on old items.

Body:
I updated my cosmos db container with this code

var containerResponse = await _cosmosContainer.ReadContainerAsync();
            var containerProperties = containerResponse.Resource;
            if (containerProperties.DefaultTimeToLive == null)
            {
                containerProperties.DefaultTimeToLive = 60 * 60 * 24 * 180; // set 180 days default TTL
                await _cosmosContainer.ReplaceContainerAsync(containerProperties);
            }

Does update Cosmos DB TTL container settings will impact on old items?


问:
AWK how to check if first column contains an ip address
I have a file that contains a list of DHCP bindings. I want to extract some of the data, however its not as straight forward as it first appeared it would be, often the hardware identifier is across multiple lines.

You can see those in the second column, they have a period at the end when they continue onto the next line.

So to sum up what I want to achieve here. Extract column 1 and 2 where there is an IP address and just column 2 where there is none, the end result being the IP and full hardware address on a single line.

The goal being to make it faster to get the hardware identifier, currently if I want to assign a static IP I have to perform up to three copy/pastes, not a big deal I know, but I would still like to be able to do it in one copy.

Data example:

```<code>10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.1146.a45b.6916.
                    7ae3.be
10.x.x.x            ff29.ed05.1200.0100.    Infinite                Manual
                    0128.c2e3.9300.0c29.
                    ed05.12
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.11e7.d0ba.2f43.
                    f135.f2
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.11b2.f37a.8a39.
                    e6bf.93
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.115c.5da2.eecf.
                    09d7.41
10.x.x.x            000c.29a0.40a3          Feb 07 2022 05:44 PM    Automatic
10.x.x.x            01e8.3935.e98c.14       Infinite                Manual
10.x.x.x            0168.b599.bed2.94       Infinite                Manual
10.x.x.x            01d0.67e5.0530.ef       Feb 07 2022 11:54 PM    Automatic
10.x.x.x            ff29.a040.a300.0100.    Infinite                Manual
                    0129.88be.c700.0c29.
                    a040.a3
</code>```

The following code I have managed to put together looking around for a solution. Searches like "awk if column 1 = ip address" came back with the regex, I am not even sure that I am using it correctly.

```<code>awk '{
    if ($1~/^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\]/) {
        ip="\n$1"
        addr=$2
    } else {
        addr="$1"
    }
    printf "%s %s",ip,addr;
}' data.txt
</code>```

I am aware I need some way to combine the addr variable too, I can work on that later, just getting the columns correctly would be a massive help. (Think I sorted the combining part, adjusted the code to the following, removing the variables.)

```<code>awk '{
    if ($1~/^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\]/) {
        printf "\nIP Address: %s", $1
        printf $2
    } else {
        printf $1
    }
}' data.txt
</code>```

So, if I can get help with how to check if the first column contains an IP address I should be there.

答:
I have solved my problem with help from this Answer to another question

It turns out I had the correct regex in the first place but had not implemented it correctly, when i tried it I missed the part about posix being for the command line and put it inside the if along with the regex. Positioning it outside of the braces solved it.

Here is my updated code with a regex to match an ip address in the first column.

```<code>awk --posix '{
    if ($1 ~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/) {
        printf "\nIP Address: %s %s", $1, $2
    } else {
        printf $1
    }
}' data.txt
echo ""
</code>```

And the result:

```<code>IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.1146.a45b.6916.7ae3.be
IP Address: 10.x.x.x ff29.ed05.1200.0100.0128.c2e3.9300.0c29.ed05.12
IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.11e7.d0ba.2f43.f135.f2
IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.11b2.f37a.8a39.e6bf.93
IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.115c.5da2.eecf.09d7.41
IP Address: 10.x.x.x 000c.29a0.40a3
IP Address: 10.x.x.x 01e8.3935.e98c.14
IP Address: 10.x.x.x 0168.b599.bed2.94
IP Address: 10.x.x.x 01d0.67e5.0530.ef
IP Address: 10.x.x.x ff29.a040.a300.0100.0129.88be.c700.0c29.a040.a3
</code>```

It's exactly how I wanted it. (added the echo to put the terminal prompt back on it's own line).

Body:
I have a file that contains a list of DHCP bindings. I want to extract some of the data, however its not as straight forward as it first appeared it would be, often the hardware identifier is across multiple lines.

You can see those in the second column, they have a period at the end when they continue onto the next line.

So to sum up what I want to achieve here. Extract column 1 and 2 where there is an IP address and just column 2 where there is none, the end result being the IP and full hardware address on a single line.

The goal being to make it faster to get the hardware identifier, currently if I want to assign a static IP I have to perform up to three copy/pastes, not a big deal I know, but I would still like to be able to do it in one copy.

Data example:

10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.1146.a45b.6916.
                    7ae3.be
10.x.x.x            ff29.ed05.1200.0100.    Infinite                Manual
                    0128.c2e3.9300.0c29.
                    ed05.12
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.11e7.d0ba.2f43.
                    f135.f2
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.11b2.f37a.8a39.
                    e6bf.93
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.115c.5da2.eecf.
                    09d7.41
10.x.x.x            000c.29a0.40a3          Feb 07 2022 05:44 PM    Automatic
10.x.x.x            01e8.3935.e98c.14       Infinite                Manual
10.x.x.x            0168.b599.bed2.94       Infinite                Manual
10.x.x.x            01d0.67e5.0530.ef       Feb 07 2022 11:54 PM    Automatic
10.x.x.x            ff29.a040.a300.0100.    Infinite                Manual
                    0129.88be.c700.0c29.
                    a040.a3

The following code I have managed to put together looking around for a solution. Searches like "awk if column 1 = ip address" came back with the regex, I am not even sure that I am using it correctly.

awk '{
    if ($1~/^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\]/) {
        ip="\n$1"
        addr=$2
    } else {
        addr="$1"
    }
    printf "%s %s",ip,addr;
}' data.txt

I am aware I need some way to combine the addr variable too, I can work on that later, just getting the columns correctly would be a massive help. (Think I sorted the combining part, adjusted the code to the following, removing the variables.)

awk '{
    if ($1~/^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\]/) {
        printf "\nIP Address: %s", $1
        printf $2
    } else {
        printf $1
    }
}' data.txt

So, if I can get help with how to check if the first column contains an IP address I should be there.

Body:
I have solved my problem with help from this Answer to another question

It turns out I had the correct regex in the first place but had not implemented it correctly, when i tried it I missed the part about posix being for the command line and put it inside the if along with the regex. Positioning it outside of the braces solved it.

Here is my updated code with a regex to match an ip address in the first column.

awk --posix '{
    if ($1 ~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/) {
        printf "\nIP Address: %s %s", $1, $2
    } else {
        printf $1
    }
}' data.txt
echo ""

And the result:

IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.1146.a45b.6916.7ae3.be
IP Address: 10.x.x.x ff29.ed05.1200.0100.0128.c2e3.9300.0c29.ed05.12
IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.11e7.d0ba.2f43.f135.f2
IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.11b2.f37a.8a39.e6bf.93
IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.115c.5da2.eecf.09d7.41
IP Address: 10.x.x.x 000c.29a0.40a3
IP Address: 10.x.x.x 01e8.3935.e98c.14
IP Address: 10.x.x.x 0168.b599.bed2.94
IP Address: 10.x.x.x 01d0.67e5.0530.ef
IP Address: 10.x.x.x ff29.a040.a300.0100.0129.88be.c700.0c29.a040.a3

It's exactly how I wanted it. (added the echo to put the terminal prompt back on it's own line).


问:
Google Drive API: the get() method on drive_service.files().list() documented?
In this link there a get method in Python:

```<code>response = drive_service.files().list(q="mimeType='image/jpeg'",
                                          spaces='drive',
                                          fields='nextPageToken, files(id, name)',
                                          pageToken=page_token).execute()
    for file in response.get('files', []):
</code>```

I guess the get() method will get a list of files, and if none, it will return an empty list, but where is this documented? The API doc does not have it. It simply says:

```<code>Returns:
  An object of the form:
...
</code>```

It did not document any method.

答:
From your script, I thought that get of for file in response.get('files', []): is the method of the built-in type. Ref

From your fields of fields='nextPageToken, files(id, name)', drive_service.files().list() returns an object like {"nextPageToken": "###", "files": [{"id": "###", "name": "###"},,,]}. Ref When files of mimeType='image/jpeg' isn't found, {"files": []} is returned.

In this case, you can also use response.get('files').

References:

get

Files: list

Body:
In this link there a get method in Python:

response = drive_service.files().list(q="mimeType='image/jpeg'",
                                          spaces='drive',
                                          fields='nextPageToken, files(id, name)',
                                          pageToken=page_token).execute()
    for file in response.get('files', []):

I guess the get() method will get a list of files, and if none, it will return an empty list, but where is this documented? The API doc does not have it. It simply says:

Returns:
  An object of the form:
...

It did not document any method.


问:
Angular 8 - click event not firing inside ngFor when iterating over object arrays
NOTE: Original post edited to remove implemention details/complexity.

I have an ngFor loop that calls a method on a service. The method returns an array that is iterated over by the for loop.

The click event binding does not work if the returned array is an array of objects. It does work if the array is of a primitive type.

***contextmenu/right-click does work in either case, so this is affecting click and not contextmenu

***click events immediately before and after this for work as expected

***the behavior is the same even if I move the hardcoded method from the service to the component

Here is the for loop in context:

```<code><div><span (click)="addVariable()"></span></div> <!-- works -->

<div *ngFor="let variable of designerService.getVariables();" (click)="onLeftClick()" (contextmenu)="onRightClick()">just a simple div</div> <!-- doesnt work -->

<div><span (click)="addVariable()"></span></div> <!-- works -->
</code>```
```<code>public addVariable() {
  alert("add variable");
}

public onLeftClick() {
  alert("left click");
}

public onRightClick() {
  alert("right click");
}
</code>```

With this implementation (or any other object type array) click will not work/fire:

```<code>public getVariables(): {name: string}[] {
  return [{"name": "dog"},{"name": "cat"},{"name": "bird"},{"name":"bear"}];
}
</code>```

With this implementation click will work:

```<code>public getVariables(): number[] {
  return [1,2,3,4,5];
}
</code>```

Super simple, doesn't work...

Any ideas on what might be the problem? I'm at the end of my rope with Angular at this point.

答:
Try this:

// YourComponent ts file
variables: {name: string}[];

constructor(public designerService: DesignerService) { }

ngOnInit() {
  this.variables = this.designerService.getVariables();
}

// Other methods
```
<pre class="lang-html prettyprint-override"><code><!-- HTML template file -->
<!-- Replace the designerService.getVariables() method call with component property 'variables' -->
<div *ngFor="let variable of variables" (click)="onLeftClick()"
(contextmenu)="onRightClick()">works</div> <!-- works -->
</code>```

There might be some code within the application that is triggering Change Detection which is causing re-rendering even before the associated click handler executes and hence the issue.

Just for testing purpose, before making the above suggested change you can also try to define an array property within the service class and then return that array from  getVariables(), and observe if it resolves the issue.

// DesignerService ts file
someArray = [{"name": "dog"},{"name": "cat"},{"name": "bird"},{"name":"bear"}];

public getVariables(): {name: string}[] {
  return this.someArray;
}
```

Body:
NOTE: Original post edited to remove implemention details/complexity.

I have an ngFor loop that calls a method on a service. The method returns an array that is iterated over by the for loop.

The click event binding does not work if the returned array is an array of objects. It does work if the array is of a primitive type.

***contextmenu/right-click does work in either case, so this is affecting click and not contextmenu

***click events immediately before and after this for work as expected

***the behavior is the same even if I move the hardcoded method from the service to the component

Here is the for loop in context:

just a simple div

public addVariable() {
  alert("add variable");
}

public onLeftClick() {
  alert("left click");
}

public onRightClick() {
  alert("right click");
}

With this implementation (or any other object type array) click will not work/fire:

public getVariables(): {name: string}[] {
  return [{"name": "dog"},{"name": "cat"},{"name": "bird"},{"name":"bear"}];
}

With this implementation click will work:

public getVariables(): number[] {
  return [1,2,3,4,5];
}

Super simple, doesn't work...

Any ideas on what might be the problem? I'm at the end of my rope with Angular at this point.

Body:
Try this:

// YourComponent ts file
variables: {name: string}[];

constructor(public designerService: DesignerService) { }

ngOnInit() {
  this.variables = this.designerService.getVariables();
}

// Other methods

<!-- HTML template file -->
<!-- Replace the designerService.getVariables() method call with component property 'variables' -->
<div *ngFor="let variable of variables" (click)="onLeftClick()"
(contextmenu)="onRightClick()">works</div> <!-- works -->

There might be some code within the application that is triggering Change Detection which is causing re-rendering even before the associated click handler executes and hence the issue.

Just for testing purpose, before making the above suggested change you can also try to define an array property within the service class and then return that array from  getVariables(), and observe if it resolves the issue.

// DesignerService ts file
someArray = [{"name": "dog"},{"name": "cat"},{"name": "bird"},{"name":"bear"}];

public getVariables(): {name: string}[] {
  return this.someArray;
}


问:
Sybase ASE : Pagination
I want to implement a code which retrieves 5 million records from DB. But when I retrieve it, the connection is open for long which causes application to get stuck for long time. Also causes Out of memory issue.

I have used PreparedStatementCreator to set the fetch size which helps the data to retrieve fast. But for that particular period, the application is unusable for other users accessing the application as it gets stuck.

So I am trying to implement batch select, but Sybase ASE 16.3 does not support Offset, Limit, Start At, etc.

I am using jdbctemplate of spring.

Can you please help with a workaround for this issue.

Regards,
Ashish M

答:
Sybase recommended using temp table to do these pagination work --</p>
```<code>eg.
create table #result (rid bigint identity, col1 int, col2 varchar...)
insert #result(col1,col2...) select ... from yourtable1, yourtable2 ... where ...

select * from #result where rid between 1 and 1000  -- page1
select * from #result where rid between 1001 and 2000 -- page2
...
</code>```

Title: Sybase ASE : Pagination

Body:
Sybase recommended using temp table to do these pagination work --

eg.
create table #result (rid bigint identity, col1 int, col2 varchar...)
insert #result(col1,col2...) select ... from yourtable1, yourtable2 ... where ...

select * from #result where rid between 1 and 1000  -- page1
select * from #result where rid between 1001 and 2000 -- page2
...


问:
Stub of Sinon using axios returns undefined
I'm testing using sinon with axios.

```<code>// index.js
{
    .. more code
    const result = await axios.get("http://save")
    const sum = result.data.sum
}
</code>```

And I made a test code by sinon and supertest for e2e test.

```<code>// index.test.js
describe('ADMINS GET API, METHOD: GET', () => {
  it('/admins', async () => {
    sandbox
      .stub(axios, 'get')
      .withArgs('http://save')
      .resolves({sum: 12});

    await supertest(app)
      .get('/admins')
      .expect(200)
      .then(async response => {
        expect(response.body.code).toBe(200);
      });
  });
});
</code>```

But when I test it, it gives me this result.

```<code> // index.js
    {
        .. more code
        const result = await axios.get("http://save")
        const sum = result.data.sum
        console.log(sum) // undefined
    }
</code>```

I think I resolved response. But it doesnt' give any response.
It just pass axios on supertest.

How can I return correct data in this case?

Thank you for reading it.

答:
The resolved value should be { data: { sum: 12 } }.

E.g.

index.js:

const express = require('express');
const axios = require('axios');
const app = express();

app.get('/admins', async (req, res) => {
  const result = await axios.get('http://save');
  const sum = result.data.sum;
  res.json({ code: 200, sum });
});

module.exports = { app };
```
<p><code>index.test.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>const supertest = require('supertest');
const axios = require('axios');
const sinon = require('sinon');
const { app } = require('./index');

describe('ADMINS GET API, METHOD: GET', () => {
  it('/admins', async () => {
    const sandbox = sinon.createSandbox();
    sandbox
      .stub(axios, 'get')
      .withArgs('http://save')
      .resolves({ data: { sum: 12 } });

    await supertest(app)
      .get('/admins')
      .expect(200)
      .then(async (response) => {
        sinon.assert.match(response.body.code, 200);
        sinon.assert.match(response.body.sum, 12);
      });
  });
});
</code>```

test result:

  ADMINS GET API, METHOD: GET
    ✓ /admins

  1 passing (22ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 index.js |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------
```

Body:
I'm testing using sinon with axios.

// index.js
{
    .. more code
    const result = await axios.get("http://save")
    const sum = result.data.sum
}

And I made a test code by sinon and supertest for e2e test.

// index.test.js
describe('ADMINS GET API, METHOD: GET', () => {
  it('/admins', async () => {
    sandbox
      .stub(axios, 'get')
      .withArgs('http://save')
      .resolves({sum: 12});

    await supertest(app)
      .get('/admins')
      .expect(200)
      .then(async response => {
        expect(response.body.code).toBe(200);
      });
  });
});

But when I test it, it gives me this result.

 // index.js
    {
        .. more code
        const result = await axios.get("http://save")
        const sum = result.data.sum
        console.log(sum) // undefined
    }

I think I resolved response. But it doesnt' give any response.
It just pass axios on supertest.

How can I return correct data in this case?

Thank you for reading it.

Body:
The resolved value should be { data: { sum: 12 } }.

E.g.

index.js:

const express = require('express');
const axios = require('axios');
const app = express();

app.get('/admins', async (req, res) => {
  const result = await axios.get('http://save');
  const sum = result.data.sum;
  res.json({ code: 200, sum });
});

module.exports = { app };

index.test.js:

const supertest = require('supertest');
const axios = require('axios');
const sinon = require('sinon');
const { app } = require('./index');

describe('ADMINS GET API, METHOD: GET', () => {
  it('/admins', async () => {
    const sandbox = sinon.createSandbox();
    sandbox
      .stub(axios, 'get')
      .withArgs('http://save')
      .resolves({ data: { sum: 12 } });

    await supertest(app)
      .get('/admins')
      .expect(200)
      .then(async (response) => {
        sinon.assert.match(response.body.code, 200);
        sinon.assert.match(response.body.sum, 12);
      });
  });
});

test result:

  ADMINS GET API, METHOD: GET
    ✓ /admins

  1 passing (22ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 index.js |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------


问:
SQL Query to get the latest transaction date for a foreign key
The title is a bit confusing but is actually accurate about what I am asking for so please bear with me as I try to explain this as concise as I could.

Basically in my mySql server, I have three tables: customerInfo, loanInfo, and transactionInfo (this is some sort of a loan system).

the loanInfo amd customerInfo has their respective primary keys connected to the transactionInfo as its foreign key, creating a relationship between the three tables. (I thought it would be important to explain how the db works for you guys)

I need a query that will give me the maximum value of date from the transactionTable where the loanID is set to a specific value therefore giving me the transaction record with the latest date among all the other transaction for a specific loan

I really hope I made this clear.

Here are some of the queries that I have tried which returned no result

SELECT MAX(date_created) FROM transactionInfo WHERE loan_id = 2;

SELECT * FROM transactionInfo WHERE date_created = (SELECT MAX(date_created) FROM transactionInfo)

EDIT for D-Shih

Here is a sample data

I want to get the transaction with the latest date where the loanID = 2,
so the query should return the transaction with 4/14/2019 as the date

答:
Try using ORDER BY descending and set LIMIT if required.

SELECT * FROM transactionInfo ORDER BY date_created DESC;
```
<p>You can also add <code>WHERE</code> clause:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT * FROM transactionInfo WHERE loan_id = 2 ORDER BY date_created DESC;
</code>```

This should get the latest transaction info according to the date_created.

Body:
Try using ORDER BY descending and set LIMIT if required.

SELECT * FROM transactionInfo ORDER BY date_created DESC;

You can also add WHERE clause:

SELECT * FROM transactionInfo WHERE loan_id = 2 ORDER BY date_created DESC;

This should get the latest transaction info according to the date_created.