问:
How to make header urls independent?
I have urls.py

```<code>urlpatterns = [
        path('video/<int:video_n>', views.video_detail, name='video_detail'),
        path('mylink1', views.mylink1, name = 'mylink1'),
    ]
</code>```

It's ok for my url mysite.com/video/12345

I have nav bar in header video_detail.html

```<code><header>
  <ul>
    <li>
      <a href="mylink1">link 1</a>
    </li>
  </ul>
</header>
</code>```

I want only links from header navbar (link 1) redirects to mysite.com/mylink1

But django engine redirects me to mysite.com/video/mylink1

How to avoid wrong redirect or make nav url independent?

答:
Well, you used didn't give the url by name, you gave string mylink1. So,

```<code><a href="{% url 'mylink1' %}">link 1</a>
</code>```

Title: How to make header urls independent?

Body:
I have urls.py

urlpatterns = [
        path('video/<int:video_n>', views.video_detail, name='video_detail'),
        path('mylink1', views.mylink1, name = 'mylink1'),
    ]

It's ok for my url mysite.com/video/12345

I have nav bar in header video_detail.html

      link 1

I want only links from header navbar (link 1) redirects to mysite.com/mylink1

But django engine redirects me to mysite.com/video/mylink1

How to avoid wrong redirect or make nav url independent?

Body:
Well, you used didn't give the url by name, you gave string mylink1. So,

<a href="{% url 'mylink1' %}">link 1</a>


来源: stackexchange

问:
printing of xml
I want to print the array into xml format but i am unable to print it.
Here is the code

```<code>if(!empty($recordsArray)){
print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>");
print("<joblist>\n");
foreach ($recordsArray as $data){
</code>```

print("".$data['user_id']."".$data['$task_id']."\n");

```<code>}
print("</joblist>\n");

}
}
</code>```

even i am unable to see

```<code><?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>
</code>```

when i am doing view source its showing

```<code><?xml version="1.0" encoding="UTF-8" ?>
<joblist>
<job><id>123</id><taskid>14</taskid></job>
</joblist>
</code>```

now what to be done to display on the web page

答: When I'm debugging and need to write xml to a browser I usually put it in a <textarea>.  You need to print the results into a container that will display html tokens like < and > literally, or go through your string and convert them all to entities.

ContentLicense: CC BY-SA 3.0

Title: printing of xml

Body:
I want to print the array into xml format but i am unable to print it.
Here is the code

if(!empty($recordsArray)){
print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>");
print("<joblist>\n");
foreach ($recordsArray as $data){

print("".$data['user_id']."".$data['$task_id']."\n");

}
print("</joblist>\n");

}
}

even i am unable to see

<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>

when i am doing view source its showing

<?xml version="1.0" encoding="UTF-8" ?>
<joblist>
<job><id>123</id><taskid>14</taskid></job>
</joblist>

now what to be done to display on the web page


问:
How to count the numbers where the absolute value is greater than a cutoff with COUNTIFS in Excel?
I have the following numbers 12,34,-15,-23,-5,45,-50 and would like to find the count of numbers where the abs(x)>=15, which in this case is 5 Is this possible with the use of COUNTIFS ? </p>

答:
Based on the inputs, following formulas can be used

=SUMPRODUCT((ABS(A2:A8)>=15)+0)

and COUNTIFS implementation would be as below

=COUNTIFS(A2:A8,">=15")+COUNTIFS(A2:A8,"<=-15")

=SUM(COUNTIFS(A2:A8,{">=15","<=-15"}))

As COUNTIFS requires range as input and therefore any math operation is not possible!

ContentLicense: CC BY-SA 4.0


问:
How to add a class to a given element?
I have an element that already has a class:

```

Now, I want to create a JavaScript function that will add a class to the div (not replace, but add).

How can I do that?

答:
```<code>document.getElementById('some_id').className+='  someclassname'
</code>```

OR:

```<code>document.getElementById('some_id').classList.add('someclassname')
</code>```

First approach helped in adding the class when second approach didn't work.

Don't forget to keep a space in front of the ' someclassname' in the first approach.

For removal you can use:

```<code>document.getElementById('some_id').classList.remove('someclassname')
</code>```

OwnerDisplayName: Blankman

Title: How to add a class to a given element?

Body:
I have an element that already has a class:

Now, I want to create a JavaScript function that will add a class to the div (not replace, but add).

How can I do that?

Body:
document.getElementById('some_id').className+='  someclassname'

OR:

document.getElementById('some_id').classList.add('someclassname')

First approach helped in adding the class when second approach didn't work.

Don't forget to keep a space in front of the ' someclassname' in the first approach.

For removal you can use:

document.getElementById('some_id').classList.remove('someclassname')


问:
Passing Class objects to Drools Rules (drt) file
I'm using Drools  Template for decision making, I have created instance of class and passed the class objects to Kie session using insert

In the drt file, I tried to compare the Template columns with Class objects and certain parameters have passed threshold , then setting the Priority based on the value in the Template file

Format of the Template file (Excel)

```<code>Parameter     Mountpoint       Threshold      Severity
Disk            /root           80              MINOR
Disk            /tmp            90              MAJOR

My class Capacity {

private String component;
private String subComponent;
privat Integer value;

public String getComponent() {
            return component;
        }
        public void setComponent(String component) {
            this.component = component;
        }
        public String getSubComponent() {
            return subComponent;
        }
        public void setSubComponent(String subComponent) {
            this.subComponent = subComponent;
        }
        public Integer getValue() {
            return value;
        }
        public void setValue(Integer value) {
            this.value = value;
        }

public Capacity()
        {
            super();
            this.component = component;
            this.subComponent = subComponent;
            this.value = value;
        }

}
</code>```

In another class, I'm initiating KieSession and injecting the capacity Class objects and loads the Templates file
Drool

```<code>        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );
    try {
        loadRuleTemplate(DATA_FILE, RULE_TEMPLATE_FILE, "OperationalMeasurement", 2, 1);
    } catch (IOException errorMsg) {
        log.error(errorMsg.getMessage());       }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSession kieSession =  kbase.newKieSession(sessionConfig, null);
    sessionClock = ksession.getSessionClock();
    ksession.insert(Capacity);
    ksession.fireAllRules();
    ksession.dispose();
</code>```

Rules file

```<code>template header
Parameter
Mountpoint
Threshold
Severity

package com.test.drools;

dialect "java"

template "OperationalMeasurement"

rule "Check_Threshold_@{row.rowNumber}"
ruleflow-group "capacityManagement"
salience 500
when
   $capacity: Capacity(component == "@{Parameter}" && subComponent == "@{Mountpoint}" && value >= "@{Threshold}")
  then
    System.out.println("Thresold cross for Component and Priority is set " + @{Severity}");
end
end template
</code>```

When i run this, component is treated as literal string instead of Capacity class variable and though i dont get any error , it simply prints all the contents of the drt file in the console.
And I dont seems to get the Sysout statements

答:
component is treated as literal string instead of Capacity class variable

Not sure what you mean by that. what "component" is being treated as a literal?

According to the generated rule you added as a comment, there are some errors in the rules being generated:

```<code>    System.out.println("Thresold crossed for Component::" +component + " and Priority is set " + Major");
</code>```

In the line above, "component" is expected to be a variable, but there is no variable with that name. There is also a missing quote before the "Major" string.
I would suggest you to change your template to something like this:

```<code>rule "Check_Threshold_@{row.rowNumber}"
ruleflow-group "capacityManagement"
salience 500
when
   $capacity: Capacity(component == "@{Parameter}" && subComponent == "@{Mountpoint}" && value >= "@{Threshold}")
  then
    System.out.println("Threshold cross for Component:: @{Parameter} and Priority is set to @{Severity}");
end
end template
</code>```

That should generate valid DRL.

One other thing that worth mentioning is that for some weird reason that I never fully understood, Drools will not complain if there are errors in your Knowledge Bases (i.e. errors in the DRL files). You have to check for errors by yourself before using a Knowledge Base. The KnowledgeBuilder class has a hasErrors() method and a getResults() methods that you can use to check for errors. If you are using a KieContainer, then you have a verify() method you can use. How are you loading your DRL into the KieBase?

Hope it helps,

Body:
I'm using Drools  Template for decision making, I have created instance of class and passed the class objects to Kie session using insert

In the drt file, I tried to compare the Template columns with Class objects and certain parameters have passed threshold , then setting the Priority based on the value in the Template file

Format of the Template file (Excel)

Parameter     Mountpoint       Threshold      Severity
Disk            /root           80              MINOR
Disk            /tmp            90              MAJOR

My class Capacity {

private String component;
private String subComponent;
privat Integer value;

public String getComponent() {
            return component;
        }
        public void setComponent(String component) {
            this.component = component;
        }
        public String getSubComponent() {
            return subComponent;
        }
        public void setSubComponent(String subComponent) {
            this.subComponent = subComponent;
        }
        public Integer getValue() {
            return value;
        }
        public void setValue(Integer value) {
            this.value = value;
        }

public Capacity()
        {
            super();
            this.component = component;
            this.subComponent = subComponent;
            this.value = value;
        }

}

In another class, I'm initiating KieSession and injecting the capacity Class objects and loads the Templates file
Drool

        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );
    try {
        loadRuleTemplate(DATA_FILE, RULE_TEMPLATE_FILE, "OperationalMeasurement", 2, 1);
    } catch (IOException errorMsg) {
        log.error(errorMsg.getMessage());       }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSession kieSession =  kbase.newKieSession(sessionConfig, null);
    sessionClock = ksession.getSessionClock();
    ksession.insert(Capacity);
    ksession.fireAllRules();
    ksession.dispose();

Rules file

template header
Parameter
Mountpoint
Threshold
Severity

package com.test.drools;

dialect "java"

template "OperationalMeasurement"

rule "Check_Threshold_@{row.rowNumber}"
ruleflow-group "capacityManagement"
salience 500
when
   $capacity: Capacity(component == "@{Parameter}" && subComponent == "@{Mountpoint}" && value >= "@{Threshold}")
  then
    System.out.println("Thresold cross for Component and Priority is set " + @{Severity}");
end
end template

When i run this, component is treated as literal string instead of Capacity class variable and though i dont get any error , it simply prints all the contents of the drt file in the console.
And I dont seems to get the Sysout statements

Body:
component is treated as literal string instead of Capacity class variable

Not sure what you mean by that. what "component" is being treated as a literal?

According to the generated rule you added as a comment, there are some errors in the rules being generated:

    System.out.println("Thresold crossed for Component::" +component + " and Priority is set " + Major");

In the line above, "component" is expected to be a variable, but there is no variable with that name. There is also a missing quote before the "Major" string.
I would suggest you to change your template to something like this:

rule "Check_Threshold_@{row.rowNumber}"
ruleflow-group "capacityManagement"
salience 500
when
   $capacity: Capacity(component == "@{Parameter}" && subComponent == "@{Mountpoint}" && value >= "@{Threshold}")
  then
    System.out.println("Threshold cross for Component:: @{Parameter} and Priority is set to @{Severity}");
end
end template

That should generate valid DRL.

One other thing that worth mentioning is that for some weird reason that I never fully understood, Drools will not complain if there are errors in your Knowledge Bases (i.e. errors in the DRL files). You have to check for errors by yourself before using a Knowledge Base. The KnowledgeBuilder class has a hasErrors() method and a getResults() methods that you can use to check for errors. If you are using a KieContainer, then you have a verify() method you can use. How are you loading your DRL into the KieBase?

Hope it helps,


问:
Vue Warning when passing data from blade template to vue
I'm getting this error from vue

[Vue warn]: Property or method "product" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

I'm not sure where I went wrong to get that error. Here is my code

Home.vue

```<code><template>
    <div class="container">
        <h1>This is the product page</h1>
    </div>
</template>

<script>
    export default {
        props: ['product'],

        data() {
          return {

          }
        },
        mounted() {
            console.log(this.product);
        }
    }
</script>
</code>```

and this is my product.blade.php

```<code><div class="row">
    <div class="col-md-12 mt-5">
        <div id="app">
            <home :product="product"></home>
        </div>
    </div>
</div>
</code>```

and this is in my ProductsController

```<code>public function show(Product $product)
{
    return view('welcome', [
        'product' => $product
    ]);
}
</code>```

答:
```<code><home :product="{{ $product }}"></home>
</code>```

The product is coming from the your controller and to use it in blade, you have to use {{ }}

Body:
I'm getting this error from vue

[Vue warn]: Property or method "product" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

I'm not sure where I went wrong to get that error. Here is my code

Home.vue

<template>

This is the product page

</template>

and this is my product.blade.php

            <home :product="product"></home>

and this is in my ProductsController

public function show(Product $product)
{
    return view('welcome', [
        'product' => $product
    ]);
}

Body:
<home :product="{{ $product }}"></home>

The product is coming from the your controller and to use it in blade, you have to use {{ }}


问:
Hello everyone, I need help, for react native launch icon
I am struggling to keep it uniform in my android mobile and android tablet. I am placing my android icon in assets/logo.png and then creating other icons for all devices using react-native set-icon --path  --background  --platform
I don't know why the app icon on the tablet is without a corner radius whereas on mobile it is okay!

Tablet version

Mobile version

It will be great if anyone can help me??
Thanks

答:
You probably missed an asset for the tablet's target DPI. I would recommend you use android studio to generate appropriate assets.

documentation

open project in android studio

Right-click the res folder and select New > Image Asset

set Icon type to "Launcher icons"

customize and save


问:
iPhone address book external change call back
I'm developing app with using of native address book. I've registered a callback to receive a notification when address book has changed externally.

```<code>ABAddressBookRegisterExternalChangeCallback(myAddrrbook, changefunction, self)
</code>```

My app can make new records inside AddressBook, to do it I'm using ABNewPersonViewController like that:

```<code>ABNewPersonViewController *controller = [[ABNewPersonViewController alloc] init];

controller.addressBook = myAddrrbook;
</code>```

The problem is, that I still receiving notifications when I using my own app like it changed somewhere else.
But when I run on the simulator, everything is OK and no notification sent when I adding a contact.
How to avoid receiving notification on device?

Does anybody had face such problem?

答:
The callback will be called whenever ANY app (including yours) modifies the device AddressBook.  According to the Apple docs:

ABAddressBookRegisterExternalChangeCallback

Registers a callback to receive notifications when the Address Book
  database is modified.

(Found on the apple developer site)

In this case, the word "External" in the callback is probably best thought of as "external to the device's own address book handling code", not "external to my app"

As far as I know, the only way to filter out changes your app makes would be to set a flag before making any changes locally, and then check the flag in the callback (although that has potential for race conditions, it shouldn't be a major issue on an iPhone in most use cases)

Body:
I'm developing app with using of native address book. I've registered a callback to receive a notification when address book has changed externally.

ABAddressBookRegisterExternalChangeCallback(myAddrrbook, changefunction, self)

My app can make new records inside AddressBook, to do it I'm using ABNewPersonViewController like that:

ABNewPersonViewController *controller = [[ABNewPersonViewController alloc] init];

controller.addressBook = myAddrrbook;

The problem is, that I still receiving notifications when I using my own app like it changed somewhere else.
But when I run on the simulator, everything is OK and no notification sent when I adding a contact.
How to avoid receiving notification on device?

Does anybody had face such problem?


问:
Angular 8 Typescript How to set value of export const from another component?
I would like to change the value of the variable named bdg_m_1 from an another component. I am able to change the value of bdg_m_1 from the same typescript file.. Here is my code..

Filename : nav.ts

```<code>var bdg_m_1:string = "10" ; // HOW TO CHANGE THIS VALUE FROM ANOTHER COMPONENT

export const navItems: INavData[] = [
  {
    name: "Menu 1",
    url: "/menu_1",
    icon: "icon-speedometer",
     badge: {
       variant: 'info',
       text: bdg_m_1,
     }
  },
];
</code>```

答:
What you actually want to do, is to manage your application's (global) state.

Option 1: Using nested components

In case you have a parent- and a child-component, just use EventEmitters. Could look like:

nav.ts

```<code>export enum MenuName = {
  Menu1 = 'Menu 1',
  Menu2 = 'Menu 2'
}

export const navItems: INavData[] = [
  {
    name: MenuItem.Menu1,
    ...
  },
];
</code>```

child.component.ts

```<code>@Output() badgeChange = new EventEmitter<{menuName: MenuName, value: string}>();

private updateBadge(menuName: MenuName, value: string) {
  this.badgeChange.next({menuName, value});
}
</code>```

and listen to the change in your parents HTML: <app-child (badeChange)="onBadgeChanged($event)"></app-child> and in TS:

```<code>onBadgeChanged(change: {menuName: MenuName, value: string}): void {
  // find menu item by `change.menuName`
  // update it's badge value
}
</code>```

Option 2: Use a service for global state

If your global state is simple, you can also use a service for your state:

nav-service.ts

```<code>export class NavService {
  navData$ = new BehaviourSubject<INavData[]>([
    {
      name: "Menu 1",
      ...
    },
  ]);

  updateBadge(menuItemName: string, value: string): void {
    // find menu item by `menuItemName` in `this.navData$.value`
    const menuItem = ...;
    if (menuItem) {
      menuItem.badge.text = value;
      this.navData$.next([...this.navData$.value]); // emit new nav data
    }
  }
}
</code>```

In this case, your menu-component would listen to changes of this.navService.navData$ and the component or service which updates the data, uses this.navService.updateBadge(...) to tell everyone that the value has changed.

Option 3: Use a state management library

If your state is more complex than just a menu, I would suggest to use a state library such as NgRx, NgXs or Akita. Follow the links to learn more about them, I use NgRx for my projects. The idea is similar to using an own service for state, except the entire state is kept in one state-object and more sophisticated concepts are introduces by these libraries.

Body:
I would like to change the value of the variable named bdg_m_1 from an another component. I am able to change the value of bdg_m_1 from the same typescript file.. Here is my code..

Filename : nav.ts

var bdg_m_1:string = "10" ; // HOW TO CHANGE THIS VALUE FROM ANOTHER COMPONENT

export const navItems: INavData[] = [
  {
    name: "Menu 1",
    url: "/menu_1",
    icon: "icon-speedometer",
     badge: {
       variant: 'info',
       text: bdg_m_1,
     }
  },
];

Body:
What you actually want to do, is to manage your application's (global) state.

Option 1: Using nested components

In case you have a parent- and a child-component, just use EventEmitters. Could look like:

nav.ts

export enum MenuName = {
  Menu1 = 'Menu 1',
  Menu2 = 'Menu 2'
}

export const navItems: INavData[] = [
  {
    name: MenuItem.Menu1,
    ...
  },
];

child.component.ts

@Output() badgeChange = new EventEmitter<{menuName: MenuName, value: string}>();

private updateBadge(menuName: MenuName, value: string) {
  this.badgeChange.next({menuName, value});
}

and listen to the change in your parents HTML: <app-child (badeChange)="onBadgeChanged($event)"></app-child> and in TS:

onBadgeChanged(change: {menuName: MenuName, value: string}): void {
  // find menu item by `change.menuName`
  // update it's badge value
}

Option 2: Use a service for global state

If your global state is simple, you can also use a service for your state:

nav-service.ts

export class NavService {
  navData$ = new BehaviourSubject<INavData[]>([
    {
      name: "Menu 1",
      ...
    },
  ]);

  updateBadge(menuItemName: string, value: string): void {
    // find menu item by `menuItemName` in `this.navData$.value`
    const menuItem = ...;
    if (menuItem) {
      menuItem.badge.text = value;
      this.navData$.next([...this.navData$.value]); // emit new nav data
    }
  }
}

In this case, your menu-component would listen to changes of this.navService.navData$ and the component or service which updates the data, uses this.navService.updateBadge(...) to tell everyone that the value has changed.

Option 3: Use a state management library

If your state is more complex than just a menu, I would suggest to use a state library such as NgRx, NgXs or Akita. Follow the links to learn more about them, I use NgRx for my projects. The idea is similar to using an own service for state, except the entire state is kept in one state-object and more sophisticated concepts are introduces by these libraries.


问:
MapStruct - @Mapper annotation don't create bean
I downloaded application from this source https://github.com/springframeworkguru/spring5-mvc-rest/tree/vendor-api
And I have a problem with MapStruct.

```<code>@Mapper
public interface CategoryMapper {

CategoryMapper INSTANCE = Mappers.getMapper(CategoryMapper.class);

CategoryDTO categoryToCategoryDTO(Category category);
</code>```

}

```<code>@Data
public class CategoryDTO {
    private Long id;
    private String name;
}
</code>```

domain class:

```<code>@Data
@Entity
public class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}
</code>```

Service class:

```<code>@Service
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;
    private final CategoryRepository categoryRepository;

    public CategoryServiceImpl(CategoryMapper categoryMapper, CategoryRepository categoryRepository) {
        this.categoryMapper = categoryMapper;
        this.categoryRepository = categoryRepository;
    }
}
</code>```

And in pom.xml dependency, I paste only two::

```<code><properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <org.mapstruct.version>1.2.0.CR2</org.mapstruct.version>
</properties>
<dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct-jdk8</artifactId>
        <version>${org.mapstruct.version}</version>
</dependency>
</code>```

And plugin:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <annotationProcessorPaths>
            <path>
                 <groupId>org.projectlombok</groupId>
                 <artifactId>lombok</artifactId>
                 <version>${lombok.version}</version>
            </path>
            <path>
                 <groupId>org.mapstruct</groupId>
                 <artifactId>mapstruct-processor</artifactId>
                 <version>${org.mapstruct.version}</version>
           </path>
        </annotationProcessorPaths>
        <compilerArgs>
           <compilerArg>
                 -Amapstruct.defaultComponentModel=spring
           </compilerArg>
        </compilerArgs>
    </configuration>
</plugin>
</code>```

Description:

```<code>Parameter 0 of constructor in
guru.springfamework.services.CategoryServiceImpl required a bean of type 'guru.springfamework.api.v1.mapper.CategoryMapper' that could not be found.
</code>```

Action:

```<code>Consider defining a bean of type 'guru.springfamework.api.v1.mapper.CategoryMapper' in your configuration.
</code>```

I think that in my Intellij annotation @Mapper don't create a bean for mapper.
I didn't change code from John GitHub.
Any idea?
I tried to change path generated source to target but this doesn't help
Thanks for help.

答:
You first have to use the Mapper like this

```<code>To use mappers as beans and use **@Autowired**,
just declare mappers as @Mapper(componentModel = "spring").
Then just inject it wherever you need this.
</code>```

Also every time you create a new mapper class always remember to do mvn clean install.

It will create the implementation file of you mapper interface in the target folder and then you can run your Spring project.

Body:
I downloaded application from this source https://github.com/springframeworkguru/spring5-mvc-rest/tree/vendor-api
And I have a problem with MapStruct.

@Mapper
public interface CategoryMapper {

CategoryMapper INSTANCE = Mappers.getMapper(CategoryMapper.class);

CategoryDTO categoryToCategoryDTO(Category category);

}

@Data
public class CategoryDTO {
    private Long id;
    private String name;
}

domain class:

@Data
@Entity
public class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

Service class:

@Service
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;
    private final CategoryRepository categoryRepository;

    public CategoryServiceImpl(CategoryMapper categoryMapper, CategoryRepository categoryRepository) {
        this.categoryMapper = categoryMapper;
        this.categoryRepository = categoryRepository;
    }
}

And in pom.xml dependency, I paste only two::

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <org.mapstruct.version>1.2.0.CR2</org.mapstruct.version>
</properties>
<dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct-jdk8</artifactId>
        <version>${org.mapstruct.version}</version>
</dependency>

And plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <annotationProcessorPaths>
            <path>
                 <groupId>org.projectlombok</groupId>
                 <artifactId>lombok</artifactId>
                 <version>${lombok.version}</version>
            </path>
            <path>
                 <groupId>org.mapstruct</groupId>
                 <artifactId>mapstruct-processor</artifactId>
                 <version>${org.mapstruct.version}</version>
           </path>
        </annotationProcessorPaths>
        <compilerArgs>
           <compilerArg>
                 -Amapstruct.defaultComponentModel=spring
           </compilerArg>
        </compilerArgs>
    </configuration>
</plugin>

Description:

Parameter 0 of constructor in
guru.springfamework.services.CategoryServiceImpl required a bean of type 'guru.springfamework.api.v1.mapper.CategoryMapper' that could not be found.

Action:

Consider defining a bean of type 'guru.springfamework.api.v1.mapper.CategoryMapper' in your configuration.

I think that in my Intellij annotation @Mapper don't create a bean for mapper.
I didn't change code from John GitHub.
Any idea?
I tried to change path generated source to target but this doesn't help
Thanks for help.

Body:
You first have to use the Mapper like this

To use mappers as beans and use **@Autowired**,
just declare mappers as @Mapper(componentModel = "spring").
Then just inject it wherever you need this.

Also every time you create a new mapper class always remember to do mvn clean install.

It will create the implementation file of you mapper interface in the target folder and then you can run your Spring project.


问:
How to check if consecutive digits in a number are even or odd?
I am doing some exercises and learning Python. I need to be able to check for an input number whether its consecutive digits are even or odd. So, if the first number is odd, the next should be even and so on in order for the terms to comply. I have the following code:

```<code>def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    cifre = cifre[::-1]
    ind = cifre[0]
    for broj in cifre:
        if cifre[0] % 2 == 0:
            # for br in range(len(cifre)):
            if cifre[ind + 1] % 2 != 0:
                ind = cifre[ind+1]

n = int(input("Unesite broj n: "))
print(par_nepar(n))
</code>```

As you can see, I am struggling with index looping. I took the input number and transformed it into a list. Created a variable for index[0] and don't really know how to loop through consecutive indexes. I know I might be able to use zip or enumerate but I think that is not a truly pythonic solution here and probably there is a simpler way to loop over consecutive list numbers and compare them to index[-1].

Input examples:

```<code>>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False
</code>```

答:
```<code>def par_nepar(n):
    cifre = list(str(n))
    flg = False
    if int(cifre[0]) % 2 == 0:
        flg = True
    for d in cifre[1:]:
        _flg = False
        if int(d) % 2 == 0:
            _flg = True
        if not flg^_flg:
            print("The number does not complies to the needed terms")
            return
        flg = _flg
    print("The number complies to the needed terms")
    return
</code>```

Body:
I am doing some exercises and learning Python. I need to be able to check for an input number whether its consecutive digits are even or odd. So, if the first number is odd, the next should be even and so on in order for the terms to comply. I have the following code:

def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    cifre = cifre[::-1]
    ind = cifre[0]
    for broj in cifre:
        if cifre[0] % 2 == 0:
            # for br in range(len(cifre)):
            if cifre[ind + 1] % 2 != 0:
                ind = cifre[ind+1]

n = int(input("Unesite broj n: "))
print(par_nepar(n))

As you can see, I am struggling with index looping. I took the input number and transformed it into a list. Created a variable for index[0] and don't really know how to loop through consecutive indexes. I know I might be able to use zip or enumerate but I think that is not a truly pythonic solution here and probably there is a simpler way to loop over consecutive list numbers and compare them to index[-1].

Input examples:

>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False


问:
Incorrect image converting YUV_420_888 into Bitmaps under Android camera2
I’m trying to convert YUV_420_888 images into bitmaps, coming from the camera2 preview. But the output image has incorrect colors.

Next is the test code I’m running to generate the bitmap. Is test code only, so please don’t do any code review about not relevant factors such as the bitmap is being recycled, or the RenderScript is continuously been created. This code is just to test the conversion from YUV to RGB and nothing more.

Other factors, the code is meant to run from API 22 and above, therefore using RenderScript specific ScriptIntrinsicYuvToRGB should be sufficient, without having to use old manual conversions which where necessary only in previous Android versions due to lack of proper YUV_420_888 support.

As RenderScript already offers a dedicated ScriptIntrinsicYuvToRGB which is meant to handle all types of YUV conversions, I think the problem could be in how I get the YUV byte data from the Image object, but I can't figure where the issue is.

To view the output bitmap in Android Studio, place a breakpoint in bitmap.recycle(), so before it gets recycled you can look at it in the Variables Debug Window by using the “view bitmap” option.

Please let me know if anyone can spot what’s wrong with the conversion:

```<code>@Override
public void onImageAvailable(ImageReader reader)
{
    RenderScript rs = RenderScript.create(this.mContext);

    final Image image = reader.acquireLatestImage();

    final Image.Plane[] planes = image.getPlanes();
    final ByteBuffer planeY = planes[0].getBuffer();
    final ByteBuffer planeU = planes[1].getBuffer();
    final ByteBuffer planeV = planes[2].getBuffer();

    // Get the YUV planes data

    final int Yb = planeY.rewind().remaining();
    final int Ub = planeU.rewind().remaining();
    final int Vb = planeV.rewind().remaining();

    final ByteBuffer yuvData = ByteBuffer.allocateDirect(Yb + Ub + Vb);

    planeY.get(yuvData.array(), 0, Yb);
    planeU.get(yuvData.array(), Yb, Vb);
    planeV.get(yuvData.array(), Yb + Vb, Ub);

    // Initialize Renderscript

    Type.Builder yuvType = new Type.Builder(rs, Element.YUV(rs))
            .setX(image.getWidth())
            .setY(image.getHeight())
            .setYuvFormat(ImageFormat.YUV_420_888);

    final Type.Builder rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs))
            .setX(image.getWidth())
            .setY(image.getHeight());

    Allocation yuvAllocation = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);
    Allocation rgbAllocation = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);

    // Convert

    yuvAllocation.copyFromUnchecked(yuvData.array());

    ScriptIntrinsicYuvToRGB scriptYuvToRgb = ScriptIntrinsicYuvToRGB.create(rs, Element.YUV(rs));
    scriptYuvToRgb.setInput(yuvAllocation);
    scriptYuvToRgb.forEach(rgbAllocation);

    // Get the bitmap

    Bitmap bitmap = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);
    rgbAllocation.copyTo(bitmap);

    // Release

    bitmap.recycle();

    yuvAllocation.destroy();
    rgbAllocation.destroy();
    rs.destroy();

    image.close();
}
</code>```

答:
RenderScript support YUV_420_888 as ScriptIntrinsicYuvToRGB's source

create Allocation & ScriptIntrinsicYuvToRGB

```<code>RenderScript renderScript = RenderScript.create(this);
ScriptIntrinsicYuvToRGB mScriptIntrinsicYuvToRGB = ScriptIntrinsicYuvToRGB.create(renderScript, Element.YUV(renderScript));
Allocation mAllocationInYUV = Allocation.createTyped(renderScript, new Type.Builder(renderScript, Element.YUV(renderScript)).setYuvFormat(ImageFormat.YUV_420_888).setX(480).setY(640).create(), Allocation.USAGE_IO_INPUT | Allocation.USAGE_SCRIPT);
Allocation mAllocationOutRGB = Allocation.createTyped(renderScript, Type.createXY(renderScript, Element.RGBA_8888(renderScript), 480, 640), Allocation.USAGE_SCRIPT | Allocation.USAGE_IO_OUTPUT);
</code>```

set Allocation.getSurface() to receive image data from camera

```<code>final CaptureRequest.Builder captureRequest = session.getDevice().createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequest.addTarget(mAllocationInYUV.getSurface());
</code>```

output to a TextureView or ImageReader or SurfaceView

```<code>mAllocationOutRGB.setSurface(new Surface(mTextureView.getSurfaceTexture()));
mAllocationInYUV.setOnBufferAvailableListener(new Allocation.OnBufferAvailableListener() {
    @Override
    public void onBufferAvailable(Allocation a) {
        a.ioReceive();
        mScriptIntrinsicYuvToRGB.setInput(a);
        mScriptIntrinsicYuvToRGB.forEach(mAllocationOutRGB);
        mAllocationOutRGB.ioSend();
    }
});
</code>```

Body:
I’m trying to convert YUV_420_888 images into bitmaps, coming from the camera2 preview. But the output image has incorrect colors.

Next is the test code I’m running to generate the bitmap. Is test code only, so please don’t do any code review about not relevant factors such as the bitmap is being recycled, or the RenderScript is continuously been created. This code is just to test the conversion from YUV to RGB and nothing more.

Other factors, the code is meant to run from API 22 and above, therefore using RenderScript specific ScriptIntrinsicYuvToRGB should be sufficient, without having to use old manual conversions which where necessary only in previous Android versions due to lack of proper YUV_420_888 support.

As RenderScript already offers a dedicated ScriptIntrinsicYuvToRGB which is meant to handle all types of YUV conversions, I think the problem could be in how I get the YUV byte data from the Image object, but I can't figure where the issue is.

To view the output bitmap in Android Studio, place a breakpoint in bitmap.recycle(), so before it gets recycled you can look at it in the Variables Debug Window by using the “view bitmap” option.

Please let me know if anyone can spot what’s wrong with the conversion:

@Override
public void onImageAvailable(ImageReader reader)
{
    RenderScript rs = RenderScript.create(this.mContext);

    final Image image = reader.acquireLatestImage();

    final Image.Plane[] planes = image.getPlanes();
    final ByteBuffer planeY = planes[0].getBuffer();
    final ByteBuffer planeU = planes[1].getBuffer();
    final ByteBuffer planeV = planes[2].getBuffer();

    // Get the YUV planes data

    final int Yb = planeY.rewind().remaining();
    final int Ub = planeU.rewind().remaining();
    final int Vb = planeV.rewind().remaining();

    final ByteBuffer yuvData = ByteBuffer.allocateDirect(Yb + Ub + Vb);

    planeY.get(yuvData.array(), 0, Yb);
    planeU.get(yuvData.array(), Yb, Vb);
    planeV.get(yuvData.array(), Yb + Vb, Ub);

    // Initialize Renderscript

    Type.Builder yuvType = new Type.Builder(rs, Element.YUV(rs))
            .setX(image.getWidth())
            .setY(image.getHeight())
            .setYuvFormat(ImageFormat.YUV_420_888);

    final Type.Builder rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs))
            .setX(image.getWidth())
            .setY(image.getHeight());

    Allocation yuvAllocation = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);
    Allocation rgbAllocation = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);

    // Convert

    yuvAllocation.copyFromUnchecked(yuvData.array());

    ScriptIntrinsicYuvToRGB scriptYuvToRgb = ScriptIntrinsicYuvToRGB.create(rs, Element.YUV(rs));
    scriptYuvToRgb.setInput(yuvAllocation);
    scriptYuvToRgb.forEach(rgbAllocation);

    // Get the bitmap

    Bitmap bitmap = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);
    rgbAllocation.copyTo(bitmap);

    // Release

    bitmap.recycle();

    yuvAllocation.destroy();
    rgbAllocation.destroy();
    rs.destroy();

    image.close();
}

Body:
RenderScript support YUV_420_888 as ScriptIntrinsicYuvToRGB's source

create Allocation & ScriptIntrinsicYuvToRGB

RenderScript renderScript = RenderScript.create(this);
ScriptIntrinsicYuvToRGB mScriptIntrinsicYuvToRGB = ScriptIntrinsicYuvToRGB.create(renderScript, Element.YUV(renderScript));
Allocation mAllocationInYUV = Allocation.createTyped(renderScript, new Type.Builder(renderScript, Element.YUV(renderScript)).setYuvFormat(ImageFormat.YUV_420_888).setX(480).setY(640).create(), Allocation.USAGE_IO_INPUT | Allocation.USAGE_SCRIPT);
Allocation mAllocationOutRGB = Allocation.createTyped(renderScript, Type.createXY(renderScript, Element.RGBA_8888(renderScript), 480, 640), Allocation.USAGE_SCRIPT | Allocation.USAGE_IO_OUTPUT);

set Allocation.getSurface() to receive image data from camera

final CaptureRequest.Builder captureRequest = session.getDevice().createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequest.addTarget(mAllocationInYUV.getSurface());

output to a TextureView or ImageReader or SurfaceView

mAllocationOutRGB.setSurface(new Surface(mTextureView.getSurfaceTexture()));
mAllocationInYUV.setOnBufferAvailableListener(new Allocation.OnBufferAvailableListener() {
    @Override
    public void onBufferAvailable(Allocation a) {
        a.ioReceive();
        mScriptIntrinsicYuvToRGB.setInput(a);
        mScriptIntrinsicYuvToRGB.forEach(mAllocationOutRGB);
        mAllocationOutRGB.ioSend();
    }
});


问:
Show name of Month
This is my output

```<code>select name as product, avg(OrderQty) as average, OrderDate
from Production.Product
join Sales.SalesOrderDetail on SalesOrderDetail.ProductID = Product.ProductID
join Sales.SalesOrderHeader on SalesOrderHeader.SalesOrderID = SalesOrderDetail.SalesOrderID
where OrderDate like '%2011%'
group by Name, OrderDate
</code>```

I want to change order Date to the month for example

2011-10-24 00.00.00.000 ==> october

答:
You can use datename() in SQL Server to get name of the month.

```<code>select
   datename(month, orderDate) AS monthName
from yourTable
</code>```

Title: Show name of Month

Body:
This is my output

select name as product, avg(OrderQty) as average, OrderDate
from Production.Product
join Sales.SalesOrderDetail on SalesOrderDetail.ProductID = Product.ProductID
join Sales.SalesOrderHeader on SalesOrderHeader.SalesOrderID = SalesOrderDetail.SalesOrderID
where OrderDate like '%2011%'
group by Name, OrderDate

I want to change order Date to the month for example

2011-10-24 00.00.00.000 ==> october

Body:
You can use datename() in SQL Server to get name of the month.

select
   datename(month, orderDate) AS monthName
from yourTable


问:
Using moment.js to determine if current time (in hour) is between certain hours
I am working on a function that'd greet its users with a time-aware greeting (Good Morning, Afternoon, Evening, Night). Here's the script that I've made

```<code>import moment from "moment";

function generateGreetings(){
    if (moment().isBetween(3, 12, 'HH')){
        return "Good Morning";
    } else if (moment().isBetween(12, 15, 'HH')){
        return "Good Afternoon";
    }   else if (moment().isBetween(15, 20, 'HH')){
        return "Good Evening";
    } else if (moment().isBetween(20, 3, 'HH')){
        return "Good Night";
    } else {
        return "Hello"
    }
}

$("greet")
.css({
    display: "block",
    fontSize: "4vw",
    textAlign: "center",
    })
.text(generateGreetings() +", name")
</code>```

But it simply wont work and just returns "Hello". I've also tried using

```<code>var currentTime = moment();
var currentHour = currentTime.hour();
</code>```

and use currentHour to replace moment() inside the function but when I do so the site just dissapears.
Hoping anyone here has any insight on what I should do to fix this issue.

答:
@Thusitha

or you can use

```<code>moment().hour()
</code>```

instead of

```<code>moment().format('HH')(
</code>```

Body:
I am working on a function that'd greet its users with a time-aware greeting (Good Morning, Afternoon, Evening, Night). Here's the script that I've made

import moment from "moment";

function generateGreetings(){
    if (moment().isBetween(3, 12, 'HH')){
        return "Good Morning";
    } else if (moment().isBetween(12, 15, 'HH')){
        return "Good Afternoon";
    }   else if (moment().isBetween(15, 20, 'HH')){
        return "Good Evening";
    } else if (moment().isBetween(20, 3, 'HH')){
        return "Good Night";
    } else {
        return "Hello"
    }
}

$("greet")
.css({
    display: "block",
    fontSize: "4vw",
    textAlign: "center",
    })
.text(generateGreetings() +", name")

But it simply wont work and just returns "Hello". I've also tried using

var currentTime = moment();
var currentHour = currentTime.hour();

and use currentHour to replace moment() inside the function but when I do so the site just dissapears.
Hoping anyone here has any insight on what I should do to fix this issue.

Body:
@Thusitha

or you can use

moment().hour()

instead of

moment().format('HH')(


问:
sklearn Pipeline: argument of type 'ColumnTransformer' is not iterable
I am attempting to use a pipeline to feed an ensemble voting classifier as I want the ensemble learner to use models that train on different feature sets. For this purpose, I followed the tutorial available at [1].

Following is the code that I could develop so far.

```<code>y = df1.index
x = preprocessing.scale(df1)

phy_features = ['A', 'B', 'C']
phy_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
phy_processer = ColumnTransformer(transformers=[('phy', phy_transformer, phy_features)])

fa_features = ['D', 'E', 'F']
fa_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
fa_processer = ColumnTransformer(transformers=[('fa', fa_transformer, fa_features)])

pipe_phy = Pipeline(steps=[('preprocessor', phy_processer ),('classifier', SVM)])
pipe_fa = Pipeline(steps=[('preprocessor', fa_processer ),('classifier', SVM)])

ens = VotingClassifier(estimators=[pipe_phy, pipe_fa])

cv = KFold(n_splits=10, random_state=None, shuffle=True)
for train_index, test_index in cv.split(x):
    x_train, x_test = x[train_index], x[test_index]
    y_train, y_test = y[train_index], y[test_index]
    ens.fit(x_train,y_train)
    print(ens.score(x_test, y_test))
</code>```

However, when running the code, I am getting an error saying TypeError: argument of type 'ColumnTransformer' is not iterable, at the line ens.fit(x_train,y_train).

Following is the complete stack trace that I am receiving.

```<code>Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2020.1.1\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2020.1.1\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/ASUS/PycharmProjects/swelltest/enemble.py", line 112, in <module>
    ens.fit(x_train,y_train)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_voting.py", line 265, in fit
    return super().fit(X, transformed_y, sample_weight)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_voting.py", line 65, in fit
    names, clfs = self._validate_estimators()
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_base.py", line 228, in _validate_estimators
    self._validate_names(names)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\utils\metaestimators.py", line 77, in _validate_names
    invalid_names = [name for name in names if '__' in name]
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\utils\metaestimators.py", line 77, in <listcomp>
    invalid_names = [name for name in names if '__' in name]
TypeError: argument of type 'ColumnTransformer' is not iterable
</code>```

Following are the values in the names list when the error is occuring.

```<code>1- ColumnTransformer(transformers=[('phy',
                                 Pipeline(steps=[('imputer',
                                                  SimpleImputer(strategy='median')),
                                                 ('scaler', StandardScaler())]),
                                 ['HR', 'RMSSD', 'SCL'])])
2- ColumnTransformer(transformers=[('fa',
                                 Pipeline(steps=[('imputer',
                                                  SimpleImputer(strategy='median')),
                                                 ('scaler', StandardScaler())]),
                                 ['Squality', 'Sneutral', 'Shappy'])])
</code>```

What is the reason for this and how can I fix it?

答:
I did manage to get the code to run using a workaround, which is bit ugly.

It seems like that the library is attempting to search for '__' substring of the ColumnTransform object, which it is unable to perform.

Since this name check doesn't have a significant effect on my functionality, I commented the following snippet at  sklearn\utils\metaestimators.py.

```<code>invalid_names = [name for name in names if '__' in name]
if invalid_names:
    raise ValueError('Estimator names must not contain __: got '
                    '{0!r}'.format(invalid_names))
</code>```

Body:
I am attempting to use a pipeline to feed an ensemble voting classifier as I want the ensemble learner to use models that train on different feature sets. For this purpose, I followed the tutorial available at [1].

Following is the code that I could develop so far.

y = df1.index
x = preprocessing.scale(df1)

phy_features = ['A', 'B', 'C']
phy_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
phy_processer = ColumnTransformer(transformers=[('phy', phy_transformer, phy_features)])

fa_features = ['D', 'E', 'F']
fa_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
fa_processer = ColumnTransformer(transformers=[('fa', fa_transformer, fa_features)])

pipe_phy = Pipeline(steps=[('preprocessor', phy_processer ),('classifier', SVM)])
pipe_fa = Pipeline(steps=[('preprocessor', fa_processer ),('classifier', SVM)])

ens = VotingClassifier(estimators=[pipe_phy, pipe_fa])

cv = KFold(n_splits=10, random_state=None, shuffle=True)
for train_index, test_index in cv.split(x):
    x_train, x_test = x[train_index], x[test_index]
    y_train, y_test = y[train_index], y[test_index]
    ens.fit(x_train,y_train)
    print(ens.score(x_test, y_test))

However, when running the code, I am getting an error saying TypeError: argument of type 'ColumnTransformer' is not iterable, at the line ens.fit(x_train,y_train).

Following is the complete stack trace that I am receiving.

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2020.1.1\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2020.1.1\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/ASUS/PycharmProjects/swelltest/enemble.py", line 112, in <module>
    ens.fit(x_train,y_train)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_voting.py", line 265, in fit
    return super().fit(X, transformed_y, sample_weight)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_voting.py", line 65, in fit
    names, clfs = self._validate_estimators()
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\ensemble\_base.py", line 228, in _validate_estimators
    self._validate_names(names)
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\utils\metaestimators.py", line 77, in _validate_names
    invalid_names = [name for name in names if '__' in name]
  File "C:\Users\ASUS\PycharmProjects\swelltest\venv\lib\site-packages\sklearn\utils\metaestimators.py", line 77, in <listcomp>
    invalid_names = [name for name in names if '__' in name]
TypeError: argument of type 'ColumnTransformer' is not iterable

Following are the values in the names list when the error is occuring.

1- ColumnTransformer(transformers=[('phy',
                                 Pipeline(steps=[('imputer',
                                                  SimpleImputer(strategy='median')),
                                                 ('scaler', StandardScaler())]),
                                 ['HR', 'RMSSD', 'SCL'])])
2- ColumnTransformer(transformers=[('fa',
                                 Pipeline(steps=[('imputer',
                                                  SimpleImputer(strategy='median')),
                                                 ('scaler', StandardScaler())]),
                                 ['Squality', 'Sneutral', 'Shappy'])])

What is the reason for this and how can I fix it?

Body:
I did manage to get the code to run using a workaround, which is bit ugly.

It seems like that the library is attempting to search for '__' substring of the ColumnTransform object, which it is unable to perform.

Since this name check doesn't have a significant effect on my functionality, I commented the following snippet at  sklearn\utils\metaestimators.py.

invalid_names = [name for name in names if '__' in name]
if invalid_names:
    raise ValueError('Estimator names must not contain __: got '
                    '{0!r}'.format(invalid_names))


问:
How do I get the selected index in a Row in flutter
Date selector

I want to build a date selector for user to select the date they want to book a class.
So far I have coded the logic to generate next 8days and display it in a row, but I have trouble getting the selected index when user tap a date.
How do I achieve that?

Thank you very much.

```<code>class TimeSlot extends StatelessWidget {
  List<Map<String, String>> get upComingDay {
    return List.generate(8, (index) {
      final weekDay = DateTime.now().add(
        Duration(days: index),
      );
      return {
        'day': DateFormat.E().format(weekDay).substring(0, 2),
        'date': DateFormat.d().format(weekDay),
      };
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: upComingDay.map((data) {
        return Column(
          children: <Widget>[
            Text(
              data['day'],
              style: TextStyle(
                color: Color.fromRGBO(30, 41, 51, 0.5),
              ),
            ),
            SizedBox(
              height: 7,
            ),
            GestureDetector(
              onTap: () {},
              child: CircleAvatar(
                backgroundColor: Color.fromRGBO(240, 242, 245, 1),
                radius: 14,
                child: CircleAvatar(
                  backgroundColor: Colors.white,
                  child: Text(
                    data['date'],
                    style: TextStyle(color: Colors.black, fontSize: 12),
                  ),
                  radius: 13,
                ),
              ),
            ),
          ],
        );
      }).toList(),
    );
  }
}
</code>```

答:
Try using this trick:

Replace

.map()

with

.asMap().entries.map()

For example:

children: upComingDay.asMap().entries.map((dataEntry) {
        return Column(
          children: <Widget>[
            Text(
              dataEntry.value['day'],
              style: TextStyle(
                color: Color.fromRGBO(30, 41, 51, 0.5),
              ),
            ),
            SizedBox(
              height: 7,
            ),
            GestureDetector(
              onTap: () {
                // Whatever you wanna use the index for, refer as dataEntry.key for index
              },
              child: CircleAvatar(
                backgroundColor: Color.fromRGBO(240, 242, 245, 1),
                radius: 14,
                child: CircleAvatar(
                  backgroundColor: Colors.white,
                  child: Text(
                    dataEntry.value['date'],
                    style: TextStyle(color: Colors.black, fontSize: 12),
                  ),
                  radius: 13,
                ),
              ),
            ),
          ],
        );
      }).toList(),
```

Does that accomplish what you're looking for?

Body:
Date selector

I want to build a date selector for user to select the date they want to book a class.
So far I have coded the logic to generate next 8days and display it in a row, but I have trouble getting the selected index when user tap a date.
How do I achieve that?

Thank you very much.

class TimeSlot extends StatelessWidget {
  List<Map<String, String>> get upComingDay {
    return List.generate(8, (index) {
      final weekDay = DateTime.now().add(
        Duration(days: index),
      );
      return {
        'day': DateFormat.E().format(weekDay).substring(0, 2),
        'date': DateFormat.d().format(weekDay),
      };
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: upComingDay.map((data) {
        return Column(
          children: <Widget>[
            Text(
              data['day'],
              style: TextStyle(
                color: Color.fromRGBO(30, 41, 51, 0.5),
              ),
            ),
            SizedBox(
              height: 7,
            ),
            GestureDetector(
              onTap: () {},
              child: CircleAvatar(
                backgroundColor: Color.fromRGBO(240, 242, 245, 1),
                radius: 14,
                child: CircleAvatar(
                  backgroundColor: Colors.white,
                  child: Text(
                    data['date'],
                    style: TextStyle(color: Colors.black, fontSize: 12),
                  ),
                  radius: 13,
                ),
              ),
            ),
          ],
        );
      }).toList(),
    );
  }
}

Body:
Try using this trick:

Replace

.map()

with

.asMap().entries.map()

For example:

children: upComingDay.asMap().entries.map((dataEntry) {
        return Column(
          children: <Widget>[
            Text(
              dataEntry.value['day'],
              style: TextStyle(
                color: Color.fromRGBO(30, 41, 51, 0.5),
              ),
            ),
            SizedBox(
              height: 7,
            ),
            GestureDetector(
              onTap: () {
                // Whatever you wanna use the index for, refer as dataEntry.key for index
              },
              child: CircleAvatar(
                backgroundColor: Color.fromRGBO(240, 242, 245, 1),
                radius: 14,
                child: CircleAvatar(
                  backgroundColor: Colors.white,
                  child: Text(
                    dataEntry.value['date'],
                    style: TextStyle(color: Colors.black, fontSize: 12),
                  ),
                  radius: 13,
                ),
              ),
            ),
          ],
        );
      }).toList(),

Does that accomplish what you're looking for?


问:
How to change gridview row color by cell value?
I have cell name "MY_CELL"
I want to create if "MY_CELL" value is OK! then that Row color will be changed with GreenYellow.

```<code>    private void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
{
if (gridView2.RowCount > 0)
            {
                for (int i = 0; i < gridView2.DataRowCount; i++)
                {

                     string text_sms2 = gridView2.GetRowCellValue(i, "MY_CELL").ToString();

                     if (text_sms2.Contains("ok"))
                    {
                        e.Appearance.BackColor = Color.GreenYellow;
                    }
                    else
                    {
                        e.Appearance.BackColor = Color.Red;
                    }
                }
            }
}
</code>```

These code seems like works but all my rows color changed with "GreenYellow".

答:
There's no need for the loop, since RowStyle event is raised for each individial row. Your code is setting apperence for each row according to the value in the last one.

Try this:

```<code>private void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e) {

  if (e.RowHandle >= 0) {
    e.HighPriority = true;
    var text = gridView2.GetRowCellDisplayText(e.RowHandle, view.Columns["MY_CELL"]);

    if(text.Contains("ok") { // mind case sensitivity!!!
      e.Appearance.BackColor = Color.GreenYellow;
    }
    else {
      e.Appearance.BackColor = Color.Red;
    }
   }
 }
</code>```

Body:
I have cell name "MY_CELL"
I want to create if "MY_CELL" value is OK! then that Row color will be changed with GreenYellow.

    private void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
{
if (gridView2.RowCount > 0)
            {
                for (int i = 0; i < gridView2.DataRowCount; i++)
                {

                     string text_sms2 = gridView2.GetRowCellValue(i, "MY_CELL").ToString();

                     if (text_sms2.Contains("ok"))
                    {
                        e.Appearance.BackColor = Color.GreenYellow;
                    }
                    else
                    {
                        e.Appearance.BackColor = Color.Red;
                    }
                }
            }
}

These code seems like works but all my rows color changed with "GreenYellow".

Body:
There's no need for the loop, since RowStyle event is raised for each individial row. Your code is setting apperence for each row according to the value in the last one.

Try this:

private void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e) {

  if (e.RowHandle >= 0) {
    e.HighPriority = true;
    var text = gridView2.GetRowCellDisplayText(e.RowHandle, view.Columns["MY_CELL"]);

    if(text.Contains("ok") { // mind case sensitivity!!!
      e.Appearance.BackColor = Color.GreenYellow;
    }
    else {
      e.Appearance.BackColor = Color.Red;
    }
   }
 }


问:
Vuejs : Open a collapse menu when a particular tab is active and close it when it is not active
I have two methods forceOpenSettings() and forceCloseSettings(). I need these for opening and closing of a collapsable section. the methods are working fine as I tested it separately. But I need to do this based on a condition, I have b-tab with 4 tabs. Out of which when i click on a tab the collpase should open, and whenever the tab becomes inactive , the collapse must close

```<code><b-tabs content-class="mt-3">
  <b-tab title="First" active><p>I'm the first tab</p></b-tab>
  <b-tab title="Second"><p>I'm the second tab</p></b-tab>
</b-tabs>
</code>```

The same thing I'am achieving in a b-collapse using @show and @hide and it working fine,

```<code><b-collapse role="tabpanel" @show="forceOpenSettings" @hide="forceCloseSettings">......</b-collapse>
</code>```

答:
Vanilla JS: Here is a Dynamic iterator that will check if active is set as an attribute...

function opendiv() {
  document.getElementById('myDiv').style.display = "block";
}

function closediv() {
  document.getElementById('myDiv').style.display = "none";
}

let tabs = document.getElementsByTagName('b-tab');
for (let i = 0; i < tabs.length; i++) {
  tabs[i].addEventListener('click', event => {
    if (tabs[i].getAttribute("active") !== null) {
      opendiv();
    } else {
      closediv();
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b-tabs content-class="mt-3">
  <b-tab title="First">
    <p>I'm the first tab</p>
  </b-tab>
  <b-tab title="Second" active>
    <p>I'm the second tab</p>
  </b-tab>
</b-tabs>

<div id="myDiv" style="display:none;">Show this div when second tab has an attribute named 'active'</div></code>```

Get the elements by their tag name... Then write your conditional statement to search for the second iteration of the elements using the key 1, which is the second tab, check to see if the attribute is not null, which means it is set, but set to nothing. If it is not present in the tag, then it will return null.

  let tabs = document.getElementsByTagName('b-tab');

  if(tabs[1].getAttribute("active") !== null){
    // run opendiv();
  }else{
    // run closediv();
  }
```

Body:
I have two methods forceOpenSettings() and forceCloseSettings(). I need these for opening and closing of a collapsable section. the methods are working fine as I tested it separately. But I need to do this based on a condition, I have b-tab with 4 tabs. Out of which when i click on a tab the collpase should open, and whenever the tab becomes inactive , the collapse must close

I'm the first tab

I'm the second tab

The same thing I'am achieving in a b-collapse using @show and @hide and it working fine,

......

Body:
Vanilla JS: Here is a Dynamic iterator that will check if active is set as an attribute...

function opendiv() {
  document.getElementById('myDiv').style.display = "block";
}

function closediv() {
  document.getElementById('myDiv').style.display = "none";
}

let tabs = document.getElementsByTagName('b-tab');
for (let i = 0; i < tabs.length; i++) {
  tabs[i].addEventListener('click', event => {
    if (tabs[i].getAttribute("active") !== null) {
      opendiv();
    } else {
      closediv();
    }
  });
}

<b-tabs content-class="mt-3">
  <b-tab title="First">
    <p>I'm the first tab</p>
  </b-tab>
  <b-tab title="Second" active>
    <p>I'm the second tab</p>
  </b-tab>
</b-tabs>

<div id="myDiv" style="display:none;">Show this div when second tab has an attribute named 'active'</div>

Get the elements by their tag name... Then write your conditional statement to search for the second iteration of the elements using the key 1, which is the second tab, check to see if the attribute is not null, which means it is set, but set to nothing. If it is not present in the tag, then it will return null.

  let tabs = document.getElementsByTagName('b-tab');

  if(tabs[1].getAttribute("active") !== null){
    // run opendiv();
  }else{
    // run closediv();
  }


问:
Puma stuck with message "Early termination of worker" on Rails 6 API only project at Elastic Beanstalk
I have a Rails 6 api-only application which I am failed to run at AWS Elastic Beanstalk. After deployment of that application, puma stucks with message "Early termination of worker". I don't have any custom configurations nor settings for that project. Simply created an environment and uploaded archived zip file.

After I kill puma processes with command pkill -9 -f puma my puma.log file looks like below:

```<code>=== puma startup: 2020-01-22 13:17:45 +0000 ===
=== puma startup: 2020-01-22 13:17:45 +0000 ===
[28858] Early termination of worker
[28856] Early termination of worker
[28862] Early termination of worker
[28865] Early termination of worker
[28869] Early termination of worker
</code>```

I searched that error and found nothing for solve.

Ruby version: 2.6.5

Puma version 4.3.1

Rails version: 6.0.2.1

I am using Puma with Ruby 2.6 running on 64bit Amazon Linux/2.11.2 on AWS.

答:
Met the same error. Turns out it is a different PATCH of puma.

I was using this stack from elastic beanstalk

```<code>Ruby 2.6 AL2 version 3.0.1
64bit Amazon Linux 2 v3.0.1 running Ruby 2.6
Ruby 2.6.6-p146
RubyGems 3.1.2
Puma 4.3.3
...
</code>```

My project's Gemfile included puma this way.

```<code>gem 'puma', '~> 4.3.3'
</code>```

My project was a boilerplate for new projects that were coming my way, so things were working fine for "old" projects until the newer patch version, puma 4.3.5 as of now, came out.

Solution is to fix the version of the gem in the Gemfile as such:

```<code>gem 'puma', '= 4.3.3'
</code>```

Lesson learnt is to always match your environment with that of your deployment tool. Keep track of the latest solution stack versions here.

Body:
I have a Rails 6 api-only application which I am failed to run at AWS Elastic Beanstalk. After deployment of that application, puma stucks with message "Early termination of worker". I don't have any custom configurations nor settings for that project. Simply created an environment and uploaded archived zip file.

After I kill puma processes with command pkill -9 -f puma my puma.log file looks like below:

=== puma startup: 2020-01-22 13:17:45 +0000 ===
=== puma startup: 2020-01-22 13:17:45 +0000 ===
[28858] Early termination of worker
[28856] Early termination of worker
[28862] Early termination of worker
[28865] Early termination of worker
[28869] Early termination of worker

I searched that error and found nothing for solve.

Ruby version: 2.6.5

Puma version 4.3.1

Rails version: 6.0.2.1

I am using Puma with Ruby 2.6 running on 64bit Amazon Linux/2.11.2 on AWS.

Body:
Met the same error. Turns out it is a different PATCH of puma.

I was using this stack from elastic beanstalk

Ruby 2.6 AL2 version 3.0.1
64bit Amazon Linux 2 v3.0.1 running Ruby 2.6
Ruby 2.6.6-p146
RubyGems 3.1.2
Puma 4.3.3
...

My project's Gemfile included puma this way.

gem 'puma', '~> 4.3.3'

My project was a boilerplate for new projects that were coming my way, so things were working fine for "old" projects until the newer patch version, puma 4.3.5 as of now, came out.

Solution is to fix the version of the gem in the Gemfile as such:

gem 'puma', '= 4.3.3'

Lesson learnt is to always match your environment with that of your deployment tool. Keep track of the latest solution stack versions here.


问:
How to catch the longest sequence of a group
The task is to find the longest sequence of a group

for instance, given DNA sequence: "AGATCAGATCTTTTTTCTAATGTCTAGGATATATCAGATCAGATCAGATCAGATCAGATC"
and it has 7 occurrences of AGATC. (AGATC) matches all occurrences.
Is it possible to write a regular expression that catches only the longest sequence, i.e. AGATCAGATCAGATCAGATCAGATC in the given text?
If this is not possible only with regex, how can I iterate through each sequence (i.e. 1st sequence is AGATCAGATC, 2nd - AGATCAGATCAGATCAGATCAGATC et cetera) in python?

答:
The central question is, "Is it possible to write a regular expression that catches only the longest sequence?" The answer is "yes":

```<code>import re

s = 'AGATC_AGATCAGATC_AGATCAGATCAGATC_AGATC_AGATCAGATC'

m = re.search(r'((?:AGATC)+)(?!.*\1)', s)
print m.group() if m else ''
  #=> "AGATCAGATCAGATC"
</code>```

Regex demo<¯\(ツ)/¯>Python demo

Python's regex engine performs the following operations.

```<code>(            begin capture group 1
  (?:AGATC)  match 'AGATC' in a non-capture group
  +          execute the non-capture group 1+ times
)            end capture group 1
(?!          begin a negative lookahead
  .*         match 0+ characters
  \1         match the content of capture group 1
)            end the negative lookahead
</code>```

For the string s above, AGATC would first be matched but the negative lookahead would find AGATC as the first part of AGATCAGATC, so the tentative match would be rejected. Then AGATCAGATC would be matched, but the negative lookahead would find AGATCAGATC as the first part of AGATCAGATCAGATC so that tentative match would also be rejected. Next, AGATCAGATCAGATC would be matched and accepted, as the negative lookahead would not find that match later in the string. (re.findall, unlike re.search, would also match AGATCAGATC at the end of the string.)

If re.findall were used there may be multiple matches after the longest one (see the last test string at the link to the regex demo), but the lengths of the matches are non-decreasing from the first to the last. Therefore, the first match, obtained using re.search is a longest match.

Body:
The central question is, "Is it possible to write a regular expression that catches only the longest sequence?" The answer is "yes":

import re

s = 'AGATC_AGATCAGATC_AGATCAGATCAGATC_AGATC_AGATCAGATC'

m = re.search(r'((?:AGATC)+)(?!.*\1)', s)
print m.group() if m else ''
  #=> "AGATCAGATCAGATC"

Regex demo<¯\(ツ)/¯>Python demo

Python's regex engine performs the following operations.

(            begin capture group 1
  (?:AGATC)  match 'AGATC' in a non-capture group
  +          execute the non-capture group 1+ times
)            end capture group 1
(?!          begin a negative lookahead
  .*         match 0+ characters
  \1         match the content of capture group 1
)            end the negative lookahead

For the string s above, AGATC would first be matched but the negative lookahead would find AGATC as the first part of AGATCAGATC, so the tentative match would be rejected. Then AGATCAGATC would be matched, but the negative lookahead would find AGATCAGATC as the first part of AGATCAGATCAGATC so that tentative match would also be rejected. Next, AGATCAGATCAGATC would be matched and accepted, as the negative lookahead would not find that match later in the string. (re.findall, unlike re.search, would also match AGATCAGATC at the end of the string.)

If re.findall were used there may be multiple matches after the longest one (see the last test string at the link to the regex demo), but the lengths of the matches are non-decreasing from the first to the last. Therefore, the first match, obtained using re.search is a longest match.


问:
How to find out: Are all commits in a given branch covered by a pull request?
our internally used development process demands that we formally prove that all commits that were pushed are covered by a review (=pull request).

I know that if we would have enabled branch protection since the beginning of existence of a repo and its branches no commit can be pushed to the protected branches without a review/pull request.

Our internal auditors unfortunately are not satisfied with only looking at pull requests and telling them "The process does not allow to not cover a commit with a review".

Any idea how this could be accomplished? Can I fetch all the data via REST API and create a report on my own or is there something already existing, did not find anything in that direction in the web ui.

Thank you

答:
You can check out extension Pull Request Manager Hub. It can list your Pull Requests of all your projects and repositories at a single place.

After you install this extension in your organization. You can go the Pull Request Manager Hub under Repos from your Azure devops Project UI page to check out the reviewers, status and other details of the PR. See below:

You can also use rest api to get all the data and create a report on your own. See below Get Pull Requests rest api.

GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId or repositoryName}/pullrequests?api-version=5.1

To get the reviewers you can use Pull Request Reviewers - List rest api.

See below example scripts in powershell to call rest api. Check here to get a personal access token.

```<code>$url ="https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId or repositoryName}/pullrequests?api-version=5.1"

$pat = "Personal Access Token"

$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))

$PRs=Invoke-RestMethod -Uri $url -Headers @{Authorization = ("Basic {0}" -f $base64AuthInfo)} -Method get -ContentType "application/json"

$PRs.value | select pullRequestId, reviewers
</code>```

Body:
You can check out extension Pull Request Manager Hub. It can list your Pull Requests of all your projects and repositories at a single place.

After you install this extension in your organization. You can go the Pull Request Manager Hub under Repos from your Azure devops Project UI page to check out the reviewers, status and other details of the PR. See below:

You can also use rest api to get all the data and create a report on your own. See below Get Pull Requests rest api.

GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId or repositoryName}/pullrequests?api-version=5.1

To get the reviewers you can use Pull Request Reviewers - List rest api.

See below example scripts in powershell to call rest api. Check here to get a personal access token.

$url ="https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId or repositoryName}/pullrequests?api-version=5.1"

$pat = "Personal Access Token"

$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))

$PRs=Invoke-RestMethod -Uri $url -Headers @{Authorization = ("Basic {0}" -f $base64AuthInfo)} -Method get -ContentType "application/json"

$PRs.value | select pullRequestId, reviewers


Title: R datatable grouping based on condition and getting count based on the conditions

Body:
I have a data table like this :

timestamp           type    status
05-01-2020 12:07:08    A      1
05-01-2020 12:36:05    A      1
05-01-2020 13:34:25    A      1
05-01-2020 23:45:02    A      1
05-01-2020 23:55:02    B      1
05-01-2020 13:44:33    B      2
06-01-2020 01:07:08    A      1
06-01-2020 10:23:05    A      1
06-01-2020 12:11:08    A      2
06-01-2020 22:06:12    B      2
07-01-2020 00:01:05    A      2
07-01-2020 02:17:09    A      1
07-01-2020 12:36:05    B      1
07-01-2020 12:07:08    B      1
07-01-2020 12:36:05    A      1
07-01-2020 12:36:05    A      1
08-01-2020 12:36:05    B      2
08-01-2020 12:36:05    B      1
08-01-2020 12:36:05    B      1
09-01-2020 12:36:05    B      1
09-01-2020 12:07:08    B      2
09-01-2020 12:36:05    B      1
11-01-2020 12:07:08    A      1
11-01-2020 12:36:05    A      1

I am trying to group it on date and type using rleid().

dt <- dt[, group_id := rleid(as.IDate(timestamp),type,status = 1)][]

Now I want to get two counts.

One is to count the number of instances inside each group which meets the condition per day.

date         type  count
05-01-2020    A      4
05-01-2020    B      1
06-01-2020    A      2
07-01-2020    A      3
07-01-2020    B      2
08-01-2020    B      2
09-01-2020    B      2
11-01-2020    A      2

Second one is to find the number of groups per day which meet the condition.

date         type  count
05-01-2020    A      1
05-01-2020    B      1
06-01-2020    A      1
07-01-2020    A      2
07-01-2020    B      1
08-01-2020    B      1
09-01-2020    B      2
11-01-2020    A      1

Body:
We can first convert the 'timestamp' to Datetime class with as.POSIXct and then convert it to Date class

library(data.table)
setDT(dt)[, timestamp := as.POSIXct(timestamp,
     format = '%m-%d-%Y %H:%M:%S')][, date := as.IDate(timestamp)]
dt[status == 1, .N, .(date, type)]
#.        date type N
#1: 2020-05-01    A 4
#2: 2020-05-01    B 1
#3: 2020-06-01    A 2
#4: 2020-07-01    A 3
#5: 2020-07-01    B 2
#6: 2020-08-01    B 2
#7: 2020-09-01    B 2
#8: 2020-11-01    A 2

For the second case

dt[, grp := rleid(type, status, date)]
dt[status == 1, .(count = uniqueN(grp)), .(date, type)]
#         date type count
#1: 2020-05-01    A     1
#2: 2020-05-01    B     1
#3: 2020-06-01    A     1
#4: 2020-07-01    A     2
#5: 2020-07-01    B     1
#6: 2020-08-01    B     1
#7: 2020-09-01    B     2
#8: 2020-11-01    A     1

data

dt <- structure(list(timestamp = structure(c(1588349228, 1588350965,
1588354465, 1588391102, 1588391702, 1588355073, 1590988028, 1591021385,
1591027868, 1591063572, 1593576065, 1593584229, 1593621365, 1593619628,
1593621365, 1593621365, 1596299765, 1596299765, 1596299765, 1598978165,
1598976428, 1598978165, 1604250428, 1604252165), class = c("POSIXct",
"POSIXt"), tzone = ""), type = c("A", "A", "A", "A", "B", "B",
"A", "A", "A", "B", "A", "A", "B", "B", "A", "A", "B", "B", "B",
"B", "B", "B", "A", "A"), status = c(1L, 1L, 1L, 1L, 1L, 2L,
1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L,
1L, 1L)), class = "data.frame", row.names = c(NA, -24L),
index = structure(integer(0), "`__status`" = c(1L,
2L, 3L, 4L, 5L, 7L, 8L, 12L, 13L, 14L, 15L, 16L, 18L, 19L, 20L,
22L, 23L, 24L, 6L, 9L, 10L, 11L, 17L, 21L)))


问:
Sorting high-scores in JavaScript?
Hello I am writing a game using javascript that takes the user's name as well as the "round" they made it to and stores it in two different arrays, and I would like to display the names coupled with the scores, highest to lowest but I'm stumped on how to do it, I can sort the rounds from highest to lowest but I can't figure out how to sort the names along with them. Please help!

my current code:

```<code>        nameScore.push(username);
        highScore.push(round);
        highScore.reverse();

        for (var i = 0; i < highScore.length; i++) {
            $("#highScore").append(nameScore[i] + "  " + highScore[i] + "<br>");
        }
</code>```

答:
Don't use two arrays that are not linked in any way. Just use one array.

```<code>const userScores = [];

// Play game, get score

userScores.push({username, roundNumber, score});
</code>```

Now you can search/sort this array and the username, the round number, and the score value are all linked together.

Title: Sorting high-scores in JavaScript?

Body:
Hello I am writing a game using javascript that takes the user's name as well as the "round" they made it to and stores it in two different arrays, and I would like to display the names coupled with the scores, highest to lowest but I'm stumped on how to do it, I can sort the rounds from highest to lowest but I can't figure out how to sort the names along with them. Please help!

my current code:

        nameScore.push(username);
        highScore.push(round);
        highScore.reverse();

        for (var i = 0; i < highScore.length; i++) {
            $("#highScore").append(nameScore[i] + "  " + highScore[i] + "
");
        }

Body:
Don't use two arrays that are not linked in any way. Just use one array.

const userScores = [];

// Play game, get score

userScores.push({username, roundNumber, score});

Now you can search/sort this array and the username, the round number, and the score value are all linked together.


问:
Rcpp and move semantic
I implemented an algorithm in C++ that returns as output a huge array of elements. Now, I would like to implement a wrapper in Rcpp so that I will be able to call this function by using R.

I specified in the Makevars file the following setting:

PKG_CXXFLAGS = -std=c++11

So that I can use the C++11 version.

```<code>// [[Rcpp::export]]
NumericMatrix compute(int width, int height)
{
  vector<data_t> weights(width * height);
  compute_weights(weights);

  NumericMatrix mat(height, width);
  copy(begin(weights), end(weights), mat.begin());

  return mat;
}
</code>```

The above wrapper function remains efficient if the NumericMatrix is moved when returned by the function, otherwise a new object will be created.

Does Rcpp exploit the move semantics? And if not, are there any workarounds to avoid the construction of the copy?

答:
The above wrapper function remains efficient if the NumericMatrix is moved when returned by the function, otherwise a new object will be created.

... And if not, are there any workarounds to avoid the construction of the copy?

I think that only a shallow copy is created by the copy constructor so there should not be any copy. See Rcpp: How to ensure deep copy of a NumericMatrix? and

https://github.com/RcppCore/Rcpp/blob/b3b0bea7403d9836397148fa310b86eb24923aba/inst/include/Rcpp/vector/Matrix.h#L74

which calls https://github.com/RcppCore/Rcpp/blob/b3b0bea7403d9836397148fa310b86eb24923aba/inst/include/Rcpp/vector/Vector.h#L62-L67

This is also confirmed by this example

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector allocate_the_vec(R_xlen_t n_ele){
  Rcpp::NumericVector out(n_ele);
  return out;
}

/*** R
# got 16 GB ram on my laptop. 3 x 7 is an issue but 2 x 7 is not
how_large <- as.integer(7 * 10^9 / 8)
the_large_vec_1 <- allocate_the_vec(how_large)
object.size(the_large_vec_1)
the_large_vec_2 <- allocate_the_vec(how_large)
*/
```

Title: Rcpp and move semantic

Body:
I implemented an algorithm in C++ that returns as output a huge array of elements. Now, I would like to implement a wrapper in Rcpp so that I will be able to call this function by using R.

I specified in the Makevars file the following setting:

PKG_CXXFLAGS = -std=c++11

So that I can use the C++11 version.

// [[Rcpp::export]]
NumericMatrix compute(int width, int height)
{
  vector<data_t> weights(width * height);
  compute_weights(weights);

  NumericMatrix mat(height, width);
  copy(begin(weights), end(weights), mat.begin());

  return mat;
}

The above wrapper function remains efficient if the NumericMatrix is moved when returned by the function, otherwise a new object will be created.

Does Rcpp exploit the move semantics? And if not, are there any workarounds to avoid the construction of the copy?


问:
IsNumeric() allowing minus at last of the values
I am using IsNumeric() function in my code to validate numbers.

IsNumeric(100)  - true,
IsNumeric(-100) - true,
IsNumeric(+100) - true,

IsNumeric(100-) - true - I have doubt in this. (100-) Is this a valid number? IsNumeric () returns true to this value.

```<code>    Dim latitude As String = "12.56346-"
    If IsNumeric(latitude) Then
        If (Convert.ToDouble(latitude) >= -90 And Convert.ToDouble(latitude) <= 90) Then
            isValidLatitude.Text = "true"
        Else
            isValidLatitude.Text = "false"
        End If
     Else
        isValidLatitude.Text = "false"
     End If
</code>```

Error while converting latitude to double

```<code>Input string was not in a correct format.
</code>```

答:
IsNumeric is from the Microsoft.VisualBasic namespace/dll, a bunch of helper stuff intended to help VB6 programmers get their arcane VB6 code /knowledge working on VB.NET

You'll note if you use other functions from the same dll such as Microsoft.VisualBasic.Conversion.Int(), or you use dedicated VB.NET converters such as CInt or CDbl these will also cope with a trailing minus sign and return a negative value

If you want to dispense with the old ways of VB6, use a numeric type's TryParse.. but all in, be consistent / if you use a function from Microsoft.VisualBasic to determine if a conversion can be made, use the vb conversion because within itself the package will be consistent but between Microsoft.VB and normal .net System there are some differences in behavior

Edit:

A couple of people have been wondering about the source code and how it uses TryParse, so why doesn't it work like using TryParse directly?

Microsoft.VisualBasic.Information.IsNumeric() uses Microsoft.VisualBasic.CompilerServices.DoubleType.TryParse() to determine whether an expression is numeric. This DoubleType.TryParse is not the same as Double.TryParse - it is a helper method again in the VB namespace that specifically sets the NumberStyles.AllowTrailingSign flag among many other flags. When parsing the number (first as non currency related, using Double.Parse, then if it fails a second attempt is made using adjusted values for currency related tests) this AllowTrailingSign flag will be considered in conjunction with other regional number formatting rules in determining if the passed in value is numeric

You'll note that on a machine obeying a USA number formatting culture, a string of "(100$)" is also declared to be numeric but calling Double.TryParse("(100$)", x) will also return false. The VB helper methods here are being a lot more liberal in what they accept than the System methods, because they're telling the System methods to be more liberal than they are by default

As noted, I've always regarded the Microsoft.VisualBasic namespace as a bunch of helper methods intended to allow terrible old VB6 code to be pasted into VB.NET and work with minimal fiddling. I wouldn't advocate using it for new projects and I remove the reference when I work on VB.NET - using it to support the VB6 notions of "just sling anything in, of any type, and it'll probably figure it out and work.. and if it doesn't we can always on error resume next" should be discarded in favour of precise and accurate about the operations executed and their intent

Body:
I am using IsNumeric() function in my code to validate numbers.

IsNumeric(100)  - true,
IsNumeric(-100) - true,
IsNumeric(+100) - true,

IsNumeric(100-) - true - I have doubt in this. (100-) Is this a valid number? IsNumeric () returns true to this value.

    Dim latitude As String = "12.56346-"
    If IsNumeric(latitude) Then
        If (Convert.ToDouble(latitude) >= -90 And Convert.ToDouble(latitude) <= 90) Then
            isValidLatitude.Text = "true"
        Else
            isValidLatitude.Text = "false"
        End If
     Else
        isValidLatitude.Text = "false"
     End If

Error while converting latitude to double

Input string was not in a correct format.


问:
How do I load the R dataset biospy from MASS package into python?
I am trying to load biospy dataset from MASS package in R into python.
But my code is getting me http 404 not found error , in reality there is a biospy dataset in R under MASS package. Does anyone know how to get through this?

Code

```<code>import statsmodels.api as sm
biospy=sm.datasets.get_rdataset("biospy","MASS")
</code>```

Error

HTTPError: HTTP Error 404: Not Found

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call
  last)  in
        1
  ----> 2 biospy=sm.datasets.get_rdataset("biospy","MASS") ValueError: Dataset biospy was not found.

答: You have mistyped "biopsy" as "biospy", which is leading to the dataset not being found.</p>

Body:
I am trying to load biospy dataset from MASS package in R into python.
But my code is getting me http 404 not found error , in reality there is a biospy dataset in R under MASS package. Does anyone know how to get through this?

Code

import statsmodels.api as sm
biospy=sm.datasets.get_rdataset("biospy","MASS")

Error

HTTPError: HTTP Error 404: Not Found

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call
  last)  in
        1
  ----> 2 biospy=sm.datasets.get_rdataset("biospy","MASS") ValueError: Dataset biospy was not found.


问:
How to do a clean SVN checkout/update in multibranch pipeline
I am using a multibranch pipeline with SVN. I currently don't use an explicit checkout scm command but I am using the declarative default checkout. My problem is, that this only seems to perform an svn update. I would however like to use the UpdateWithCleanUpdater update strategy.

I have seen here that there is a possibility to modify the scm object -  but not without granting further permissions:

```<code>import hudson.scm.subversion.UpdateWithCleanUpdater
scm.setWorkspaceUpdater(new UpdateWithCleanUpdater())
</code>```

Is there a simple way to only configure the updater while keeping all the other information from the multibranch configuration and having to set the branch, credentials, server, .... again manually?

I have tried checkout scm: [workspaceUpdater: [$class: 'UpdateWithCleanUpdater']] but this doesn't work

答:
In a declarative pipeline stage, make sure that the options contain:

```<code>options {
  skipDefaultCheckout()
}
</code>```

and the steps section starts with a script block like:

```<code>script {
  myScm = scm
  myScm.setWorkspaceUpdater(new hudson.scm.subversion.UpdateWithRevertUpdater())
  checkout myScm
}
</code>```

More info on the different types of workspace updaters for Subversion is here: https://javadoc.jenkins.io/plugin/subversion/hudson/scm/subversion/WorkspaceUpdater.html

And yes, you may need to approve some scripts on the approval page:

```<code>http://<myjenkins>/scriptApproval/
</code>```

Body:
I am using a multibranch pipeline with SVN. I currently don't use an explicit checkout scm command but I am using the declarative default checkout. My problem is, that this only seems to perform an svn update. I would however like to use the UpdateWithCleanUpdater update strategy.

I have seen here that there is a possibility to modify the scm object -  but not without granting further permissions:

import hudson.scm.subversion.UpdateWithCleanUpdater
scm.setWorkspaceUpdater(new UpdateWithCleanUpdater())

Is there a simple way to only configure the updater while keeping all the other information from the multibranch configuration and having to set the branch, credentials, server, .... again manually?

I have tried checkout scm: [workspaceUpdater: [$class: 'UpdateWithCleanUpdater']] but this doesn't work

Body:
In a declarative pipeline stage, make sure that the options contain:

options {
  skipDefaultCheckout()
}

and the steps section starts with a script block like:

script {
  myScm = scm
  myScm.setWorkspaceUpdater(new hudson.scm.subversion.UpdateWithRevertUpdater())
  checkout myScm
}

More info on the different types of workspace updaters for Subversion is here: https://javadoc.jenkins.io/plugin/subversion/hudson/scm/subversion/WorkspaceUpdater.html

And yes, you may need to approve some scripts on the approval page:

http://<myjenkins>/scriptApproval/