问:
Fill a 6x6 grid with 6 colors without same colors touching each other
I'm trying to create a board game with p5.js (Javascript)

To set up the game board which is a 6 by 6 grid, I have to fill the grid with 6 colors in a way that no horizontal or vertical touching cells have the same color. And all 6 colors have to be used in 6 cells.

But now I'm struggling a bit creating an algorithm that places the colors randomly but keeping the rules.

I tried to start at the top left corner, filling with a random color.
Then I start to fill the cell to the left and the bottom with a different color.

The problem is, that when the script wants to fill the last few cells, there are no colors left to use (either already 6 cells filled or a remaining color is a neighbor)

Example:
Still two cells need to be red, but only one place is left for red (under white):

```<code>//fill placedColors Array with zeros
placedColors = [];
for(let i=0; i<6; i++) {
    placedColors[i] = 0;
}

//fill allIndexes Array with indizies to keep control of visited cells
let allIndexes = [];
for(let i=0; i<36; i++) {
    allIndexes.push(i);
}

//build board
//when I set the limit to 36 the script runs forever because no solution is found
for(let i=0; i<33; i++) {
    fillCells(i);
}

function fillCells(index) {
    //get top and left color
    let topColor = false;
    //index is in the second row
    if(index >= 6) {
        topColor = cells[index-6].color;
    }

    let leftColor = false;
    //index is not in the first column
    if(index % 6 > 0 && index > 0) {
        leftColor = cells[index-1].color;
    }

    if(allIndexes.indexOf(index) > -1) {
        cells.push(new Cell(index, pickColor(topColor, leftColor)));
    }

    //mark index as visited
    var allIndexesIndex = allIndexes.indexOf(index);
    if (allIndexesIndex !== -1) {
        allIndexes.splice(allIndexesIndex, 1);
    }
}

function pickColor(invalidColor1,invalidColor2) {
    let colorFound = false;
    do {
        randColor = floor(random(6));

        if(placedColors[randColor] < 6 && randColor!=invalidColor1 && randColor!=invalidColor2) {
            placedColors[randColor]++;
            colorFound = true;
        }
    } while(!colorFound);

    return randColor;
}

</code>```

答:
An easy approach is to start with a valid coloring (for example, any 6x6 latin square is a valid coloring) and them mix it up by finding a pair of things that can be swapped, and swap them.

An improvement (to increase mixing speed, and to prevent the algorithm getting stuck) is to allow at most one cell to be invalid (ie: one cell which  if removed leaves the remainder in a valid coloring). If there's no invalid cell, then swap two random cells if at least one of them will be valid after the swap. And if there's one invalid cell, pick that cell and one other random cell to be swapped, assuming again swapping leaves at least one of them valid. Again repeat lots of time, stopping only when the coloring is valid.

An implementation of this idea (sorry, not Javascript) is here: https://go.dev/play/p/sxMvLxHfhmC

Body:
I'm trying to create a board game with p5.js (Javascript)

To set up the game board which is a 6 by 6 grid, I have to fill the grid with 6 colors in a way that no horizontal or vertical touching cells have the same color. And all 6 colors have to be used in 6 cells.

But now I'm struggling a bit creating an algorithm that places the colors randomly but keeping the rules.

I tried to start at the top left corner, filling with a random color.
Then I start to fill the cell to the left and the bottom with a different color.

The problem is, that when the script wants to fill the last few cells, there are no colors left to use (either already 6 cells filled or a remaining color is a neighbor)

Example:
Still two cells need to be red, but only one place is left for red (under white):

//fill placedColors Array with zeros
placedColors = [];
for(let i=0; i<6; i++) {
    placedColors[i] = 0;
}

//fill allIndexes Array with indizies to keep control of visited cells
let allIndexes = [];
for(let i=0; i<36; i++) {
    allIndexes.push(i);
}

//build board
//when I set the limit to 36 the script runs forever because no solution is found
for(let i=0; i<33; i++) {
    fillCells(i);
}

function fillCells(index) {
    //get top and left color
    let topColor = false;
    //index is in the second row
    if(index >= 6) {
        topColor = cells[index-6].color;
    }

    let leftColor = false;
    //index is not in the first column
    if(index % 6 > 0 && index > 0) {
        leftColor = cells[index-1].color;
    }

    if(allIndexes.indexOf(index) > -1) {
        cells.push(new Cell(index, pickColor(topColor, leftColor)));
    }

    //mark index as visited
    var allIndexesIndex = allIndexes.indexOf(index);
    if (allIndexesIndex !== -1) {
        allIndexes.splice(allIndexesIndex, 1);
    }
}

function pickColor(invalidColor1,invalidColor2) {
    let colorFound = false;
    do {
        randColor = floor(random(6));

        if(placedColors[randColor] < 6 && randColor!=invalidColor1 && randColor!=invalidColor2) {
            placedColors[randColor]++;
            colorFound = true;
        }
    } while(!colorFound);

    return randColor;
}


来源: stackexchange

问:
how to merge two arrays of objects in javascript?
here is a sample example where there are two arrays and we have a merge() to which we pass the arrays. the merge() should return the merged array such that it should merge the objects which have same name.</p>
```<code>let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = merge(arr1, arr2)

output :
arr3 should be :
[
 {
    name: "Person1",
    age: 20,
    email: "person1@mail.com"
  },
   {
    name: "Person2",
    age: 30
  },
   {
    name: "Person3",
    age: 25
  }
]
</code>```

答:
Try this :

let arr1 = [{
    name: "Person1",
    age: 20
}, {
    name: "Person2",
    age: 30
}];
let arr2 = [{
    name: "Person1",
    email: "person1@mail.com"
}, {
    name: "Person3",
    age: 25
}];
function copy(source, destination) {
    for (let prop in source) {
        destination[prop] = source[prop];
    }
}
function merge(arr1, arr2) {
    let newArray = [];
    for (let i = 0, obj1; obj1 = arr1[i]; ++i) {
        let obj = {};
        copy(obj1, obj);
        for (let j = 0, obj2; obj2 = arr2[j]; ++j) {
            if (obj1.name === obj2.name) {
                copy(obj2, obj);
            }
        }
        newArray.push(obj);
    }
    for (let i = 0, obj2; obj2 = arr2[i]; ++i) {
        let here = false;
        for (let j = 0, obj1; obj1 = arr1[j]; ++j) {
            if (obj1.name === obj2.name) {
                here = true;
            }
        }
        if (!here) {
            newArray.push(obj2);
        }
    }
    return newArray;
}
let arr3 = merge(arr1, arr2);
console.log(arr3);```

ContentLicense: CC BY-SA 4.0

Body:
here is a sample example where there are two arrays and we have a merge() to which we pass the arrays. the merge() should return the merged array such that it should merge the objects which have same name.

let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = merge(arr1, arr2)

output :
arr3 should be :
[
 {
    name: "Person1",
    age: 20,
    email: "person1@mail.com"
  },
   {
    name: "Person2",
    age: 30
  },
   {
    name: "Person3",
    age: 25
  }
]


问:
Unhandled Exception: NoSuchMethodError: The method 'map' was called on null. Tried calling: map(Closure: (dynamic) => Reply)
#this is my model class where the error is pointing at,the error is E/flutter (29710): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.
E/flutter (29710): Receiver: null
E/flutter (29710): Tried calling: map(Closure: (dynamic) => Reply)</p>
```<code>   import 'dart:convert';

StudentHomeworkreply studentHomeworkreplyFromJson(String str) => StudentHomeworkreply.fromJson(json.decode(str));

String studentHomeworkreplyToJson(StudentHomeworkreply data) => json.encode(data.toJson());

class StudentHomeworkreply {
  StudentHomeworkreply({
    this.id,
    this.schoolid,
    this.classid,
    this.subjectid,
    this.title,
    this.teacherId,
    this.sectionId,
    this.content,
    this.submissionDate,
    this.filelinks,
    this.filenames,
    this.fileUniquenames,
    this.createdAt,
    this.updatedAt,
    this.students,
  });

  int id;
  String schoolid;
  String classid;
  String subjectid;
  String title;
  String teacherId;
  String sectionId;
  String content;
  DateTime submissionDate;
  String filelinks;
  String filenames;
  String fileUniquenames;
  DateTime createdAt;
  DateTime updatedAt;
  List<Student> students;

  factory StudentHomeworkreply.fromJson(Map<String, dynamic> json) => StudentHomeworkreply(
    id: json["id"],
    schoolid: json["schoolid"],
    classid: json["CLASSID"],
    subjectid: json["SUBJECTID"],
    title: json["title"],
    teacherId: json["teacher_id"],
    sectionId: json["section_id"],
    content: json["CONTENT"],
    submissionDate: DateTime.parse(json["submission_date"]),
    filelinks: json["filelinks"],
    filenames: json["filenames"],
    fileUniquenames: json["fileUniquenames"],
    createdAt: DateTime.parse(json["created_at"]),
    updatedAt: DateTime.parse(json["updated_at"]),
    students: List<Student>.from(json["students"].map((x) => Student.fromJson(x))).toList(), //this is the place the error is pointing.........
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "schoolid": schoolid,
    "CLASSID": classid,
    "SUBJECTID": subjectid,
    "title": title,
    "teacher_id": teacherId,
    "section_id": sectionId,
    "CONTENT": content,
    "submission_date": "${submissionDate.year.toString().padLeft(4, '0')}-${submissionDate.month.toString().padLeft(2, '0')}-${submissionDate.day.toString().padLeft(2, '0')}",
    "filelinks": filelinks,
    "filenames": filenames,
    "fileUniquenames": fileUniquenames,
    "created_at": createdAt.toIso8601String(),
    "updated_at": updatedAt.toIso8601String(),
    "students": List<dynamic>.from(students.map((x) => x.toJson())),
  };
}

class Student {
  Student({
    this.stname,
    this.rollno,
    this.regno,
    this.homeworkStatus,
    this.replies,
  });

  String stname;
  int rollno;
  String regno;
  HomeworkStatus homeworkStatus;
  List<Reply> replies;

  factory Student.fromJson(Map<String, dynamic> json) => Student(
    stname: json["STNAME"],
    rollno: json["ROLLNO"],
    regno: json["REGNO"],
    homeworkStatus: homeworkStatusValues.map[json["homeworkStatus"]],
    replies:List<Reply>.from(json["replies"].map((x) => Reply.fromJson(x))).toList() //this is the place the error is pointing.........
  );

  Map<String, dynamic> toJson() => {
    "STNAME": stname,
    "ROLLNO": rollno,
    "REGNO": regno,
    "homeworkStatus": homeworkStatusValues.reverse[homeworkStatus],
    "replies":replies!=null??List<dynamic>.from(replies.map((x) => x.toJson()).toList()),
  };
}

enum HomeworkStatus { COMPLETED, PENDING }

final homeworkStatusValues = EnumValues({
  "completed": HomeworkStatus.COMPLETED,
  "pending": HomeworkStatus.PENDING
});

class Reply {
  Reply({
    this.comments,
    this.id,
    this.schoolid,
    this.filenames,
    this.homeworkId,
    this.filelinks,
    this.fileUniquenames,
    this.homeworkStatus,
    this.regno,
    this.teacherId,
    this.replyFrom,
    this.status,
    this.createdAt,
  });

  String comments;
  int id;
  String schoolid;
  String filenames;
  int homeworkId;
  String filelinks;
  String fileUniquenames;
  String homeworkStatus;
  String regno;
  String teacherId;
  String replyFrom;
  String status;
  DateTime createdAt;

  factory Reply.fromJson(Map<String, dynamic> json) => Reply(
    comments: json["comments"],
    id: json["id"],
    schoolid: json["schoolid"],
    filenames: json["filenames"],
    homeworkId: json["homework_id"],
    filelinks: json["filelinks"],
    fileUniquenames: json["fileUniquenames"],
    homeworkStatus: json["homework_status"],
    regno: json["regno"],
    teacherId: json["teacher_id"] == null ? null : json["teacher_id"],
    replyFrom: json["reply_from"],
    status: json["status"],
    createdAt: DateTime.parse(json["created_at"]),
  );

  Map<String, dynamic> toJson() => {
    "comments": comments,
    "id": id,
    "schoolid": schoolid,
    "filenames": filenames,
    "homework_id": homeworkId,
    "filelinks": filelinks,
    "fileUniquenames": fileUniquenames,
    "homework_status": homeworkStatus,
    "regno": regno,
    "teacher_id": teacherId == null ? null : teacherId,
    "reply_from": replyFrom,
    "status": status,
    "created_at": createdAt.toIso8601String(),
  };
}

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String> reverseMap;

  EnumValues(this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}
</code>```

答:
When you use .from for creating a list, it shouldn't have toList() at the end.

Change this line.

```<code>students: List<Student>.from(json["students"].map((x) => Student.fromJson(x))).toList(),
</code>```

To one of these:

First:

```<code>students: List<Student>.from(json["students"].map((x) => Student.fromJson(x))),
</code>```

Or:

```<code>students: (json["students"] as List).map((i) => Student.fromJson(i)).toList(),
</code>```

Body:
#this is my model class where the error is pointing at,the error is E/flutter (29710): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.
E/flutter (29710): Receiver: null
E/flutter (29710): Tried calling: map(Closure: (dynamic) => Reply)

   import 'dart:convert';

StudentHomeworkreply studentHomeworkreplyFromJson(String str) => StudentHomeworkreply.fromJson(json.decode(str));

String studentHomeworkreplyToJson(StudentHomeworkreply data) => json.encode(data.toJson());

class StudentHomeworkreply {
  StudentHomeworkreply({
    this.id,
    this.schoolid,
    this.classid,
    this.subjectid,
    this.title,
    this.teacherId,
    this.sectionId,
    this.content,
    this.submissionDate,
    this.filelinks,
    this.filenames,
    this.fileUniquenames,
    this.createdAt,
    this.updatedAt,
    this.students,
  });

  int id;
  String schoolid;
  String classid;
  String subjectid;
  String title;
  String teacherId;
  String sectionId;
  String content;
  DateTime submissionDate;
  String filelinks;
  String filenames;
  String fileUniquenames;
  DateTime createdAt;
  DateTime updatedAt;
  List<Student> students;

  factory StudentHomeworkreply.fromJson(Map<String, dynamic> json) => StudentHomeworkreply(
    id: json["id"],
    schoolid: json["schoolid"],
    classid: json["CLASSID"],
    subjectid: json["SUBJECTID"],
    title: json["title"],
    teacherId: json["teacher_id"],
    sectionId: json["section_id"],
    content: json["CONTENT"],
    submissionDate: DateTime.parse(json["submission_date"]),
    filelinks: json["filelinks"],
    filenames: json["filenames"],
    fileUniquenames: json["fileUniquenames"],
    createdAt: DateTime.parse(json["created_at"]),
    updatedAt: DateTime.parse(json["updated_at"]),
    students: List<Student>.from(json["students"].map((x) => Student.fromJson(x))).toList(), //this is the place the error is pointing.........
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "schoolid": schoolid,
    "CLASSID": classid,
    "SUBJECTID": subjectid,
    "title": title,
    "teacher_id": teacherId,
    "section_id": sectionId,
    "CONTENT": content,
    "submission_date": "${submissionDate.year.toString().padLeft(4, '0')}-${submissionDate.month.toString().padLeft(2, '0')}-${submissionDate.day.toString().padLeft(2, '0')}",
    "filelinks": filelinks,
    "filenames": filenames,
    "fileUniquenames": fileUniquenames,
    "created_at": createdAt.toIso8601String(),
    "updated_at": updatedAt.toIso8601String(),
    "students": List<dynamic>.from(students.map((x) => x.toJson())),
  };
}

class Student {
  Student({
    this.stname,
    this.rollno,
    this.regno,
    this.homeworkStatus,
    this.replies,
  });

  String stname;
  int rollno;
  String regno;
  HomeworkStatus homeworkStatus;
  List<Reply> replies;

  factory Student.fromJson(Map<String, dynamic> json) => Student(
    stname: json["STNAME"],
    rollno: json["ROLLNO"],
    regno: json["REGNO"],
    homeworkStatus: homeworkStatusValues.map[json["homeworkStatus"]],
    replies:List<Reply>.from(json["replies"].map((x) => Reply.fromJson(x))).toList() //this is the place the error is pointing.........
  );

  Map<String, dynamic> toJson() => {
    "STNAME": stname,
    "ROLLNO": rollno,
    "REGNO": regno,
    "homeworkStatus": homeworkStatusValues.reverse[homeworkStatus],
    "replies":replies!=null??List<dynamic>.from(replies.map((x) => x.toJson()).toList()),
  };
}

enum HomeworkStatus { COMPLETED, PENDING }

final homeworkStatusValues = EnumValues({
  "completed": HomeworkStatus.COMPLETED,
  "pending": HomeworkStatus.PENDING
});

class Reply {
  Reply({
    this.comments,
    this.id,
    this.schoolid,
    this.filenames,
    this.homeworkId,
    this.filelinks,
    this.fileUniquenames,
    this.homeworkStatus,
    this.regno,
    this.teacherId,
    this.replyFrom,
    this.status,
    this.createdAt,
  });

  String comments;
  int id;
  String schoolid;
  String filenames;
  int homeworkId;
  String filelinks;
  String fileUniquenames;
  String homeworkStatus;
  String regno;
  String teacherId;
  String replyFrom;
  String status;
  DateTime createdAt;

  factory Reply.fromJson(Map<String, dynamic> json) => Reply(
    comments: json["comments"],
    id: json["id"],
    schoolid: json["schoolid"],
    filenames: json["filenames"],
    homeworkId: json["homework_id"],
    filelinks: json["filelinks"],
    fileUniquenames: json["fileUniquenames"],
    homeworkStatus: json["homework_status"],
    regno: json["regno"],
    teacherId: json["teacher_id"] == null ? null : json["teacher_id"],
    replyFrom: json["reply_from"],
    status: json["status"],
    createdAt: DateTime.parse(json["created_at"]),
  );

  Map<String, dynamic> toJson() => {
    "comments": comments,
    "id": id,
    "schoolid": schoolid,
    "filenames": filenames,
    "homework_id": homeworkId,
    "filelinks": filelinks,
    "fileUniquenames": fileUniquenames,
    "homework_status": homeworkStatus,
    "regno": regno,
    "teacher_id": teacherId == null ? null : teacherId,
    "reply_from": replyFrom,
    "status": status,
    "created_at": createdAt.toIso8601String(),
  };
}

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String> reverseMap;

  EnumValues(this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}

Body:
When you use .from for creating a list, it shouldn't have toList() at the end.

Change this line.

students: List<Student>.from(json["students"].map((x) => Student.fromJson(x))).toList(),

To one of these:

First:

students: List<Student>.from(json["students"].map((x) => Student.fromJson(x))),

Or:

students: (json["students"] as List).map((i) => Student.fromJson(i)).toList(),


问:
segregate duplicates and non duplicates from a list of objects based on property on multiple property in java 8
I want to segregate duplicates and non duplicates from a list of objects based on property customerId and customerRegistration using java 8

segregate meaning

if I have 3 record with same customerId and customerRegistration, first record should add into nonduplicate list and 2 nd 3 record should be add in to duplicate list.

I have below pojo class created hashcode and equals method based on customerId and customerRegistration.

```<code>public class Asset {

private String customerName;
private int customerId;
private String Type;
private String customerRegistration;
private int assetTagList;
private String rso;
private String active;
private int billableUser;
private int billableAsset;

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Asset asset = (Asset) o;
    return customerId == asset.customerId && Objects.equals(customerRegistration, asset.customerRegistration);
}

@Override
public int hashCode() {
    return Objects.hash(customerId, customerRegistration);
}
</code>```

}

I have written below logic in java7 which will work fine ,is there any way I can write using stream(convert forloop logic in the below code to stream)?

```<code>public  Map<String ,List<Asset>> execute1() throws IOException {

    List<Asset> assetList=new ArrayList<>();
    Set<Asset> set=new HashSet<>();
    List<Asset> duplicateList=new ArrayList<>();
    List<Asset> nonDuplicateList=new ArrayList<>();
    Map<String ,List<Asset>> map = new HashMap<>();
    Asset asset1 = new Asset("French Customer1", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
    Asset asset2 = new Asset("French Customer2", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);

    Asset asset3 = new Asset("French Customer3", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset4= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset5= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);

    Asset asset6 = new Asset("French Customer5", 674, "Vehicle", "KNH 9008", 175, "FR", "Yes", 0, 0);

    assetList.add(asset1);
    assetList.add(asset2);
    assetList.add(asset3);
    assetList.add(asset4);
    assetList.add(asset5);
    assetList.add(asset6);

    for (Asset assetTemp:assetList){
        if(set.add(assetTemp)){
            nonDuplicateList.add(assetTemp);
        }
        else {
            duplicateList.add(assetTemp);
        }
    }

    map.put("duplicate",duplicateList);
    map.put("nonDuplicateList",nonDuplicateList);

   return map
}
</code>```

expecting output like below(from input assetList which is defined in the above execute1 function)

nonDuplicateList should have (asset1,asset3,asset6):

```<code>Asset asset1 = new Asset("French Customer1", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
Asset asset3 = new Asset("French Customer3", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
Asset asset6 = new Asset("French Customer5", 674, "Vehicle", "KNH 9008", 175, "FR", "Yes", 0, 0);
</code>```

duplicateList should have:(asset2,asset4,asset5)

```<code>Asset asset2 = new Asset("French Customer2", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
Asset asset4= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
Asset asset5= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
</code>```

答:
You could use the same approach of using Set<Asset> set and collect it to a map using partitioningBy collector. Even though it would not cause much issue in the given example, Please read this answer to know why you shouldn't use a Collector to mutate an existing collection.

assetList.stream().collect(Collectors.partitioningBy(set::add));
```

This would return a map with Boolean key, where true would be non-duplicates.

Body:
I want to segregate duplicates and non duplicates from a list of objects based on property customerId and customerRegistration using java 8

segregate meaning

if I have 3 record with same customerId and customerRegistration, first record should add into nonduplicate list and 2 nd 3 record should be add in to duplicate list.

I have below pojo class created hashcode and equals method based on customerId and customerRegistration.

public class Asset {

private String customerName;
private int customerId;
private String Type;
private String customerRegistration;
private int assetTagList;
private String rso;
private String active;
private int billableUser;
private int billableAsset;

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Asset asset = (Asset) o;
    return customerId == asset.customerId && Objects.equals(customerRegistration, asset.customerRegistration);
}

@Override
public int hashCode() {
    return Objects.hash(customerId, customerRegistration);
}

}

I have written below logic in java7 which will work fine ,is there any way I can write using stream(convert forloop logic in the below code to stream)?

public  Map<String ,List<Asset>> execute1() throws IOException {

    List<Asset> assetList=new ArrayList<>();
    Set<Asset> set=new HashSet<>();
    List<Asset> duplicateList=new ArrayList<>();
    List<Asset> nonDuplicateList=new ArrayList<>();
    Map<String ,List<Asset>> map = new HashMap<>();
    Asset asset1 = new Asset("French Customer1", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
    Asset asset2 = new Asset("French Customer2", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);

    Asset asset3 = new Asset("French Customer3", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset4= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset5= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);

    Asset asset6 = new Asset("French Customer5", 674, "Vehicle", "KNH 9008", 175, "FR", "Yes", 0, 0);

    assetList.add(asset1);
    assetList.add(asset2);
    assetList.add(asset3);
    assetList.add(asset4);
    assetList.add(asset5);
    assetList.add(asset6);

    for (Asset assetTemp:assetList){
        if(set.add(assetTemp)){
            nonDuplicateList.add(assetTemp);
        }
        else {
            duplicateList.add(assetTemp);
        }
    }

    map.put("duplicate",duplicateList);
    map.put("nonDuplicateList",nonDuplicateList);

   return map
}

expecting output like below(from input assetList which is defined in the above execute1 function)

nonDuplicateList should have (asset1,asset3,asset6):

Asset asset1 = new Asset("French Customer1", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
Asset asset3 = new Asset("French Customer3", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
Asset asset6 = new Asset("French Customer5", 674, "Vehicle", "KNH 9008", 175, "FR", "Yes", 0, 0);

duplicateList should have:(asset2,asset4,asset5)

Asset asset2 = new Asset("French Customer2", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
Asset asset4= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
Asset asset5= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);

Body:
You could use the same approach of using Set<Asset> set and collect it to a map using partitioningBy collector. Even though it would not cause much issue in the given example, Please read this answer to know why you shouldn't use a Collector to mutate an existing collection.

assetList.stream().collect(Collectors.partitioningBy(set::add));

This would return a map with Boolean key, where true would be non-duplicates.


问:
"error: RPC failed; curl 56 GnuTLS recv error (-110): The TLS connection was non-properly terminated"
Dear community when I clone the project from bitbucket this error message apperas

"error: RPC failed; curl 56 GnuTLS recv error (-110): The TLS connection was non-properly terminated"

Does anyone know how can I fix it ??
Thanks in advance.

答:
fatal: unable to access 'https://github.com/****': GnuTLS recv error (-110): The TLS connection was non-properly terminated.

solution：
https://stdworkflow.com/782/fatal-cannot-access-https-github-com-gnutls-recv-error-110-the-tls-connection-was-non-pr

run commands as follows：

apt-get install gnutls-bin
git config --global http.sslVerify false
git config --global http.postBuffer 1048576000
```


问:
How to ask for confirmation before performing an actionin ruby on rails?
I have a delete button where I want to ask for confirmation before deleting the record. I want to put a custom message in German and German terms for 'OK' and 'cancel'.

```<code><%= button_to 'Record löschen', action: 'delete_all_record', id: params[:id], redirect_back: params[:redirect_back]%>
</code>```

so, when I press record löshen button it should ask for confirmation and then perform the deletion action.

答:
Just a quick tip for rails 7</p>
```<code><%= button_to 'Record löschen',
  {action: 'delete_all_record', id: params[:id]},
  form: {data: {turbo_confirm: 'Sind Sie sicher?'}} %>
</code>```

Body:
I have a delete button where I want to ask for confirmation before deleting the record. I want to put a custom message in German and German terms for 'OK' and 'cancel'.

<%= button_to 'Record löschen', action: 'delete_all_record', id: params[:id], redirect_back: params[:redirect_back]%>

so, when I press record löshen button it should ask for confirmation and then perform the deletion action.

Body:
Just a quick tip for rails 7

<%= button_to 'Record löschen',
  {action: 'delete_all_record', id: params[:id]},
  form: {data: {turbo_confirm: 'Sind Sie sicher?'}} %>


问:
How to group together boxes of different traces for subplots in plotly?
In the documentation about plotly boxes we are told that for Group Box plots we use boxmode so that to group together boxes for each value x

```<code>fig.update_layout(
    yaxis_title='normalized moisture',
    boxmode='group' # group together boxes of the different traces for each value of x
)
</code>```

My question is how do you apply this in case you are using Box subplots?
An example would be nice.

In my case I have 5 box subplots and I have put boxmode in the layout but this affects all subplots, even the ones that have only one trace for each value of x, which gives a weird appearance to the plot.

Related to this, if you have 5 box subplots with only one trace for x value, the boxmode option affects the plots anyway

答:
extending https://plotly.com/python/box-plots/#grouped-box-plots example to do sub plots

this does work, however it does offset x-axis in subplots (either as rows or columns)

have tried setting various xaxis layout parameters to prevent offsetting without success

is this the behaviour you are noting does not work well in sub-plots?

import itertools
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np

x = ['day 1', 'day 1', 'day 1', 'day 1', 'day 1', 'day 1',
     'day 2', 'day 2', 'day 2', 'day 2', 'day 2', 'day 2']

fig = make_subplots(rows=1, cols=3)
for r,n in itertools.product(range(3), ["kale","carrots","radishes"]):
    fig.add_trace(go.Box(x=[f"{xx}.{r}" for xx in x], y=np.random.uniform(0,1, len(x)), name=f"{n}-{r}"), row=1, col=r+1)

fig.update_layout(boxmode="group")
fig.show()

fig = make_subplots(rows=3, cols=1)
for r,n in itertools.product(range(3), ["kale","carrots","radishes"]):
    fig.add_trace(go.Box(x=[f"{xx}.{r}" for xx in x], y=np.random.uniform(0,1, len(x)), name=f"{n}-{r}"), row=r+1, col=1)

fig.update_layout(boxmode="group")

```

Body:
In the documentation about plotly boxes we are told that for Group Box plots we use boxmode so that to group together boxes for each value x

fig.update_layout(
    yaxis_title='normalized moisture',
    boxmode='group' # group together boxes of the different traces for each value of x
)

My question is how do you apply this in case you are using Box subplots?
An example would be nice.

In my case I have 5 box subplots and I have put boxmode in the layout but this affects all subplots, even the ones that have only one trace for each value of x, which gives a weird appearance to the plot.

Related to this, if you have 5 box subplots with only one trace for x value, the boxmode option affects the plots anyway


问:
Github Fetch and Merge problems
I forked github repository month ago. I created branch "test".

Yesterday I opened it on GitHub (page) and I clicked "Fetch and Merge" button (on branch "test"), after that I updated branch with some changes. Later I created PR to origin repository. When I opened PR page it shows my change and also other's people changes that was added to my repository when I fetched code!

Also test "Prettier" returned this errors:

```<code>fatal: You are not currently on a branch.
To push the history leading to the current (detached HEAD)
</code>```

In this PR I created only one change but it shows 50... I don't want that. Can someone help me?

I was trying a lot of things on Youtube, Stackoverflow but still I can't fix it!

答:
Okay

if you're working with other people in the same project, there are two things that you have to consider before pushing your changes to the remote repository

you need to have the latest changes made by others to be in your local repository (or forked one), so when you push yours, there will be no conflicts, otherwise Git will not let you push to the remote repo unless you  force the push by the flag -f, which is not recommended because it will make conflicts for other peoples

so you need to fetch/merge, and then push, and when you'll make a pull request to the repo, this will just show the changes you made, not other's changes because they are already in the remote repo

so

```<code>git pull
</code>```

solve conflicts if you find them
and then

```<code>git push
</code>```

Title: Github Fetch and Merge problems

Body:
I forked github repository month ago. I created branch "test".

Yesterday I opened it on GitHub (page) and I clicked "Fetch and Merge" button (on branch "test"), after that I updated branch with some changes. Later I created PR to origin repository. When I opened PR page it shows my change and also other's people changes that was added to my repository when I fetched code!

Also test "Prettier" returned this errors:

fatal: You are not currently on a branch.
To push the history leading to the current (detached HEAD)

In this PR I created only one change but it shows 50... I don't want that. Can someone help me?

I was trying a lot of things on Youtube, Stackoverflow but still I can't fix it!

Body:
Okay

if you're working with other people in the same project, there are two things that you have to consider before pushing your changes to the remote repository

you need to have the latest changes made by others to be in your local repository (or forked one), so when you push yours, there will be no conflicts, otherwise Git will not let you push to the remote repo unless you  force the push by the flag -f, which is not recommended because it will make conflicts for other peoples

so you need to fetch/merge, and then push, and when you'll make a pull request to the repo, this will just show the changes you made, not other's changes because they are already in the remote repo

so

git pull

solve conflicts if you find them
and then

git push


问:
vuetify v-select chip unselect on click
So I have this v-select:

```<code>        <v-select
          v-model="myModel"
          label="My Label"
          :items="items"
          multiple
          chips
        ></v-select>
</code>```

I would like to add the behavior that clicking on a v-chip removes it from the selected list.

Can anyone help on that? I checked the documentation, but there is not attribute nor events regarding this use case.

Thanks for the help

答:
There is selection slot in v-select https://vuetifyjs.com/en/api/v-select/#slots

const vuetifyOptions = {}
    Vue.use(Vuetify)

    new Vue({
        el: '#app',
        vuetify: new Vuetify(vuetifyOptions),
        data: () => ({
          myModel: [],
          items: [
          "https://picsum.photos/200/200",
          "https://picsum.photos/300/200",
          "https://picsum.photos/250/200"
        ],

        }),
        methods: {
          deleteItem(item) {
            this.myModel = this.myModel.filter(find => find !== item);
          }
        },
    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet"/>

<div id="app">
  <v-app>
    <v-select
          v-model="myModel"
          label="My Label"
          :items="items"
          multiple
          chips
        >
      <template #selection="selection">
        <v-chip @click="deleteItem(selection.item)" v-text="selection.item"></v-chip>
      </template>

    </v-select>
  </v-app>
</div></code>```

Title: vuetify v-select chip unselect on click

Body:
So I have this v-select:

        <v-select
          v-model="myModel"
          label="My Label"
          :items="items"
          multiple
          chips
        ></v-select>

I would like to add the behavior that clicking on a v-chip removes it from the selected list.

Can anyone help on that? I checked the documentation, but there is not attribute nor events regarding this use case.

Thanks for the help

Body:
There is selection slot in v-select https://vuetifyjs.com/en/api/v-select/#slots

const vuetifyOptions = {}
    Vue.use(Vuetify)

    new Vue({
        el: '#app',
        vuetify: new Vuetify(vuetifyOptions),
        data: () => ({
          myModel: [],
          items: [
          "https://picsum.photos/200/200",
          "https://picsum.photos/300/200",
          "https://picsum.photos/250/200"
        ],

        }),
        methods: {
          deleteItem(item) {
            this.myModel = this.myModel.filter(find => find !== item);
          }
        },
    })

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet"/>

<div id="app">
  <v-app>
    <v-select
          v-model="myModel"
          label="My Label"
          :items="items"
          multiple
          chips
        >
      <template #selection="selection">
        <v-chip @click="deleteItem(selection.item)" v-text="selection.item"></v-chip>
      </template>

    </v-select>
  </v-app>
</div>


问:
Move a worksheet in a workbook using openpyxl or xl* or xlsxwriter?
I've read the docs for, openpyxl, xlwt, xlrd, xlutils, xlsxwriter. I don't find a way to move a sheet in an Excel workbook. Tests added a worksheet to the ends.

Concretely, I have a calendar of sorts, ['JAN','FEB',...,'DEC'] and I need to replace months as the need arises.

How do you order the sheets in an Excel workbook if you don't move them? Can you insert a sheet after or before a specified sheet?

Only one other post I can find on SO uses win32com and Book.Worksheets.Add(After=Sheet); seems strange none of these modules would have this method.

Default seems to add sheet at end of workbook. I could copy the destination file, until the updated sheet is reached,  insert new sheet, and continue original copy to the end. (inspired by this post)

答:
My answer is for basic moving of sheets. I am using move_sheets function in openpyxl

Say you have sheets named Sheet 1 : "abc" and Sheet 2: "xyz" and you want to move xyz from 2nd position to first

```<code>import openpyxl as xl
wb = xl.load_worksheet("C:\\Users\\Desktop\\testfile.xlsx") #load worksheet using the excel file path, make sure you load the file from correct path
wb.active = 1 #the sheet index starts from 0 , hence 1 will select the second sheet ie xyz
wb.move_sheet(wb.active, offset = -1) #this will offset the current active sheet which is xyz be one position to the left which in our case is 1st position
wb.save(//path where you want to save the file.xlsx)
</code>```

Body:
My answer is for basic moving of sheets. I am using move_sheets function in openpyxl

Say you have sheets named Sheet 1 : "abc" and Sheet 2: "xyz" and you want to move xyz from 2nd position to first

import openpyxl as xl
wb = xl.load_worksheet("C:\\Users\\Desktop\\testfile.xlsx") #load worksheet using the excel file path, make sure you load the file from correct path
wb.active = 1 #the sheet index starts from 0 , hence 1 will select the second sheet ie xyz
wb.move_sheet(wb.active, offset = -1) #this will offset the current active sheet which is xyz be one position to the left which in our case is 1st position
wb.save(//path where you want to save the file.xlsx)


问:
setContent of an textarea with tinyMCE
I have some textareas and all of them are with tinyMCE.

I would like to set the content of the specific textarea, but I can't find how.

I have tryed this:

```<code> tinyMCE.get('title').setContent(selected_article_title);
</code>```

here is my textarea:

```<code><textarea style="width: 95%;" name="Title"  id="title"></textarea>
</code>```

And here my tinyMCE init:

```<code>tinyMCE.init({
// General options
mode : "specific_textareas",
theme : "advanced",
width: "100%",
plugins : "pagebreak,paste,fullscreen,visualchars",

// Theme options
theme_advanced_buttons1 : "code,|,bold,italic,underline,|,sub,sup,|,charmap,|,fullscreen,|,bullist,numlist,|,pasteword",
theme_advanced_buttons2 :"",
theme_advanced_buttons3 :"",
theme_advanced_buttons4 :"",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
valid_elements : "i,sub,sup",
invalid_elements : "p, script",
editor_deselector : "mceOthers"
});
</code>```

I don't know why this is not working, I am using the exemple from the tinyMCE website http://www.tinymce.com/wiki.php/API3:method.tinymce.Editor.setContent

答:
I just wrote this instead of setContent

```<code>const textarea = document.querySelector('#title')
textarea.innerHTML = selected_article_title
</code>```

and it worked

ContentLicense: CC BY-SA 3.0

Title: setContent of an textarea with tinyMCE

Body:
I have some textareas and all of them are with tinyMCE.

I would like to set the content of the specific textarea, but I can't find how.

I have tryed this:

 tinyMCE.get('title').setContent(selected_article_title);

here is my textarea:

<textarea style="width: 95%;" name="Title"  id="title"></textarea>

And here my tinyMCE init:

tinyMCE.init({
// General options
mode : "specific_textareas",
theme : "advanced",
width: "100%",
plugins : "pagebreak,paste,fullscreen,visualchars",

// Theme options
theme_advanced_buttons1 : "code,|,bold,italic,underline,|,sub,sup,|,charmap,|,fullscreen,|,bullist,numlist,|,pasteword",
theme_advanced_buttons2 :"",
theme_advanced_buttons3 :"",
theme_advanced_buttons4 :"",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
valid_elements : "i,sub,sup",
invalid_elements : "p, script",
editor_deselector : "mceOthers"
});

I don't know why this is not working, I am using the exemple from the tinyMCE website http://www.tinymce.com/wiki.php/API3:method.tinymce.Editor.setContent

Body:
I just wrote this instead of setContent

const textarea = document.querySelector('#title')
textarea.innerHTML = selected_article_title

and it worked


问:
Delete row from table using button - Bootstrap Table
I'm trying the row to be deleted when I click the delete icon in the table using bootstrap table.

My table:

```<code><table id="checkDataTable">
    <thead style="color: #31708f; background-color: #d9edf7 ">
        <tr>
            <th data-field="AssetReference">Referans</th>
            <th data-field="Customer">Müsteri</th>
            <th data-field="ReceiverCompanyName">Alici Firma</th>
            <th data-field="Tools" data-formatter="StatuFormatter">Islem</th>
        </tr>
    </thead>
</table>
</code>```

Javascript:

```<code>function StatuFormatter(value, row, index) {

    return "<a onclick='removeAssetEconomyCheckBillOfLadingRow()'><i class='fa fa-trash fa-2x' aria-hidden='true'></i></a>";
}

function removeAssetEconomyCheckBillOfLadingRow(id) {
    alert(id);
}
</code>```

It's fine until the removeAssetEconomyCheckBillOfLadingRow function.

How can I delete inside this function?

答:
Please try below:

$(document).on('click', 'button.deleteRow', function(event) {
  $(this).closest("tr").remove();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="checkDataTable" class="table">
  <thead style="color: #31708f; background-color: #d9edf7 ">
    <tr>
      <th data-field="AssetReference">Referans</th>
      <th data-field="Customer">Müşteri</th>
      <th data-field="ReceiverCompanyName">Alıcı Firma</th>
      <th data-field="Tools" data-formatter="StatuFormatter">İşlem</th>
    </tr>
  </thead>
  <tobdy>
    <tr>
      <td>Data1</td>
      <td>Data1</td>
      <td>Data1</td>
      <td><button type="button" class="deleteRow">
                    Delete
                    </button></td>
    </tr>
    <tr>
      <td>Data2</td>
      <td>Data2</td>
      <td>Data2</td>
      <td><button type="button" class="deleteRow">
                    Delete
                    </button></td>
    </tr>
    <tr>
      <td>Data3</td>
      <td>Data3</td>
      <td>Data3</td>
      <td><button type="button" class="deleteRow">
                    Delete
                    </button></td>
    </tr>
  </tobdy>
</table></code>```

Body:
I'm trying the row to be deleted when I click the delete icon in the table using bootstrap table.

My table:

            Referans
            Müsteri
            Alici Firma
            Islem

Javascript:

function StatuFormatter(value, row, index) {

    return "";
}

function removeAssetEconomyCheckBillOfLadingRow(id) {
    alert(id);
}

It's fine until the removeAssetEconomyCheckBillOfLadingRow function.

How can I delete inside this function?

Body:
Please try below:

$(document).on('click', 'button.deleteRow', function(event) {
  $(this).closest("tr").remove();
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="checkDataTable" class="table">
  <thead style="color: #31708f; background-color: #d9edf7 ">
    <tr>
      <th data-field="AssetReference">Referans</th>
      <th data-field="Customer">Müşteri</th>
      <th data-field="ReceiverCompanyName">Alıcı Firma</th>
      <th data-field="Tools" data-formatter="StatuFormatter">İşlem</th>
    </tr>
  </thead>
  <tobdy>
    <tr>
      <td>Data1</td>
      <td>Data1</td>
      <td>Data1</td>
      <td><button type="button" class="deleteRow">
                    Delete
                    </button></td>
    </tr>
    <tr>
      <td>Data2</td>
      <td>Data2</td>
      <td>Data2</td>
      <td><button type="button" class="deleteRow">
                    Delete
                    </button></td>
    </tr>
    <tr>
      <td>Data3</td>
      <td>Data3</td>
      <td>Data3</td>
      <td><button type="button" class="deleteRow">
                    Delete
                    </button></td>
    </tr>
  </tobdy>
</table>


问:
Dart DateFormat inconsistency
I'm trying to parse date string that looks like this Feb0920221500 (month, day in month, year, hours, minutes). But when I use MMMddyyyyHmm pattern I always get a FormatException. Furthermore intl's DateFormat fails to parse back a date which it has formatted before:

import 'package:intl/intl.dart';

void main() {
  final dateFormat = DateFormat("MMMddyyyyHmm");
  final dateString = dateFormat.format(DateTime.now());
  print(dateString);
  final date = dateFormat.parse(dateString);
  print(date);
}
```
<p>Output:</p>
```Feb0920221511
Uncaught Error: FormatException: Trying to read yyyy from Feb0920221511 at position 13
```

What am I doing wrong?

答:
You are running into this issue: https://github.com/dart-lang/intl/issues/210

TL/DR: Both methods are not designed to work fully reversible, if I understood the package maintainers correctly.

Try to introduce field separators like a space or a dot as a workaround:

  final dateFormat = DateFormat("MMM dd yyyy H mm");
  final dateString = dateFormat.format(DateTime.now());
  print(dateString);
  print(dateFormat.parseStdaterict(dateString));
```
<p>If the format of the given date String cannot be changed, you still have the possibility to make it work with a hack like this. Just make sure to handle errors gracefully.</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:intl/intl.dart';

Future<void> main() async {
  final parsedDate = 'Feb0920221511'.parseToDate();
  print(parsedDate.toIso8601String());
}

extension CustomDateParser on String {
  DateTime parseToDate() {
    try {
      final month = substring(0, 3);
      final day = substring(3, 5);
      final year = substring(5, 9);
      final hour = substring(9, 11);
      final minute = substring(11, 13);

      final paddedDateString = '$month $day $year $hour $minute';
      final dateFormat = DateFormat('MMM dd yyyy H mm');
      return dateFormat.parse(paddedDateString);
    } catch (e) {
      // handle error
      print(e);
      rethrow;
    }
  }
}
</code>```

Title: Dart DateFormat inconsistency

Body:
I'm trying to parse date string that looks like this Feb0920221500 (month, day in month, year, hours, minutes). But when I use MMMddyyyyHmm pattern I always get a FormatException. Furthermore intl's DateFormat fails to parse back a date which it has formatted before:

import 'package:intl/intl.dart';

void main() {
  final dateFormat = DateFormat("MMMddyyyyHmm");
  final dateString = dateFormat.format(DateTime.now());
  print(dateString);
  final date = dateFormat.parse(dateString);
  print(date);
}

Output:

Feb0920221511
Uncaught Error: FormatException: Trying to read yyyy from Feb0920221511 at position 13

What am I doing wrong?

Body:
You are running into this issue: https://github.com/dart-lang/intl/issues/210

TL/DR: Both methods are not designed to work fully reversible, if I understood the package maintainers correctly.

Try to introduce field separators like a space or a dot as a workaround:

  final dateFormat = DateFormat("MMM dd yyyy H mm");
  final dateString = dateFormat.format(DateTime.now());
  print(dateString);
  print(dateFormat.parseStdaterict(dateString));

If the format of the given date String cannot be changed, you still have the possibility to make it work with a hack like this. Just make sure to handle errors gracefully.

import 'package:intl/intl.dart';

Future<void> main() async {
  final parsedDate = 'Feb0920221511'.parseToDate();
  print(parsedDate.toIso8601String());
}

extension CustomDateParser on String {
  DateTime parseToDate() {
    try {
      final month = substring(0, 3);
      final day = substring(3, 5);
      final year = substring(5, 9);
      final hour = substring(9, 11);
      final minute = substring(11, 13);

      final paddedDateString = '$month $day $year $hour $minute';
      final dateFormat = DateFormat('MMM dd yyyy H mm');
      return dateFormat.parse(paddedDateString);
    } catch (e) {
      // handle error
      print(e);
      rethrow;
    }
  }
}


问:
I have built my Nuxt app through Cloud Build, how do I now deploy it?
I created a simple Nuxt app,

added a cloudbuild.yaml...

```<code>steps:
- name: node:16
  entrypoint: npm
  args: ['install']
- name: node:16
  entrypoint: npm
  args: ['run', 'build']
</code>```

The build ran successfully but I have no idea where the files created from the build went, and how I now deploy this build. Locally I would just run npm run start but when I tried adding that to my cloudbuild the build logs just showed listening on localhost:3000. In any case, I have a feeling I shouldn't be adding the start command to my build.

I am very new to CI/CD. I have previously deployed this code on Heroku with minimal difficulty but now I'm trying to run it on GCP and struggling.

I have seen examples of running the build locally and then pushing the whole thing to GCP but I'd like to be able to do it all automatically just from a push to master.

答:
Assuming you have the gcloud CLI and an AppYAML file (can have any name so long as the extension is .yaml), you simply have to go to the directory YourAppYaml.yaml is in and run this command:

```<code>gcloud app deploy YourAppYaml.yaml
</code>```

(If you would prefer to not have to type YourAppYaml.yaml/--appyaml=YourAppYaml.yaml every time you run gcloud app deploy, you can simply rename YourAppYaml.yaml to app.yaml)

Given that you've specified wanting to "be able to do it all automatically just from a push to master", I believe what you're looking for is this, however doing it through Cloud build does require that you include the following step (otherwise you're just building without deploying, which would defeat the purpose):

`cloudbuild.yaml` (aka `Cloud Build build config file`):

- name: node:16
  entrypoint: npm
  args: ['run', 'install']
- name: node:16
  entrypoint: npm
  args: ['run', 'build']
- name: "gcr.io/cloud-builders/gcloud"
  args: ["app", "deploy"]
timeout: "1600s"
```
<h3>If you want to deploy it manually without using a trigger:</h3>
```gcloud builds submit --config cloudbuild.yaml .
```

You can find more detailed instructions on how to perform Google Cloud Build builds from CLI using either Dockerfiles or YAMLs here (the .yaml and Dockerfile examples are in the same gcloud tab, I've linked text to direct you to the .yaml version within said tab)

Alternatively there is [Github Actions] (https://github.com/features/actions), more specifically this google action that deploys to app engine (I would recommend reading the description thoroughly, as some Google documentation can have important information that is easy to overlook)

Body:
I created a simple Nuxt app,

added a cloudbuild.yaml...

steps:
- name: node:16
  entrypoint: npm
  args: ['install']
- name: node:16
  entrypoint: npm
  args: ['run', 'build']

The build ran successfully but I have no idea where the files created from the build went, and how I now deploy this build. Locally I would just run npm run start but when I tried adding that to my cloudbuild the build logs just showed listening on localhost:3000. In any case, I have a feeling I shouldn't be adding the start command to my build.

I am very new to CI/CD. I have previously deployed this code on Heroku with minimal difficulty but now I'm trying to run it on GCP and struggling.

I have seen examples of running the build locally and then pushing the whole thing to GCP but I'd like to be able to do it all automatically just from a push to master.

Body:
Assuming you have the gcloud CLI and an AppYAML file (can have any name so long as the extension is .yaml), you simply have to go to the directory YourAppYaml.yaml is in and run this command:

gcloud app deploy YourAppYaml.yaml

(If you would prefer to not have to type YourAppYaml.yaml/--appyaml=YourAppYaml.yaml every time you run gcloud app deploy, you can simply rename YourAppYaml.yaml to app.yaml)

Given that you've specified wanting to "be able to do it all automatically just from a push to master", I believe what you're looking for is this, however doing it through Cloud build does require that you include the following step (otherwise you're just building without deploying, which would defeat the purpose):

`cloudbuild.yaml` (aka `Cloud Build build config file`):

- name: node:16
  entrypoint: npm
  args: ['run', 'install']
- name: node:16
  entrypoint: npm
  args: ['run', 'build']
- name: "gcr.io/cloud-builders/gcloud"
  args: ["app", "deploy"]
timeout: "1600s"

If you want to deploy it manually without using a trigger:

gcloud builds submit --config cloudbuild.yaml .

You can find more detailed instructions on how to perform Google Cloud Build builds from CLI using either Dockerfiles or YAMLs here (the .yaml and Dockerfile examples are in the same gcloud tab, I've linked text to direct you to the .yaml version within said tab)

Alternatively there is [Github Actions] (https://github.com/features/actions), more specifically this google action that deploys to app engine (I would recommend reading the description thoroughly, as some Google documentation can have important information that is easy to overlook)


问:
Does azure durable functions always require yield when calling activities?
I have a problem where i have been working with durable functions and my fuction app resources are drained, usually as i understand it, durable function activities when executed with yield are executed in ansynchronous or parallel mode, so in this example F1 and F2 all called at the same time and when both results are created they will be aggregated here in my list and the whole orchestration will be done, is it possible to execute functions without yield and in sequential order?

```<code>import logging
import json

import azure.functions as func
import azure.durable_functions as df

def orchestrator_function(context: df.DurableOrchestrationContext):
    result1 = yield context.call_activity('F1', 'arg')
    result2 = yield context.call_activity('F2', 'arg')
    return [result1, result2]

main = df.Orchestrator.create(orchestrator_function)
</code>```

答:
As you are using the orchestrator function which is also known as generator function so it has to use Yield Keyword.  There is no way to execute the function without the Yield keyword. In your case, to execute function sequential order you can use function chaining by which we can execute functions one by one.

for further details, you can check the related links

Durable Functions Overview - Azure | Microsoft Docs

 Simple statements — Python 3.10.2 documentation

Glossary — Python 3.10.2 documentation

Body:
I have a problem where i have been working with durable functions and my fuction app resources are drained, usually as i understand it, durable function activities when executed with yield are executed in ansynchronous or parallel mode, so in this example F1 and F2 all called at the same time and when both results are created they will be aggregated here in my list and the whole orchestration will be done, is it possible to execute functions without yield and in sequential order?

import logging
import json

import azure.functions as func
import azure.durable_functions as df

def orchestrator_function(context: df.DurableOrchestrationContext):
    result1 = yield context.call_activity('F1', 'arg')
    result2 = yield context.call_activity('F2', 'arg')
    return [result1, result2]

main = df.Orchestrator.create(orchestrator_function)


问:
Getting command not found: rasa on using rasa commands
I have installed rasa using:

```<code>pip3 install rasa
</code>```

When I try to use rasa commands like:

```<code>rasa init
</code>```

I get zsh errors:

command not found: rasa error

I am on Mac OS Catalina, using:

Python version 2.7.16

Python3 version 3.7.6

pip version 19.2.3

My path variable looks like this:

```<code>/Library/Frameworks/Python.framework/Versions/3.7/bin
:/usr/local/bin
:/usr/bin
:/bin
:/usr/sbin
:/sbin
</code>```

答:
I solved this problem by downgrading python specifically 3.6.8. However, you can install any version from Python 3.6.x to 3.8.x, and NOT 3.9.

Tips: Don't add variable paths while installing multiple versions of python.

In my case, I had 3.9 python and didn't want to uninstall it because I was a working project on the 3.9 version. If you have the same case, then follow the steps. Otherwise, you can alter step2 : python -m venv project_name\venv

Step 1: Install python from above given ranges. Again, please don't install python 3.9 because it is not currently compatible.

Step 2: Delete the existing virtual environment, if you have already created it while priviously installing the rasa. Make new one

```<code>> C:\Users\name\AppData\Local\Programs\Python\Python36\python -m venv project_name\venv
</code>```

(venv: name of the virtual environment)

This command allows creating a new virtual environment with python just you installed it through step1. You can check python -m version

Step 3: Activate the environment

```<code>> project_name\venv\Scripts\acitvate.bat
</code>```

Step 4: Finally, start installing the rasa:

```<code>> pip install rasa
</code>```

Step 5:

```<code>> rasa init
</code>```

Note: I wasn't using anaconda. If you are currently using an anaconda environment, please do needful with the above steps.

If you still cannot resolve it, please follow thread or you can post there your specific query.

Body:
I have installed rasa using:

pip3 install rasa

When I try to use rasa commands like:

rasa init

I get zsh errors:

command not found: rasa error

I am on Mac OS Catalina, using:

Python version 2.7.16

Python3 version 3.7.6

pip version 19.2.3

My path variable looks like this:

/Library/Frameworks/Python.framework/Versions/3.7/bin
:/usr/local/bin
:/usr/bin
:/bin
:/usr/sbin
:/sbin

Body:
I solved this problem by downgrading python specifically 3.6.8. However, you can install any version from Python 3.6.x to 3.8.x, and NOT 3.9.

Tips: Don't add variable paths while installing multiple versions of python.

In my case, I had 3.9 python and didn't want to uninstall it because I was a working project on the 3.9 version. If you have the same case, then follow the steps. Otherwise, you can alter step2 : python -m venv project_name\venv

Step 1: Install python from above given ranges. Again, please don't install python 3.9 because it is not currently compatible.

Step 2: Delete the existing virtual environment, if you have already created it while priviously installing the rasa. Make new one

> C:\Users\name\AppData\Local\Programs\Python\Python36\python -m venv project_name\venv

(venv: name of the virtual environment)

This command allows creating a new virtual environment with python just you installed it through step1. You can check python -m version

Step 3: Activate the environment

> project_name\venv\Scripts\acitvate.bat

Step 4: Finally, start installing the rasa:

> pip install rasa

Step 5:

> rasa init

Note: I wasn't using anaconda. If you are currently using an anaconda environment, please do needful with the above steps.

If you still cannot resolve it, please follow thread or you can post there your specific query.


问:
Generic logging of function parameters in exception handling
A lot of my C# code follows this pattern:

```<code>void foo(string param1, string param2, string param3)
{
    try
    {
         // do something...
    }
    catch(Exception ex)
    {
        LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message));
    }
}
</code>```

Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string?
OR
Do you have a more generic / better way of doing this?

答:
Late to the party but I did something along these lines a year or so ago:
Github Repo

The idea of this setup is much like what your after, but with the ability to hook it up globally, there is more code than I would like there but it works and once plugged in, works for what your after.

If you take a quick look at the ProxyLogger.cs, consider this a wrapper, it will encapsulate any method it is given and execute it while handling the logging of the error as set here. This can then be setup with dependency injection for anything and everything you wish to log, e.g.:

```<code>public void ConfigureServices(HostBuilderContext hostBuilder, IServiceCollection services)
    {
        services.AddOptions();
        services.AddSingleton<IHostedService, HostedService>();

        services.AddSingleton<IMyClass, MyClass>();

        // Logging added for both the hosted service and the example class
        services.Decorate<IMyClass, ProxyLogger<IMyClass>>();
        services.Decorate<IHostedService, ProxyLogger<IHostedService>>();
    }
</code>```

You register your services as normal, but on top of that, you can decorate them with the proxy logger to handle the execution and log the details before, after, on failure etc, with FULL params.
I was obsessed with this for a while and this is as best as I could get it, but it works really well.

OwnerDisplayName: Guy

ContentLicense: CC BY-SA 2.5

Body:
A lot of my C# code follows this pattern:

void foo(string param1, string param2, string param3)
{
    try
    {
         // do something...
    }
    catch(Exception ex)
    {
        LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message));
    }
}

Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string?
OR
Do you have a more generic / better way of doing this?

Body:
Late to the party but I did something along these lines a year or so ago:
Github Repo

The idea of this setup is much like what your after, but with the ability to hook it up globally, there is more code than I would like there but it works and once plugged in, works for what your after.

If you take a quick look at the ProxyLogger.cs, consider this a wrapper, it will encapsulate any method it is given and execute it while handling the logging of the error as set here. This can then be setup with dependency injection for anything and everything you wish to log, e.g.:

public void ConfigureServices(HostBuilderContext hostBuilder, IServiceCollection services)
    {
        services.AddOptions();
        services.AddSingleton<IHostedService, HostedService>();

        services.AddSingleton<IMyClass, MyClass>();

        // Logging added for both the hosted service and the example class
        services.Decorate<IMyClass, ProxyLogger<IMyClass>>();
        services.Decorate<IHostedService, ProxyLogger<IHostedService>>();
    }

You register your services as normal, but on top of that, you can decorate them with the proxy logger to handle the execution and log the details before, after, on failure etc, with FULL params.
I was obsessed with this for a while and this is as best as I could get it, but it works really well.


问:
Combining data from multiple tables when using Group By
I have data in about 20 different tables. Each table has a column EnterDateTime for the data / time the data in those tables was added. I'm already using a combination of DATEPART (ISO_WEEK) and GROUP BY to view how much data was added for each week using the following query:

```<code>SELECT DATEPART (ISO_WEEK, EnterDateTime) WeekNum, COUNT (*) as COUNT
FROM TABLE 1
GROUP BY DATEPART (ISO_WEEK, EnterDateTime)
ORDER BY WeekNum
</code>```

Which is giving results like this, for the data in Table 1:

```<code>WeekNum | Count
1       | 1084
2       | 5257
3       | 2152
4       | 5172
</code>```

I am then doing the same query on Table 2:

```<code>WeekNum | Count
1       | 362
2       | 153
3       | 78
4       | 216
</code>```

And so on, and so on, for each of the 20 tables. This is time consuming.

Ideally, I'd like to see this in a single output, like this, so I only have to run one query, instead of about 20:

```<code>WeekNum | Table 1 Count  | Table 2 Count | Table 3 Count
1       | 1084           | 362           |  x
2       | 5257           | 153           |  x
3       | 2152           | 78            |  x
4       | 5172           | 216           |  x
</code>```

Is this possible? Thank you for your help.

答:
With a bit of text editing efforts you can create a query type of</p>
```<code>select WeekNum, min(Count1) Count1,.. min(Count20) Count20
from(
    SELECT DATEPART(ISO_WEEK, EnterDateTime) WeekNum, COUNT (*) as COUNT1, null  as COUNT2, .., null as COUNT20
    FROM TABLE1
    GROUP BY DATEPART (ISO_WEEK, EnterDateTime)

    union all
    ..

    SELECT DATEPART(ISO_WEEK, EnterDateTime) WeekNum, null, .., null, COUNT(*)
    FROM TABLE20
    GROUP BY DATEPART (ISO_WEEK, EnterDateTime)
) t
group by WeekNum
order by WeekNum;
</code>```

Body:
I have data in about 20 different tables. Each table has a column EnterDateTime for the data / time the data in those tables was added. I'm already using a combination of DATEPART (ISO_WEEK) and GROUP BY to view how much data was added for each week using the following query:

SELECT DATEPART (ISO_WEEK, EnterDateTime) WeekNum, COUNT (*) as COUNT
FROM TABLE 1
GROUP BY DATEPART (ISO_WEEK, EnterDateTime)
ORDER BY WeekNum

Which is giving results like this, for the data in Table 1:

WeekNum | Count
1       | 1084
2       | 5257
3       | 2152
4       | 5172

I am then doing the same query on Table 2:

WeekNum | Count
1       | 362
2       | 153
3       | 78
4       | 216

And so on, and so on, for each of the 20 tables. This is time consuming.

Ideally, I'd like to see this in a single output, like this, so I only have to run one query, instead of about 20:

WeekNum | Table 1 Count  | Table 2 Count | Table 3 Count
1       | 1084           | 362           |  x
2       | 5257           | 153           |  x
3       | 2152           | 78            |  x
4       | 5172           | 216           |  x

Is this possible? Thank you for your help.

Body:
With a bit of text editing efforts you can create a query type of

select WeekNum, min(Count1) Count1,.. min(Count20) Count20
from(
    SELECT DATEPART(ISO_WEEK, EnterDateTime) WeekNum, COUNT (*) as COUNT1, null  as COUNT2, .., null as COUNT20
    FROM TABLE1
    GROUP BY DATEPART (ISO_WEEK, EnterDateTime)

    union all
    ..

    SELECT DATEPART(ISO_WEEK, EnterDateTime) WeekNum, null, .., null, COUNT(*)
    FROM TABLE20
    GROUP BY DATEPART (ISO_WEEK, EnterDateTime)
) t
group by WeekNum
order by WeekNum;


问:
Parallel.ForEach Ordered Execution
I am trying to execute parallel functions on a list of objects using the new C# 4.0 Parallel.ForEach function. This is a very long maintenance process. I would like to make it execute in the order of the list so that I can stop and continue execution at the previous point. How do I do this?

Here is an example. I have a list of objects: a1 to a100. This is the current order:

```<code>a1, a51, a2, a52, a3, a53...
</code>```

I want this order:

```<code>a1, a2, a3, a4...
</code>```

I am OK with some objects being run out of order, but as long as I can find a point in the list where I can say that all objects before this point were run. I read the parallel programming csharp whitepaper and didn't see anything about it. There isn't a setting for this in the ParallelOptions class.

答:
For anyone else who comes across this question - if you're looping over an array or list (rather than an IEnumberable ), you can use the overload of Parallel.Foreach that gives the element index to maintain original order too.</p>

```<code>string[] MyArray; // array of stuff to do parallel tasks on
string[] ProcessedArray = new string[MyArray.Length];
Parallel.ForEach(MyArray, (ArrayItem,loopstate,ArrayElementIndex) =>
{
    string ProcessedArrayItem = TaskToDo(ArrayItem);
    ProcessedArray[ArrayElementIndex] = ProcessedArrayItem;
});
</code>```

Title: Parallel.ForEach Ordered Execution

Body:
I am trying to execute parallel functions on a list of objects using the new C# 4.0 Parallel.ForEach function. This is a very long maintenance process. I would like to make it execute in the order of the list so that I can stop and continue execution at the previous point. How do I do this?

Here is an example. I have a list of objects: a1 to a100. This is the current order:

a1, a51, a2, a52, a3, a53...

I want this order:

a1, a2, a3, a4...

I am OK with some objects being run out of order, but as long as I can find a point in the list where I can say that all objects before this point were run. I read the parallel programming csharp whitepaper and didn't see anything about it. There isn't a setting for this in the ParallelOptions class.

Body:
For anyone else who comes across this question - if you're looping over an array or list (rather than an IEnumberable ), you can use the overload of Parallel.Foreach that gives the element index to maintain original order too.

string[] MyArray; // array of stuff to do parallel tasks on
string[] ProcessedArray = new string[MyArray.Length];
Parallel.ForEach(MyArray, (ArrayItem,loopstate,ArrayElementIndex) =>
{
    string ProcessedArrayItem = TaskToDo(ArrayItem);
    ProcessedArray[ArrayElementIndex] = ProcessedArrayItem;
});


问:
Tcl: best way to test for empty list
Sorry, that's a very trivial question, but it seems to be so trivial that I can't find any recommendation: What is the best way in Tcl to test whether a list is empty? I would go for if {$myList eq ""} ..., or is there a better way? Thanks for your help!

答:
I just want to share some test code which shows that if {$myList eq ""}... can be much slower than if {![llength $myList}} ...:

```<code>set repeats 10
foreach n {10 100 1000 10000 20000} {
    puts "n = $n"
    puts [time {
        set l [list]
        for {set i 0} {$i < $n} {incr i} {
            lappend l $i
        }
    } $repeats]
    puts [time {
        set l [list]
        for {set i 0} {$i < $n} {incr i} {
            lappend l $i
            if {![llength $l]} {
                puts "empty (llength)"
            }
        }
    } $repeats]
    puts [time {
        set l [list]
        for {set i 0} {$i < $n} {incr i} {
            lappend l $i
            if {$l eq ""} {
                puts "empty (eq)"
            }
        }
    } $repeats]
}
</code>```

Here is the output; for each value of n: baseline (no check), check with llength, check with eq:

n = 10
5.0 microseconds per iteration
14.1 microseconds per iteration
14.0 microseconds per iteration
n = 100
40.6 microseconds per iteration
44.0 microseconds per iteration
105.8 microseconds per iteration
n = 1000
374.4 microseconds per iteration
440.7 microseconds per iteration
6240.1 microseconds per iteration
n = 10000
3534.4 microseconds per iteration
4485.8 microseconds per iteration
667206.0 microseconds per iteration
n = 20000
7576.7 microseconds per iteration
9051.9 microseconds per iteration
2761285.3 microseconds per iteration
```

I would guess that the solution using if {$l eq ""}... is very slow since does a conversion from a list to a string every time the check is done. Or is there a different explanation?

Title: Tcl: best way to test for empty list

Body:
I just want to share some test code which shows that if {$myList eq ""}... can be much slower than if {![llength $myList}} ...:

set repeats 10
foreach n {10 100 1000 10000 20000} {
    puts "n = $n"
    puts [time {
        set l [list]
        for {set i 0} {$i < $n} {incr i} {
            lappend l $i
        }
    } $repeats]
    puts [time {
        set l [list]
        for {set i 0} {$i < $n} {incr i} {
            lappend l $i
            if {![llength $l]} {
                puts "empty (llength)"
            }
        }
    } $repeats]
    puts [time {
        set l [list]
        for {set i 0} {$i < $n} {incr i} {
            lappend l $i
            if {$l eq ""} {
                puts "empty (eq)"
            }
        }
    } $repeats]
}

Here is the output; for each value of n: baseline (no check), check with llength, check with eq:

n = 10
5.0 microseconds per iteration
14.1 microseconds per iteration
14.0 microseconds per iteration
n = 100
40.6 microseconds per iteration
44.0 microseconds per iteration
105.8 microseconds per iteration
n = 1000
374.4 microseconds per iteration
440.7 microseconds per iteration
6240.1 microseconds per iteration
n = 10000
3534.4 microseconds per iteration
4485.8 microseconds per iteration
667206.0 microseconds per iteration
n = 20000
7576.7 microseconds per iteration
9051.9 microseconds per iteration
2761285.3 microseconds per iteration

I would guess that the solution using if {$l eq ""}... is very slow since does a conversion from a list to a string every time the check is done. Or is there a different explanation?


问:
Running command after sudo login
I'm trying to execute below code to execute sudo commands but I do not know how execute commands after sudo login

```<code>String[] commands = {"sudo su - myname;","id"};
JSch jsch = new JSch();
String username = "myuser";
com.jcraft.jsch.Session session =
        jsch.getSession(username,"hostname", 22);
session.setPassword("my@123");
session.connect();
Channel channel=session.openChannel("exec");
for(int a=0;a<=commands.length;a++){
    ((ChannelExec)channel).setCommand("sudo su - myname;");
    ((ChannelExec)channel).setErrStream(System.err);
    ((ChannelExec) channel).setPty(true);
    channel.connect();
    System.out.println("id *******");
    OutputStream out=channel.getOutputStream();
    out.write(("my@123\n").getBytes());
    out.flush();
    InputStream in=channel.getInputStream();
    byte[] tmp=new byte[1024];
    while(true){
        while(in.available()>0){
            int i=in.read(tmp, 0, 1024);
            if(i<0)break;
            System.out.print(new String(tmp, 0, i));
        }
        if(channel.isClosed()){
            System.out.println("exit-status: "+channel.getExitStatus());
            break;
        }
    }
}
</code>```

答:
```<code>public static void testCh() throws JSchException, IOException, InterruptedException {

    int port=22;
    String name ="username";
    String ip ="ipHost";
    String password ="******";

    JSch jsch = new JSch();
    Session session = jsch.getSession(name, ip, port);
    session.setPassword(password);
    session.setConfig("StrictHostKeyChecking", "no");
    System.out.println("Establishing Connection...");
    session.connect();
    System.out.println("Connection established.");

    ChannelExec channelExec = (ChannelExec)session.openChannel("exec");

    InputStream in = channelExec.getInputStream();

    channelExec.setCommand("sudo su - myroot");
    channelExec.connect();
    OutputStream out = channelExec.getOutputStream();
    out.write(("cd /my/sub/directory/\n").getBytes());
    out.write(("ls -lrt *file_pattern* | tail -1\n").getBytes());
    out.flush();

    byte[] bt = new byte[1024];
    while (true) {
        while (in.available() > 0) {
            int i = in.read(bt, 0, 1024);
            if (i < 0) {
                break;
            }
            String str = new String(bt, 0, i);
            //displays the output of the command executed.
            System.out.print(str);

        }
        if (channelExec.isClosed()) {
            break;
        }
</code>```

Title: Running command after sudo login

Body:
I'm trying to execute below code to execute sudo commands but I do not know how execute commands after sudo login

String[] commands = {"sudo su - myname;","id"};
JSch jsch = new JSch();
String username = "myuser";
com.jcraft.jsch.Session session =
        jsch.getSession(username,"hostname", 22);
session.setPassword("my@123");
session.connect();
Channel channel=session.openChannel("exec");
for(int a=0;a<=commands.length;a++){
    ((ChannelExec)channel).setCommand("sudo su - myname;");
    ((ChannelExec)channel).setErrStream(System.err);
    ((ChannelExec) channel).setPty(true);
    channel.connect();
    System.out.println("id *******");
    OutputStream out=channel.getOutputStream();
    out.write(("my@123\n").getBytes());
    out.flush();
    InputStream in=channel.getInputStream();
    byte[] tmp=new byte[1024];
    while(true){
        while(in.available()>0){
            int i=in.read(tmp, 0, 1024);
            if(i<0)break;
            System.out.print(new String(tmp, 0, i));
        }
        if(channel.isClosed()){
            System.out.println("exit-status: "+channel.getExitStatus());
            break;
        }
    }
}


问:
Insert trigger doesnt do what i want it to do
i made a trigger which should avoid inserting a record  in the  rental 'uitlening' table if the person has an overdue payment (Boete). Unfortunately it doesnt work and i cant find the reason why. 'Boete' is an attribute of another table than rental. Can someone help me?

CREATE TRIGGER [dbo].[Trigger_uitlening]
ON [dbo].[Uitlening]
FOR INSERT
AS
BEGIN
    DECLARE @Boete decimal(10, 2);

    SET @Boete = (SELECT Boete FROM Lid WHERE LidNr = (SELECT LidNr FROM inserted));
    IF @Boete = 0
    BEGIN
        INSERT INTO Uitlening
        SELECT *
        FROM inserted;
    END;
END;
```

答: Attention! When you create a trigger by FOR INSERT or AFTER INSERT then don't write insert into table select * from inserted, because DB will insert data automatically, you can do only ROLLBACK this process.  But, when creating a trigger by INSTEAD OF INSERT then you must write insert into table select * from inserted, else inserting not be doing.


问:
How to make this shape with border radius?
I have trouble reproducing this shape using the border-radius:

Right now I obtain this:

Here is my css code (it's inside a grid):

```<code> .container-11-1 {
    grid-column: 1;
    grid-row: 1 / 3;
    background: #e4cab6;
    border-bottom-left-radius: 50%;
    border-bottom-right-radius: 50%;
    margin-bottom: 30px; //otherwise the bottom stick to the section below and it's even worse
}
</code>```

答:
I have made it for you, check it from the example.
Also, here is from codepen which gives you an idea.

.container-11-1 {
    width: 100%;
    height: calc(100vw - 300px);  /* Calculate `px` as you want*/
    grid-column: 1;
    grid-row: 1 / 3;
    background: #e4cab6;
    border-bottom-left-radius: 50%;
    border-bottom-right-radius: 50%;
    margin: auto;
}
.body{
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container-11-1"></div>
</body></code>```

Body:
I have trouble reproducing this shape using the border-radius:

Right now I obtain this:

Here is my css code (it's inside a grid):

 .container-11-1 {
    grid-column: 1;
    grid-row: 1 / 3;
    background: #e4cab6;
    border-bottom-left-radius: 50%;
    border-bottom-right-radius: 50%;
    margin-bottom: 30px; //otherwise the bottom stick to the section below and it's even worse
}

Body:
I have made it for you, check it from the example.
Also, here is from codepen which gives you an idea.

.container-11-1 {
    width: 100%;
    height: calc(100vw - 300px);  /* Calculate `px` as you want*/
    grid-column: 1;
    grid-row: 1 / 3;
    background: #e4cab6;
    border-bottom-left-radius: 50%;
    border-bottom-right-radius: 50%;
    margin: auto;
}
.body{
  width: 100%;
}

<body>
  <div class="container-11-1"></div>
</body>


问:
Next.js - Can we call custom hooks in GetStaticProps()
Is there any way for us to use the custom hook in getStaticProps(). The reason for this, is beacuse, we are using the Contentful CMS to fetch the data, from the Delivery API, and it is easier for us to have custom hooks to fetch certain data.

Now when we call, for example useHomePageData in getStaticProps() function, we get the error when trying to use simple object destructing to get the data.

```<code>Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
</code>```

This is the code we have in getStaticProps()

```<code>export function getStaticProps() {
const { data, isPending, error } = useFetchPagesProps('phasePage');
const { name, title, slug, sections } = data;

return {
 props: {
     name,
     title,
     slug,
     sections
  }
 }
}
</code>```

I know what this error means, but still does someone know for example any npm library or something like that, so that we can use this custom-hook?

P.S: We are also using useEffect() inside the custom-hook so that can cause the problems I think

答:
This is against React Hooks rules and its best practices, and you have to avoid this mentality at all costs, but there are sometimes that you just want to do it wrong ;). in those circumstances you can create a kinda global variable and trick the React to think that you're obeying the rules but clearly you're not :).

the code would be something like this:

```<code>//use the hook in one the parents component which you know that would be initialized earlier
//for example maybe _app.js file

let hackTheHooksRules;
function MyApp({ Component, pageProps }) {
  hackTheHooksRules = useFetchPagesProps("phasePage");
  return <Component {...pageProps} />
}
export default MyApp;
export hackTheHooksRules;
</code>```

and in the destination where you want to use it, you should do something like this:

```<code>import {hackTheHooksRules} from 'path-to-that-file'
export function getStaticProps() {
  const { data, isPending, error } = hackTheHooksRules || {};
  const { name, title, slug, sections } = data;

  return {
    props: {
      name,
      title,
      slug,
      sections
    }
  };
}
</code>```

NOTE: again this is not recommended but sometimes The heart wants what it wants and who are you to blame it

here is the the rules of hooks which you should try to obey them: reactjs.org/docs/hooks-rules.html

Body:
Is there any way for us to use the custom hook in getStaticProps(). The reason for this, is beacuse, we are using the Contentful CMS to fetch the data, from the Delivery API, and it is easier for us to have custom hooks to fetch certain data.

Now when we call, for example useHomePageData in getStaticProps() function, we get the error when trying to use simple object destructing to get the data.

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

This is the code we have in getStaticProps()

export function getStaticProps() {
const { data, isPending, error } = useFetchPagesProps('phasePage');
const { name, title, slug, sections } = data;

return {
 props: {
     name,
     title,
     slug,
     sections
  }
 }
}

I know what this error means, but still does someone know for example any npm library or something like that, so that we can use this custom-hook?

P.S: We are also using useEffect() inside the custom-hook so that can cause the problems I think

Body:
This is against React Hooks rules and its best practices, and you have to avoid this mentality at all costs, but there are sometimes that you just want to do it wrong ;). in those circumstances you can create a kinda global variable and trick the React to think that you're obeying the rules but clearly you're not :).

the code would be something like this:

//use the hook in one the parents component which you know that would be initialized earlier
//for example maybe _app.js file

let hackTheHooksRules;
function MyApp({ Component, pageProps }) {
  hackTheHooksRules = useFetchPagesProps("phasePage");
  return <Component {...pageProps} />
}
export default MyApp;
export hackTheHooksRules;

and in the destination where you want to use it, you should do something like this:

import {hackTheHooksRules} from 'path-to-that-file'
export function getStaticProps() {
  const { data, isPending, error } = hackTheHooksRules || {};
  const { name, title, slug, sections } = data;

  return {
    props: {
      name,
      title,
      slug,
      sections
    }
  };
}

NOTE: again this is not recommended but sometimes The heart wants what it wants and who are you to blame it

here is the the rules of hooks which you should try to obey them: reactjs.org/docs/hooks-rules.html


问:
Error: Member not found: 'packageRoot', how to solve ignore: deprecated_member_use in Flutter?
In my flutter project, I have made some updates of plugins and then used flutter upgrade. After that, whenever I am running my flutter project it is showing following error-

```<code>    /C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.2/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'.
          io.Platform.packageRoot; // ignore: deprecated_member_use
                      ^^^^^^^^^^^ FAILURE: Build failed with an exception.

* Where: Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s Exception: Gradle task assembleDebug failed with exit code 1
</code>```

So, I need a suggestion that how can I solve this issue?

答:
I fixed it :
compileSdkVersion 31,
and upgrade kotlin-version</p>

Body:
In my flutter project, I have made some updates of plugins and then used flutter upgrade. After that, whenever I am running my flutter project it is showing following error-

    /C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.2/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'.
          io.Platform.packageRoot; // ignore: deprecated_member_use
                      ^^^^^^^^^^^ FAILURE: Build failed with an exception.

* Where: Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s Exception: Gradle task assembleDebug failed with exit code 1

So, I need a suggestion that how can I solve this issue?


问:
Hello! How to do this with a function for date and year?
--7. Create a query which lists out all of the events which took place in February 2005:--</p>
```<code>SELECT *
FROM tblEvent
WHERE EventDate BETWEEN '2005-02-01' AND '20050228';
</code>```

答:
Simplify syntax is to build a function-based index (FBI) on the date column as shown below:</p>
```<code>create index
   index_name
on
   tblEvent
(to_char(EventDate, 'Mon-YYYY')):

select
  *
from
   tblEvent
where
to_char(EventDate,'Mon-YYYY')='Feb-2005';
</code>```

Body:
--7. Create a query which lists out all of the events which took place in February 2005:--

SELECT *
FROM tblEvent
WHERE EventDate BETWEEN '2005-02-01' AND '20050228';

Body:
Simplify syntax is to build a function-based index (FBI) on the date column as shown below:

create index
   index_name
on
   tblEvent
(to_char(EventDate, 'Mon-YYYY')):

select
  *
from
   tblEvent
where
to_char(EventDate,'Mon-YYYY')='Feb-2005';


问:
is base64 encoding url safe?
I'm using a node.bcrypt.js hash returning hex numbers in node.js for a password reset token.

```<code>user.reset_password_token = require('crypto').randomBytes(32).toString('hex'
);
</code>```

Should I also base64 encode the token before I pass it around in urls (ie: link reset email)?

Is there any benefit to doing this?

I seem to recall base64 encoding can contain forward slashes which would mess up the path:

```<code>   var token = user.reset_password_token;

   //is there any benefit to doing base64 encoding?
   var encoded_token = new Buffer(token).toString('base64');

   var reset_link = 'http://example.com/reset/'+ encoded_token;
   sendResetLink( reset_link );
</code>```

答:
You don't need a third-party library for that. You can just use base64url encoding (starting from nodejs v14.18.0)

const encoded_token = Buffer.from(token).toString('base64url');
```

Title: is base64 encoding url safe?

Body:
I'm using a node.bcrypt.js hash returning hex numbers in node.js for a password reset token.

user.reset_password_token = require('crypto').randomBytes(32).toString('hex'
);

Should I also base64 encode the token before I pass it around in urls (ie: link reset email)?

Is there any benefit to doing this?

I seem to recall base64 encoding can contain forward slashes which would mess up the path:

   var token = user.reset_password_token;

   //is there any benefit to doing base64 encoding?
   var encoded_token = new Buffer(token).toString('base64');

   var reset_link = 'http://example.com/reset/'+ encoded_token;
   sendResetLink( reset_link );


问:
.NET 6 System.PlatformNotSupportedException: Microsoft.Data.SqlClient is not supported on this platform With Fitnesse
When creating a new .net 6 project with Microsoft.Data.SqlClient It works fine. But When running through a .net 6 fitnesse project with fitsharp we are getting this error:

System.PlatformNotSupportedException: Microsoft.Data.SqlClient is not supported on this platform

Dependancies:

Fitsharp 2022.1.15

Lextm.SharpSnmpLib 12.4.0

Microsoft.Data.SqlClient 4.1.0

I've tried adding <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> to .csproj

That bypassed some errors, But the PlatformNotSupportedExcpetion is still present.

When converting to a console app and running from program. It works fine. But it won't work when running through fitnesse with fitsharp

答:
The work around for now was to downgrade Microsoft.Data.SqlClient to 2.0.1. And install the Microsoft.Data.SqlClient.SNI.Runtime v2.0.1 nuget package. Having <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> was needed, but this didn't copy the Microsoft.Data dll's to bin on build. So These two dll's needed to be move to bin:

packages\microsoft.data.sqlclient.sni.runtime\2.0.1\runtimes\win-x64\native\Microsoft.Data.SqlClient.SNI.dll

packages\microsoft.data.sqlclient\2.0.1\runtimes\win\lib\netcoreapp3.1\Microsoft.Data.SqlClient.dll

A Similar solution was found here for .NET Core 3.1:

Issues for Fitsharp in Github

Naun, answered it on 13th July, but the difference for .NET 6 was to also install the Microsoft.Data.SqlClient.SNI.Runtime v2.0.1 nuget package and copy different versions of the dll's


问:
Notepad++ multiline regex
I've got hundreds of files of the type linked here:
http://pastebin.com/fGgLfZf8

But I want to remove all the comments that occupies more than one line
eg.

```

<p>should be left untouched, while </p>

<pre class="lang-none prettyprint-override"><code><!--
************
blablabla
************
-->
</code>```

should be removed.

I know the Notepad++ feature to lookup through more than a document with regexp and I'm tryin to use it but I have some difficulty.
For a start I'm trying this regexp:

<\!\-\-(.*?)\-\->
```

which tested in here: http://www.regextester.com/ works at least partially (because it highlights the comments made of just on line)
But if I copy and paste this regexp on Notepad++ it will match just the one-line comments =\

Does anybody know how to do this in Notepad++?

答:
A simple trick if it was a single document, is to convert the line endings to Unix .

Menu: [Edit] -> [EOL Conversion] -> [Unix]

Then just use simple \n to detect newline in your expression.

This way you don't have to change expressions constructed/copied from some online regex builders.

note: don't forget to switch line endings back to Windows, just in case.

Title: Notepad++ multiline regex

Body:
I've got hundreds of files of the type linked here:
http://pastebin.com/fGgLfZf8

But I want to remove all the comments that occupies more than one line
eg.

should be left untouched, while

should be removed.

I know the Notepad++ feature to lookup through more than a document with regexp and I'm tryin to use it but I have some difficulty.
For a start I'm trying this regexp:

<\!\-\-(.*?)\-\->

which tested in here: http://www.regextester.com/ works at least partially (because it highlights the comments made of just on line)
But if I copy and paste this regexp on Notepad++ it will match just the one-line comments =\

Does anybody know how to do this in Notepad++?


问:
Helm convert data for nginx template
Im using the following file by helm

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-cfg
data:
  default.conf: |-
  {{ .Files.Get "config/nginx.conf" | nindent 4 }}
</code>```

and I got the following error:

Error: YAML parse error on ops/templates/config/nginx.conf: error converting YAML to JSON: yaml: line 4: mapping values are not allowed in this context

The nginx file looks like following

nginx.conf

```<code>server {
    listen       80;
    listen  [::]:80;
    server_name: {{ print "kiftb." .Values.global.host | quote }} // this is the error line
...
</code>```

The line with the sever_name create the error.

Any idea how to solve it?

update

As suggested by @Evan I've tried to remove the colon,

```<code>server_name {{ print "kiftb." .Values.global.host | quote }}
</code>```

And I got an error:

```<code>error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go value of type releaseutil.SimpleHead
helm.go:81: [debug] error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go value of type releaseutil.SimpleHead
</code>```

Any Idea how to overcome this? is there any workaround ?

答:
Sounds like you put the conf file in a wrong path. Helm deals with all the files inside ${chart_path}/templates/ as template or tpl files, which should be composed in YAML file. So basically you are facing the issue that helm are trying to parse ops/templates/config/nginx.conf as a template file, and definitely it will fail.
The solution would be: move your conf file out of the path ops/templates, use ops/config/nginx.conf would be fine, and you even do not need change anything in your configmap script, it will work.

Title: Helm convert data for nginx template

Body:
Im using the following file by helm

apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-cfg
data:
  default.conf: |-
  {{ .Files.Get "config/nginx.conf" | nindent 4 }}

and I got the following error:

Error: YAML parse error on ops/templates/config/nginx.conf: error converting YAML to JSON: yaml: line 4: mapping values are not allowed in this context

The nginx file looks like following

nginx.conf

server {
    listen       80;
    listen  [::]:80;
    server_name: {{ print "kiftb." .Values.global.host | quote }} // this is the error line
...

The line with the sever_name create the error.

Any idea how to solve it?

update

As suggested by @Evan I've tried to remove the colon,

server_name {{ print "kiftb." .Values.global.host | quote }}

And I got an error:

error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go value of type releaseutil.SimpleHead
helm.go:81: [debug] error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go value of type releaseutil.SimpleHead

Any Idea how to overcome this? is there any workaround ?