问:
java.lang.StackOverflowError(Cyclic Reference) with JPA and Mapstruct
I am new to mapstruct. I am trying to map the Entity object(bidirectional) to DTO object using Mapstruct.
I am able to retrieve the entity object using JPA repository and when I try to map the same to DTo object I am getting java.lang.StackOverflowError.

Code:

```<code>@Entity
@Table(name = "product_category")
@Getter
@Setter
@ToString(exclude = {"products"})

public class ProductCategory extends BaseModel<String> {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FARM_PRODUCT_CATEGORY_GENERATOR")
    @SequenceGenerator(name = "FARM_PRODUCT_CATEGORY_GENERATOR", sequenceName = "FARM_PRODUCT_CATEGORY_GENERATOR_SEQ", allocationSize = 1)
    @Column(name = "farm_product_category_id")
    public Long productCategoryId;

    @Column(name="category_name")
    public String categoryName;

    @OneToMany(mappedBy = "productCategory", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    public List<FarmProducts> products;

}

@Entity
@Table(name="farm_products")
@Getter
@Setter
@ToString(exclude= "productCategory")
public class FarmProducts extends BaseModel<String> {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FARM_PRODUCT_GENERATOR")
    @SequenceGenerator(name = "FARM_PRODUCT_GENERATOR", sequenceName = "FARM_PRODUCT_GENERATOR_SEQ", allocationSize = 1)
    @Column(name = "farm_product_id")
    public Long productId;

    @ManyToOne
    @JoinColumn(name = "farm_product_category_id")
    public ProductCategory productCategory;

    @Column(name = "product_name")
    public String product;

    @Column(name = "is_deleted")
    public String isDeleted;

}
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseModel<U> {

    @CreatedBy
    protected U createdBy;

    @CreatedDate
    @Temporal(TemporalType.TIMESTAMP)
    protected Date creationDate;

    @LastModifiedBy
    protected U lastModifiedBy;

    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    protected Date lastModifiedDate;

}
</code>```

DTO class:

```<code>@Data
public class AuditDTO implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -775795624442449273L;

    public String createdBy;

    public Date creationDate;

    public Date lastModifiedBy;

    public Date lastModifiedDate;

}

@Data
public class FarmProductCategoryDTO extends AuditDTO implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 7016941232710915827L;

    public Long productCategoryId;

    public List<FarmProductDTO> products;

}

@Data
public class FarmProductDTO extends AuditDTO implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 6164359760527049606L;

    public Long productId;

    public FarmProductCategoryDTO farmProductCategoryVO;

    public String product;

    public String isDeleted;

}
</code>```

Repository class:

```<code>@Repository
public interface FarmProductCategoryRepository  extends JpaRepository<ProductCategory, Long>{

    List<ProductCategory> findAll();

}
</code>```

Service class:

```<code>@Service
public class FarmProductServiceImpl implements FarmProductService {

    @Autowired
    FarmProductCategoryRepository farmProductRepository;

    @Autowired
    ProductCategoryMapper productCategoryMapper;

    /**
     *
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
    public List<FarmProductCategoryDTO> farmProductList() {
        List<FarmProductCategoryDTO>  farmCategories = null;
         List<ProductCategory> productCategory = farmProductRepository.findAll();
         System.out.println("farmProduct"+productCategory.size());

         farmCategories = productCategoryMapper.productCategoryToProductCategoryDTO(productCategory);

        return farmCategories;
    }
}
</code>```

Mapper class:

```<code>@Mapper(componentModel = "spring",uses=ProductMapper.class)
public interface ProductCategoryMapper {
    @Mapping(source = "products", target = "products")
    FarmProductCategoryDTO productCategoryToProductCategoryDTO(ProductCategory productCategory);

    List<FarmProductCategoryDTO> productCategoryToProductCategoryDTO(List<ProductCategory> productCategory);

    ProductCategory FarmProductCategoryDTOToProductCategory(FarmProductCategoryDTO farmProductCategoryDTO);
}

@Mapper(componentModel="spring")

public interface ProductMapper  {

    /*
     * @Mappings({
     *
     * @Mapping(source="productCategory",target = "farmProductCategoryVO",
     * ignore=true),
     *
     * })
     */

     FarmProductDTO farmProductToProductDto(FarmProducts farmProducts);

     List<FarmProductDTO> farmProductsToFarmProductsDtos(List<FarmProducts> callRecords);

}
</code>```

I have bidirectional mapping.

When I try to fetch the all the category from DB works fine. and when I try to map the same to DTO to object using mapstruct, I am getting below error.

```<code>java.lang.StackOverflowError
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:42)
at com.company.farmer.mapper.dto.ProductMapperImpl.productCategoryToFarmProductCategoryDTO(ProductMapperImpl.java:58)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductToProductDto(ProductMapperImpl.java:29)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:44)
at com.company.farmer.mapper.dto.ProductMapperImpl.productCategoryToFarmProductCategoryDTO(ProductMapperImpl.java:58)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductToProductDto(ProductMapperImpl.java:29)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:44)
at com.company.farmer.mapper.dto.ProductMapperImpl.productCategoryToFarmProductCategoryDTO(ProductMapperImpl.java:58)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductToProductDto(ProductMapperImpl.java:29)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:44)
at com.company.farmer.mapper.dto.ProductMapperImpl.productCategoryToFarmProductCategoryDTO(ProductMapperImpl.java:58)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductToProductDto(ProductMapperImpl.java:29)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:44)
at com.company.farmer.mapper.dto.ProductMapperImpl.productCategoryToFarmProductCategoryDTO(ProductMapperImpl.java:58)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductToProductDto(ProductMapperImpl.java:29)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:44)
</code>```

答:
When mapping with cycles you would have to break that cycle somehow:

Using @Context

Have a look at the mapstruct-mapping-with-cycles example.

Ignore on some level

Like in your commented out code.

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

    @Mapping(source="productCategory",target = "farmProductCategoryVO", ignore=true)
    FarmProductDTO farmProductToProductDto(FarmProducts farmProducts);

    List<FarmProductDTO> farmProductsToFarmProductsDtos(List<FarmProducts> callRecords);
}
</code>```

Body:
I am new to mapstruct. I am trying to map the Entity object(bidirectional) to DTO object using Mapstruct.
I am able to retrieve the entity object using JPA repository and when I try to map the same to DTo object I am getting java.lang.StackOverflowError.

Code:

@Entity
@Table(name = "product_category")
@Getter
@Setter
@ToString(exclude = {"products"})

public class ProductCategory extends BaseModel<String> {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FARM_PRODUCT_CATEGORY_GENERATOR")
    @SequenceGenerator(name = "FARM_PRODUCT_CATEGORY_GENERATOR", sequenceName = "FARM_PRODUCT_CATEGORY_GENERATOR_SEQ", allocationSize = 1)
    @Column(name = "farm_product_category_id")
    public Long productCategoryId;

    @Column(name="category_name")
    public String categoryName;

    @OneToMany(mappedBy = "productCategory", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    public List<FarmProducts> products;

}

@Entity
@Table(name="farm_products")
@Getter
@Setter
@ToString(exclude= "productCategory")
public class FarmProducts extends BaseModel<String> {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FARM_PRODUCT_GENERATOR")
    @SequenceGenerator(name = "FARM_PRODUCT_GENERATOR", sequenceName = "FARM_PRODUCT_GENERATOR_SEQ", allocationSize = 1)
    @Column(name = "farm_product_id")
    public Long productId;

    @ManyToOne
    @JoinColumn(name = "farm_product_category_id")
    public ProductCategory productCategory;

    @Column(name = "product_name")
    public String product;

    @Column(name = "is_deleted")
    public String isDeleted;

}
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseModel {

    @CreatedBy
    protected U createdBy;

    @CreatedDate
    @Temporal(TemporalType.TIMESTAMP)
    protected Date creationDate;

    @LastModifiedBy
    protected U lastModifiedBy;

    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    protected Date lastModifiedDate;

}

DTO class:

@Data
public class AuditDTO implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -775795624442449273L;

    public String createdBy;

    public Date creationDate;

    public Date lastModifiedBy;

    public Date lastModifiedDate;

}

@Data
public class FarmProductCategoryDTO extends AuditDTO implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 7016941232710915827L;

    public Long productCategoryId;

    public List<FarmProductDTO> products;

}

@Data
public class FarmProductDTO extends AuditDTO implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 6164359760527049606L;

    public Long productId;

    public FarmProductCategoryDTO farmProductCategoryVO;

    public String product;

    public String isDeleted;

}

Repository class:

@Repository
public interface FarmProductCategoryRepository  extends JpaRepository<ProductCategory, Long>{

    List<ProductCategory> findAll();

}

Service class:

@Service
public class FarmProductServiceImpl implements FarmProductService {

    @Autowired
    FarmProductCategoryRepository farmProductRepository;

    @Autowired
    ProductCategoryMapper productCategoryMapper;

    /**
     *
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
    public List<FarmProductCategoryDTO> farmProductList() {
        List<FarmProductCategoryDTO>  farmCategories = null;
         List<ProductCategory> productCategory = farmProductRepository.findAll();
         System.out.println("farmProduct"+productCategory.size());

         farmCategories = productCategoryMapper.productCategoryToProductCategoryDTO(productCategory);

        return farmCategories;
    }
}

Mapper class:

@Mapper(componentModel = "spring",uses=ProductMapper.class)
public interface ProductCategoryMapper {
    @Mapping(source = "products", target = "products")
    FarmProductCategoryDTO productCategoryToProductCategoryDTO(ProductCategory productCategory);

    List<FarmProductCategoryDTO> productCategoryToProductCategoryDTO(List<ProductCategory> productCategory);

    ProductCategory FarmProductCategoryDTOToProductCategory(FarmProductCategoryDTO farmProductCategoryDTO);
}

@Mapper(componentModel="spring")

public interface ProductMapper  {

    /*
     * @Mappings({
     *
     * @Mapping(source="productCategory",target = "farmProductCategoryVO",
     * ignore=true),
     *
     * })
     */

     FarmProductDTO farmProductToProductDto(FarmProducts farmProducts);

     List<FarmProductDTO> farmProductsToFarmProductsDtos(List<FarmProducts> callRecords);

}

I have bidirectional mapping.

When I try to fetch the all the category from DB works fine. and when I try to map the same to DTO to object using mapstruct, I am getting below error.

java.lang.StackOverflowError
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:42)
at com.company.farmer.mapper.dto.ProductMapperImpl.productCategoryToFarmProductCategoryDTO(ProductMapperImpl.java:58)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductToProductDto(ProductMapperImpl.java:29)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:44)
at com.company.farmer.mapper.dto.ProductMapperImpl.productCategoryToFarmProductCategoryDTO(ProductMapperImpl.java:58)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductToProductDto(ProductMapperImpl.java:29)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:44)
at com.company.farmer.mapper.dto.ProductMapperImpl.productCategoryToFarmProductCategoryDTO(ProductMapperImpl.java:58)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductToProductDto(ProductMapperImpl.java:29)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:44)
at com.company.farmer.mapper.dto.ProductMapperImpl.productCategoryToFarmProductCategoryDTO(ProductMapperImpl.java:58)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductToProductDto(ProductMapperImpl.java:29)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:44)
at com.company.farmer.mapper.dto.ProductMapperImpl.productCategoryToFarmProductCategoryDTO(ProductMapperImpl.java:58)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductToProductDto(ProductMapperImpl.java:29)
at com.company.farmer.mapper.dto.ProductMapperImpl.farmProductsToFarmProductsDtos(ProductMapperImpl.java:44)

Body:
When mapping with cycles you would have to break that cycle somehow:

Using @Context

Have a look at the mapstruct-mapping-with-cycles example.

Ignore on some level

Like in your commented out code.

@Mapper
public interface ProductMapper  {

    @Mapping(source="productCategory",target = "farmProductCategoryVO", ignore=true)
    FarmProductDTO farmProductToProductDto(FarmProducts farmProducts);

    List<FarmProductDTO> farmProductsToFarmProductsDtos(List<FarmProducts> callRecords);
}


来源: stackexchange

问:
Top part of my website disappears when I resize it vertically
I'm trying to create a responsive log in page for a college, but when I resize the window vertically the logo and basically the top part disappears.

Currently I'm designing for an iPhone 7 using the dev tools in Google Chrome to help me with the view. When I open the website on my Huawei phone and tap the password field the keyboard pushes the page up and the logo partially disappears. This does not happen on my iPhone.

I think the problem is somewhere in my div elements. Sorry if its a dumb question, I'm a beginner.

Website: https://borislav1333.000webhostapp.com/

body
{
 margin: 0;
}

img
{
 max-width: 300px;
 position: absolute;
 top: 60px;
 left: 37px;
 z-index: 1;

}

.container
{
 width: 375px;
 height: 667px;
 background-color: white;
 margin: auto;
 position: absolute;
 left: 50%;
 top: 50%;
 transform: translate(-50%, -50%);
 font-family: Georgia;
}

.form-back
{
 width: 200px;
 background-color: white;
 z-index: 1;
 margin: 0 auto;
 padding: 45px;
 position: absolute;
 top: 80%;
 left: 50%;
 transform: translate(-50%, -80%);
 text-align: center;
 font-size: 18px;
}

input[type=text], input[type=password]
{
 width: 100%;
 padding: 10px;
 margin: 8px 0px 8px;
 border: solid 1px #aaa;
 border-radius: 4px;
}

button
{
 width: 100%;
 height: 50px;
 border: none;
 border-radius: 30px;
 border-color: white;
 background-color: #e52791;
 font-family: Georgia;
 transition: background-color 0.7s ease-out;
}

button:hover
{
 background-color: #02356a;
 color: white;
 transition: background-color 0.7s ease;
}

.submit
{
 position: relative;
 top: 30px;
}

::placeholder
{
 font-family: georgia;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
 <div class="img"><img src="logo.jpg"></div>

 <div class="form-back">
  <form action="message.html" onsubmit="return validation()">
    <div>
     <label for="accountNum">Metric Number</label><br>
     <input type="text" id="accountNum" name="accountNum" placeholder="Metric Number..."><br>
    </div>

    <div>
     <label for="surname">Password:</label><br>
     <input type="password" id="surname" name="surname" placeholder="Password..."><br>
    </div>

    <div class="submit">
     <button type="submit">Log In</button>
    </div>
 </div>
</div></code>```

答:
As per your code you have used position absolute value in many elements. I think this problem which you are facing is happening due to this absolute. I have updated your CSS code and added snippet below. Replace it and check, I wish you problem will be resolved :

         body
          {
              margin: 0;
          }

          img
          {
              width: 100%;
              max-width: 300px;
              z-index: 1;
              margin: 0 auto;
          }

          .container
          {
              margin: 0 auto;
              font-family: Georgia;
              text-align: center;
          }

          .form-back
          {
              width: 100%;

              background:transparent;
              margin: 0 auto;
              padding: 45px;
              text-align: center;
              font-size: 18px;
          }

          input[type=text], input[type=password]
          {
              width: 100%;
              padding: 10px;
              margin: 8px 0px 8px;
              border: solid 1px #aaa;
              border-radius: 4px;
          }

          button
          {
              width: 100%;
              height: 50px;
              border: none;
              border-radius: 30px;
              border-color: white;
              background-color: #e52791;
              font-family: Georgia;
              transition: background-color 0.7s ease-out;
          }

          button:hover
          {
              background-color: #02356a;
              color: white;
              transition: background-color 0.7s ease;
          }

          .submit
          {
              position: relative;
              top: 30px;
          }

          ::placeholder
          {
              font-family: georgia;
          }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<div class="container">
    <div class="img"><img src="https://borislav1333.000webhostapp.com/logo.jpg"></div>

    <div class="form-back">
        <form action="message.html" onsubmit="return validation()">
                <div>
                    <label for="accountNum">Metric Number</label><br>
                    <input type="text" id="accountNum" name="accountNum" placeholder="Metric Number..."><br>
                </div>

                <div>
                    <label for="surname">Password:</label><br>
                    <input type="password" id="surname" name="surname" placeholder="Password..."><br>
                </div>

                <div class="submit">
                    <button type="submit">Log In</button>
                </div>
              </form>
    </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a responsive log in page for a college, but when I resize the window vertically the logo and basically the top part disappears.

Currently I'm designing for an iPhone 7 using the dev tools in Google Chrome to help me with the view. When I open the website on my Huawei phone and tap the password field the keyboard pushes the page up and the logo partially disappears. This does not happen on my iPhone.

I think the problem is somewhere in my div elements. Sorry if its a dumb question, I'm a beginner.

Website: https://borislav1333.000webhostapp.com/

body
{
 margin: 0;
}

img
{
 max-width: 300px;
 position: absolute;
 top: 60px;
 left: 37px;
 z-index: 1;

}

.container
{
 width: 375px;
 height: 667px;
 background-color: white;
 margin: auto;
 position: absolute;
 left: 50%;
 top: 50%;
 transform: translate(-50%, -50%);
 font-family: Georgia;
}

.form-back
{
 width: 200px;
 background-color: white;
 z-index: 1;
 margin: 0 auto;
 padding: 45px;
 position: absolute;
 top: 80%;
 left: 50%;
 transform: translate(-50%, -80%);
 text-align: center;
 font-size: 18px;
}

input[type=text], input[type=password]
{
 width: 100%;
 padding: 10px;
 margin: 8px 0px 8px;
 border: solid 1px #aaa;
 border-radius: 4px;
}

button
{
 width: 100%;
 height: 50px;
 border: none;
 border-radius: 30px;
 border-color: white;
 background-color: #e52791;
 font-family: Georgia;
 transition: background-color 0.7s ease-out;
}

button:hover
{
 background-color: #02356a;
 color: white;
 transition: background-color 0.7s ease;
}

.submit
{
 position: relative;
 top: 30px;
}

::placeholder
{
 font-family: georgia;
}

  <form action="message.html" onsubmit="return validation()">

     Metric Number

     <input type="text" id="accountNum" name="accountNum" placeholder="Metric Number...">

     Password:

     <input type="password" id="surname" name="surname" placeholder="Password...">

     <button type="submit">Log In</button>

Body:
As per your code you have used position absolute value in many elements. I think this problem which you are facing is happening due to this absolute. I have updated your CSS code and added snippet below. Replace it and check, I wish you problem will be resolved :

         body
          {
              margin: 0;
          }

          img
          {
              width: 100%;
              max-width: 300px;
              z-index: 1;
              margin: 0 auto;
          }

          .container
          {
              margin: 0 auto;
              font-family: Georgia;
              text-align: center;
          }

          .form-back
          {
              width: 100%;

              background:transparent;
              margin: 0 auto;
              padding: 45px;
              text-align: center;
              font-size: 18px;
          }

          input[type=text], input[type=password]
          {
              width: 100%;
              padding: 10px;
              margin: 8px 0px 8px;
              border: solid 1px #aaa;
              border-radius: 4px;
          }

          button
          {
              width: 100%;
              height: 50px;
              border: none;
              border-radius: 30px;
              border-color: white;
              background-color: #e52791;
              font-family: Georgia;
              transition: background-color 0.7s ease-out;
          }

          button:hover
          {
              background-color: #02356a;
              color: white;
              transition: background-color 0.7s ease;
          }

          .submit
          {
              position: relative;
              top: 30px;
          }

          ::placeholder
          {
              font-family: georgia;
          }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<div class="container">
    <div class="img"><img src="https://borislav1333.000webhostapp.com/logo.jpg"></div>

    <div class="form-back">
        <form action="message.html" onsubmit="return validation()">
                <div>
                    <label for="accountNum">Metric Number</label><br>
                    <input type="text" id="accountNum" name="accountNum" placeholder="Metric Number..."><br>
                </div>

                <div>
                    <label for="surname">Password:</label><br>
                    <input type="password" id="surname" name="surname" placeholder="Password..."><br>
                </div>

                <div class="submit">
                    <button type="submit">Log In</button>
                </div>
              </form>
    </div>
</div>


问:
How to make IntelliJ 2019.3+ not interpret XPath selectors as CSS selectors?
How to make IntelliJ 2019.3+ not interpret XPath selectors as CSS selectors?

In my case, I'm using Jest (a JavaScript Webdriver testing framework) and the $-notation shorthand which I suspect IntelliJ is interpreting as jQuery (which otherwise does require a valid CSS selection). See the screenshot below.

The testing code functions as intended, but these warnings are troublesome.

答:
Exactly - IDEA treats $  as jQuery and thus "jQuery-CSS" language is auto-injected in $() calls.
Deselecting the js: JQuery selectors language injection in Settings | Editor | Language Injections should fix the issue:


问:
UITableView Multiple Checkmark Selection
Having read a couple of the questions asked relating to this, I can get the functionality to work. However my list is long and scrollable, so when I scroll up and down the selection of the checkmarks are all over the place. selectedIndexes is a NSMutableArray. Any ideas?

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];

    if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
        [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
        [selectedIndexes addObject:[NSNumber numberWithInt:indexPath.row]];

    }
    else {
        [selectedCell setAccessoryType:UITableViewCellAccessoryNone];
        [selectedIndexes removeObject:[NSNumber numberWithInt:indexPath.row]];

    }

    [tableView deselectRowAtIndexPath:indexPath animated:NO];

}
</code>```

In my cellForRowAtIndexPath: i have the following check.

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CustomCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    NSDictionary *dictionary = [natures objectAtIndex:indexPath.section];
    NSArray *array = [dictionary objectForKey:@"Name"];
    NSString *cellValue = [array objectAtIndex:indexPath.row];
    cell.textLabel.text = cellValue;

    for (int i = 0; i < selectedIndexes.count; i++) {
        NSUInteger num = [[selectedIndexes objectAtIndex:i] intValue];

        if (num == indexPath.row) {
            [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
        }
        else {
            [cell setAccessoryType:UITableViewCellAccessoryNone];
        }

    }

    return cell;
}
</code>```

答:
You need to modify your cellForRowAtIndexPath to be the following:

```<code>// Assume cell is not checked -- if it is the loop below will check it.
[cell setAccessoryType:UITableViewCellAccessoryNone];
for (int i = 0; i < selectedIndexes.count; i++) {
        NSUInteger num = [[selectedIndexes objectAtIndex:i] intValue];

        if (num == indexPath.row) {
            [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
            // Once we find a match there is no point continuing the loop
            break;
        }
    }
</code>```

You need to do this because a reusable cell might have the checkmark set -- so you need to clear it. Hope this helps.

Incidentally, using an NSSet would probably be a more elegant solution!

ContentLicense: CC BY-SA 3.0

Body:
Having read a couple of the questions asked relating to this, I can get the functionality to work. However my list is long and scrollable, so when I scroll up and down the selection of the checkmarks are all over the place. selectedIndexes is a NSMutableArray. Any ideas?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];

    if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
        [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
        [selectedIndexes addObject:[NSNumber numberWithInt:indexPath.row]];

    }
    else {
        [selectedCell setAccessoryType:UITableViewCellAccessoryNone];
        [selectedIndexes removeObject:[NSNumber numberWithInt:indexPath.row]];

    }

    [tableView deselectRowAtIndexPath:indexPath animated:NO];

}

In my cellForRowAtIndexPath: i have the following check.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CustomCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    NSDictionary *dictionary = [natures objectAtIndex:indexPath.section];
    NSArray *array = [dictionary objectForKey:@"Name"];
    NSString *cellValue = [array objectAtIndex:indexPath.row];
    cell.textLabel.text = cellValue;

    for (int i = 0; i < selectedIndexes.count; i++) {
        NSUInteger num = [[selectedIndexes objectAtIndex:i] intValue];

        if (num == indexPath.row) {
            [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
        }
        else {
            [cell setAccessoryType:UITableViewCellAccessoryNone];
        }

    }

    return cell;
}

Body:
You need to modify your cellForRowAtIndexPath to be the following:

// Assume cell is not checked -- if it is the loop below will check it.
[cell setAccessoryType:UITableViewCellAccessoryNone];
for (int i = 0; i < selectedIndexes.count; i++) {
        NSUInteger num = [[selectedIndexes objectAtIndex:i] intValue];

        if (num == indexPath.row) {
            [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
            // Once we find a match there is no point continuing the loop
            break;
        }
    }

You need to do this because a reusable cell might have the checkmark set -- so you need to clear it. Hope this helps.

Incidentally, using an NSSet would probably be a more elegant solution!


Title: A function incorporating all combination list

Body:
I'm trying to make a function which holds all combination elements of list. The detail is like this.

This is when list elements are [1,2,3] and n=4.
example,

elements=[1,2,3]
all_data=[]

for x_1 in elements:
    tmp=[]
    tmp.append(x_1)
    all_data.append(tmp)
    for x_2 in elements:
        tmp=[]
        tmp.append(x_1)
        tmp.append(x_2)
        all_data.append(tmp)
        for x_3 in elements:
            tmp=[]
            tmp.append(x_1)
            tmp.append(x_2)
            tmp.append(x_3)
            all_data.append(tmp)
            for x_4 in elements:
                tmp=[]
                tmp.append(x_1)
                tmp.append(x_2)
                tmp.append(x_3)
                tmp.append(x_4)
                all_data.append(tmp)
all_data

Output is →

[[1],
 [1, 1],
 [1, 1, 1],
 [1, 1, 1, 1],
 [1, 1, 1, 2],
 [1, 1, 1, 3],
 [1, 1, 2],
 [1, 1, 2, 1],
 [1, 1, 2, 2],
 [1, 1, 2, 3],
 [1, 1, 3],
 [1, 1, 3, 1],
 [1, 1, 3, 2],
 [1, 1, 3, 3],
 [1, 2],
 [1, 2, 1],
 [1, 2, 1, 1],
 [1, 2, 1, 2],
 [1, 2, 1, 3],
 [1, 2, 2],
 [1, 2, 2, 1],
 [1, 2, 2, 2],
 [1, 2, 2, 3],
 [1, 2, 3],
 [1, 2, 3, 1],
 [1, 2, 3, 2],
 [1, 2, 3, 3],
 [1, 3],
 [1, 3, 1],
 [1, 3, 1, 1],
 [1, 3, 1, 2],
 [1, 3, 1, 3],
 [1, 3, 2],
 [1, 3, 2, 1],
 [1, 3, 2, 2],
 [1, 3, 2, 3],
 [1, 3, 3],
 [1, 3, 3, 1],
 [1, 3, 3, 2],
 [1, 3, 3, 3],
 [2],
 [2, 1],
 .....
 [3, 2, 3],
 [3, 2, 3, 1],
 [3, 2, 3, 2],
 [3, 2, 3, 3],
 [3, 3],
 [3, 3, 1],
 [3, 3, 1, 1],
 [3, 3, 1, 2],
 [3, 3, 1, 3],
 [3, 3, 2],
 [3, 3, 2, 1],
 [3, 3, 2, 2],
 [3, 3, 2, 3],
 [3, 3, 3],
 [3, 3, 3, 1],
 [3, 3, 3, 2],
 [3, 3, 3, 3]]

But what I wanna achieve is to make a function of this doing for n times using (probably) loop statement.
So, the function's output I wanna make should be going to be like,

[[1],
[1,1],
......
[1,1,1,1,......,1], #(1 of n times)
[1,1,1,1,......,2],
......
[6],
[6,6],
......
[6,6,6,6,......,6]] #(n times)

Though I've spent almost whole week to tackle this question, not yet reached to any solution.
Could anyone give me some tips or happen to know any ideas?
Any clue is very welcome.

Thank you.

Body:
It seems that what you want is the cartesian product of k elements in the list for k in [1, 4].

If this is the case, you could use itertools.product and compute the product for k=1,2,3,4

>>> res = list(itertools.chain.from_iterable(itertools.product([1,2,3], repeat=k) for k in range(1,5)))
>>> res
[(1,), (2,), (3,), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3), (1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 1, 3), (1, 1, 2, 1), (1, 1, 2, 2), (1, 1, 2, 3), (1, 1, 3, 1), (1, 1, 3, 2), (1, 1, 3, 3), (1, 2, 1, 1), (1, 2, 1, 2), (1, 2, 1, 3), (1, 2, 2, 1), (1, 2, 2, 2), (1, 2, 2, 3), (1, 2, 3, 1), (1, 2, 3, 2), (1, 2, 3, 3), (1, 3, 1, 1), (1, 3, 1, 2), (1, 3, 1, 3), (1, 3, 2, 1), (1, 3, 2, 2), (1, 3, 2, 3), (1, 3, 3, 1), (1, 3, 3, 2), (1, 3, 3, 3), (2, 1, 1, 1), (2, 1, 1, 2), (2, 1, 1, 3), (2, 1, 2, 1), (2, 1, 2, 2), (2, 1, 2, 3), (2, 1, 3, 1), (2, 1, 3, 2), (2, 1, 3, 3), (2, 2, 1, 1), (2, 2, 1, 2), (2, 2, 1, 3), (2, 2, 2, 1), (2, 2, 2, 2), (2, 2, 2, 3), (2, 2, 3, 1), (2, 2, 3, 2), (2, 2, 3, 3), (2, 3, 1, 1), (2, 3, 1, 2), (2, 3, 1, 3), (2, 3, 2, 1), (2, 3, 2, 2), (2, 3, 2, 3), (2, 3, 3, 1), (2, 3, 3, 2), (2, 3, 3, 3), (3, 1, 1, 1), (3, 1, 1, 2), (3, 1, 1, 3), (3, 1, 2, 1), (3, 1, 2, 2), (3, 1, 2, 3), (3, 1, 3, 1), (3, 1, 3, 2), (3, 1, 3, 3), (3, 2, 1, 1), (3, 2, 1, 2), (3, 2, 1, 3), (3, 2, 2, 1), (3, 2, 2, 2), (3, 2, 2, 3), (3, 2, 3, 1), (3, 2, 3, 2), (3, 2, 3, 3), (3, 3, 1, 1), (3, 3, 1, 2), (3, 3, 1, 3), (3, 3, 2, 1), (3, 3, 2, 2), (3, 3, 2, 3), (3, 3, 3, 1), (3, 3, 3, 2), (3, 3, 3, 3)]
>>> len(res)
120

In case you don't need all the values you can just iterate over each of them:

for k in range(1,4):
   for t in itertools.product([1,2,3], repeat=k):
      ...


问:
AttributeError: 'int' object has no attribute 'feat'
I'm having quite a weird issue with my code:

So I am trying to build a classifier and in my 'predict' part of the code I have written:

```<code>def predict(self, feature):
        node = self.tree
        for i in range(len(feature)):
            if feature[node.feat] == 0:
                 node = node.left
            else:
                 node = node.right
</code>```

To check whether to move left or right.

And this is my node class:

```<code>class Node():
    def __init__(self, data):
        self.left = None
        self.right = None
        self.feat = 0
</code>```

However, when I run the code, I seem to be getting the issue
AttributeError: 'int' object has no attribute 'feat'

答:
Sorry my bad the issue is solved,

I was just returning an int in one of my recursive call instead of a node object

Body:
I'm having quite a weird issue with my code:

So I am trying to build a classifier and in my 'predict' part of the code I have written:

def predict(self, feature):
        node = self.tree
        for i in range(len(feature)):
            if feature[node.feat] == 0:
                 node = node.left
            else:
                 node = node.right

To check whether to move left or right.

And this is my node class:

class Node():
    def __init__(self, data):
        self.left = None
        self.right = None
        self.feat = 0

However, when I run the code, I seem to be getting the issue
AttributeError: 'int' object has no attribute 'feat'


问:
npm run fails because IntelliJ can't find npm even though it is installed
On my windows 10, in my build.sbt in Intellij IDE, I have a function def runDevBuild(implicit dir: File): Int = ifUiInstalled(runScript("npm run build")). When I run it, I get error 'npm' is not recognized as an internal or external command, operable program or batch file.. npm is installed and I have added it in the PATH variable.

```<code>C:\Users\surface>where npm
C:\Program Files\nodejs\npm
C:\Program Files\nodejs\npm.cmd
</code>```

I have also added paths to npm and node in Intellij settings.

Why is the script not running?

答:
delete the node_modules from your directory.use git bash run this command </p>

```<code>npm -i -g
</code>```

Body:
On my windows 10, in my build.sbt in Intellij IDE, I have a function def runDevBuild(implicit dir: File): Int = ifUiInstalled(runScript("npm run build")). When I run it, I get error 'npm' is not recognized as an internal or external command, operable program or batch file.. npm is installed and I have added it in the PATH variable.

C:\Users\surface>where npm
C:\Program Files\nodejs\npm
C:\Program Files\nodejs\npm.cmd

I have also added paths to npm and node in Intellij settings.

Why is the script not running?

Body:
delete the node_modules from your directory.use git bash run this command

npm -i -g


问:
JPA Composite PK referenced by FKs in One to Many Relationship
I am trying to map the tables below into JPA. The relationships are one-to-many between user_tax and tax and user_tax and user. It has confused me the fact that i have a composite primary key, and i need to map the foreign keys to these 2 keys.

the error message: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: entity.Tax.user_tax in entity.UserTax.taxs

```<code>             tax           user_tax         user
           --------        --------        ------
         PK|t_id  |--------| t_id |PK-FK  |u_name|
           |t_name|   PK-FK| u_id |-------|u_id  | PK
           |      |        | name |       |      |
</code>```

Here is my Entities:

```<code> @Entity
 @Table(name = "user")
 @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    public class User implements Serializable {

       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
         private Long id;

       @Column(name="u_name")
         private String uname;

          getters + setters
        }
</code>```

```<code> @Entity
 @Table(name = "tax")
 @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    public class Tax implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;

        @Column(name = "t_name")
          private String tname;
</code>```

```<code>   @Embeddable
    public class UserTaxId implements Serializable {

      @Column(name="u_id")
        private Long uId;

        @Column(name="t_id")
        private Long tId;
</code>```

```<code>  @Entity
  @Table(name = "user_tax")
  @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    public class UserTax implements Serializable {

      @EmbeddedId
        private UserTaxId userTaxId;

      @OneToMany(fetch = FetchType.LAZY, mappedBy = "user_tax")
        private List<User> users;

      @OneToMany(fetch = FetchType.LAZY, mappedBy = "user_tax")
        private List<Tax> taxs;
</code>```

答:
I will post here what worked for me after 3 days of research.

Brian Vosburgh correctly posted the UserTax class:

```<code> @Entity
@Table(name = "user_tax")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class UserTax implements Serializable {

    @EmbeddedId
    private UserTaxId userTaxId;

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("uId") // maps uId attribute of embedded id
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("tId") // maps tId attribute of embedded id
    private Tax tax;

    ...
}
</code>```

However, i was getting error meassages and my code wasn't compiling. Then i also had to edit the User and Tax classes:

```<code> @Entity
     @Table(name = "user")
     @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
        public class User implements Serializable {

           @Id
           @GeneratedValue(strategy = GenerationType.IDENTITY)
             private Long id;

           @OneToMany(
            mappedBy = "tid",
            cascade = CascadeType.ALL,
            orphanRemoval = true
        )
        private List<UserTax> tax = new ArrayList<>();

           @Column(name="u_name")
             private String uname;

              getters + setters
            }

    @Entity
     @Table(name = "tax")
     @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
        public class Tax implements Serializable {

            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
              private Long id;

           @OneToMany(
            mappedBy = "uid",
            cascade = CascadeType.ALL,
            orphanRemoval = true
        )
        private List<UserTax> taxs = new ArrayList<>();

            @Column(name = "t_name")
              private String tname;

    setters+getters

    }
</code>```

Here is the link where i found the solution to my problem: https://vladmihalcea.com/the-best-way-to-map-a-many-to-many-association-with-extra-columns-when-using-jpa-and-hibernate/

Body:
I am trying to map the tables below into JPA. The relationships are one-to-many between user_tax and tax and user_tax and user. It has confused me the fact that i have a composite primary key, and i need to map the foreign keys to these 2 keys.

the error message: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: entity.Tax.user_tax in entity.UserTax.taxs

             tax           user_tax         user
           --------        --------        ------
         PK|t_id  |--------| t_id |PK-FK  |u_name|
           |t_name|   PK-FK| u_id |-------|u_id  | PK
           |      |        | name |       |      |

Here is my Entities:

 @Entity
 @Table(name = "user")
 @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    public class User implements Serializable {

       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
         private Long id;

       @Column(name="u_name")
         private String uname;

          getters + setters
        }

 @Entity
 @Table(name = "tax")
 @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    public class Tax implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;

        @Column(name = "t_name")
          private String tname;

   @Embeddable
    public class UserTaxId implements Serializable {

      @Column(name="u_id")
        private Long uId;

        @Column(name="t_id")
        private Long tId;

  @Entity
  @Table(name = "user_tax")
  @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    public class UserTax implements Serializable {

      @EmbeddedId
        private UserTaxId userTaxId;

      @OneToMany(fetch = FetchType.LAZY, mappedBy = "user_tax")
        private List<User> users;

      @OneToMany(fetch = FetchType.LAZY, mappedBy = "user_tax")
        private List<Tax> taxs;

Body:
I will post here what worked for me after 3 days of research.

Brian Vosburgh correctly posted the UserTax class:

 @Entity
@Table(name = "user_tax")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class UserTax implements Serializable {

    @EmbeddedId
    private UserTaxId userTaxId;

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("uId") // maps uId attribute of embedded id
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("tId") // maps tId attribute of embedded id
    private Tax tax;

    ...
}

However, i was getting error meassages and my code wasn't compiling. Then i also had to edit the User and Tax classes:

 @Entity
     @Table(name = "user")
     @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
        public class User implements Serializable {

           @Id
           @GeneratedValue(strategy = GenerationType.IDENTITY)
             private Long id;

           @OneToMany(
            mappedBy = "tid",
            cascade = CascadeType.ALL,
            orphanRemoval = true
        )
        private List<UserTax> tax = new ArrayList<>();

           @Column(name="u_name")
             private String uname;

              getters + setters
            }

    @Entity
     @Table(name = "tax")
     @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
        public class Tax implements Serializable {

            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
              private Long id;

           @OneToMany(
            mappedBy = "uid",
            cascade = CascadeType.ALL,
            orphanRemoval = true
        )
        private List<UserTax> taxs = new ArrayList<>();

            @Column(name = "t_name")
              private String tname;

    setters+getters

    }

Here is the link where i found the solution to my problem: https://vladmihalcea.com/the-best-way-to-map-a-many-to-many-association-with-extra-columns-when-using-jpa-and-hibernate/


问:
Why is the Ajax response adding the post details WP
For some reason the below Ajax response is adding the post details, and that is not the intended application.

I want to use only the post id that returns in the end.
Furthermore I tried to figure out why is my Ajax returning the details in text type and not in JSON type as I wished for?.

This is the outcome of the response

Here is my JS code:

```<code>createRate(){
    var ourNewPost = {
        'title': $(".new-rate-title").val(),
        'content': $('.new-rate-body').val(),
        'rate': $('.custom-star:checked').val(),
        'productId': $('.submit-rate').data('id')
    }

    $.ajax({
        // adding nonce key to make wordpress know we are looged in and has the permision to do that method.
        beforeSend: (xhr) => {
            xhr.setRequestHeader('X-WP-Nonce', ylsData.nonce);
        },
        url: ylsData.root_url + '/wp-json/yls/v1/rating/',
        type: 'POST',
        data: ourNewPost,
        dataType:"text",
        success: (response) => {

            console.log('congrats');
            console.log(response);
        },
        error: (response) => {
            console.log('failed');
            console.log(response);

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

and here is my php route code:

```<code>add_action('rest_api_init','ylsRateRoute');

function ylsRateRoute(){
    register_rest_route('yls/v1','rating',array(
        'methods' => 'POST',
        'callback'=> 'createLike'
    ));

}

function createLike($data){
    if(is_user_logged_in()){
        $title = sanitize_text_field($data['title']);
        $content = sanitize_text_field($data['content']);
        $rateNum = sanitize_text_field($data['rate']);
        $productId = sanitize_text_field($data['productId']);
        if(get_post_type($productId) == 'product'){
            return wp_insert_post(array(
                'post_title' => $title,
                'post_type' => 'rate',
                'post_content' => $content,
                'post_status' => 'publish',
                'meta_input' => array(
                    'rate_related_product' => $productId,
                    'rating_rate' => $rateNum
                )
              ));
        }else{
            die("Invalid product id");
        }
      }else{
        die("you must be logged in first");
      }
}
</code>```

答:
So to answer your question about 'why is my Ajax returning the details in text type and not in JSON`

It is because you are asking for an array to be returned (not JSON)

```<code>return wp_insert_post(array(...

</code>```

If you want a response in JSON format use json_encode()

Body:
For some reason the below Ajax response is adding the post details, and that is not the intended application.

I want to use only the post id that returns in the end.
Furthermore I tried to figure out why is my Ajax returning the details in text type and not in JSON type as I wished for?.

This is the outcome of the response

Here is my JS code:

createRate(){
    var ourNewPost = {
        'title': $(".new-rate-title").val(),
        'content': $('.new-rate-body').val(),
        'rate': $('.custom-star:checked').val(),
        'productId': $('.submit-rate').data('id')
    }

    $.ajax({
        // adding nonce key to make wordpress know we are looged in and has the permision to do that method.
        beforeSend: (xhr) => {
            xhr.setRequestHeader('X-WP-Nonce', ylsData.nonce);
        },
        url: ylsData.root_url + '/wp-json/yls/v1/rating/',
        type: 'POST',
        data: ourNewPost,
        dataType:"text",
        success: (response) => {

            console.log('congrats');
            console.log(response);
        },
        error: (response) => {
            console.log('failed');
            console.log(response);

        }
    });
}

and here is my php route code:

add_action('rest_api_init','ylsRateRoute');

function ylsRateRoute(){
    register_rest_route('yls/v1','rating',array(
        'methods' => 'POST',
        'callback'=> 'createLike'
    ));

}

function createLike($data){
    if(is_user_logged_in()){
        $title = sanitize_text_field($data['title']);
        $content = sanitize_text_field($data['content']);
        $rateNum = sanitize_text_field($data['rate']);
        $productId = sanitize_text_field($data['productId']);
        if(get_post_type($productId) == 'product'){
            return wp_insert_post(array(
                'post_title' => $title,
                'post_type' => 'rate',
                'post_content' => $content,
                'post_status' => 'publish',
                'meta_input' => array(
                    'rate_related_product' => $productId,
                    'rating_rate' => $rateNum
                )
              ));
        }else{
            die("Invalid product id");
        }
      }else{
        die("you must be logged in first");
      }
}

Body:
So to answer your question about 'why is my Ajax returning the details in text type and not in JSON`

It is because you are asking for an array to be returned (not JSON)

return wp_insert_post(array(...

If you want a response in JSON format use json_encode()


问:
C++ card validation issue
I'm a bit of a coding noob and I'm trying to get a simple Luhn algorithm to do a credit card validation check. I've got this far and I can't quite see what's wrong with the way I've done it, but the answer is always true.

If anyone can help, I'd be really grateful.

```<code>#include <iostream>
#include <cstring>
using namespace std;

bool validate(char card_number[]);

int main(int argc, char *argv[])
{
   cout << validate(argv[1]) << endl;
   return 0;
}

bool validate(char card_number[])
{
   bool valid = false;
   int length = 0;
   int step_1 = 0;
   int step_2 = 0;
   int result = 0;

   while (card_number[length] != '\0') {
       length++;
   }

   for (int i = card_number[0]; i < card_number[length]; i++) {

       if (( i % 2 != 0 && i != 0)) {

           int temp = card_number[i] - '0';

           if((temp / 10) >= 1) {
               step_1 = step_1 + (temp / 10) + (temp % 10);
           } else {

               step_1 = step_1 + temp;
           }
       } else {

           step_2 = step_2 + card_number[i] - '0';
       }
   }
   result = step_1 + step_2;

   if (result % 10 == 0) {
       valid = true;
   }

   return valid;
}

</code>```

答:
To implement the Luhn algorithm (at least the one described in this Wikipedia page) you should iterate through each digit of the card number and apply some transformations.

After calculating the length of the number, the loop in the posted code looks like this

```<code>for (int i = card_number[0]; i < card_number[length]; i++) { // ...
//           ^^^^^^^^^^^^^^      ^^^^^^^^^^^^^^^^^^^
</code>```

Where card_number is a null-terminated char array inputted by the command line, so that the former is equivalent to something like

```<code>for (int i = '7'; i < 0; i++) { // ...
//           ^^^      ^  Note that any "digit" would have a value greater than 0
</code>```

This loop would be just skipped and result would always remain equal to 0.

The rest of the code seems partial or not conforming to algorithm (if the one I linked is the actual one needed by the OP). Here is a possible implementation.

```<code>if (length == 0)
    return false;

int sum = 0;
// Loop over the array from the beginning (the "left" side of the number)
for (int i = 0; i < length - 1; ++i)
{
    int digit = card_number[i] - '0';

    // Now determine if this is an odd or even position, but from the
    // "right" side of the number
    if ( (length - 1 - i) % 2 )
    {
        // You missed this part, according to https://en.wikipedia.org/wiki/Luhn_algorithm
        digit *= 2;

        // If it's not a single digit anymore...
        if ( digit > 9 )
        {
            // Reduce to one digit again
            digit -= 9;
        }
    }

    sum += digit;
}

// You missed this part too, always according to Wikipedia
if ( (sum * 9) % 10  !=  card_number[length - 1] - '0') {
    return false;
}

return true;
</code>```

Title: C++ card validation issue

Body:
I'm a bit of a coding noob and I'm trying to get a simple Luhn algorithm to do a credit card validation check. I've got this far and I can't quite see what's wrong with the way I've done it, but the answer is always true.

If anyone can help, I'd be really grateful.

#include <iostream>
#include <cstring>
using namespace std;

bool validate(char card_number[]);

int main(int argc, char *argv[])
{
   cout << validate(argv[1]) << endl;
   return 0;
}

bool validate(char card_number[])
{
   bool valid = false;
   int length = 0;
   int step_1 = 0;
   int step_2 = 0;
   int result = 0;

   while (card_number[length] != '\0') {
       length++;
   }

   for (int i = card_number[0]; i < card_number[length]; i++) {

       if (( i % 2 != 0 && i != 0)) {

           int temp = card_number[i] - '0';

           if((temp / 10) >= 1) {
               step_1 = step_1 + (temp / 10) + (temp % 10);
           } else {

               step_1 = step_1 + temp;
           }
       } else {

           step_2 = step_2 + card_number[i] - '0';
       }
   }
   result = step_1 + step_2;

   if (result % 10 == 0) {
       valid = true;
   }

   return valid;
}

Body:
To implement the Luhn algorithm (at least the one described in this Wikipedia page) you should iterate through each digit of the card number and apply some transformations.

After calculating the length of the number, the loop in the posted code looks like this

for (int i = card_number[0]; i < card_number[length]; i++) { // ...
//           ^^^^^^^^^^^^^^      ^^^^^^^^^^^^^^^^^^^

Where card_number is a null-terminated char array inputted by the command line, so that the former is equivalent to something like

for (int i = '7'; i < 0; i++) { // ...
//           ^^^      ^  Note that any "digit" would have a value greater than 0

This loop would be just skipped and result would always remain equal to 0.

The rest of the code seems partial or not conforming to algorithm (if the one I linked is the actual one needed by the OP). Here is a possible implementation.

if (length == 0)
    return false;

int sum = 0;
// Loop over the array from the beginning (the "left" side of the number)
for (int i = 0; i < length - 1; ++i)
{
    int digit = card_number[i] - '0';

    // Now determine if this is an odd or even position, but from the
    // "right" side of the number
    if ( (length - 1 - i) % 2 )
    {
        // You missed this part, according to https://en.wikipedia.org/wiki/Luhn_algorithm
        digit *= 2;

        // If it's not a single digit anymore...
        if ( digit > 9 )
        {
            // Reduce to one digit again
            digit -= 9;
        }
    }

    sum += digit;
}

// You missed this part too, always according to Wikipedia
if ( (sum * 9) % 10  !=  card_number[length - 1] - '0') {
    return false;
}

return true;


问:
how do i add links to search suggestions?
I am a fairly new at coding with js and i only have a brief self taught knowledge in html.
any help would be very appreciated, thank you.

This is the javascript for a search box with an autocomplete function. i am asking as to how i can add links for each variables.

```<code><script>
$(document).ready(function(){
    $('input.autocomplete').autocomplete({
        data: {
            "Single Seats": null,
            "Multiple Seats": null,
            "Beds": null,
            "Entertainment": null,
            "Tables": null,
            "Storage": null,
            "Sets": null,
            "Other": null
        }
    });
});
</script>
</code>```

答:
i think you need this:</p>

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>

</body>
</html>
</code>```

Body:
i think you need this:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>

</body>
</html>


问:
Why Double::compareTo can be used as an argument of Stream.max(Comparator<? super T> comparator)
The api for Stream.max requires an argument of type Comparator<? super T>, and for Comparator, the only abstract method is

```<code>int compare(T o1, T o2)
</code>```

but Double::compareTo, the compareTo api is

```<code>public int compareTo(Double anotherDouble)
</code>```

why just provide one argument, so why can Double::compareTo use as argument of Stream

```<code>Optional<T> max(Comparator<? super T> comparator)
</code>```

答:
The below MyComparator implement a Comparator. It takes two arguments.

It's the same as the lambda expression (d1,d2) -> d1.compareTo(d2)

and the same as the method reference Double::compareTo

The method reference is the same because d1 is a Double, so Java assumes the compareTo method is to be called on the first Double. The other argument d2 becomes the argument for the method called. This is also very nicely explained by @Andronicus.

The 3 variants in this example are equivalent:

```<code>import java.util.List;
import java.util.Comparator;

class MyComparator implements Comparator<Double> {
  public int compare(Double d1, Double d2) {    // (d1,d2) ->
    return d1.compareTo(d2);                    // d1.compareTo(d2)
  }
}

public class Testing {
    public static void main(String[] args) {
      List<Double> list = List.of(1.1,2.2,3.3,4.4,5.5,6.6,7.7);

      Double maxClass =
        list.stream()
            .max(new MyComparator())
            .orElse(Double.NEGATIVE_INFINITY);

      Double maxLamdba =
        list.stream()
            .max((d1,d2) -> d1.compareTo(d2))
            .orElse(Double.NEGATIVE_INFINITY);

      Double maxMethodreference =
        list.stream()
            .max(Double::compareTo)
            .orElse(Double.NEGATIVE_INFINITY);
   }
}
</code>```

Body:
The api for Stream.max requires an argument of type Comparator<? super T>, and for Comparator, the only abstract method is

int compare(T o1, T o2)

but Double::compareTo, the compareTo api is

public int compareTo(Double anotherDouble)

why just provide one argument, so why can Double::compareTo use as argument of Stream

Optional<T> max(Comparator<? super T> comparator)

Body:
The below MyComparator implement a Comparator. It takes two arguments.

It's the same as the lambda expression (d1,d2) -> d1.compareTo(d2)

and the same as the method reference Double::compareTo

The method reference is the same because d1 is a Double, so Java assumes the compareTo method is to be called on the first Double. The other argument d2 becomes the argument for the method called. This is also very nicely explained by @Andronicus.

The 3 variants in this example are equivalent:

import java.util.List;
import java.util.Comparator;

class MyComparator implements Comparator<Double> {
  public int compare(Double d1, Double d2) {    // (d1,d2) ->
    return d1.compareTo(d2);                    // d1.compareTo(d2)
  }
}

public class Testing {
    public static void main(String[] args) {
      List<Double> list = List.of(1.1,2.2,3.3,4.4,5.5,6.6,7.7);

      Double maxClass =
        list.stream()
            .max(new MyComparator())
            .orElse(Double.NEGATIVE_INFINITY);

      Double maxLamdba =
        list.stream()
            .max((d1,d2) -> d1.compareTo(d2))
            .orElse(Double.NEGATIVE_INFINITY);

      Double maxMethodreference =
        list.stream()
            .max(Double::compareTo)
            .orElse(Double.NEGATIVE_INFINITY);
   }
}


问:
Error running 'webdriver-manager start' on Windows 8.1
I am attempting to run end-to-end test for an angular project using protractor and am getting the following error when I run the command 'webdriver-manager start'

I have run webdriver-manager update, and selenium standalone and chromedriver are up to date.

I have java installed. java -version returns

I also have the path to java in my system environment variables (C:\Program Files\Java\jre1.8.0_31\bin)

Does anyone have any idea how to fix this error?

答:
SPAWN command is not available in windows.

Install git. git bash will be installed too.

Now add git bash path to the PATH environment variable.

Restart your command prompt and it will run.


问:
How do I obtain (recreate) the bearer token used in AzureDevOps Pipelines?
I have a failed yaml Infrastructure-as-Code deployment that is failing at the first yaml step:

```<code>- task: ArchiveFiles@1
  displayName: 'Archive createADPDC.ps1 DSC files '
  inputs:
    rootFolder: 'Core/Templates/createADPDC.ps1'
    includeRootFolder: false
    replaceExistingArchive: true
    archiveFile: '$(Build.ArtifactStagingDirectory)/createADPDC.ps1.zip'
</code>```

To troubleshoot this, I've started a line-by-line attempt to simulate what's being done on the hosted pipeline servers, and am getting stuck at the bearer token. Unless there is a better way to diagnose why files are missing from ArtifactStagingDirectory, I'm running the commands below to inspect the files and structure that's being downloaded.

```<code>git init "C:\a\1\s"
Initialized empty Git repository in C:/a/1/s/.git/
git remote add origin https://MyLabs@dev.azure.com/MyLabs/Core/_git/Core
git config gc.auto 0
git config --get-all http.https://MyLabs@dev.azure.com/MyLabs/Core/_git/Core.extraheader
git config --get-all http.proxy
git -c http.extraheader="AUTHORIZATION: bearer ***" fetch --force --tags --prune --progress --no-recurse-submodules origin
fatal: Authentication failed for 'https://dev.azure.com/MyLabs/Core/_git/Core/'
</code>```

Question

Either:

What is a better way to determine or understand why the ArchiveFiles would return

[error]ENOENT: no such file or directory, stat 'D:\a\1\s\Core\Templates\createADPDC.ps1'

What is the correct way to obtain the bearer token (PAT?) for use in the command line located in the logs

答:
Are you sure the directory is correct?

You can access the PAT in pipeline scripts by using $(system.accesstoken).
Make sure you enable persistcredentials at the job level in your yml

Body:
I have a failed yaml Infrastructure-as-Code deployment that is failing at the first yaml step:

- task: ArchiveFiles@1
  displayName: 'Archive createADPDC.ps1 DSC files '
  inputs:
    rootFolder: 'Core/Templates/createADPDC.ps1'
    includeRootFolder: false
    replaceExistingArchive: true
    archiveFile: '$(Build.ArtifactStagingDirectory)/createADPDC.ps1.zip'

To troubleshoot this, I've started a line-by-line attempt to simulate what's being done on the hosted pipeline servers, and am getting stuck at the bearer token. Unless there is a better way to diagnose why files are missing from ArtifactStagingDirectory, I'm running the commands below to inspect the files and structure that's being downloaded.

git init "C:\a\1\s"
Initialized empty Git repository in C:/a/1/s/.git/
git remote add origin https://MyLabs@dev.azure.com/MyLabs/Core/_git/Core
git config gc.auto 0
git config --get-all http.https://MyLabs@dev.azure.com/MyLabs/Core/_git/Core.extraheader
git config --get-all http.proxy
git -c http.extraheader="AUTHORIZATION: bearer ***" fetch --force --tags --prune --progress --no-recurse-submodules origin
fatal: Authentication failed for 'https://dev.azure.com/MyLabs/Core/_git/Core/'

Question

Either:

What is a better way to determine or understand why the ArchiveFiles would return

[error]ENOENT: no such file or directory, stat 'D:\a\1\s\Core\Templates\createADPDC.ps1'

What is the correct way to obtain the bearer token (PAT?) for use in the command line located in the logs


问:
Binding CornerRadius to two boolean properties
Let's say I have a Border whose DataContext is an object of type MyViewModel. MyViewModel has bool properties called RoundLeft and RoundRight. When RoundLeft is true, I want the CornerRadius of the border to be 6,0,0,6. When RoundRight is true, I want 0,6,6,0. When both are true, I want 6,6,6,6.

I've described my first two attempts below. I haven't given up yet, but I wanted to see if anyone else might have any ideas.

Attempt #1

I got it partially working by binding to the MyViewModel instance itself (not a specific property) and using an IValueConverter that builds the correct CornerRadius object. This works on initial load. The problem is that the binding is monitoring changes of the object as a whole rather than changes to the specific RoundLeft and RoundRight properties, e.g. if RoundLeft changes, the border's CornerRadius doesn't.

Binding:

```<code><Border CornerRadius="{Binding Converter={StaticResource myShiftCornerRadiusConverter}}" />
</code>```

Converter:

```<code>public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var myViewModel = value as MyViewModel;
        if (myViewModel != null)
        {
            return new CornerRadius(
                myViewModel.RoundLeft ? 6 : 0,
                myViewModel.RoundRight ? 6 : 0,
                myViewModel.RoundRight ? 6 : 0,
                myViewModel.RoundLeft ? 6 : 0);
        }
        else
        {
            return new CornerRadius(6);
        }
    }
</code>```

Attempt #2

This blog post from Colin Eberhardt looked promising, but I'm getting vague XamlParseExceptions and ComExceptions. Here's my XAML:

```<code><Border>
<ce:MultiBindings>
    <ce:MultiBinding TargetProperty="CornerRadius" Converter="{StaticResource myCornerRadiusConverter}">
        <ce:MultiBinding.Bindings>
            <ce:BindingCollection>
                <Binding Path="RoundLeft" />
                <Binding Path="RoundRight" />
            </ce:BindingCollection>
        </ce:MultiBinding.Bindings>
    </ce:MultiBinding>
</ce:MultiBindings>
</Border>
</code>```

Here's my converter, although the execution never gets this far, i.e. my breakpoint is never hit.

```<code>public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (values.Length == 2 && values.All(v => v is bool))
        {
            var roundLeft = (bool)values[0];
            var roundRight = (bool)values[1];

            return new CornerRadius(
                roundLeft ? 6 : 0,
                roundRight ? 6 : 0,
                roundRight ? 6 : 0,
                roundLeft ? 6 : 0);
        }
        else
        {
            return new CornerRadius(6);
        }
    }
</code>```

答:
What about DataTrigger and an appropriate model property:</p>

```<code><Border Height="25" Width="45" BorderThickness="5" BorderBrush="Green">
    <Border.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Round}"  Value="Left">
                    <Setter Property="Border.CornerRadius" Value="6,0,0,6"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Round}"  Value="Right">
                    <Setter Property="Border.CornerRadius" Value="0,6,6,0"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Round}"  Value="Both">
                    <Setter Property="Border.CornerRadius" Value="6"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
    <TextBlock Text="{Binding Text}"/>
</Border>
</code>```

Body:
Let's say I have a Border whose DataContext is an object of type MyViewModel. MyViewModel has bool properties called RoundLeft and RoundRight. When RoundLeft is true, I want the CornerRadius of the border to be 6,0,0,6. When RoundRight is true, I want 0,6,6,0. When both are true, I want 6,6,6,6.

I've described my first two attempts below. I haven't given up yet, but I wanted to see if anyone else might have any ideas.

Attempt #1

I got it partially working by binding to the MyViewModel instance itself (not a specific property) and using an IValueConverter that builds the correct CornerRadius object. This works on initial load. The problem is that the binding is monitoring changes of the object as a whole rather than changes to the specific RoundLeft and RoundRight properties, e.g. if RoundLeft changes, the border's CornerRadius doesn't.

Binding:

<Border CornerRadius="{Binding Converter={StaticResource myShiftCornerRadiusConverter}}" />

Converter:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var myViewModel = value as MyViewModel;
        if (myViewModel != null)
        {
            return new CornerRadius(
                myViewModel.RoundLeft ? 6 : 0,
                myViewModel.RoundRight ? 6 : 0,
                myViewModel.RoundRight ? 6 : 0,
                myViewModel.RoundLeft ? 6 : 0);
        }
        else
        {
            return new CornerRadius(6);
        }
    }

Attempt #2

This blog post from Colin Eberhardt looked promising, but I'm getting vague XamlParseExceptions and ComExceptions. Here's my XAML:

<Border>
<ce:MultiBindings>
    <ce:MultiBinding TargetProperty="CornerRadius" Converter="{StaticResource myCornerRadiusConverter}">
        <ce:MultiBinding.Bindings>
            <ce:BindingCollection>
                <Binding Path="RoundLeft" />
                <Binding Path="RoundRight" />
            </ce:BindingCollection>
        </ce:MultiBinding.Bindings>
    </ce:MultiBinding>
</ce:MultiBindings>
</Border>

Here's my converter, although the execution never gets this far, i.e. my breakpoint is never hit.

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (values.Length == 2 && values.All(v => v is bool))
        {
            var roundLeft = (bool)values[0];
            var roundRight = (bool)values[1];

            return new CornerRadius(
                roundLeft ? 6 : 0,
                roundRight ? 6 : 0,
                roundRight ? 6 : 0,
                roundLeft ? 6 : 0);
        }
        else
        {
            return new CornerRadius(6);
        }
    }

Body:
What about DataTrigger and an appropriate model property:

<Border Height="25" Width="45" BorderThickness="5" BorderBrush="Green">
    <Border.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Round}"  Value="Left">
                    <Setter Property="Border.CornerRadius" Value="6,0,0,6"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Round}"  Value="Right">
                    <Setter Property="Border.CornerRadius" Value="0,6,6,0"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Round}"  Value="Both">
                    <Setter Property="Border.CornerRadius" Value="6"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
    <TextBlock Text="{Binding Text}"/>
</Border>


问:
Python: Adding 3 weeks to any date
I need help with a program.

How do I add 3 weeks (21 days) to any given date when the user can control the date?

The user will enter the date YYYY-MM-DD.

Below I'm trying to locate the hyphen and make sure there is only 2. This is what I have so far but all it does is repeat itself, can someone tell me where I went wrong ?:

```<code>date = raw_input("Enter date: ")
i = 0
while i <= len(date):
    if date[i] != "-":
    i = i + 1
print date
</code>```

Now I'm picking out year, month, day. Is there an easier way to do this cause I need to account for the change months etc ?

```<code>year = date[0:4]
month = date[5:7]
day = date[9:11]
</code>```

thanks

答:
Try this, I am sure its the shortest and easiest way to go</p>
```<code>
from dateutil.relativedelta import relativedelta

period = date.today() + relativedelta(weeks=+1)

</code>```

Title: Python: Adding 3 weeks to any date

Body:
I need help with a program.

How do I add 3 weeks (21 days) to any given date when the user can control the date?

The user will enter the date YYYY-MM-DD.

Below I'm trying to locate the hyphen and make sure there is only 2. This is what I have so far but all it does is repeat itself, can someone tell me where I went wrong ?:

date = raw_input("Enter date: ")
i = 0
while i <= len(date):
    if date[i] != "-":
    i = i + 1
print date

Now I'm picking out year, month, day. Is there an easier way to do this cause I need to account for the change months etc ?

year = date[0:4]
month = date[5:7]
day = date[9:11]

thanks

Body:
Try this, I am sure its the shortest and easiest way to go

from dateutil.relativedelta import relativedelta

period = date.today() + relativedelta(weeks=+1)


问:
Highlighting Scatterplot Power bi
I have data from different insurance companies.
For these companies I made a scatterplot with Net Premium on the X Axis and Net profit on the y axis.

In the Report I also have 3 bar charts and a table.
I have filters for years, category and company.
The scatterplot ignores the years filter and is filtered by the category filter.

I am trying to highlight the chosen Company in, and only in, the scatterplot.
For example, I filter for a category so my scatterplots shows all data points for the given companies that lie within the category.
Now I want the "company filter" to highlight the data point in my scatterplot.

I tried to do this with conditional formatting but my scatterplot does not take conditional formatting.

I also looked at the method on this site
http://sqljason.com/2018/03/highlighting-scatter-charts-in-power-bi-using-dax.html
This however is not what I want because I don't want to have another bar chart.

I want my company filter to directly highlight my scatterplot. Does anyone know a way how to do this?

答:
You can do this by editing your interactions. Select the filter you want to edit the interaction for. You now get a tab format, select it and select "Edit interactions".

In the example below, I selected the Score filter and disable the Employee table from acting on the filter.

Title: Highlighting Scatterplot Power bi


问:
How to parse specific HTML table from website on python
I am a beginner in web scraping with python. I am trying to parse the table of places of worship in Langkawi Island. This is the website I am referring to http://www.jaik.gov.my/?page_id=658

I've entered the the following in python:-

```<code>import requests

import lxml.html as lh

import pandas as pd

langkawi_url = 'http://www.jaik.gov.my/?page_id=658'

page = requests.get(langkawi_url)

doc = lh.fromstring(page.content)

tr_elements = doc.xpath('//td')

[len(T) for T in tr_elements[:12]]

tr_elements = doc.xpath('//tr')

col = []
i = 0

for t in tr_elements[0]:
    i+=1
    name=t.text_content()
    print("%d:%s" % (i,name))
    col.append((name,[]))
</code>```

Apparently the output I got is this:-

```<code>1:Sun
2:Mon
3:Tue
4:Wed
5:Thu
6:Fri
7:Sat
</code>```

I was hoping to get this:-

```<code>1:BIL
2:KARIAH MASJID
3:ALAMAT
4:MUKIM
</code>```

Your advise and guidance is much appreciated.

Thank you!

答:
Try changing your code to something like:

```<code>tr_elements = doc.xpath('//td/strong')
col = []
for t in tr_elements:
    col.append(t.text)
print(col)
</code>```

Output:

```<code>['BIL', 'KARIAH MASJID', 'ALAMAT', 'MUKIM']
</code>```

Body:
I am a beginner in web scraping with python. I am trying to parse the table of places of worship in Langkawi Island. This is the website I am referring to http://www.jaik.gov.my/?page_id=658

I've entered the the following in python:-

import requests

import lxml.html as lh

import pandas as pd

langkawi_url = 'http://www.jaik.gov.my/?page_id=658'

page = requests.get(langkawi_url)

doc = lh.fromstring(page.content)

tr_elements = doc.xpath('//td')

[len(T) for T in tr_elements[:12]]

tr_elements = doc.xpath('//tr')

col = []
i = 0

for t in tr_elements[0]:
    i+=1
    name=t.text_content()
    print("%d:%s" % (i,name))
    col.append((name,[]))

Apparently the output I got is this:-

1:Sun
2:Mon
3:Tue
4:Wed
5:Thu
6:Fri
7:Sat

I was hoping to get this:-

1:BIL
2:KARIAH MASJID
3:ALAMAT
4:MUKIM

Your advise and guidance is much appreciated.

Thank you!

Body:
Try changing your code to something like:

tr_elements = doc.xpath('//td/strong')
col = []
for t in tr_elements:
    col.append(t.text)
print(col)

Output:

['BIL', 'KARIAH MASJID', 'ALAMAT', 'MUKIM']


问:
Override Array Values with another one
I like to learn how to combine two associative array which has same keys but different values like how we do in jQuery with var options = $.extend(defaults, options);

```<code>$first = array("name"=>"John","last_name"=>"McDonald","City"=>"World"); //default values
$second = array("name"=>"Michael","last_name"=>"Jackson"); //user provided

$result = combine($first,$second);

//output array("name"=>"Michael","last_name"=>"Jackson","City"=>"World");
</code>```

I am looking for something built-in instead of writing a entire new function to provide this feature. Of course if you have something neat, just let me know.

Thanks...

答:
I've never found a built-in function for this (simple) need, so I developed a custom function in order to override a $default array with an $override array:

```<code>function array_override( $default, $override )
{
    foreach( $default as $k=>$v )
    {
        if( isset( $override[$k] ) ) $default[$k] = $override[$k];
    }
    return $default;
}
</code>```

As you can see, values in $default are overridden only if are set on the $override array; otherwise the $default value remain on the returned array.

Title: Override Array Values with another one

Body:
I like to learn how to combine two associative array which has same keys but different values like how we do in jQuery with var options = $.extend(defaults, options);

$first = array("name"=>"John","last_name"=>"McDonald","City"=>"World"); //default values
$second = array("name"=>"Michael","last_name"=>"Jackson"); //user provided

$result = combine($first,$second);

//output array("name"=>"Michael","last_name"=>"Jackson","City"=>"World");

I am looking for something built-in instead of writing a entire new function to provide this feature. Of course if you have something neat, just let me know.

Thanks...

Body:
I've never found a built-in function for this (simple) need, so I developed a custom function in order to override a $default array with an $override array:

function array_override( $default, $override )
{
    foreach( $default as $k=>$v )
    {
        if( isset( $override[$k] ) ) $default[$k] = $override[$k];
    }
    return $default;
}

As you can see, values in $default are overridden only if are set on the $override array; otherwise the $default value remain on the returned array.


问:
Numpy/Scipy : solving several least squares with the same design matrix
I face a least square problem that i solve via scipy.linalg.lstsq(M,b), where :

M has shape (n,n)

b has shape (n,)

The issue is that i have to solve it a bunch of time for different b's. How can i do something more efficient ? I guess that lstsq does a lot of things independently of the value of b.

Ideas ?

答:
In the case your linear system is well-determined, I'll store M LU decomposition and use it for all the b's individually or simply do one solve call for 2d-array B representing the horizontally stacked b's, it really depends on your problem here but this is globally the same idea. Let's suppose you've got each b one at a time, then:

```<code>import numpy as np
from scipy.linalg import lstsq, lu_factor, lu_solve, svd, pinv

# as you didn't specified any practical dimensions
n = 100
# number of b's
nb_b = 10

# generate random n-square matrix M
M = np.random.rand(n**2).reshape(n,n)

# Set of nb_b of right hand side vector b as columns
B = np.random.rand(n*nb_b).reshape(n,nb_b)

# compute pivoted LU decomposition of M
M_LU = lu_factor(M)
# then solve for each b
X_LU = np.asarray([lu_solve(M_LU,B[:,i]) for i in range(nb_b)])
</code>```

but if it is under or over-determined, you need to use lstsq as you did:

```<code>X_lstsq = np.asarray([lstsq(M,B[:,i])[0] for i in range(nb_b)])
</code>```

or simply store the pseudo-inverse M_pinv with pinv (built on lstsq) or pinv2 (built on SVD):

```<code># compute the pseudo-inverse of M
M_pinv = pinv(M)
X_pinv = np.asarray([np.dot(M_pinv,B[:,i]) for i in range(nb_b)])
</code>```

or you can also do the work by yourself, as in pinv2 for instance, just store the SVD of M, and solve this manually:

```<code># compute svd of M
U,s,Vh = svd(M)

def solve_svd(U,s,Vh,b):
    # U diag(s) Vh x = b <=> diag(s) Vh x = U.T b = c
    c = np.dot(U.T,b)
    # diag(s) Vh x = c <=> Vh x = diag(1/s) c = w (trivial inversion of a diagonal matrix)
    w = np.dot(np.diag(1/s),c)
    # Vh x = w <=> x = Vh.H w (where .H stands for hermitian = conjugate transpose)
    x = np.dot(Vh.conj().T,w)
    return x

X_svd = np.asarray([solve_svd(U,s,Vh,B[:,i]) for i in range(nb_b)])
</code>```

which all give the same result if checked with np.allclose (unless the system is not well-determined resulting in the LU direct approach failure). Finally in terms of performances:

```<code>%timeit M_LU = lu_factor(M); X_LU = np.asarray([lu_solve(M_LU,B[:,i]) for i in range(nb_b)])
1000 loops, best of 3: 1.01 ms per loop

%timeit X_lstsq = np.asarray([lstsq(M,B[:,i])[0] for i in range(nb_b)])
10 loops, best of 3: 47.8 ms per loop

%timeit M_pinv = pinv(M); X_pinv = np.asarray([np.dot(M_pinv,B[:,i]) for i in range(nb_b)])
100 loops, best of 3: 8.64 ms per loop

%timeit U,s,Vh = svd(M); X_svd = np.asarray([solve_svd(U,s,Vh,B[:,i]) for i in range(nb_b)])
100 loops, best of 3: 5.68 ms per loop
</code>```

Nevertheless, it's up to you to check these with appropriate dimensions.

Hope this helps.

Body:
In the case your linear system is well-determined, I'll store M LU decomposition and use it for all the b's individually or simply do one solve call for 2d-array B representing the horizontally stacked b's, it really depends on your problem here but this is globally the same idea. Let's suppose you've got each b one at a time, then:

import numpy as np
from scipy.linalg import lstsq, lu_factor, lu_solve, svd, pinv

# as you didn't specified any practical dimensions
n = 100
# number of b's
nb_b = 10

# generate random n-square matrix M
M = np.random.rand(n**2).reshape(n,n)

# Set of nb_b of right hand side vector b as columns
B = np.random.rand(n*nb_b).reshape(n,nb_b)

# compute pivoted LU decomposition of M
M_LU = lu_factor(M)
# then solve for each b
X_LU = np.asarray([lu_solve(M_LU,B[:,i]) for i in range(nb_b)])

but if it is under or over-determined, you need to use lstsq as you did:

X_lstsq = np.asarray([lstsq(M,B[:,i])[0] for i in range(nb_b)])

or simply store the pseudo-inverse M_pinv with pinv (built on lstsq) or pinv2 (built on SVD):

# compute the pseudo-inverse of M
M_pinv = pinv(M)
X_pinv = np.asarray([np.dot(M_pinv,B[:,i]) for i in range(nb_b)])

or you can also do the work by yourself, as in pinv2 for instance, just store the SVD of M, and solve this manually:

# compute svd of M
U,s,Vh = svd(M)

def solve_svd(U,s,Vh,b):
    # U diag(s) Vh x = b <=> diag(s) Vh x = U.T b = c
    c = np.dot(U.T,b)
    # diag(s) Vh x = c <=> Vh x = diag(1/s) c = w (trivial inversion of a diagonal matrix)
    w = np.dot(np.diag(1/s),c)
    # Vh x = w <=> x = Vh.H w (where .H stands for hermitian = conjugate transpose)
    x = np.dot(Vh.conj().T,w)
    return x

X_svd = np.asarray([solve_svd(U,s,Vh,B[:,i]) for i in range(nb_b)])

which all give the same result if checked with np.allclose (unless the system is not well-determined resulting in the LU direct approach failure). Finally in terms of performances:

%timeit M_LU = lu_factor(M); X_LU = np.asarray([lu_solve(M_LU,B[:,i]) for i in range(nb_b)])
1000 loops, best of 3: 1.01 ms per loop

%timeit X_lstsq = np.asarray([lstsq(M,B[:,i])[0] for i in range(nb_b)])
10 loops, best of 3: 47.8 ms per loop

%timeit M_pinv = pinv(M); X_pinv = np.asarray([np.dot(M_pinv,B[:,i]) for i in range(nb_b)])
100 loops, best of 3: 8.64 ms per loop

%timeit U,s,Vh = svd(M); X_svd = np.asarray([solve_svd(U,s,Vh,B[:,i]) for i in range(nb_b)])
100 loops, best of 3: 5.68 ms per loop

Nevertheless, it's up to you to check these with appropriate dimensions.

Hope this helps.


问:
LIMIT on main table if join tables have where clause
I have three table Contact, Company, Individuals. Contact can have only one company and can have multiple Individuals. I am trying to fetch Contacts along with associated data and with multiple OR clauses which contain conditions for both the associated table. Also I just want to apply limit only on Contact table.

Here is query:-

```<code>SELECT          "Contact"."contactType",
                "Contact"."id",
                "Contact"."createdAt",
                "Contact"."updatedAt",
                "Company"."id"            AS "Company.id",
                "Company"."name"          AS "Company.name",
                "Company"."compType"   AS "Company.compType",
                "Company"."affType" AS "Company.affType",
                "Company"."lsNo"     AS "Company.lsNo",
                "Individuals"."id"        AS "Individuals.id",
                "Individuals"."firstName" AS "Individuals.firstName"
FROM            "Contacts"    AS "Contact"
INNER JOIN      "Companies"         AS "Company"
ON              "Contact"."id" = "Company"."ContactId"
LEFT OUTER JOIN "Individuals" AS "Individuals"
ON              "Contact"."id" = "Individuals"."ContactId"
WHERE           (
                       "Company"."affType" ilike ANY (array['abc','xyz'])
                AND    "Contact"."contactType" ilike ANY (array['def','jkl'])
                AND             (
                                                lower(cast("Company"."name" AS text)) LIKE '%abc%'
                                OR              lower(cast("Company"."compType" AS text)) LIKE '%as%'
                                OR              lower(cast("Company"."lsNo" AS text)) LIKE '%as%'
                                OR              lower(cast("Individuals"."firstName" AS text)) LIKE '%as%'))
ORDER BY    "Company"."name" ASC LIMIT 10 OFFSET 0;
</code>```

The problem with above query is that limit is getting applied on Individuals.

答:
You would want to use a lateral join with a subquery:

```<code>LEFT JOIN LATERAL
    (SELECT * from "Individuals" WHERE "Contact"."id" = "Individuals"."ContactId" LIMIT 10) as "Individuals" on true
</code>```

Although you might want to apply some sort of ORDER BY to specify which individuals have priority to be returned.

You probably also want to move/copy lower(cast("Individuals"."firstName" AS text)) LIKE '%as%' from the outer WHERE clause into the subquery.

Body:
I have three table Contact, Company, Individuals. Contact can have only one company and can have multiple Individuals. I am trying to fetch Contacts along with associated data and with multiple OR clauses which contain conditions for both the associated table. Also I just want to apply limit only on Contact table.

Here is query:-

SELECT          "Contact"."contactType",
                "Contact"."id",
                "Contact"."createdAt",
                "Contact"."updatedAt",
                "Company"."id"            AS "Company.id",
                "Company"."name"          AS "Company.name",
                "Company"."compType"   AS "Company.compType",
                "Company"."affType" AS "Company.affType",
                "Company"."lsNo"     AS "Company.lsNo",
                "Individuals"."id"        AS "Individuals.id",
                "Individuals"."firstName" AS "Individuals.firstName"
FROM            "Contacts"    AS "Contact"
INNER JOIN      "Companies"         AS "Company"
ON              "Contact"."id" = "Company"."ContactId"
LEFT OUTER JOIN "Individuals" AS "Individuals"
ON              "Contact"."id" = "Individuals"."ContactId"
WHERE           (
                       "Company"."affType" ilike ANY (array['abc','xyz'])
                AND    "Contact"."contactType" ilike ANY (array['def','jkl'])
                AND             (
                                                lower(cast("Company"."name" AS text)) LIKE '%abc%'
                                OR              lower(cast("Company"."compType" AS text)) LIKE '%as%'
                                OR              lower(cast("Company"."lsNo" AS text)) LIKE '%as%'
                                OR              lower(cast("Individuals"."firstName" AS text)) LIKE '%as%'))
ORDER BY    "Company"."name" ASC LIMIT 10 OFFSET 0;

The problem with above query is that limit is getting applied on Individuals.

Body:
You would want to use a lateral join with a subquery:

LEFT JOIN LATERAL
    (SELECT * from "Individuals" WHERE "Contact"."id" = "Individuals"."ContactId" LIMIT 10) as "Individuals" on true

Although you might want to apply some sort of ORDER BY to specify which individuals have priority to be returned.

You probably also want to move/copy lower(cast("Individuals"."firstName" AS text)) LIKE '%as%' from the outer WHERE clause into the subquery.


问:
How to make a cartopy figure become larger?
I am working with Cartopy and I want to make the image bigger. It has a large legnth but I hope to make the width bigger.
This is the code I have so far. I tried changing the figsize, but it only made the colorbar larger.

```<code>fig = plt.figure(figsize=(15,5))
ax = plt.axes(projection=ccrs.PlateCarree())
x = ax.contourf(lon,lat,sum_mag_sq, 30, cmap='RdBu_r')
ax.coastlines()
gridlines = ax.gridlines(draw_labels=True)
cbar = plt.colorbar(x, fraction=.046, pad=0.04)
cbar.set_label('Power Spectrum (m$^2$/# frequencies)', labelpad=15, y=.5, rotation=270)
plt.title('Frequency Summed Power Spectrum (2018-2019)', y=1.2)
plt.show(
</code>```

答:
To get a plot of a map with colorbar you must specify several parameters. Here is a working code that demonstrates how to set values of figsize and colorbar to obtain better plot.

```<code>import matplotlib.pyplot as plt
import cartopy.crs as ccrs
#import cartopy.feature as cfeature
import numpy as np

# make up data for plotting
xmin, xmax, ymin, ymax = -55, 15, -4, 4
#extent = [xmin, xmax, ymin, ymax]
width = 4
height = 4
xs = np.linspace(xmin, xmax, width)
ys = np.linspace(ymin, ymax, height)
x2d, y2d = np.meshgrid(xs, ys)
z2d = (x2d+y2d)

fig = plt.figure(figsize=(20,5))  # set figsize (width, height) here
ax = plt.axes(projection=ccrs.PlateCarree())

ct = ax.contourf(x2d, y2d, z2d, 30, cmap='RdBu_r')

ax.coastlines()
gridlines = ax.gridlines(draw_labels=True)

# create a colorbar
cbar = plt.colorbar(ct, fraction=.08, pad=0.04, shrink=0.5, aspect=12)
cbar.set_label('Power Spectrum (m$^2$/# frequencies)', labelpad=15, y=.5, rotation=270)

plt.title('Frequency Summed Power Spectrum (2018-2019)', y=1.2)
plt.show()
</code>```

The output plot:

Body:
I am working with Cartopy and I want to make the image bigger. It has a large legnth but I hope to make the width bigger.
This is the code I have so far. I tried changing the figsize, but it only made the colorbar larger.

fig = plt.figure(figsize=(15,5))
ax = plt.axes(projection=ccrs.PlateCarree())
x = ax.contourf(lon,lat,sum_mag_sq, 30, cmap='RdBu_r')
ax.coastlines()
gridlines = ax.gridlines(draw_labels=True)
cbar = plt.colorbar(x, fraction=.046, pad=0.04)
cbar.set_label('Power Spectrum (m$^2$/# frequencies)', labelpad=15, y=.5, rotation=270)
plt.title('Frequency Summed Power Spectrum (2018-2019)', y=1.2)
plt.show(

Body:
To get a plot of a map with colorbar you must specify several parameters. Here is a working code that demonstrates how to set values of figsize and colorbar to obtain better plot.

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
#import cartopy.feature as cfeature
import numpy as np

# make up data for plotting
xmin, xmax, ymin, ymax = -55, 15, -4, 4
#extent = [xmin, xmax, ymin, ymax]
width = 4
height = 4
xs = np.linspace(xmin, xmax, width)
ys = np.linspace(ymin, ymax, height)
x2d, y2d = np.meshgrid(xs, ys)
z2d = (x2d+y2d)

fig = plt.figure(figsize=(20,5))  # set figsize (width, height) here
ax = plt.axes(projection=ccrs.PlateCarree())

ct = ax.contourf(x2d, y2d, z2d, 30, cmap='RdBu_r')

ax.coastlines()
gridlines = ax.gridlines(draw_labels=True)

# create a colorbar
cbar = plt.colorbar(ct, fraction=.08, pad=0.04, shrink=0.5, aspect=12)
cbar.set_label('Power Spectrum (m$^2$/# frequencies)', labelpad=15, y=.5, rotation=270)

plt.title('Frequency Summed Power Spectrum (2018-2019)', y=1.2)
plt.show()

The output plot: