问:
Correct way to approach splitting a trait
I have 3 traits:

```<code>trait Worker

...

trait StringWorker extends Worker {
  def workString(): Iterator[String]
}

...

trait IntWorker extends Worker {
  def workInt(): Iterator[Int]
}
</code>```

Some of my classes extend only StringWorker, while others extend both StringWorker and IntWorker

My code obtains the correct parser depending on some pattern matching like so:

```<code>def getCorrectWorkerProvider: () => Worker = {
  case SomeCase => getStringWorkerProvider()
  case _ => getIntWorkerProvider()
}
</code>```

If I keep the traits the same as written above, then I'll pretty much always have to do something like this pseudocode:

```<code>if working with string, then getCorrectWorkerProvider().asInstanceOf[StringWorker].workString

if working with int, then getCorrectWorkerProvider().asInstanceOf[IntWorker].workInt
</code>```

whereas if I changed the definition of the traits to something like this:

```<code>trait Worker {
  def workString(): Iterator[String]
  def workInt(): Iterator[Int]
}

trait StringWorker extends Worker
trait IntWorker extends Worker
</code>```

then I would never have to use .asInstanceOf[SomeWorker] to invoke the correct method.
I believe the first way is more correct and intuitive as the methods are specific to a certain Worker, but the second way seems to be less of a headache.

答:
What I believe you're you're looking for is called the typeclass pattern.  Here's an article that explains the idea.  Basically the way it works is you create a function that takes a value of type T and an implicit parameter which is the Worker[T], and then scala's implicit resolution mechanism finds the right Worker[T] for you.

Here's an example:

object Main {
    def main(args: Array[String]): Unit = {
        work("String")
        work(3)
    }

    def work[T](value: T)(implicit worker: Worker[T]) = {
        worker.work(value)
    }
}

trait Worker[T]{
    def work(t: T): Iterator[T]
}

object Worker {
    implicit val stringWorker: Worker[String] = (t: String) => Iterator(t)
    implicit val intWorker: Worker[Int] = (t: Int) => Iterator(t)
}
```

Body:
I have 3 traits:

trait Worker

...

trait StringWorker extends Worker {
  def workString(): Iterator[String]
}

...

trait IntWorker extends Worker {
  def workInt(): Iterator[Int]
}

Some of my classes extend only StringWorker, while others extend both StringWorker and IntWorker

My code obtains the correct parser depending on some pattern matching like so:

def getCorrectWorkerProvider: () => Worker = {
  case SomeCase => getStringWorkerProvider()
  case _ => getIntWorkerProvider()
}

If I keep the traits the same as written above, then I'll pretty much always have to do something like this pseudocode:

if working with string, then getCorrectWorkerProvider().asInstanceOf[StringWorker].workString

if working with int, then getCorrectWorkerProvider().asInstanceOf[IntWorker].workInt

whereas if I changed the definition of the traits to something like this:

trait Worker {
  def workString(): Iterator[String]
  def workInt(): Iterator[Int]
}

trait StringWorker extends Worker
trait IntWorker extends Worker

then I would never have to use .asInstanceOf[SomeWorker] to invoke the correct method.
I believe the first way is more correct and intuitive as the methods are specific to a certain Worker, but the second way seems to be less of a headache.


来源: stackexchange

问:
Use js to append an ul to an li
yeah you read it right i'm trying to append an ul element in an existing li element and create a sub list. I'm using code from codepen (https://codepen.io/Pestov/pen/AvQmxv) to make a genealogy tree and i would like to create dynamically the tree. For this, i have to create a sub ul element in a previously created li, then had two li to that sub ul.

----EDIT----
My problem is: HierarchyRequestError: Failed to execute 'appendChild' on 'Node': The new child element contains the parent.
Js seems to think that my ul is my parent but in fact it's a new sub ul.

Here's my code:

```<code><div class="tree" id="tree"></div>

function launchTree(){
    var div = document.getElementById("tree");
  var ul = document.createElement("ul");
  var li = document.createElement("li");
  var a = document.createElement("a");
  //create the main ul element
  ul.setAttribute("id", "main_ul");
  div.appendChild(ul)
  //put my first parent
  li.setAttribute("id", "AC_Lila_li");
  a.setAttribute("data-content", "AC Lila");
  a.setAttribute("id", "AC_Lila_a");

  ul.appendChild(li);
  li.appendChild(a);
  //create my sub ul to put childs !!!! here's the problem!!!
  ul.setAttribute("id", "AC_Lila_ul");
  li.appendChild(ul)
  //create my first child
  li.setAttribute("id", "Queen_Elisa_li");
  a.setAttribute("data-content", "Queen Elisa");
  a.setAttribute("id", "Queen_Elisa_a");

  ul.appendChild(li);
  li.appendChild(a);
  //create my second child
  li.setAttribute("id", "Wendy_li");
  a.setAttribute("data-content", "Wendy");
  a.setAttribute("id", "Wendy_a");

  ul.appendChild(li);
  li.appendChild(a);

}
</code>```

I hope i'm clear of what i wanted to do and thanks for your help!

答:
A way to do that :</p>
```<code>const
  divTree = document.querySelector('#tree')
,  infos =
  [ { elmLI : { id:'AC_Lila_li' },     elmA: { id:'AC_Lila_a',     'data-content': 'AC Lila'     } }
  , { elmLI : { id:'Queen_Elisa_li' }, elmA: { id:'Queen_Elisa_a', 'data-content': 'Queen Elisa' } }
  , { elmLI : { id:'Wendy_li' },       elmA: { id:'Wendy_a',       'data-content': 'Wendy'       } }
  ];

// launchTree()

function launchTree()
  {
  let nvUL = divTree.appendChild( document.createElement('ul') )

  nvUL.id = 'main_ul'

  for (let { elmLI, elmA } of infos )
    {
    let
      nvLI = nvUL.appendChild( document.createElement('li') )
    , nvA  = nvLI.appendChild( document.createElement('a')  )
      ;
    nvLI.id             = elmLI.id
    nvA.id              = elmA.id
    nvA.dataset.content = elmA['data-content']
    nvA.textContent     = '-----'
    }
  }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Use js to append an ul to an li

Body:
yeah you read it right i'm trying to append an ul element in an existing li element and create a sub list. I'm using code from codepen (https://codepen.io/Pestov/pen/AvQmxv) to make a genealogy tree and i would like to create dynamically the tree. For this, i have to create a sub ul element in a previously created li, then had two li to that sub ul.

----EDIT----
My problem is: HierarchyRequestError: Failed to execute 'appendChild' on 'Node': The new child element contains the parent.
Js seems to think that my ul is my parent but in fact it's a new sub ul.

Here's my code:

function launchTree(){
    var div = document.getElementById("tree");
  var ul = document.createElement("ul");
  var li = document.createElement("li");
  var a = document.createElement("a");
  //create the main ul element
  ul.setAttribute("id", "main_ul");
  div.appendChild(ul)
  //put my first parent
  li.setAttribute("id", "AC_Lila_li");
  a.setAttribute("data-content", "AC Lila");
  a.setAttribute("id", "AC_Lila_a");

  ul.appendChild(li);
  li.appendChild(a);
  //create my sub ul to put childs !!!! here's the problem!!!
  ul.setAttribute("id", "AC_Lila_ul");
  li.appendChild(ul)
  //create my first child
  li.setAttribute("id", "Queen_Elisa_li");
  a.setAttribute("data-content", "Queen Elisa");
  a.setAttribute("id", "Queen_Elisa_a");

  ul.appendChild(li);
  li.appendChild(a);
  //create my second child
  li.setAttribute("id", "Wendy_li");
  a.setAttribute("data-content", "Wendy");
  a.setAttribute("id", "Wendy_a");

  ul.appendChild(li);
  li.appendChild(a);

}

I hope i'm clear of what i wanted to do and thanks for your help!

Body:
A way to do that :

const
  divTree = document.querySelector('#tree')
,  infos =
  [ { elmLI : { id:'AC_Lila_li' },     elmA: { id:'AC_Lila_a',     'data-content': 'AC Lila'     } }
  , { elmLI : { id:'Queen_Elisa_li' }, elmA: { id:'Queen_Elisa_a', 'data-content': 'Queen Elisa' } }
  , { elmLI : { id:'Wendy_li' },       elmA: { id:'Wendy_a',       'data-content': 'Wendy'       } }
  ];

// launchTree()

function launchTree()
  {
  let nvUL = divTree.appendChild( document.createElement('ul') )

  nvUL.id = 'main_ul'

  for (let { elmLI, elmA } of infos )
    {
    let
      nvLI = nvUL.appendChild( document.createElement('li') )
    , nvA  = nvLI.appendChild( document.createElement('a')  )
      ;
    nvLI.id             = elmLI.id
    nvA.id              = elmA.id
    nvA.dataset.content = elmA['data-content']
    nvA.textContent     = '-----'
    }
  }


问:
What's an example of Ruby code that's "too clever"?
I was having a discussion with some programmer friends who said that they see Ruby programmers (in particular) producing a lot of code that's "too clever". So I'm wondering what would that look like? I'm referring to the unnecessary use of an obscure language feature in a context in which something straightforward would have worked just as well or better. Know any good Ruby examples of this?</p>

答:
Many of the examples in this article would seem to qualify:

21 Ruby Tricks You Should Be Using In Your Own Code.

The title of the article was a bit of a giveaway, given that it reads "Should" instead of "Should Not". Code "should" be transparent. Code "should not" be tricky.

OwnerDisplayName: amsterdam

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: amsterdam

OwnerDisplayName: rahul


问:
Memory leaking recursive javascript functions in IE,FF,GoogleChrome
```<code><html>
    <body>
        <h1 id="t">Initial</h1>
            <script>
                var cnt=0;
                setTimeout("addCounter()",100);
                addCounter=function(){
                    ++cnt;
                    if (cnt>1000000) cnt=0;
                    document.getElementById('t').firstChild.nodeValue='Counter: #'+(cnt);
                    setTimeout("addCounter()",100);
                }
            </script>
    </body>
</html>
</code>```

When I run this sample code in Internet Explorer/Firefox/Chrome, the memory usage increases until the browser/os runs out of memory and the browser crashes!

Any one can help me to rewrite the code that not wast memory? Or I have report it as a bug for browser developer?

答:
After I increased memory of test machine, I found that after a while the memory usage did not increase any more! It seem the garbage collector (or any thing that is responsible for real free unused memory) is not optimized for low memory systems (like which one I used im my first tests)
In fact Chrome after spending about 50M is ok now, IE 9 after 30M. and I did not check FF yet!</p>

ContentLicense: CC BY-SA 3.0

Body:
Initial

When I run this sample code in Internet Explorer/Firefox/Chrome, the memory usage increases until the browser/os runs out of memory and the browser crashes!

Any one can help me to rewrite the code that not wast memory? Or I have report it as a bug for browser developer?


问:
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 2167)
```<code>response = requests.request("POST", url, headers=headers, json=payload)
print(response.text)
print(type(response.text))
print(json.loads(response.text))
</code>```

Result

```<code>{"sku_id":"H7047001_S_24SM-2021130001B","primary_category_code":"AA31554520001","primary_category_name_en":"Gadgets & Electronics > Camera & Accessories > Camera Bag & Strap & Protector > Screen Protector","primary_category_name_chi":"大腦場 > 攝影器材 > 相機袋 相機帶 屏幕保護 > 屏幕保護","cat_codes":"AA31554520001","cat_names_en":"Gadgets & Electronics > Camera & Accessories > Camera Bag & Strap & Protector > Screen Protector","cat_names_chi":"大腦場 > 攝影器材 > 相機袋 相機帶 屏幕保護 > 屏幕保護","name_en":"iPhone 13 Pro Max tempered glass screen protector (suitable for iphone 13 )","name_chi":"iphone 13 Pro 鋼化保護貼(iphone 13 6.1通用)","brand_name_en":"hoco.","brand_name_chi":"hoco.","summary_en":"<p>1. PC nano edge, not broken edge<br/>2. The frame is higher than the glass surface to prevent the screen from breaking<br/>3. 3D arc edge<br/>4. Thickness 0.33mm<br/></p>","summary_chi":"<p>1，PC納米邊，不碎邊<br/>2，邊框高出玻璃面，防止摔碎屏幕<br/>3，3D弧邊<br/>4，厚度0.33mm<br/></p>","description_en":null,"description_chi":null,"image_urls":"https://cdn-mms.hktvmall.com/hktv/mms/uploadProductImage/c566/17e4/6c51/JmaqphYnzt20211130215445_1200.jpg | https://cdn-mms.hktvmall.com/hktv/mms/uploadProductImage/6f12/126c/4331/RyLUqftEEq20211130215435_1200.jpg | https://cdn-mms.hktvmall.com/hktv/mms/uploadProductImage/7820/ccd1/4779/AhlVGiJOgN20211130215443_1200.jpg","creation_time":"2021-11-30T21:57:23+08:00","store_code":"H7047001","original_price":99.0,"discount_price":49.000000500000006,"stock_available":5,"out_of_stock_since":null,"max_order_quantity":null,"total_shipped_quantity":null,"manu_country_en":"China","manu_country_chi":"中國","height":100.0,"length":50.0,"width":20.0,"dimension_unit":"mm","weight":0.1,"weight_unit":"kg","colors":null,"storage_type":"","packing_spec_en":"","packing_spec_chi":"","packing_box_type":"F","delivery_mode":"hktv-standard-delivery","pickup_days":"1/2/3/4/5/6","num_days_to_be_ready":0,"online_date":null,"offline_date":null,"loyalty_point":0.0,"shelf_life":0.0,"warranty_period":0,"warranty_period_unit":null,"warranty_supplier_en":null,"warranty_supplier_chi":null,"virtual_store_code":null,"virtual_store_name_en":null,"virtual_store_name_chi":null,"primary_store":"H7047001"}
{"sku_id":"H7047001_S_24SM-20210705002","primary_category_code":"AA73502030001","primary_category_name_en":"Sports & Travel > Outdoor Personal Cares > Sun Care > UV Shield Sun Sleeves","primary_category_name_chi":"運動旅行 > 戶外護理用品 > 防矖用品 > 防曬手袖","cat_codes":"AA73502030001","cat_names_en":"Sports & Travel > Outdoor Personal Cares > Sun Care > UV Shield Sun Sleeves","cat_names_chi":"運動旅行 > 戶外護理用品 > 防矖用品 > 防曬手袖","name_en":"MIT Children's Effective Cooling Mosquito Anti-UV Sleeve-American Eagle","name_chi":"『台灣製』兒童高效涼感防蚊抗UV袖套-美國鷹","brand_name_en":"24-LS","brand_name_chi":"24-LS","summary_en":"1. Add Tanatex EULAN natural and powerful anti-mosquito ingredients<br />2. SGS certified UPF50+ effective sun protection!<br />3. The formaldehyde-free ingredients can be worn by children with peace of mind<br />4. Effectively avoid all kinds of mosquito bites<br />5. Ice ore coffee cool yarn material, cool to the touch and fast heat dissipation<br />6. Using Lycra elastic fiber, it fits snugly and is washable<br />7. Can be used as a foot cover","summary_chi":"1. 添加Tanatex EULAN類天然強效防蚊成分<br />2. SGS認證UPF50+有效防曬!<br />3. 無甲醛成份可以安心讓小朋友配帶<br />4. 有效避免各種蚊蟲叮咬<br />5. 冰礦咖啡涼感紗材質，觸感清涼，散熱快<br />6. 使用萊卡彈性纖維，服貼合身耐水洗<br />7.可當腳套","description_en":"Composition: 90% nylon (coffee yarn), 10% elastic fiber<br />. Specifications: Children's sleeves<br />. Size: Flat size: about 30CM long, arm width 7.5CM/maximum stretch: about 84CM long, 20CM arm width<br />. Origin: Taiwan","description_chi":"成分：尼龍90%(咖啡紗)、彈性纖維10%<br />．規格：兒童袖套<br />．尺寸：平量尺寸:約長30CM，臂寬7.5CM/最大拉伸:約長84CM，臂寬20CM<br />．產地：台灣","image_urls":"https://images.hktv-img.com/images/HKTV/23661/24SM-20210705002_main_67904340_20210705222213_01_1200.jpg","creation_time":"2021-07-05T15:20:00+08:00","store_code":"H7047001","original_price":99.0,"discount_price":59.0000004,"stock_available":1,"out_of_stock_since":null,"max_order_quantity":null,"total_shipped_quantity":2,"manu_country_en":"Taiwan","manu_country_chi":"台灣","height":80.0,"length":50.0,"width":20.0,"dimension_unit":"mm","weight":0.1,"weight_unit":"kg","colors":null,"storage_type":"","packing_spec_en":"","packing_spec_chi":"","packing_box_type":"H","delivery_mode":"hktv-standard-delivery","pickup_days":"1/2/3/4/5/6","num_days_to_be_ready":0,"online_date":null,"offline_date":"2099-01-01T00:00:00+08:00","loyalty_point":0.0,"shelf_life":0.0,"warranty_period":null,"warranty_period_unit":null,"warranty_supplier_en":null,"warranty_supplier_chi":null,"virtual_store_code":null,"virtual_store_name_en":null,"virtual_store_name_chi":null,"primary_store":"H7047001"}

<class 'str'>

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 2167)
</code>```

How can I solve this problem? I am stuck in json.loads.

I would like to put it into dictionary and then put it into dataframe and export into csv.

答:
it looks like you have two dictionaries in the response text, therefore you can do:

```<code>json_responses = response.text.split('\n')
for item in json_responses:
    if item != '':
        print(json.loads(item))
</code>```

to load each of the dictionaries.

Body:
response = requests.request("POST", url, headers=headers, json=payload)
print(response.text)
print(type(response.text))
print(json.loads(response.text))

Result

{"sku_id":"H7047001_S_24SM-2021130001B","primary_category_code":"AA31554520001","primary_category_name_en":"Gadgets & Electronics > Camera & Accessories > Camera Bag & Strap & Protector > Screen Protector","primary_category_name_chi":"大腦場 > 攝影器材 > 相機袋 相機帶 屏幕保護 > 屏幕保護","cat_codes":"AA31554520001","cat_names_en":"Gadgets & Electronics > Camera & Accessories > Camera Bag & Strap & Protector > Screen Protector","cat_names_chi":"大腦場 > 攝影器材 > 相機袋 相機帶 屏幕保護 > 屏幕保護","name_en":"iPhone 13 Pro Max tempered glass screen protector (suitable for iphone 13 )","name_chi":"iphone 13 Pro 鋼化保護貼(iphone 13 6.1通用)","brand_name_en":"hoco.","brand_name_chi":"hoco.","summary_en":"
1. PC nano edge, not broken edge
2. The frame is higher than the glass surface to prevent the screen from breaking
3. 3D arc edge
4. Thickness 0.33mm

","summary_chi":"
1，PC納米邊，不碎邊
2，邊框高出玻璃面，防止摔碎屏幕
3，3D弧邊
4，厚度0.33mm

","description_en":null,"description_chi":null,"image_urls":"https://cdn-mms.hktvmall.com/hktv/mms/uploadProductImage/c566/17e4/6c51/JmaqphYnzt20211130215445_1200.jpg | https://cdn-mms.hktvmall.com/hktv/mms/uploadProductImage/6f12/126c/4331/RyLUqftEEq20211130215435_1200.jpg | https://cdn-mms.hktvmall.com/hktv/mms/uploadProductImage/7820/ccd1/4779/AhlVGiJOgN20211130215443_1200.jpg","creation_time":"2021-11-30T21:57:23+08:00","store_code":"H7047001","original_price":99.0,"discount_price":49.000000500000006,"stock_available":5,"out_of_stock_since":null,"max_order_quantity":null,"total_shipped_quantity":null,"manu_country_en":"China","manu_country_chi":"中國","height":100.0,"length":50.0,"width":20.0,"dimension_unit":"mm","weight":0.1,"weight_unit":"kg","colors":null,"storage_type":"","packing_spec_en":"","packing_spec_chi":"","packing_box_type":"F","delivery_mode":"hktv-standard-delivery","pickup_days":"1/2/3/4/5/6","num_days_to_be_ready":0,"online_date":null,"offline_date":null,"loyalty_point":0.0,"shelf_life":0.0,"warranty_period":0,"warranty_period_unit":null,"warranty_supplier_en":null,"warranty_supplier_chi":null,"virtual_store_code":null,"virtual_store_name_en":null,"virtual_store_name_chi":null,"primary_store":"H7047001"}
{"sku_id":"H7047001_S_24SM-20210705002","primary_category_code":"AA73502030001","primary_category_name_en":"Sports & Travel > Outdoor Personal Cares > Sun Care > UV Shield Sun Sleeves","primary_category_name_chi":"運動旅行 > 戶外護理用品 > 防矖用品 > 防曬手袖","cat_codes":"AA73502030001","cat_names_en":"Sports & Travel > Outdoor Personal Cares > Sun Care > UV Shield Sun Sleeves","cat_names_chi":"運動旅行 > 戶外護理用品 > 防矖用品 > 防曬手袖","name_en":"MIT Children's Effective Cooling Mosquito Anti-UV Sleeve-American Eagle","name_chi":"『台灣製』兒童高效涼感防蚊抗UV袖套-美國鷹","brand_name_en":"24-LS","brand_name_chi":"24-LS","summary_en":"1. Add Tanatex EULAN natural and powerful anti-mosquito ingredients
2. SGS certified UPF50+ effective sun protection!
3. The formaldehyde-free ingredients can be worn by children with peace of mind
4. Effectively avoid all kinds of mosquito bites
5. Ice ore coffee cool yarn material, cool to the touch and fast heat dissipation
6. Using Lycra elastic fiber, it fits snugly and is washable
7. Can be used as a foot cover","summary_chi":"1. 添加Tanatex EULAN類天然強效防蚊成分
2. SGS認證UPF50+有效防曬!
3. 無甲醛成份可以安心讓小朋友配帶
4. 有效避免各種蚊蟲叮咬
5. 冰礦咖啡涼感紗材質，觸感清涼，散熱快
6. 使用萊卡彈性纖維，服貼合身耐水洗
7.可當腳套","description_en":"Composition: 90% nylon (coffee yarn), 10% elastic fiber
. Specifications: Children's sleeves
. Size: Flat size: about 30CM long, arm width 7.5CM/maximum stretch: about 84CM long, 20CM arm width
. Origin: Taiwan","description_chi":"成分：尼龍90%(咖啡紗)、彈性纖維10%
．規格：兒童袖套
．尺寸：平量尺寸:約長30CM，臂寬7.5CM/最大拉伸:約長84CM，臂寬20CM
．產地：台灣","image_urls":"https://images.hktv-img.com/images/HKTV/23661/24SM-20210705002_main_67904340_20210705222213_01_1200.jpg","creation_time":"2021-07-05T15:20:00+08:00","store_code":"H7047001","original_price":99.0,"discount_price":59.0000004,"stock_available":1,"out_of_stock_since":null,"max_order_quantity":null,"total_shipped_quantity":2,"manu_country_en":"Taiwan","manu_country_chi":"台灣","height":80.0,"length":50.0,"width":20.0,"dimension_unit":"mm","weight":0.1,"weight_unit":"kg","colors":null,"storage_type":"","packing_spec_en":"","packing_spec_chi":"","packing_box_type":"H","delivery_mode":"hktv-standard-delivery","pickup_days":"1/2/3/4/5/6","num_days_to_be_ready":0,"online_date":null,"offline_date":"2099-01-01T00:00:00+08:00","loyalty_point":0.0,"shelf_life":0.0,"warranty_period":null,"warranty_period_unit":null,"warranty_supplier_en":null,"warranty_supplier_chi":null,"virtual_store_code":null,"virtual_store_name_en":null,"virtual_store_name_chi":null,"primary_store":"H7047001"}

<class 'str'>

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 2167)

How can I solve this problem? I am stuck in json.loads.

I would like to put it into dictionary and then put it into dataframe and export into csv.

Body:
it looks like you have two dictionaries in the response text, therefore you can do:

json_responses = response.text.split('\n')
for item in json_responses:
    if item != '':
        print(json.loads(item))

to load each of the dictionaries.


问:
Azure Cosmos DB multi-type documents query
I am trying to query Cosmos DB via SQL API. I have a straightforward data model with different types of documents within the same container (since they're related to each other) and I'm using a custom type key for each document that defines the document type following this tutorial.
Here's how my documents look like:

```<code>document a:
{
   "id": 1,
   "b_id": 2,
   "c_id": 3,
   "foo": "bar",
   "type": "a"
}
document b:
{
   "id": 2,
   "baz": "qux",
   "type": "b"
}
document c:
{
   "id": 3,
   "quux": "quuz",
   "type": "c"
}
</code>```

I know that the join synatx is different in Cosmos DB and only works within the same document. I am trying to find a way to retrieve document a with all its attributes retrieved from document b and c:

```<code>{
   "id": 1,
   "foo": "bar",
   "baz": "qux",
   "quux": "quuz"
}
</code>```

Is it possible in an efficient way? If not, I'm considering to normalize data before writing to Cosmos. Something like:

```<code>{
   "id": 1,
   "b" : { "baz": "qux" },
   "c" : { "quux": "quuz" }
}
</code>```

But this way I have to write the entire b and c in each document while it seems having a reference to them makes it more efficient from capacity viewpoint.

答:
Your data model here is not really correct for the type of data you have here. You typically only reference data when there is a many-to-many relationship. Even then you only store one relationship per document. The only way to retrieve related data using your data model here is to query the container twice.

What you have in your data here is a one-to-many (or one-to-few) where you have references to multiple documents from a single document.

In those scenarios you can or should embed the child items if the relationship is one-to-few. If it is a rather large or unbounded one-to-many, then you should model the data such that you can retrieve all related items with a common property and value.

In your scenario here, if this is just a small number of child documents, I would embed them. Then if you've modeled your data such that you know both the partition key and id for your data, you can very efficiently retrieve this data using a point read ReadItemAsync() rather than using a query. This is both super fast and very efficient.

Body:
I am trying to query Cosmos DB via SQL API. I have a straightforward data model with different types of documents within the same container (since they're related to each other) and I'm using a custom type key for each document that defines the document type following this tutorial.
Here's how my documents look like:

document a:
{
   "id": 1,
   "b_id": 2,
   "c_id": 3,
   "foo": "bar",
   "type": "a"
}
document b:
{
   "id": 2,
   "baz": "qux",
   "type": "b"
}
document c:
{
   "id": 3,
   "quux": "quuz",
   "type": "c"
}

I know that the join synatx is different in Cosmos DB and only works within the same document. I am trying to find a way to retrieve document a with all its attributes retrieved from document b and c:

{
   "id": 1,
   "foo": "bar",
   "baz": "qux",
   "quux": "quuz"
}

Is it possible in an efficient way? If not, I'm considering to normalize data before writing to Cosmos. Something like:

{
   "id": 1,
   "b" : { "baz": "qux" },
   "c" : { "quux": "quuz" }
}

But this way I have to write the entire b and c in each document while it seems having a reference to them makes it more efficient from capacity viewpoint.


问:
how can I get the function to return index of 2 numbers that add up to a target value
I am writing a function to take a list of integers and an integer called target and return the indices of the two numbers in the list such that they add up to target. But my code doesn't work the way it should. The function ends up not printing anything at all. How can I fix this? I am a beginner and I can't figure out what's wrong :(</p>
```<code>def solution(list, target):
    firstindex = 0
    secondindex = -1

    while(firstindex <= len(list)-1):

        if list[firstindex] + list[secondindex] == target:
            print(f"The sum was found at index {firstindex} and {secondindex}")
            break

        else:
            firstindex = firstindex + 1
            secondindex = secondindex - 1

#I am calling the function here
solution([1,2,3,4,5, 6], 5)
</code>```

答:
Don't use list as the variable name for the first list the function is taking, it is a keyword in python.

edit:

you are refering to the keyword list in your function which represents a type object in python.  You are basically referring to the classification of the object.  Instead assign your variable to another name such as def solution(original, target):

Body:
I am writing a function to take a list of integers and an integer called target and return the indices of the two numbers in the list such that they add up to target. But my code doesn't work the way it should. The function ends up not printing anything at all. How can I fix this? I am a beginner and I can't figure out what's wrong :(

def solution(list, target):
    firstindex = 0
    secondindex = -1

    while(firstindex <= len(list)-1):

        if list[firstindex] + list[secondindex] == target:
            print(f"The sum was found at index {firstindex} and {secondindex}")
            break

        else:
            firstindex = firstindex + 1
            secondindex = secondindex - 1

#I am calling the function here
solution([1,2,3,4,5, 6], 5)


问:
I don't know what to put in the view placeholder
I keep getting an error to insert "proxy: /GeometryProxy/" even when "proxy" is a state variable. I have the code for the preview below. I don't know what to put in the placeholder and I am confused. I have included my full code to review. Please look below.

```<code>struct MathematicallyMainController_Previews: PreviewProvider {
static var previews: some View {
    MathematicallyMainController(proxy: // what do i put here?)
}
</code>```

}

My full code:

This is where the problem with the 'var' is happening.

```<code>struct MathematicallyMainController: View {
@StateObject var tabBarModel = TabBarViewModel()
@Environment(\.colorScheme) var colorScheme
@State var selectedIndex = 0
@State var isSelectedA = false
@State var isSelectedB = false
@State var isSelectedC = false
@State var isSelectedD = false
@State var isSelectedE = false
@State var proxy: GeometryProxy
var body: some View {
    ZStack {
        let bottomEdge = proxy.safeAreaInsets.bottom
        switch selectedIndex {
        case 0:
            HomeViewController()
        case 1:
            BrowseView()
        case 2:
            RewardsView()
        case 3:
            EssentialsView()
        case 4:
            SchoolModeView()
        default:
            HomeViewController()
        }
        ZStack {
            RoundedRectangle(cornerRadius: 15)
                .fill(.regularMaterial)
                .colorScheme(colorScheme == .dark ? .dark : .light)
            HStack(alignment: .center) {
                Button {
                   selectedIndex = 0
                } label: {
                    if selectedIndex == 0 {
                        ZStack {
                            Circle()
                                .blur(radius: 20)
                                .foregroundColor(.blue)
                                .frame(width: 60)
                                .padding([.leading, .trailing], 5)
                            Image(systemName: "house.fill")
                                .font(.title)
                                .foregroundColor(colorScheme == .dark ? .black : .white)
                                .padding([.leading, .trailing], 5)
                        }
                    } else {
                        Image(systemName: "house.fill")
                            .font(.title)
                            .foregroundColor(colorScheme == .dark ? .white : .black)
                    }
                }
                Button {
                    selectedIndex = 1
                } label: {
                    if selectedIndex == 1 {
                        ZStack {
                            Circle()
                                .blur(radius: 20)
                                .foregroundColor(.indigo)
                                .frame(width: 60)
                                .padding(.leading, 15)
                            Image(systemName: "rectangle.stack.fill")
                                .font(.title)
                                .foregroundColor(colorScheme == .dark ? .black : .white)
                                .padding(.leading, 15)
                        }
                    } else {
                        Image(systemName: "rectangle.stack.fill")
                            .font(.title)
                            .foregroundColor(colorScheme == .dark ? .white : .black)
                            .padding(.leading, 15)
                    }
                }
                Button {
                    selectedIndex = 2
                } label: {
                    if selectedIndex == 2 {
                        ZStack {
                            Circle()
                                .blur(radius: 20)
                                .foregroundColor(.orange)
                                .frame(width: 60)
                                .padding([.trailing, .leading], 15)
                            Image(systemName: "circle.dotted")
                                .font(.title)
                                .foregroundColor(colorScheme == .dark ? .black : .white)
                                .padding([.trailing, .leading], 15)
                        }
                    } else {
                        Image(systemName: "circle.dotted")
                            .font(.title)
                            .foregroundColor(colorScheme == .dark ? .white : .black)
                            .padding(.trailing, 15)
                            .padding(.leading, 15)
                    }
                }
                Button {
                    selectedIndex = 3
                } label: {
                    if selectedIndex == 3 {
                        ZStack {
                            Circle()
                                .blur(radius: 20)
                                .foregroundColor(.green)
                                .frame(width: 60)
                                .padding(.trailing, 15)
                            Image(systemName: "doc.text.image")
                                .font(.title)
                                .foregroundColor(colorScheme == .dark ? .black : .white)
                                .padding(.trailing, 15)
                        }
                    } else {
                        Image(systemName: "doc.text.image")
                            .font(.title)
                            .foregroundColor(colorScheme == .dark ? .white : .black)
                            .padding(.trailing, 15)
                    }
                }
                Button {
                    selectedIndex = 4
                } label: {
                    if selectedIndex == 4 {
                        ZStack {
                            Circle()
                                .blur(radius: 20)
                                .foregroundColor(.purple)
                                .frame(width: 60)
                                .padding([.leading, .trailing], 5)
                            Image(systemName: "graduationcap.fill")
                                .font(.title)
                                .foregroundColor(colorScheme == .dark ? .black : .white)
                                .padding([.leading, .trailing], 5)
                        }
                    } else {
                        Image(systemName: "graduationcap.fill")
                            .font(.title)
                            .foregroundColor(colorScheme == .dark ? .white : .black)
                    }
                }
            }
            .colorScheme(colorScheme == .dark ? .dark : .light)
            .padding(.horizontal)
        }
        .frame(height: 60)
        .shadow(color: .primary, radius: -10)
        .shadow(color: .black, radius: 10)
        .padding([.horizontal])
        .padding(.bottom)
        .frame(maxHeight: .infinity, alignment: .bottom)
        .modifier(OffsetModifier())
        .environmentObject(tabBarModel)
        .offset(y: tabBarModel.tabState == .floating ? 0 : bottomEdge)
    }
}
</code>```

}

This is my ViewModifier I have included to create the scrolling animation.

```<code>struct OffsetModifier: ViewModifier {
@EnvironmentObject var model: TabBarViewModel
func body(content: Content) -> some View {
    content
        .overlay(
            GeometryReader { proxy -> Color in
                let minY = proxy.frame(in: .global).minY

                DispatchQueue.main.async {

                    let durationOffset: CGFloat = 35

                    if minY < model.offset {
                        if model.offset < 0 && -minY > (model.lastStoredOffset + durationOffset) {
                            withAnimation(.easeOut.speed(1)) {
                                model.tabState = .floating
                            }
                            model.lastStoredOffset = -model.offset
                        }
                    }

                    if minY > model.offset && -minY < (model.lastStoredOffset + durationOffset) {
                        withAnimation(.easeOut.speed(1)) {
                            model.tabState = .expanded
                        }
                        model.lastStoredOffset = -model.offset
                    }

                    model.offset = minY
                }
                return Color.clear
            }
            ,alignment: .top
        )
}
</code>```

}

答:
The only time you ever use proxy is on this line:

```<code>let bottomEdge = proxy.safeAreaInsets.bottom
</code>```

Therefore, there's no reason to pass in the entire GeometryProxy -- you can just pass in the bottom inset. Also, it definitely doesn't need to be a @State variable -- @State is used when the View needs to mutate its state over time -- this is just a parameter being passed in.

Change this line:

```<code>@State var proxy: GeometryProxy
</code>```

to:

```<code>var bottomInset : CGFloat = 0
</code>```

Because it has a default value, your preview can turn into this:

```<code>static var previews: some View {
    MathematicallyMainController()
}
</code>```

If you really wanted to pass a value (say, from the parent of the View), you would do something like this:

```<code>GeometryReader { proxy in
  //other view code...
  MathematicallyMainController(bottomInset: proxy.safeAreaInsets.bottom)
  //other code...
}
</code>```

There's also the option of moving the GeometryReader inside of MathematicallyMainController, but I'm assuming there's a reason you had it outside to begin with.

All of that being said, it looks like you have some unnecessary and unused code that you could clean up. For example, none of the isSelectedA-E variables ever get used. There's probably more here that can be refactored, but is outside of the scope of the present question.

Body:
I keep getting an error to insert "proxy: /GeometryProxy/" even when "proxy" is a state variable. I have the code for the preview below. I don't know what to put in the placeholder and I am confused. I have included my full code to review. Please look below.

struct MathematicallyMainController_Previews: PreviewProvider {
static var previews: some View {
    MathematicallyMainController(proxy: // what do i put here?)
}

}

My full code:

This is where the problem with the 'var' is happening.

struct MathematicallyMainController: View {
@StateObject var tabBarModel = TabBarViewModel()
@Environment(\.colorScheme) var colorScheme
@State var selectedIndex = 0
@State var isSelectedA = false
@State var isSelectedB = false
@State var isSelectedC = false
@State var isSelectedD = false
@State var isSelectedE = false
@State var proxy: GeometryProxy
var body: some View {
    ZStack {
        let bottomEdge = proxy.safeAreaInsets.bottom
        switch selectedIndex {
        case 0:
            HomeViewController()
        case 1:
            BrowseView()
        case 2:
            RewardsView()
        case 3:
            EssentialsView()
        case 4:
            SchoolModeView()
        default:
            HomeViewController()
        }
        ZStack {
            RoundedRectangle(cornerRadius: 15)
                .fill(.regularMaterial)
                .colorScheme(colorScheme == .dark ? .dark : .light)
            HStack(alignment: .center) {
                Button {
                   selectedIndex = 0
                } label: {
                    if selectedIndex == 0 {
                        ZStack {
                            Circle()
                                .blur(radius: 20)
                                .foregroundColor(.blue)
                                .frame(width: 60)
                                .padding([.leading, .trailing], 5)
                            Image(systemName: "house.fill")
                                .font(.title)
                                .foregroundColor(colorScheme == .dark ? .black : .white)
                                .padding([.leading, .trailing], 5)
                        }
                    } else {
                        Image(systemName: "house.fill")
                            .font(.title)
                            .foregroundColor(colorScheme == .dark ? .white : .black)
                    }
                }
                Button {
                    selectedIndex = 1
                } label: {
                    if selectedIndex == 1 {
                        ZStack {
                            Circle()
                                .blur(radius: 20)
                                .foregroundColor(.indigo)
                                .frame(width: 60)
                                .padding(.leading, 15)
                            Image(systemName: "rectangle.stack.fill")
                                .font(.title)
                                .foregroundColor(colorScheme == .dark ? .black : .white)
                                .padding(.leading, 15)
                        }
                    } else {
                        Image(systemName: "rectangle.stack.fill")
                            .font(.title)
                            .foregroundColor(colorScheme == .dark ? .white : .black)
                            .padding(.leading, 15)
                    }
                }
                Button {
                    selectedIndex = 2
                } label: {
                    if selectedIndex == 2 {
                        ZStack {
                            Circle()
                                .blur(radius: 20)
                                .foregroundColor(.orange)
                                .frame(width: 60)
                                .padding([.trailing, .leading], 15)
                            Image(systemName: "circle.dotted")
                                .font(.title)
                                .foregroundColor(colorScheme == .dark ? .black : .white)
                                .padding([.trailing, .leading], 15)
                        }
                    } else {
                        Image(systemName: "circle.dotted")
                            .font(.title)
                            .foregroundColor(colorScheme == .dark ? .white : .black)
                            .padding(.trailing, 15)
                            .padding(.leading, 15)
                    }
                }
                Button {
                    selectedIndex = 3
                } label: {
                    if selectedIndex == 3 {
                        ZStack {
                            Circle()
                                .blur(radius: 20)
                                .foregroundColor(.green)
                                .frame(width: 60)
                                .padding(.trailing, 15)
                            Image(systemName: "doc.text.image")
                                .font(.title)
                                .foregroundColor(colorScheme == .dark ? .black : .white)
                                .padding(.trailing, 15)
                        }
                    } else {
                        Image(systemName: "doc.text.image")
                            .font(.title)
                            .foregroundColor(colorScheme == .dark ? .white : .black)
                            .padding(.trailing, 15)
                    }
                }
                Button {
                    selectedIndex = 4
                } label: {
                    if selectedIndex == 4 {
                        ZStack {
                            Circle()
                                .blur(radius: 20)
                                .foregroundColor(.purple)
                                .frame(width: 60)
                                .padding([.leading, .trailing], 5)
                            Image(systemName: "graduationcap.fill")
                                .font(.title)
                                .foregroundColor(colorScheme == .dark ? .black : .white)
                                .padding([.leading, .trailing], 5)
                        }
                    } else {
                        Image(systemName: "graduationcap.fill")
                            .font(.title)
                            .foregroundColor(colorScheme == .dark ? .white : .black)
                    }
                }
            }
            .colorScheme(colorScheme == .dark ? .dark : .light)
            .padding(.horizontal)
        }
        .frame(height: 60)
        .shadow(color: .primary, radius: -10)
        .shadow(color: .black, radius: 10)
        .padding([.horizontal])
        .padding(.bottom)
        .frame(maxHeight: .infinity, alignment: .bottom)
        .modifier(OffsetModifier())
        .environmentObject(tabBarModel)
        .offset(y: tabBarModel.tabState == .floating ? 0 : bottomEdge)
    }
}

}

This is my ViewModifier I have included to create the scrolling animation.

struct OffsetModifier: ViewModifier {
@EnvironmentObject var model: TabBarViewModel
func body(content: Content) -> some View {
    content
        .overlay(
            GeometryReader { proxy -> Color in
                let minY = proxy.frame(in: .global).minY

                DispatchQueue.main.async {

                    let durationOffset: CGFloat = 35

                    if minY < model.offset {
                        if model.offset < 0 && -minY > (model.lastStoredOffset + durationOffset) {
                            withAnimation(.easeOut.speed(1)) {
                                model.tabState = .floating
                            }
                            model.lastStoredOffset = -model.offset
                        }
                    }

                    if minY > model.offset && -minY < (model.lastStoredOffset + durationOffset) {
                        withAnimation(.easeOut.speed(1)) {
                            model.tabState = .expanded
                        }
                        model.lastStoredOffset = -model.offset
                    }

                    model.offset = minY
                }
                return Color.clear
            }
            ,alignment: .top
        )
}

}

Body:
The only time you ever use proxy is on this line:

let bottomEdge = proxy.safeAreaInsets.bottom

Therefore, there's no reason to pass in the entire GeometryProxy -- you can just pass in the bottom inset. Also, it definitely doesn't need to be a @State variable -- @State is used when the View needs to mutate its state over time -- this is just a parameter being passed in.

Change this line:

@State var proxy: GeometryProxy

to:

var bottomInset : CGFloat = 0

Because it has a default value, your preview can turn into this:

static var previews: some View {
    MathematicallyMainController()
}

If you really wanted to pass a value (say, from the parent of the View), you would do something like this:

GeometryReader { proxy in
  //other view code...
  MathematicallyMainController(bottomInset: proxy.safeAreaInsets.bottom)
  //other code...
}

There's also the option of moving the GeometryReader inside of MathematicallyMainController, but I'm assuming there's a reason you had it outside to begin with.

All of that being said, it looks like you have some unnecessary and unused code that you could clean up. For example, none of the isSelectedA-E variables ever get used. There's probably more here that can be refactored, but is outside of the scope of the present question.


问:
require.cache equivalent in ES modules
ES Modules docs states:

require.cache is not used by import. It has a separate cache.

So where's this separate cache? Is it accessible after all?

I'm looking for invalidating module caching as it can be done in CommonJS modules (node.js require() cache - possible to invalidate?)

答:
I saw your thread on the nodeJS github and your answer is there: the cache is designed to be immutable. There's also a good suggestion to use Workers, with each instance having its own fresh imports. Short of that, if you need this behaviour (which doesn't exist for a reason), is there perhaps a better way to design your application to not need it?

EDIT: The issue on GH: https://github.com/nodejs/help/issues/1399

Title: require.cache equivalent in ES modules


问:
Sort a list of object w.r.t to a particular member/state
I have a list of java object that have 4 members.

```<code>int id;
String name;
String age;
int order;
</code>```

I want to sort the list of this object w.r.t name

答:
Sort all member/state on behalf of value of myString i.e if myString is name then sort by name vice versa.

```<code>  Collections.sort(list, new Comparator<com.MyObject>() {

          public int compare(com.MyObject object1, com.MyObject object2) {

            if(myString.equalsIgnoreCase("name")){
            return object1.getName().compareTo(object2.getName());

          }else if(myString.equalsIgnoreCase("age")){
            return object1.getAge().compareTo(object2.getAge());

          }else{
            return object1.getOrder() - object2.getOrder();
          }
      }
  });
</code>```

Body:
I have a list of java object that have 4 members.

int id;
String name;
String age;
int order;

I want to sort the list of this object w.r.t name

Body:
Sort all member/state on behalf of value of myString i.e if myString is name then sort by name vice versa.

  Collections.sort(list, new Comparator<com.MyObject>() {

          public int compare(com.MyObject object1, com.MyObject object2) {

            if(myString.equalsIgnoreCase("name")){
            return object1.getName().compareTo(object2.getName());

          }else if(myString.equalsIgnoreCase("age")){
            return object1.getAge().compareTo(object2.getAge());

          }else{
            return object1.getOrder() - object2.getOrder();
          }
      }
  });


问:
Precedence of function application
In order to illustrate function application has the highest precedence in Haskell the following example was provided (by schoolofhaskell):

```<code>sq b = b * b
main = print $
-- show
    sq 3+1
-- /show
</code>```

The result here is 10.

What puzzles me is that the argument constitutes a function application too. Consider the operator + being a short-cut of a function. So when the argument is taken, I would expect that its function application now takes precedence over the original one.

Written that way it delivers the expected result:

```<code>sq b = b * b
main = print $
    sq ((+) 3 1 )
</code>```

Any explanation?

答:
The addition operator is syntactically different from a function application, and that is what determines its operator precedence.

If you rewrite your addition (3 + 1) as a function application ((+) 3 1), the slice (+) follows special slicing rules inside its own parentheses, but outside the slice it's just another parenthesized expression.

Note that your "expected result" is not really parallel to your original example:

```<code>sq 3 + 1      -- original example, parsed `(sq 3) + 1`

sq ((+) 3 1)  -- "expected result", has added parentheses to force your parse

sq (3 + 1)    -- this is the operator version of "expected result"
</code>```

In Haskell, the parentheses are not part of function application -- they are used solely for grouping!

That is to say:  like (+) is just another parenthesized expression, so is (3 + 1)

Title: Precedence of function application

Body:
In order to illustrate function application has the highest precedence in Haskell the following example was provided (by schoolofhaskell):

sq b = b * b
main = print $
-- show
    sq 3+1
-- /show

The result here is 10.

What puzzles me is that the argument constitutes a function application too. Consider the operator + being a short-cut of a function. So when the argument is taken, I would expect that its function application now takes precedence over the original one.

Written that way it delivers the expected result:

sq b = b * b
main = print $
    sq ((+) 3 1 )

Any explanation?

Body:
The addition operator is syntactically different from a function application, and that is what determines its operator precedence.

If you rewrite your addition (3 + 1) as a function application ((+) 3 1), the slice (+) follows special slicing rules inside its own parentheses, but outside the slice it's just another parenthesized expression.

Note that your "expected result" is not really parallel to your original example:

sq 3 + 1      -- original example, parsed `(sq 3) + 1`

sq ((+) 3 1)  -- "expected result", has added parentheses to force your parse

sq (3 + 1)    -- this is the operator version of "expected result"

In Haskell, the parentheses are not part of function application -- they are used solely for grouping!

That is to say:  like (+) is just another parenthesized expression, so is (3 + 1)


问:
How to convert a String column to Date column for a PySpark dataframe using strptime function?
I want to convert a string column to a date column for a pyspark dataframe as follows :

|Date|
+-------+---
|10-Nov-15|

|11-Oct-17|

I know strptime function would work, but unable to use it with PySpark dataframe.

答:
You can use the to_date function.

```<code>import pyspark.sql.functions as F
......

df = df.withColumn('Date', F.to_date(F.lpad('Date', 9, '0'), 'dd-MMM-yy'))
df.printSchema()
df.show(truncate=False)
</code>```

Body:
You can use the to_date function.

import pyspark.sql.functions as F
......

df = df.withColumn('Date', F.to_date(F.lpad('Date', 9, '0'), 'dd-MMM-yy'))
df.printSchema()
df.show(truncate=False)


问:
How do I create a scrapy TextResponse object from html?
I'm sending a POST request to an API using scrapy.FormRequest and receiving a TextResponse object back. The body of this object looks like so:

```<code>{
"Refiners": ...
"Results": ...
}
</code>```

I am only interested in the Results portion of the response as it contains HTML that I would like to parse.

As such, I am trying to creating a new TextResponse object containing only the Results portion in the body, so that I am able to use the response.css method on it.

I tried the following and it yielded an empty response body. Any thoughts on why and how to fix this?

```<code>new_response = scrapy.http.TextResponse(response.json()["Results"])
</code>```

答:
You can use the HTMLResponse class and you need to provide the body and encoding arguments in the constructor.

from scrapy.http import HtmlResponse
new_response = HtmlResponse(url="some_url", body=response.json()["Results"], encoding="utf-8")
```

You can then use new_response.css(...) to select elements.

Body:
I'm sending a POST request to an API using scrapy.FormRequest and receiving a TextResponse object back. The body of this object looks like so:

{
"Refiners": ...
"Results": ...
}

I am only interested in the Results portion of the response as it contains HTML that I would like to parse.

As such, I am trying to creating a new TextResponse object containing only the Results portion in the body, so that I am able to use the response.css method on it.

I tried the following and it yielded an empty response body. Any thoughts on why and how to fix this?

new_response = scrapy.http.TextResponse(response.json()["Results"])

Body:
You can use the HTMLResponse class and you need to provide the body and encoding arguments in the constructor.

from scrapy.http import HtmlResponse
new_response = HtmlResponse(url="some_url", body=response.json()["Results"], encoding="utf-8")

You can then use new_response.css(...) to select elements.


问:
JQuery UI Autocomplete not working in ASP.NET MVC
I am trying to implement an autocomplete in ASP.NET MVC 3, following this post
but I really can't get it to work. I have looked at a series of other posts and blogs, but no success so far.

I have a DB table which contains regions (in Japanese), like so:

1 ハイチ; 2 ドミニカ共和国; 3 南アフリカ

basically a [key, Name] pair.

In my repository I am doing the following call:

```<code>public IQueryable<Region> GetAllRegions()
    {
        return db.Regions;
    }
</code>```

Getting the raw data, which I pass to the controller, pair down the data according to input and the concatenate to a string like so:

```<code>    public class RegionsController : Controller
{
    Region_Repository rr = new Region_Repository();

    public string FindRegions(string q)
    {
        List<string> regions = rr.GetAllRegions().Select(r => r.Name).Where(s => s.StartsWith(q)).ToList();

        return string.Join("\n", regions);
    }

}
</code>```

The controller when accessed via server/Regions/FindRegions/?q=ハ return a page with the single entry "ハイチ" as expected.

On the page I have a textbox with id "#NewRegion" and the script

```<code><script type="text/javascript">
$(document).ready(function () {
    $("#NewRegion").autocomplete('@Url.Action("FindRegions", "Regions")');
})
</script>
</code>```

which I placed underneath the textbox.

I have references to JQuery and JQueryUI from Google API which work since I am executing other JQuery and using the JQueryUI datepicker successfully on this page.

I tried placing the script in a separate file and hardcoding the url as '/Regions/FindRegions', but no change. I had a look in firebug (second day only, so not very proficient at using it yet) and the script doesn't seem to get executed.
The controller is called fine when accessed via URL, but anything I enter into the textbox does not get passed to the controller...

Can anybody see anything wrong with this?

答:
I got it working in the following way. I changed the controller to return Json data like this:

```<code>public ActionResult FindRegions(string term)
    {
        var regionNames = rr.GetAllRegions().Select(r => r.Name).Where(s => s.Contains(term)).ToList();

        return Json(regionNames, JsonRequestBehavior.AllowGet);
    }
</code>```

note: the AllowGet is there so I could check the result via url, so for debug only.
And the autocomplete script became:

```<code>$(function () {
$('#NewRegion').autocomplete({ source: '/Regions/FindRegions' } );
});
</code>```

Now it works, but I am still not sure why.

Body:
I am trying to implement an autocomplete in ASP.NET MVC 3, following this post
but I really can't get it to work. I have looked at a series of other posts and blogs, but no success so far.

I have a DB table which contains regions (in Japanese), like so:

1 ハイチ; 2 ドミニカ共和国; 3 南アフリカ

basically a [key, Name] pair.

In my repository I am doing the following call:

public IQueryable<Region> GetAllRegions()
    {
        return db.Regions;
    }

Getting the raw data, which I pass to the controller, pair down the data according to input and the concatenate to a string like so:

    public class RegionsController : Controller
{
    Region_Repository rr = new Region_Repository();

    public string FindRegions(string q)
    {
        List<string> regions = rr.GetAllRegions().Select(r => r.Name).Where(s => s.StartsWith(q)).ToList();

        return string.Join("\n", regions);
    }

}

The controller when accessed via server/Regions/FindRegions/?q=ハ return a page with the single entry "ハイチ" as expected.

On the page I have a textbox with id "#NewRegion" and the script

which I placed underneath the textbox.

I have references to JQuery and JQueryUI from Google API which work since I am executing other JQuery and using the JQueryUI datepicker successfully on this page.

I tried placing the script in a separate file and hardcoding the url as '/Regions/FindRegions', but no change. I had a look in firebug (second day only, so not very proficient at using it yet) and the script doesn't seem to get executed.
The controller is called fine when accessed via URL, but anything I enter into the textbox does not get passed to the controller...

Can anybody see anything wrong with this?

Body:
I got it working in the following way. I changed the controller to return Json data like this:

public ActionResult FindRegions(string term)
    {
        var regionNames = rr.GetAllRegions().Select(r => r.Name).Where(s => s.Contains(term)).ToList();

        return Json(regionNames, JsonRequestBehavior.AllowGet);
    }

note: the AllowGet is there so I could check the result via url, so for debug only.
And the autocomplete script became:

$(function () {
$('#NewRegion').autocomplete({ source: '/Regions/FindRegions' } );
});

Now it works, but I am still not sure why.


问:
403 Forbidden on ESPv2, GKE AutoPilot, WIF
I'm following the Getting started with Endpoints for GKE with ESPv2. I'm using Workload Identity Federation and Autopilot on the GKE cluster.

I've been running into the error:

F0110 03:46:24.304229       8 server.go:54] fail to initialize config manager: http call to GET https://servicemanagement.googleapis.com/v1/services/name:bookstore.endpoints.<project>.cloud.goog/rollouts?filter=status=SUCCESS returns not 200 OK: 403 Forbidden

Which ultimately leads to a transport failure error and shut down of the Pod.

My first step was to investigate permission issues, but I could really use some outside perspective on this as I've been going around in circles on this.

Here's my config:

```<code>>> gcloud container clusters describe $GKE_CLUSTER_NAME \
--zone=$GKE_CLUSTER_ZONE \
--format='value[delimiter="\n"](nodePools[].config.oauthScopes)'
</code>```
```<code>['https://www.googleapis.com/auth/devstorage.read_only',
'https://www.googleapis.com/auth/logging.write',
'https://www.googleapis.com/auth/monitoring',
'https://www.googleapis.com/auth/service.management.readonly',
'https://www.googleapis.com/auth/servicecontrol',
'https://www.googleapis.com/auth/trace.append']

</code>```
```<code>>> gcloud container clusters describe $GKE_CLUSTER_NAME \
--zone=$GKE_CLUSTER_ZONE \
--format='value[delimiter="\n"](nodePools[].config.serviceAccount)'
default
default
</code>```

Service-Account-Name: test-espv2

Roles

```<code>Cloud Trace Agent
Owner
Service Account Token Creator
Service Account User
Service Controller
Workload Identity User
</code>```

I've associated the WIF svc-act with the Cluster with the following yaml

```<code>apiVersion: v1
kind: ServiceAccount
metadata:
  annotations:
    iam.gke.io/gcp-service-account: test-espv2@<project>.iam.gserviceaccount.com
  name: test-espv2
  namespace: eventing
</code>```

And then I've associated the pod with the test-espv2 svc-act

```<code>---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: esp-grpc-bookstore
  namespace: eventing
spec:
  replicas: 1
  selector:
    matchLabels:
      app: esp-grpc-bookstore
  template:
    metadata:
      labels:
        app: esp-grpc-bookstore
    spec:
      serviceAccountName: test-espv2
</code>```

Since the gcr.io/endpoints-release/endpoints-runtime:2 is limited,
I created a test container and deployed it into the same eventing namespace.

Within the container, I'm able to retrieve the endpoint service config with the following command:

```<code>curl --fail -o "service.json" -H "Authorization: Bearer $(gcloud auth print-access-token)" \
 "https://servicemanagement.googleapis.com/v1/services/${SERVICE}/configs/${CONFIG_ID}?view=FULL"
</code>```

And also within the container, I'm running as the impersonated service account, tested with:

```<code>curl -H "Metadata-Flavor: Google" http://169.254.169.254/computeMetadata/v1/instance/service-accounts/
</code>```

Are there any other tests I can run to help me debug this issue?

Thanks in advance,

答:
I've finally figured out the issue. It was in 2 parts.

Redeployment of app, paying special attention and verification of the kubectl annotate serviceaccount commands

add-iam-policy-binding for both serviceController and cloudtrace.agent

omitting nodeSelector: iam.gke.io/gke-metadata-server-enabled: "true"  due to Autopilot

Doing this enabled a successful kube deployment as displayed by the logs.

Next error I had was

```<code><h1>Error: Server Error</h1>
<h2>The server encountered a temporary error and could not complete your request.<p>Please try again in 30 seconds.</h2>
</code>```

This was fixed by turning my attention back to my Kube cluster.
Looking through the events in my ingress service, since I was in a shared-vpc and my security policies only allowed firewall management from the host project, the deployment was failing to update the firewall rules.

Manually provisioning them, as shown here :

https://cloud.google.com/kubernetes-engine/docs/concepts/ingress#manually_provision_firewall_rules_from_the_host_project

solved my issues.

Body:
I'm following the Getting started with Endpoints for GKE with ESPv2. I'm using Workload Identity Federation and Autopilot on the GKE cluster.

I've been running into the error:

F0110 03:46:24.304229       8 server.go:54] fail to initialize config manager: http call to GET https://servicemanagement.googleapis.com/v1/services/name:bookstore.endpoints.<project>.cloud.goog/rollouts?filter=status=SUCCESS returns not 200 OK: 403 Forbidden

Which ultimately leads to a transport failure error and shut down of the Pod.

My first step was to investigate permission issues, but I could really use some outside perspective on this as I've been going around in circles on this.

Here's my config:

>> gcloud container clusters describe $GKE_CLUSTER_NAME \
--zone=$GKE_CLUSTER_ZONE \
--format='value[delimiter="\n"](nodePools[].config.oauthScopes)'

['https://www.googleapis.com/auth/devstorage.read_only',
'https://www.googleapis.com/auth/logging.write',
'https://www.googleapis.com/auth/monitoring',
'https://www.googleapis.com/auth/service.management.readonly',
'https://www.googleapis.com/auth/servicecontrol',
'https://www.googleapis.com/auth/trace.append']

>> gcloud container clusters describe $GKE_CLUSTER_NAME \
--zone=$GKE_CLUSTER_ZONE \
--format='value[delimiter="\n"](nodePools[].config.serviceAccount)'
default
default

Service-Account-Name: test-espv2

Roles

Cloud Trace Agent
Owner
Service Account Token Creator
Service Account User
Service Controller
Workload Identity User

I've associated the WIF svc-act with the Cluster with the following yaml

apiVersion: v1
kind: ServiceAccount
metadata:
  annotations:
    iam.gke.io/gcp-service-account: test-espv2@<project>.iam.gserviceaccount.com
  name: test-espv2
  namespace: eventing

And then I've associated the pod with the test-espv2 svc-act

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: esp-grpc-bookstore
  namespace: eventing
spec:
  replicas: 1
  selector:
    matchLabels:
      app: esp-grpc-bookstore
  template:
    metadata:
      labels:
        app: esp-grpc-bookstore
    spec:
      serviceAccountName: test-espv2

Since the gcr.io/endpoints-release/endpoints-runtime:2 is limited,
I created a test container and deployed it into the same eventing namespace.

Within the container, I'm able to retrieve the endpoint service config with the following command:

curl --fail -o "service.json" -H "Authorization: Bearer $(gcloud auth print-access-token)" \
 "https://servicemanagement.googleapis.com/v1/services/${SERVICE}/configs/${CONFIG_ID}?view=FULL"

And also within the container, I'm running as the impersonated service account, tested with:

curl -H "Metadata-Flavor: Google" http://169.254.169.254/computeMetadata/v1/instance/service-accounts/

Are there any other tests I can run to help me debug this issue?

Thanks in advance,

Body:
I've finally figured out the issue. It was in 2 parts.

Redeployment of app, paying special attention and verification of the kubectl annotate serviceaccount commands

add-iam-policy-binding for both serviceController and cloudtrace.agent

omitting nodeSelector: iam.gke.io/gke-metadata-server-enabled: "true"  due to Autopilot

Doing this enabled a successful kube deployment as displayed by the logs.

Next error I had was

<h1>Error: Server Error</h1>
<h2>The server encountered a temporary error and could not complete your request.<p>Please try again in 30 seconds.</h2>

This was fixed by turning my attention back to my Kube cluster.
Looking through the events in my ingress service, since I was in a shared-vpc and my security policies only allowed firewall management from the host project, the deployment was failing to update the firewall rules.

Manually provisioning them, as shown here :

https://cloud.google.com/kubernetes-engine/docs/concepts/ingress#manually_provision_firewall_rules_from_the_host_project

solved my issues.


问:
EF Core - Add Unique Constraint
I'd like to add unique constraint using model builder in ASP.NET Core

.NET 5

EF Core 5..

Here is what I found:

```<code>        modelBuilder.Entity<Ticker>()
            .HasIndex(r => r.Name)
            .IsUnique();
</code>```

However after updating database it adds index instead of constraint.
Is there the way to add constraint?
Thanks for the answer.

答:
Although you use .HasIndex(r => r.Name).IsUnique(),it will create a unique Index instead of Constraint. But the effect are the same. It will prevent you adding duplicated value for Name.

However after updating database it adds index instead of constraint. Is there the way to add constraint?

If you must add Constraint, I suggest you use HasAlternateKey method which enables you to create an alternate key by placing a unique constraint:

```<code>modelBuilder.Entity<Ticker>()
           .HasAlternateKey(r => r.Name);
</code>```

Then you can see it adds the unique constraint like below in database:

Title: EF Core - Add Unique Constraint

Body:
I'd like to add unique constraint using model builder in ASP.NET Core

.NET 5

EF Core 5..

Here is what I found:

        modelBuilder.Entity<Ticker>()
            .HasIndex(r => r.Name)
            .IsUnique();

However after updating database it adds index instead of constraint.
Is there the way to add constraint?
Thanks for the answer.

Body:
Although you use .HasIndex(r => r.Name).IsUnique(),it will create a unique Index instead of Constraint. But the effect are the same. It will prevent you adding duplicated value for Name.

However after updating database it adds index instead of constraint. Is there the way to add constraint?

If you must add Constraint, I suggest you use HasAlternateKey method which enables you to create an alternate key by placing a unique constraint:

modelBuilder.Entity<Ticker>()
           .HasAlternateKey(r => r.Name);

Then you can see it adds the unique constraint like below in database:


问:
error: index.js: Cannot find module 'babel-plugin-r' React Native
What I have Done to cause the Error:
I have a freshly installed Bare React Native Project . I wanted to use Drawer Navigation and had to install React Native Reanimated 2.3.0-alpha.2 .

what I have already tried to resolve the error

I have installed fresh bare react native project

Cleared Metro Cache

Tried to use Reanimated 2.0.0

I have Followed all the steps from https://www.reanimated2.com/docs/next/installation.

Error

BUNDLE  ./index.js

error: index.js: Cannot find module 'babel-plugin-r'
Require stack:

D:\Work\React Native\React Native with Node\healthapp\node_modules@babel\core\lib\config\files\plugins.js

D:\Work\React Native\React Native with Node\healthapp\node_modules@babel\core\lib\config\files\index.js

D:\Work\React Native\React Native with Node\healthapp\node_modules@babel\core\lib\index.js

D:\Work\React Native\React Native with Node\healthapp\node_modules\metro-transform-worker\src\index.js

D:\Work\React Native\React Native with Node\healthapp\node_modules\metro\src\DeltaBundler\Worker.js

D:\Work\React Native\React Native with Node\healthapp\node_modules\metro\node_modules\jest-worker\build\workers\processChild.js

答:
I hope you resolved this issue already. But just in case or someone else needs it in my case it was due to the Ellipsis(...) I left when I copied the this portion of code from the instructions:

```<code>module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
      ... //<---HERE Remove this
      'react-native-reanimated/plugin',
  ],
};
</code>```

https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation/

Body:
I hope you resolved this issue already. But just in case or someone else needs it in my case it was due to the Ellipsis(...) I left when I copied the this portion of code from the instructions:

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
      ... //<---HERE Remove this
      'react-native-reanimated/plugin',
  ],
};

https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation/


问:
How to merge different columns into a new one made with the merged columns' name
I'm trying to clean my dataset. The dataset comes from a survey that had a randomizer. It displayed different scenarios to each participant.
My dataset now has a column for each different scenario with the name I chose for it (e.g.: A_SM_GIL or D_DF_GIL etc.). The underscore "" separates the different scenarios variables that are combined together to form a new scenario. A, D_, B_, N_ are the timing for a disclosure message during the advertising, respectively AFTER, DURING, BEFORE,and NONEF. SM_, and DF_, stand for the type of terminology used. Respectively SYNTHETIC MEDIA, and DEEPFAKE. The last bit, LOR_, GIL_, describes the brand's ad. Respectively L'Oreal, Gillette.

What I am left now is a bunch of columns that show with a "1" the scenario each observation was exposed to before answering a 7point likert scale to measure their attitudes towards the ad shown. The scale used is called ADTEST (AD_) and has different items (BORING_1, IRRITATING_1, etc).

Only 1 scenario for observation is possible. So one observation will have a column with 1 and all the others with NAs.

My goal is to compare the different scenarios' attitudes. For example, studying if positioning the disclosure before the ad makes a difference than positioning it after the ad. I would like to plot the different answers (using a 7 point likert scale i.e.: AD_BORING_1 etc) people gave but divided into the different scenarios to compare them.

```<code>structure(list(D_DF_GIL = c(NA, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA, NA,
1, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA), A_SM_GIL = c(NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA), A_DF_GIL = c(NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, NA, NA, NA, NA, NA, 1, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, 1, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), N_DF_GILL = c(1,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
1, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA), AD_BORING_1 = c("7",
"6", "5", "3", "4", "3", "5", "2", "4", "5", "3", "2", "5", "3",
"4", "4", "5", "5", "1", "1", "4", "7", "4", "4", "3", "6", "1",
"5", "2", "5", "3", "2", "2", "7", "6", "6", "6", "5", "4", "4",
"6", "7", "3", "2", "1", "5", "5", "5", "5", "5", "6", "4", "5",
"3", "5", "2", "7", "5", "2", "2", "3", "1", "5", "5", "4", "5",
"1", "3", "2", "6", "5", "1", "3", "3", "5", "6", "5", "6", "2",
"3", "5", "6", "5", "4", "6", "5", "4", "3", "5", "5", "4", "6",
"2", "4", "6", "3", "4", "5", "3", "2", "6", "6", "5", "6", "3",
"2", "6", "5", "4", "2", "3", "6", "4", "7", "3", "1", "4", "4",
"5", "4", "2", "5", "6", "3", "5", "6", "4", "2", "5", "5", "3",
"2", "3", "1", "6", "2", "1", "5", "5", "2", "6", "1", "6", "5",
"2", "5", "2", "2", "4", "2", "2", "4", "4", "6", "3", "5", "5",
"3", "2", "4", "7", "4", "4", "2", "5", "3", "2", "3", "3", "4",
"2", "5", "6", "4", "4", "7", "4", "6", "3", "4", "2", "4", "3",
"2", "6", "5", "5", "5", "4", "2", "3", "3", "5", "5", "6", "6",
"7", "4", "2", "6", "3", "6", "4", "2", "7", "6", "4", "3", "2",
"5", "5", "6", "5", "2", "7", "2", "3", "5", "2", "3", "5", "5",
"5", "2", "4", "3", "5", "2", "3", "3", "2", "5", "5", "3", "3",
"5", "3", "2", "5", "3", "7", "5", "5", "5", "4", "2", "4", "2",
"3", "4", "5", "2", "5", "7", "6", "4", "5", "6", "3", "5", "3",
"2", "4", "5", "5", "3", "1", "4", "7", "5", "6", "3", "3", "4",
"5", "6", "5", "4", "1", "5", "2", "3", "7", "3", "4", "5", "3",
"3", "5", "5", "2", "5", "4", "5", "2", "6", "2", "6", "4", "2",
"3", "4", "6", "3", "2", "5", "2", "6", "2", "1", "3", "4", "1",
"2", "5", "4", "3", "7", "5", "6", "6", "3", "4", "2", "4", "5",
"2", "4", "3", "3", "2", "2", "3", "5", "3", "1", "3", "2", "2",
"4", "2", "2", "3", "1", "4", "2", "5", "2", "5", "5", "5", "2",
"5", "5", "4", "2", "7", "5", "5", "3", "4", "5", "3", "4", "3",
"2", "5"), AD_IRRITATING_1 = c("4", "7", "3", "5", "4", "3",
"4", "4", "4", "3", "4", "2", "2", "4", "1", "2", "1", "4", "1",
"1", "4", "7", "5", "4", "2", "2", "6", "4", "2", "5", "1", "2",
"2", "4", "2", "5", "4", "6", "4", "4", "7", "6", "3", "2", "1",
"4", "2", "2", "4", "2", "7", "5", "2", "5", "2", "2", "6", "2",
"5", "2", "2", "4", "6", "5", "4", "3", "2", "5", "1", "4", "2",
"2", "2", "2", "2", "4", "5", "3", "5", "5", "1", "4", "4", "5",
"4", "4", "4", "4", "4", "2", "2", "4", "2", "5", "7", "4", "5",
"3", "2", "1", "4", "6", "3", "6", "3", "2", "6", "2", "3", "2",
"2", "4", "2", "7", "3", "1", "4", "5", "2", "4", "1", "5", "5",
"5", "5", "6", "2", "3", "5", "5", "2", "2", "3", "2", "6", "2",
"1", "4", "2", "2", "5", "2", "2", "3", "2", "4", "2", "2", "2",
"2", "2", "4", "5", "5", "1", "5", "2", "5", "1", "2", "2", "4",
"5", "2", "4", "3", "2", "5", "2", "4", "2", "2", "4", "3", "5",
"5", "3", "3", "1", "5", "2", "5", "6", "3", "4", "2", "6", "4",
"4", "2", "2", "2", "2", "2", "4", "1", "6", "3", "2", "5", "1",
"4", "5", "2", "2", "2", "6", "1", "1", "2", "3", "5", "7", "5",
"7", "2", "3", "2", "3", "2", "1", "2", "5", "2", "4", "4", "6",
"2", "3", "3", "1", "5", "4", "4", "3", "4", "4", "2", "4", "4",
"5", "4", "6", "4", "4", "2", "5", "2", "2", "2", "7", "2", "3",
"6", "5", "3", "3", "6", "1", "6", "2", "2", "5", "4", "2", "4",
"1", "2", "4", "6", "4", "1", "2", "4", "2", "2", "4", "3", "1",
"2", "2", "4", "4", "3", "5", "2", "4", "4", "5", "5", "3", "5",
"4", "2", "2", "4", "5", "4", "2", "5", "2", "4", "3", "2", "1",
"2", "2", "6", "5", "2", "1", "2", "1", "3", "6", "4", "4", "6",
"3", "4", "4", "2", "2", "1", "4", "1", "2", "3", "2", "2", "5",
"2", "3", "7", "7", "3", "2", "2", "3", "3", "1", "5", "2", "1",
"4", "2", "5", "2", "5", "4", "4", "2", "5", "6", "2", "1", "2",
"4", "4", "2", "5", "2", "4", "2", "5", "2", "7")), row.names = c(NA,
-367L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

I was thinking I could create a new column made of the other columns' name if a condition is met (in this case the fact that a column has a 1 and not NA).

Something like this

Another problem is all around the dataset there are other columns, so I need to specify exactly the columns to analyze.

Thank you so much for your time.

答:
I'd do it like this:</p>
```<code>scenario_cols = df %>%
  select(D_DF_GIL:N_DF_GILL) %>%
  names

df$new_col = scenario_cols[apply(
  df[scenario_cols], 1,
  \(x) if(all(is.na(x))) NA else which.max(x)
)]
df$new_col
 #  [1] "N_DF_GILL" NA          NA          NA          "A_SM_GIL"  NA          NA          "D_DF_GIL"
 #  [9] "N_DF_GILL" NA          NA          NA          NA          "D_DF_GIL"  NA          NA
 # [17] NA          NA          NA          NA          NA          NA          NA          NA
 # [25] NA          NA          NA          NA          NA          NA          "N_DF_GILL" NA
 # [33] "A_DF_GIL"  NA          NA          "A_SM_GIL"  NA          NA          NA          "A_SM_GIL"
 # ...
</code>```

Body:
I'm trying to clean my dataset. The dataset comes from a survey that had a randomizer. It displayed different scenarios to each participant.
My dataset now has a column for each different scenario with the name I chose for it (e.g.: A_SM_GIL or D_DF_GIL etc.). The underscore "" separates the different scenarios variables that are combined together to form a new scenario. A, D_, B_, N_ are the timing for a disclosure message during the advertising, respectively AFTER, DURING, BEFORE,and NONEF. SM_, and DF_, stand for the type of terminology used. Respectively SYNTHETIC MEDIA, and DEEPFAKE. The last bit, LOR_, GIL_, describes the brand's ad. Respectively L'Oreal, Gillette.

What I am left now is a bunch of columns that show with a "1" the scenario each observation was exposed to before answering a 7point likert scale to measure their attitudes towards the ad shown. The scale used is called ADTEST (AD_) and has different items (BORING_1, IRRITATING_1, etc).

Only 1 scenario for observation is possible. So one observation will have a column with 1 and all the others with NAs.

My goal is to compare the different scenarios' attitudes. For example, studying if positioning the disclosure before the ad makes a difference than positioning it after the ad. I would like to plot the different answers (using a 7 point likert scale i.e.: AD_BORING_1 etc) people gave but divided into the different scenarios to compare them.

structure(list(D_DF_GIL = c(NA, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA, NA,
1, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA), A_SM_GIL = c(NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA), A_DF_GIL = c(NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, NA, NA, NA, NA, NA, 1, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, 1, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), N_DF_GILL = c(1,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
1, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA), AD_BORING_1 = c("7",
"6", "5", "3", "4", "3", "5", "2", "4", "5", "3", "2", "5", "3",
"4", "4", "5", "5", "1", "1", "4", "7", "4", "4", "3", "6", "1",
"5", "2", "5", "3", "2", "2", "7", "6", "6", "6", "5", "4", "4",
"6", "7", "3", "2", "1", "5", "5", "5", "5", "5", "6", "4", "5",
"3", "5", "2", "7", "5", "2", "2", "3", "1", "5", "5", "4", "5",
"1", "3", "2", "6", "5", "1", "3", "3", "5", "6", "5", "6", "2",
"3", "5", "6", "5", "4", "6", "5", "4", "3", "5", "5", "4", "6",
"2", "4", "6", "3", "4", "5", "3", "2", "6", "6", "5", "6", "3",
"2", "6", "5", "4", "2", "3", "6", "4", "7", "3", "1", "4", "4",
"5", "4", "2", "5", "6", "3", "5", "6", "4", "2", "5", "5", "3",
"2", "3", "1", "6", "2", "1", "5", "5", "2", "6", "1", "6", "5",
"2", "5", "2", "2", "4", "2", "2", "4", "4", "6", "3", "5", "5",
"3", "2", "4", "7", "4", "4", "2", "5", "3", "2", "3", "3", "4",
"2", "5", "6", "4", "4", "7", "4", "6", "3", "4", "2", "4", "3",
"2", "6", "5", "5", "5", "4", "2", "3", "3", "5", "5", "6", "6",
"7", "4", "2", "6", "3", "6", "4", "2", "7", "6", "4", "3", "2",
"5", "5", "6", "5", "2", "7", "2", "3", "5", "2", "3", "5", "5",
"5", "2", "4", "3", "5", "2", "3", "3", "2", "5", "5", "3", "3",
"5", "3", "2", "5", "3", "7", "5", "5", "5", "4", "2", "4", "2",
"3", "4", "5", "2", "5", "7", "6", "4", "5", "6", "3", "5", "3",
"2", "4", "5", "5", "3", "1", "4", "7", "5", "6", "3", "3", "4",
"5", "6", "5", "4", "1", "5", "2", "3", "7", "3", "4", "5", "3",
"3", "5", "5", "2", "5", "4", "5", "2", "6", "2", "6", "4", "2",
"3", "4", "6", "3", "2", "5", "2", "6", "2", "1", "3", "4", "1",
"2", "5", "4", "3", "7", "5", "6", "6", "3", "4", "2", "4", "5",
"2", "4", "3", "3", "2", "2", "3", "5", "3", "1", "3", "2", "2",
"4", "2", "2", "3", "1", "4", "2", "5", "2", "5", "5", "5", "2",
"5", "5", "4", "2", "7", "5", "5", "3", "4", "5", "3", "4", "3",
"2", "5"), AD_IRRITATING_1 = c("4", "7", "3", "5", "4", "3",
"4", "4", "4", "3", "4", "2", "2", "4", "1", "2", "1", "4", "1",
"1", "4", "7", "5", "4", "2", "2", "6", "4", "2", "5", "1", "2",
"2", "4", "2", "5", "4", "6", "4", "4", "7", "6", "3", "2", "1",
"4", "2", "2", "4", "2", "7", "5", "2", "5", "2", "2", "6", "2",
"5", "2", "2", "4", "6", "5", "4", "3", "2", "5", "1", "4", "2",
"2", "2", "2", "2", "4", "5", "3", "5", "5", "1", "4", "4", "5",
"4", "4", "4", "4", "4", "2", "2", "4", "2", "5", "7", "4", "5",
"3", "2", "1", "4", "6", "3", "6", "3", "2", "6", "2", "3", "2",
"2", "4", "2", "7", "3", "1", "4", "5", "2", "4", "1", "5", "5",
"5", "5", "6", "2", "3", "5", "5", "2", "2", "3", "2", "6", "2",
"1", "4", "2", "2", "5", "2", "2", "3", "2", "4", "2", "2", "2",
"2", "2", "4", "5", "5", "1", "5", "2", "5", "1", "2", "2", "4",
"5", "2", "4", "3", "2", "5", "2", "4", "2", "2", "4", "3", "5",
"5", "3", "3", "1", "5", "2", "5", "6", "3", "4", "2", "6", "4",
"4", "2", "2", "2", "2", "2", "4", "1", "6", "3", "2", "5", "1",
"4", "5", "2", "2", "2", "6", "1", "1", "2", "3", "5", "7", "5",
"7", "2", "3", "2", "3", "2", "1", "2", "5", "2", "4", "4", "6",
"2", "3", "3", "1", "5", "4", "4", "3", "4", "4", "2", "4", "4",
"5", "4", "6", "4", "4", "2", "5", "2", "2", "2", "7", "2", "3",
"6", "5", "3", "3", "6", "1", "6", "2", "2", "5", "4", "2", "4",
"1", "2", "4", "6", "4", "1", "2", "4", "2", "2", "4", "3", "1",
"2", "2", "4", "4", "3", "5", "2", "4", "4", "5", "5", "3", "5",
"4", "2", "2", "4", "5", "4", "2", "5", "2", "4", "3", "2", "1",
"2", "2", "6", "5", "2", "1", "2", "1", "3", "6", "4", "4", "6",
"3", "4", "4", "2", "2", "1", "4", "1", "2", "3", "2", "2", "5",
"2", "3", "7", "7", "3", "2", "2", "3", "3", "1", "5", "2", "1",
"4", "2", "5", "2", "5", "4", "4", "2", "5", "6", "2", "1", "2",
"4", "4", "2", "5", "2", "4", "2", "5", "2", "7")), row.names = c(NA,
-367L), class = c("tbl_df", "tbl", "data.frame"))

I was thinking I could create a new column made of the other columns' name if a condition is met (in this case the fact that a column has a 1 and not NA).

Something like this

Another problem is all around the dataset there are other columns, so I need to specify exactly the columns to analyze.

Thank you so much for your time.

Body:
I'd do it like this:

scenario_cols = df %>%
  select(D_DF_GIL:N_DF_GILL) %>%
  names

df$new_col = scenario_cols[apply(
  df[scenario_cols], 1,
  \(x) if(all(is.na(x))) NA else which.max(x)
)]
df$new_col
 #  [1] "N_DF_GILL" NA          NA          NA          "A_SM_GIL"  NA          NA          "D_DF_GIL"
 #  [9] "N_DF_GILL" NA          NA          NA          NA          "D_DF_GIL"  NA          NA
 # [17] NA          NA          NA          NA          NA          NA          NA          NA
 # [25] NA          NA          NA          NA          NA          NA          "N_DF_GILL" NA
 # [33] "A_DF_GIL"  NA          NA          "A_SM_GIL"  NA          NA          NA          "A_SM_GIL"
 # ...


问:
PHP Multidimensional Array Length
This is a multidimensional PHP array.

```<code>$stdnt = array(
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94),
);
</code>```

I can find out the length of the array. That means

```<code>count($stdnt); // output is 4

[
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94)
] `
</code>```

But can't get the internal array length.

How can I ?

答:
```<code>  // You may try as per this sample

  $cars=array(
    array("volvo",43,56),
    array("bmw",54,678)
  );
  $mySubSize=sizeof($cars);
  for ($i=0;$i<$mySubSize;$i++) {
    foreach ($cars[$i] as $value) {
      echo "$value <br>";
    }
  }
</code>```

Title: PHP Multidimensional Array Length

Body:
This is a multidimensional PHP array.

$stdnt = array(
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94),
);

I can find out the length of the array. That means

count($stdnt); // output is 4

[
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94)
] `

But can't get the internal array length.

How can I ?


问:
Why does python say that there is an attribute error for cvzone.Classifier()
I am trying to make object recognition in python and I am having this error message come up when I run my code:

```<code>AttributeError: module 'cvzone' has no attribute 'Classifier'
</code>```

This is my code:

```<code>import cvzone
import cv2

cap = cv2.VideoCapture(0)
myClassifier = cvzone.Classifier('converted_keras/keras_model.h5','converted_keras/labels.txt')
</code>```

Can anyone help?

答:
Try this

from cvzone.ClassificationModule import Classifier

Then

myClassifier = Classifier('converted_keras/keras_model.h5','converted_keras/labels.txt')

Body:
I am trying to make object recognition in python and I am having this error message come up when I run my code:

AttributeError: module 'cvzone' has no attribute 'Classifier'

This is my code:

import cvzone
import cv2

cap = cv2.VideoCapture(0)
myClassifier = cvzone.Classifier('converted_keras/keras_model.h5','converted_keras/labels.txt')

Can anyone help?