问:
Aggregate total and unique counts based on value type and unique visitorId - MongoDB
Similar to another question I had (Here). But now I'm trying to count unique and total events on daily basis for each event type, based on the following data shape:

```<code>{
    username: "jack",
    events: [
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "01234567-0ebb-4238-8bf7-01234567"
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-23T12:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "meeting",
       createdAt: "2022-01-23T11:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "meeting",
       createdAt: "2022-01-23T12:26:11.214Z",
       visitorInfo: {
            visitorId: "01234567-0ebb-4238-8bf7-01234567"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-30T10:26:11.214Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     },
    {
       eventType: "party",
       createdAt: "2022-01-30T10:16:11.214Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-30T12:36:11.224Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-30T11:46:11.314Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     }
       ]

    }
</code>```

I'm trying to count events (all and unique ones based on visitorId) on date (daily).
This is what I have so far (thanks to @R2D2's guide on the approach):

```<code> Event.aggregate([
  { $match: { username: 'jack' } },

  { $unwind: "$events" },

  {
    $project: {
      totalPartyEvents: {
        $cond: [
          {
            $eq: ["$events.eventType", "party"],
          },
          1,
          0,
        ],
      },

    uniquePartyEvents: { // where I'm stuck. I need to count unique events based on visitorId on current date for 'party' event type.
        $cond: [
          {
            $eq: ["$events.eventType", "party"],
          },
          1,
          0,
        ],
      },

      totalMeetingEvents: {
        $cond: [
          {
            $eq: ["$events.eventType", "meeting"],
          },
          1,
          0,
        ],
      },

    uniqueMeetingEvents: { // do the same for other events. maybe there's a better way to combine these (with facets).
        $cond: [
          {
            $eq: ["$events.eventType", "meeting"],
          },
          1,
          0,
        ],
      },

      date: "$events.createdAt",
    },
  },

  {
    $group: {
      _id: {
        $dateToString: { format: "%Y-%m-%d", date: "$date" },
      },

      totalPartyEvents: {
        $sum: "$totalMeetingEvents",
      },
      uniquePartyEvents: {
        $sum: "$totalMeetingEvents",
      },

      totalMeetingEvents: {
        $sum: "$totalMeetingEvents",
      },

      uniqueMeetingEvents: {
        $sum: "$uniqueMeetingEvents",
      },
    },
  },
  {
    $project: {
      date: "$_id",
      uniquePartyEvents: 1,
      totalPartyEvents: 1,
      totalMeetingEvents:1,
      uniqueMeetingEvents: 1,

    },
  },
  {
    $group: {
      _id: "0",
      dateAndEventFrequency: {
        $push: "$$ROOT",
      },
    },
  },
  {
    $project: {
      _id: 0,
      dateAndEventFrequency: 1,
    },
  },
]);
</code>```

I tried using $addToSet but it's not used with $project (it works with $group).
Any new approach is welcome based on the data shape and the desired result I'm expecting. I used $project because I was already using it.

Basically what I'm hoping to get in the end:

```<code>dateAndEventFrequency: [
    {
    _id: "2022-01-23",
    totalPartyEvents: 3,
    uniquePartyEvents: 2,
    totalMeetingEvents: 3,
    uniqueMeetingEvents: 2,
    date: "2022-01-23",
    },
   {
    _id: "2022-01-30",
    totalPartyEvents: 2,
    uniquePartyEvents: 1,
    totalMeetingEvents: 2,
    uniqueMeetingEvents: 1,
    date: "2022-01-30",
    },
]
</code>```

I'm using Mongoose and Nodejs. Any help or guidance is appreciated. Thanks!

答:
mongo playground</p>
```<code>db.collection.aggregate([
  {
    $match: {
      username: "jack"
    }
  },
  {
    "$unwind": "$events"
  },
  {
    "$match": {
      "events.eventType": {
        "$in": [
          "meeting",
          "party"
        ]
      }
    }
  },
  {
    "$group": {
      "_id": {
        date: {
          "$dateToString": {
            format: "%Y-%m-%d",
            date: "$events.createdAt"
          }
        },
        "visitorId": "$events.visitorInfo.visitorId",
        "eventType": "$events.eventType"
      },
      "count": {
        "$sum": 1
      }
    }
  },
  {
    "$group": {
      "_id": {
        "date": "$_id.date",
        "eventType": "$_id.eventType"
      },
      "uniqueTotal": {
        "$sum": 1
      },
      total: {
        "$sum": "$count"
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.date",
      "partyUniqueTotal": {
        "$sum": {
          "$cond": [
            {
              $eq: [
                "$_id.eventType",
                "party"
              ],

            },
            "$uniqueTotal",
            0
          ]
        }
      },
      "totalPartyEvents": {
        "$sum": {
          "$cond": [
            {
              $eq: [
                "$_id.eventType",
                "party"
              ],

            },
            "$total",
            0
          ]
        }
      },
      "meetingUniqueTotal": {
        "$sum": {
          "$cond": [
            {
              $eq: [
                "$_id.eventType",
                "meeting"
              ],

            },
            "$uniqueTotal",
            0
          ]
        }
      },
      "totalmeetingEvents": {
        "$sum": {
          "$cond": [
            {
              $eq: [
                "$_id.eventType",
                "meeting"
              ],

            },
            "$total",
            0
          ]
        }
      }
    }
  }
])
</code>```

Body:
Similar to another question I had (Here). But now I'm trying to count unique and total events on daily basis for each event type, based on the following data shape:

{
    username: "jack",
    events: [
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "01234567-0ebb-4238-8bf7-01234567"
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-23T12:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "meeting",
       createdAt: "2022-01-23T11:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "meeting",
       createdAt: "2022-01-23T12:26:11.214Z",
       visitorInfo: {
            visitorId: "01234567-0ebb-4238-8bf7-01234567"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-30T10:26:11.214Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     },
    {
       eventType: "party",
       createdAt: "2022-01-30T10:16:11.214Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-30T12:36:11.224Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     },
    {
       eventType: "meeting",
       createdAt: "2022-01-30T11:46:11.314Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     }
       ]

    }

I'm trying to count events (all and unique ones based on visitorId) on date (daily).
This is what I have so far (thanks to @R2D2's guide on the approach):

 Event.aggregate([
  { $match: { username: 'jack' } },

  { $unwind: "$events" },

  {
    $project: {
      totalPartyEvents: {
        $cond: [
          {
            $eq: ["$events.eventType", "party"],
          },
          1,
          0,
        ],
      },

    uniquePartyEvents: { // where I'm stuck. I need to count unique events based on visitorId on current date for 'party' event type.
        $cond: [
          {
            $eq: ["$events.eventType", "party"],
          },
          1,
          0,
        ],
      },

      totalMeetingEvents: {
        $cond: [
          {
            $eq: ["$events.eventType", "meeting"],
          },
          1,
          0,
        ],
      },

    uniqueMeetingEvents: { // do the same for other events. maybe there's a better way to combine these (with facets).
        $cond: [
          {
            $eq: ["$events.eventType", "meeting"],
          },
          1,
          0,
        ],
      },

      date: "$events.createdAt",
    },
  },

  {
    $group: {
      _id: {
        $dateToString: { format: "%Y-%m-%d", date: "$date" },
      },

      totalPartyEvents: {
        $sum: "$totalMeetingEvents",
      },
      uniquePartyEvents: {
        $sum: "$totalMeetingEvents",
      },

      totalMeetingEvents: {
        $sum: "$totalMeetingEvents",
      },

      uniqueMeetingEvents: {
        $sum: "$uniqueMeetingEvents",
      },
    },
  },
  {
    $project: {
      date: "$_id",
      uniquePartyEvents: 1,
      totalPartyEvents: 1,
      totalMeetingEvents:1,
      uniqueMeetingEvents: 1,

    },
  },
  {
    $group: {
      _id: "0",
      dateAndEventFrequency: {
        $push: "$$ROOT",
      },
    },
  },
  {
    $project: {
      _id: 0,
      dateAndEventFrequency: 1,
    },
  },
]);

I tried using $addToSet but it's not used with $project (it works with $group).
Any new approach is welcome based on the data shape and the desired result I'm expecting. I used $project because I was already using it.

Basically what I'm hoping to get in the end:

dateAndEventFrequency: [
    {
    _id: "2022-01-23",
    totalPartyEvents: 3,
    uniquePartyEvents: 2,
    totalMeetingEvents: 3,
    uniqueMeetingEvents: 2,
    date: "2022-01-23",
    },
   {
    _id: "2022-01-30",
    totalPartyEvents: 2,
    uniquePartyEvents: 1,
    totalMeetingEvents: 2,
    uniqueMeetingEvents: 1,
    date: "2022-01-30",
    },
]

I'm using Mongoose and Nodejs. Any help or guidance is appreciated. Thanks!

Body:
mongo playground

db.collection.aggregate([
  {
    $match: {
      username: "jack"
    }
  },
  {
    "$unwind": "$events"
  },
  {
    "$match": {
      "events.eventType": {
        "$in": [
          "meeting",
          "party"
        ]
      }
    }
  },
  {
    "$group": {
      "_id": {
        date: {
          "$dateToString": {
            format: "%Y-%m-%d",
            date: "$events.createdAt"
          }
        },
        "visitorId": "$events.visitorInfo.visitorId",
        "eventType": "$events.eventType"
      },
      "count": {
        "$sum": 1
      }
    }
  },
  {
    "$group": {
      "_id": {
        "date": "$_id.date",
        "eventType": "$_id.eventType"
      },
      "uniqueTotal": {
        "$sum": 1
      },
      total: {
        "$sum": "$count"
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.date",
      "partyUniqueTotal": {
        "$sum": {
          "$cond": [
            {
              $eq: [
                "$_id.eventType",
                "party"
              ],

            },
            "$uniqueTotal",
            0
          ]
        }
      },
      "totalPartyEvents": {
        "$sum": {
          "$cond": [
            {
              $eq: [
                "$_id.eventType",
                "party"
              ],

            },
            "$total",
            0
          ]
        }
      },
      "meetingUniqueTotal": {
        "$sum": {
          "$cond": [
            {
              $eq: [
                "$_id.eventType",
                "meeting"
              ],

            },
            "$uniqueTotal",
            0
          ]
        }
      },
      "totalmeetingEvents": {
        "$sum": {
          "$cond": [
            {
              $eq: [
                "$_id.eventType",
                "meeting"
              ],

            },
            "$total",
            0
          ]
        }
      }
    }
  }
])


来源: stackexchange

问:
How to get current file path if launched from a shortcut in python?
I'm running python 3.9 on Windows 10.

I want to know if my script was launched from a shortcut file,
and if it is this I want to know how to get the current full path of that shortcut

Thank you in advance

答: Call the GetStartupInfo Windows function and check for the STARTF_TITLEISLINKNAME flag.

ContentLicense: CC BY-SA 4.0


问:
Calculate difference between date column entries and date minimum Pyspark
I feel like this is a stupid question, but I cannot seem to figure it out, so here goes. I have a PySpark data frame and one of the columns consists of dates. I want to compute the difference between each date in this column and the minimum date in the column, for the purpose of filtering to the past numberDays. I've tried several possibilities but nothing seems to work. Here is my most recent attempt:

```<code>df = df.filter(
        F.datediff(
            F.col("collection_date"),
            F.lit(F.min(F.col("collection_date")))
        ) >= numberDays
    )
</code>```

But I've also tried:

```<code>df_new = df.withColumn("days", df.select("collection_date") - df.select("collection_date").min())
</code>```

and

```<code>df_new = df.withColumn("days", df.select("collection_date") - df.select(F.min("collection_date")))
</code>```

There's probably a few others, but I can't seem to get this to work, although I'm sure there's an incredibly simple answer.

答:
I found a solution that I don't really care for, but it appears to work.

```<code>df = df.filter(
        F.datediff(
            F.col("collection_date"),
            F.lit(df.agg(F.min(df["collection_date"])).collect()[0][0])
        ) >= numberDays
    )
</code>```

I'm don't think it's particularly good practice to put a collect() operation in the middle of the code, but this works. If anyone has a more "Sparky" solution, please let me know.

EDIT 3/21/2022:
Here is a more Spark-y way of doing this:

```<code>df = (
        df
        .sort(F.col("collection_date").asc())
        .filter(
            F.datediff(
                F.col("collection_date"),
                F.lit(df.select(F.min("collection_date")).first()["min(collection_date)"])
            ) >= numberDays
        )
    )
</code>```

Body:
I feel like this is a stupid question, but I cannot seem to figure it out, so here goes. I have a PySpark data frame and one of the columns consists of dates. I want to compute the difference between each date in this column and the minimum date in the column, for the purpose of filtering to the past numberDays. I've tried several possibilities but nothing seems to work. Here is my most recent attempt:

df = df.filter(
        F.datediff(
            F.col("collection_date"),
            F.lit(F.min(F.col("collection_date")))
        ) >= numberDays
    )

But I've also tried:

df_new = df.withColumn("days", df.select("collection_date") - df.select("collection_date").min())

and

df_new = df.withColumn("days", df.select("collection_date") - df.select(F.min("collection_date")))

There's probably a few others, but I can't seem to get this to work, although I'm sure there's an incredibly simple answer.

Body:
I found a solution that I don't really care for, but it appears to work.

df = df.filter(
        F.datediff(
            F.col("collection_date"),
            F.lit(df.agg(F.min(df["collection_date"])).collect()[0][0])
        ) >= numberDays
    )

I'm don't think it's particularly good practice to put a collect() operation in the middle of the code, but this works. If anyone has a more "Sparky" solution, please let me know.

EDIT 3/21/2022:
Here is a more Spark-y way of doing this:

df = (
        df
        .sort(F.col("collection_date").asc())
        .filter(
            F.datediff(
                F.col("collection_date"),
                F.lit(df.select(F.min("collection_date")).first()["min(collection_date)"])
            ) >= numberDays
        )
    )


问:
LINQ - Remove Parts of Expression Tree
I have the following LINQ query:

```<code>var query = session.Query<Event>()
    .Fetch(e => e.Venue); // Fetch is an IQueryable extension which does a join

// Code needed here to remove the fetch part

var num = query.Count(); // This then hits the database
</code>```

Unfortunately this throws an error as fetch is not supported for a count method. At this stage i'm sure you're thinking why don't i remove the fetch part. However i have simplified my example and this is not possible. What i'd ideally like to be able to do is navigate the expression tree for the LINQ query and remove any calls to Fetch before i call Count.

I'd appreciate it if someone could show how this is possible. Thanks

答:
It is possible to change expression trees at runtime (by building a new one out of the existing one), since O/RM tools such as LINQ to SQL and Entity Framework do this constantly, but it's not really easy. It has become easier with the introduction of the ExpressionVisitor class of .NET 4.0, but still don't expect it to be simple.

Here is an article that shows an example of this.

ContentLicense: CC BY-SA 3.0

Title: LINQ - Remove Parts of Expression Tree

Body:
I have the following LINQ query:

var query = session.Query<Event>()
    .Fetch(e => e.Venue); // Fetch is an IQueryable extension which does a join

// Code needed here to remove the fetch part

var num = query.Count(); // This then hits the database

Unfortunately this throws an error as fetch is not supported for a count method. At this stage i'm sure you're thinking why don't i remove the fetch part. However i have simplified my example and this is not possible. What i'd ideally like to be able to do is navigate the expression tree for the LINQ query and remove any calls to Fetch before i call Count.

I'd appreciate it if someone could show how this is possible. Thanks


问:
How to apply 2 regex patterns simultaneously in grep
I would like to check for 2 patterns across a piece of text (a total of 4 delimiters).

Either one of the two patterns matches is fine.  However when they qualify, I would like the results to be next to each other side by side.

This is the INPUT TEXT (it contains two separate long lines. Actual input text is much more. I have chosen relevent snippets as shown below):

```<code>Query Response #5: [2659] ID,(0010,0030) DA #8 [19801024] PatientÆs Birth Date,,,(0020,000D) UI #42 Station Title,,,>(0040,0002) DA #8 [20301212] Scheduled Procedure Step Start Date,,,>(0040,0003) TM #4Information

Query Response #6: ID, (0010,0030) DA #8 [19410203] PatientÆs Birth Date, Title,,,>(0040,0002) DA #8 [20210826] Scheduled Procedure Step Start Date, FIND]
</code>```

This is the DESIRED OUTPUT:

```<code>19801024 20301212
19410203 20210826
</code>```

There are 2 pairs of delimiters. The 1st set of delimiters is this:

```<code>(0010,0030) DA #8 [
] Patient
</code>```

The 2nd set of delimiters is this:

```<code>(0040,0002) DA #8 [
] Scheduled Procedure Step Start Date
</code>```

I am able to apply each pair of delimiter by itself.  Specifically, when I do this:

```<code>grep -o -P "(?<=0010,0030\) DA #8 \[).*(?=\] Patient)"
</code>```

I get this output:

```<code>19801024
19410203
</code>```

When I apply this 2nd pair of delimiter like this below:

```<code>grep -o -P "(?<=0040,0002\) DA #8 \[).*(?=\] Scheduled Procedure Step Start Date)"
</code>```

I get this output:

```<code>20301212
20210826
</code>```

How do I issue a correct combined grep command such that the output result is as shown below? :

```<code>19801024 20301212
19410203 20210826
</code>```

I tried this following approach without success:

```<code>grep -e "(?<=0040,0002\) DA #8 \[).*(?=\] Scheduled Procedure Step Start Date)" -e "(?<=0010,0030\) DA #8 \[).*(?=\] Patient)"
</code>```

The error message I get is follows:

```<code>grep: Unmatched ) or \)
</code>```

Thanks in advance. I hope my question is clear.  (Please note I'm using grep under Windows10. The outer quatations marks have to be double quotation marks)

答:
With your shown samples only, please try following awk program. Written and tested in GNU awk should work in any awk. Simple explanation would be, making  PatientÆs Birth Date as field separator for all lines then in main program checking 1st field if its equal to regex ^Query Response.*DA #8 \[[0-9]+\]$ then getting value between [ and ](excluding [ and ]) and saving it into val variable. Then checking condition if 2nd field matches to ^,.*DA #8[[:space:]]+ then  again getting values between [ and ] and printing val variable and current $2's value, which is required output.

```<code>awk -F' PatientÆs Birth Date' '
$1~/^Query Response.*DA #8 \[[0-9]+\]$/{
  val=""
  gsub(/.*\[|\]$/,"",$1)
  val=$1
}
$2~/^,.*DA #8[[:space:]]+/{
  gsub(/.*\[|\].*/,"",$2)
  print val,$2
}
'  Input_file
</code>```

Body:
I would like to check for 2 patterns across a piece of text (a total of 4 delimiters).

Either one of the two patterns matches is fine.  However when they qualify, I would like the results to be next to each other side by side.

This is the INPUT TEXT (it contains two separate long lines. Actual input text is much more. I have chosen relevent snippets as shown below):

Query Response #5: [2659] ID,(0010,0030) DA #8 [19801024] PatientÆs Birth Date,,,(0020,000D) UI #42 Station Title,,,>(0040,0002) DA #8 [20301212] Scheduled Procedure Step Start Date,,,>(0040,0003) TM #4Information

Query Response #6: ID, (0010,0030) DA #8 [19410203] PatientÆs Birth Date, Title,,,>(0040,0002) DA #8 [20210826] Scheduled Procedure Step Start Date, FIND]

This is the DESIRED OUTPUT:

19801024 20301212
19410203 20210826

There are 2 pairs of delimiters. The 1st set of delimiters is this:

(0010,0030) DA #8 [
] Patient

The 2nd set of delimiters is this:

(0040,0002) DA #8 [
] Scheduled Procedure Step Start Date

I am able to apply each pair of delimiter by itself.  Specifically, when I do this:

grep -o -P "(?<=0010,0030\) DA #8 \[).*(?=\] Patient)"

I get this output:

19801024
19410203

When I apply this 2nd pair of delimiter like this below:

grep -o -P "(?<=0040,0002\) DA #8 \[).*(?=\] Scheduled Procedure Step Start Date)"

I get this output:

20301212
20210826

How do I issue a correct combined grep command such that the output result is as shown below? :

19801024 20301212
19410203 20210826

I tried this following approach without success:

grep -e "(?<=0040,0002\) DA #8 \[).*(?=\] Scheduled Procedure Step Start Date)" -e "(?<=0010,0030\) DA #8 \[).*(?=\] Patient)"

The error message I get is follows:

grep: Unmatched ) or \)

Thanks in advance. I hope my question is clear.  (Please note I'm using grep under Windows10. The outer quatations marks have to be double quotation marks)

Body:
With your shown samples only, please try following awk program. Written and tested in GNU awk should work in any awk. Simple explanation would be, making  PatientÆs Birth Date as field separator for all lines then in main program checking 1st field if its equal to regex ^Query Response.*DA #8 \[[0-9]+\]$ then getting value between [ and ](excluding [ and ]) and saving it into val variable. Then checking condition if 2nd field matches to ^,.*DA #8[[:space:]]+ then  again getting values between [ and ] and printing val variable and current $2's value, which is required output.

awk -F' PatientÆs Birth Date' '
$1~/^Query Response.*DA #8 \[[0-9]+\]$/{
  val=""
  gsub(/.*\[|\]$/,"",$1)
  val=$1
}
$2~/^,.*DA #8[[:space:]]+/{
  gsub(/.*\[|\].*/,"",$2)
  print val,$2
}
'  Input_file


问:
jQuery accessing next class child
How can I access .prev or .next class inside menuclass when clicking on .childclass class.

So far I came up with this

```<code>$(".childclass").click(function(){
    jQuery(this).parent().find('menuclass').children('.next')
});
</code>```

Html logic

```<code><div class="parentclass">

<div class="menuclass">

<div class="next"></div>
<div class="prev"></div>

</div>

<div class="childclass">

</div>

</div>
</code>```

答:
Try this</p>
```<code>$(".childclass").click(function(){
    jQuery(this).closest('.parentclass').find('.menuclass .next');
});
</code>```

Title: jQuery accessing next class child

Body:
How can I access .prev or .next class inside menuclass when clicking on .childclass class.

So far I came up with this

$(".childclass").click(function(){
    jQuery(this).parent().find('menuclass').children('.next')
});

Html logic

Body:
Try this

$(".childclass").click(function(){
    jQuery(this).closest('.parentclass').find('.menuclass .next');
});


问:
How to traverse a json file and find the key name using value?
can anyone please help me to find the solution
I am having a JSON file like below

```<code>    {
   "Parent1": ["Child1", "Child2","Child5"],
   "Parent2": ["Child3", "Child4","Child5"]
    }
</code>```

expectation: Python code to find the parent name using child name

User input: Child1

Expected output : Parent1

OR

User input: Child5

Expected output : Parent1,Parent2

答:
This is an apporach you can use

```<code>choice = input("Enter search string ")
ans = []
for i,j in data.items():
    if choice in j:
        ans.append(i)
</code>```

ans will now contain the keys you need as a list

Body:
can anyone please help me to find the solution
I am having a JSON file like below

    {
   "Parent1": ["Child1", "Child2","Child5"],
   "Parent2": ["Child3", "Child4","Child5"]
    }

expectation: Python code to find the parent name using child name

User input: Child1

Expected output : Parent1

OR

User input: Child5

Expected output : Parent1,Parent2

Body:
This is an apporach you can use

choice = input("Enter search string ")
ans = []
for i,j in data.items():
    if choice in j:
        ans.append(i)

ans will now contain the keys you need as a list


问:
What is the best way to determine how a missing reference in a Visual Studio project can be found?
I'm using Visual Studio 2008 and I'm trying to get a project that I didn't create to build.

In the  references folder of this project there are four DLLs with the exclamation icon whose Path property is empty. The  in the .csproj file points to an output directory which I don't think is the initial location of these DLLs.

I believe that I have the most recent copies of the DLLs in question (they are used in several related projects). I could place them in this project's directory but I want to determine their original location so I don't have to modify the project and solution files (which are used by other developers in other remote locations).

I would ask the original developers but they're located in a time zone where it's 1 a.m. so I though someone here could help me out.

Thanks in advance.

答:
Open the .csproj file in a text editor an locate the missing references.

If the entry is like this:

```<code><Reference Include="AssemblyName"/>
</code>```

then it's located in the default folder for that application and somewhere on the search path.

If the entry is like this:

```<code><Reference Include="AssemblyName">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>Path\AssemblyName.dll</HintPath>
</Reference>
</code>```

Then the file should be put in the folder referred to by Path.

Body:
Open the .csproj file in a text editor an locate the missing references.

If the entry is like this:

<Reference Include="AssemblyName"/>

then it's located in the default folder for that application and somewhere on the search path.

If the entry is like this:

<Reference Include="AssemblyName">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>Path\AssemblyName.dll</HintPath>
</Reference>

Then the file should be put in the folder referred to by Path.


问:
Hashing raw bytes in C++?
I want to write a function that takes two types T, U such that sizeof(T)+sizeof(U)<=8 and gets a uint64_t by just reinterpreting their bytes one after the other. However this does not seem to work. I am certain there is a quicker and more elegant (and correct) way to do it but I have no clue. Any tips are greatly appreciated.

```<code>#include <cstdint>
#include <iostream>
#include <vector>

template <typename T, typename U>
constexpr auto hash8(T x, U y) {
  static_assert(sizeof(T) + sizeof(U) <= 8);

  uint64_t u = 0;
  uint64_t v = 0;
  auto px = (uint8_t*)&x;
  auto py = (uint8_t*)&y;
  for (auto i = 0; i < sizeof(T); ++i) {
    u |= (uint64_t)px[i];
    u <<= 8;
  }
  for (auto i = 0; i < sizeof(U); ++i) {
    v |= (uint64_t)py[i];
    v <<= 8;
  }

  return u << (sizeof(U) * 8) | v;
}

int main() {
  std::cout << hash8(131, 0) << '\n';
  std::cout << hash8(132, 0) << '\n';
  std::cout << hash8(500, 0) << '\n';
}
</code>```

答:
The easiest way is usually to do a memcpy:

```<code>#include <cstdint>
#include <cstring> // for memcpy

template <typename T, typename U>
auto hash8(T x, U y) {
  static_assert(sizeof(T) + sizeof(U) <= 8);

  uint64_t u = 0;
  char* u_ptr = reinterpret_cast<char*>(&u);
  std::memcpy(u_ptr, &x, sizeof x);
  std::memcpy(u_ptr+sizeof x, &y, sizeof y);
  return u;
}
</code>```

Any decent compiler will inline the memcpy call to a few bit operations, if the size parameter is known at compile time (and reasonably small).

If you actually need a constexpr function you can try using std::bit_cast from C++20 (maybe difficult if either input parameter does not have a size of 1, 2, 4, or 8).

Title: Hashing raw bytes in C++?

Body:
I want to write a function that takes two types T, U such that sizeof(T)+sizeof(U)<=8 and gets a uint64_t by just reinterpreting their bytes one after the other. However this does not seem to work. I am certain there is a quicker and more elegant (and correct) way to do it but I have no clue. Any tips are greatly appreciated.

#include <cstdint>
#include <iostream>
#include <vector>

template <typename T, typename U>
constexpr auto hash8(T x, U y) {
  static_assert(sizeof(T) + sizeof(U) <= 8);

  uint64_t u = 0;
  uint64_t v = 0;
  auto px = (uint8_t*)&x;
  auto py = (uint8_t*)&y;
  for (auto i = 0; i < sizeof(T); ++i) {
    u |= (uint64_t)px[i];
    u <<= 8;
  }
  for (auto i = 0; i < sizeof(U); ++i) {
    v |= (uint64_t)py[i];
    v <<= 8;
  }

  return u << (sizeof(U) * 8) | v;
}

int main() {
  std::cout << hash8(131, 0) << '\n';
  std::cout << hash8(132, 0) << '\n';
  std::cout << hash8(500, 0) << '\n';
}

Body:
The easiest way is usually to do a memcpy:

#include <cstdint>
#include <cstring> // for memcpy

template <typename T, typename U>
auto hash8(T x, U y) {
  static_assert(sizeof(T) + sizeof(U) <= 8);

  uint64_t u = 0;
  char* u_ptr = reinterpret_cast<char*>(&u);
  std::memcpy(u_ptr, &x, sizeof x);
  std::memcpy(u_ptr+sizeof x, &y, sizeof y);
  return u;
}

Any decent compiler will inline the memcpy call to a few bit operations, if the size parameter is known at compile time (and reasonably small).

If you actually need a constexpr function you can try using std::bit_cast from C++20 (maybe difficult if either input parameter does not have a size of 1, 2, 4, or 8).


问:
Angular6 Can't use ternary operator in ngClass with multiple entries
I'm trying to add multiple classes by ngClass, and I'm confused as to why I can't use ternary operator here.

```<code><div [ngClass]="{'otherClass': otherFlag, classFlag ? 'class--true': 'class--false'}>
</code>```

I get the following error:

```<code>Parser Error: Missing expected } at column 37 in [{'otherClass': otherFlag, classFlag ? 'class--true': 'class--false'}]
</code>```

I'm aware I can do the following:

```<code><div [ngClass]="{
'otherClass': otherFlag,
'class--true': classFlag,
'class--false': !classFlag
}">
</code>```

Just trying to understand why I can't use ternary operator here (or maybe I'm doing it wrong). I would appreciate the help in understanding this.

Edit: Thank you for both answers. I mostly understood it thanks to Bryan's answer, but both were helpful.

答:
They just can't be combined in that way. Use one or the other. For multi condition use example 3, for tenerary use example 1 or 2.

  I will be class false

I will be class true

I will be class true

```

Example: https://stackblitz.com/edit/angular-ivy-hmnctu?file=src%2Fapp%2Fapp.component.html

Body:
I'm trying to add multiple classes by ngClass, and I'm confused as to why I can't use ternary operator here.

I get the following error:

Parser Error: Missing expected } at column 37 in [{'otherClass': otherFlag, classFlag ? 'class--true': 'class--false'}]

I'm aware I can do the following:

Just trying to understand why I can't use ternary operator here (or maybe I'm doing it wrong). I would appreciate the help in understanding this.

Edit: Thank you for both answers. I mostly understood it thanks to Bryan's answer, but both were helpful.

Body:
They just can't be combined in that way. Use one or the other. For multi condition use example 3, for tenerary use example 1 or 2.

<div [ngClass]="classFlag === false ? 'class--true' : 'class--false'">
  I will be class false
</div>

<div [ngClass]="classFlag === true ? 'class--true' : 'class--false'">
I will be class true
</div>

<div [ngClass]="{ otherClass: otherFlag === true }">I will be class true</div>

Example: https://stackblitz.com/edit/angular-ivy-hmnctu?file=src%2Fapp%2Fapp.component.html


问:
Importing Class 'missing required positional arguments'?
I am trying to create an instance of the class = Button. I understand that I have to initialize Button into my Menü class to use its variables. But PyCharm is telling me that 4 required positional arguments are missing.
I am a beginner to Python/Pygame so if possible keep it simple:)</p>
```<code>import pygame
import os
import sys

pygame.init()
#Button Klasse:
class Button(): #Klasse mit Namen 'Button' erstellen
  def __init__(self, x, y, image, scale): #init Methode definieren

    width = image.get_width() #Imageweite herausfinden
    height = image.get_height() #Imagehöhe herausfinden
    self.image = pygame.transform.scale(image, (int(width * scale), (int(height * scale))))
    self.rect = self.image.get_rect()  # Rechteck erstellen
    self.rect.topleft = (x, y)  # Rechteck Position definieren
    self.clicked = False #Klick-Zustand auf False gesetzt
    self.start_img = pygame.image.load('pong_test.png').convert_alpha()  # Bild für start_img ausw#hlen

#Erstellte Klasse auf Fenster platzieren
def draw(self, screen):

    action = False #Variable "action" = False setzen
    pos = pygame.mouse.get_pos() #Mausposition bestimmen und in 'pos' speichern
    if self.rect.collidepoint(pos): #Überprüfen ob Maus mit Rechteck kollidiert
        if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False: #Linke Maustaste gefrückt(0) + Klick-Zustand = False dann:
            self.clicked = True #Klick-Zustand auf True setzen und:
            action = True #Action = True setzen
    if pygame.mouse.get_pressed()[0] == 0: #Andernfalls ich kein Klick dann:
        self.clicked = False #Klick-Zustand auf False setzen

    screen.blit(self.image, (self.rect.x, self.rect.y)) #Blit Imagedatei auf Rechteckposition x und y

    return action #Gibt 'action' zurück

class Highscore():

    def __init__(self):
        self.font = pygame.font.SysFont('Comic Sans MS', 30)
        self.HighscoreX = 100
        self.HighscoreY = 100
        self.Highscore = int(Highscore.readHS(self))

    def readHS(self):
        with open('Highscore.CSV', 'r') as f:
            return f.read()
    def showHS(self):
        self.high_render = self.font.render('Highscore:' + str(self.Highscore), True, (250, 0, 0))
        self.screen.blit(self.high_render, (self.HighscoreX, self.HighscoreY))

class Menü(Highscore, Button):

    def __init__(self):
        Highscore.__init__(self)
        Button.__init__(self,)

        self.fenster_height = 1000  # Fensterhöhe definieren
        self.fenster_width = 600  # Fensterbreite definieren
        self.screen = pygame.display.set_mode((self.fenster_height, self.fenster_width))
        self.run = True
        self.font = pygame.font.SysFont('Comic Sans MS', 32)
        self.screen.fill((96, 144, 189))  # Screen mit Farbe (255,255,255) füllen
        Highscore.readHS(self)
        Highscore.showHS(self)

    def runMenü(self):
        while True:  # Während "run = TRUE"
            Spiel1_button = Button(500, 300, self.start_img, 0.5)

            if Spiel1_button.draw(self.screen):

                for event in pygame.event.get():
                       # fenster schließen
                    if event.type == pygame.QUIT:

                        pygame.quit()
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        print('test')

                pygame.display.update()  # Fenster wird aktualisiert

menu = Menü()
menu.runMenü()
</code>```

答:
The __init__ method in Button takes 5 arguments self, x, y, image, scale:

```<code>class Button(): #Klasse mit Namen 'Button' erstellen
  def __init__(self, x, y, image, scale): #init Methode definieren

</code>```

Yet you only pass 1 in the Highscore init method.

```<code>Button.__init__(self,)
</code>```

You'll have to either pass all arguments you defined or remove them from Button.__init__.

Body:
I am trying to create an instance of the class = Button. I understand that I have to initialize Button into my Menü class to use its variables. But PyCharm is telling me that 4 required positional arguments are missing.
I am a beginner to Python/Pygame so if possible keep it simple:)

import pygame
import os
import sys

pygame.init()
#Button Klasse:
class Button(): #Klasse mit Namen 'Button' erstellen
  def __init__(self, x, y, image, scale): #init Methode definieren

    width = image.get_width() #Imageweite herausfinden
    height = image.get_height() #Imagehöhe herausfinden
    self.image = pygame.transform.scale(image, (int(width * scale), (int(height * scale))))
    self.rect = self.image.get_rect()  # Rechteck erstellen
    self.rect.topleft = (x, y)  # Rechteck Position definieren
    self.clicked = False #Klick-Zustand auf False gesetzt
    self.start_img = pygame.image.load('pong_test.png').convert_alpha()  # Bild für start_img ausw#hlen

#Erstellte Klasse auf Fenster platzieren
def draw(self, screen):

    action = False #Variable "action" = False setzen
    pos = pygame.mouse.get_pos() #Mausposition bestimmen und in 'pos' speichern
    if self.rect.collidepoint(pos): #Überprüfen ob Maus mit Rechteck kollidiert
        if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False: #Linke Maustaste gefrückt(0) + Klick-Zustand = False dann:
            self.clicked = True #Klick-Zustand auf True setzen und:
            action = True #Action = True setzen
    if pygame.mouse.get_pressed()[0] == 0: #Andernfalls ich kein Klick dann:
        self.clicked = False #Klick-Zustand auf False setzen

    screen.blit(self.image, (self.rect.x, self.rect.y)) #Blit Imagedatei auf Rechteckposition x und y

    return action #Gibt 'action' zurück

class Highscore():

    def __init__(self):
        self.font = pygame.font.SysFont('Comic Sans MS', 30)
        self.HighscoreX = 100
        self.HighscoreY = 100
        self.Highscore = int(Highscore.readHS(self))

    def readHS(self):
        with open('Highscore.CSV', 'r') as f:
            return f.read()
    def showHS(self):
        self.high_render = self.font.render('Highscore:' + str(self.Highscore), True, (250, 0, 0))
        self.screen.blit(self.high_render, (self.HighscoreX, self.HighscoreY))

class Menü(Highscore, Button):

    def __init__(self):
        Highscore.__init__(self)
        Button.__init__(self,)

        self.fenster_height = 1000  # Fensterhöhe definieren
        self.fenster_width = 600  # Fensterbreite definieren
        self.screen = pygame.display.set_mode((self.fenster_height, self.fenster_width))
        self.run = True
        self.font = pygame.font.SysFont('Comic Sans MS', 32)
        self.screen.fill((96, 144, 189))  # Screen mit Farbe (255,255,255) füllen
        Highscore.readHS(self)
        Highscore.showHS(self)

    def runMenü(self):
        while True:  # Während "run = TRUE"
            Spiel1_button = Button(500, 300, self.start_img, 0.5)

            if Spiel1_button.draw(self.screen):

                for event in pygame.event.get():
                       # fenster schließen
                    if event.type == pygame.QUIT:

                        pygame.quit()
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        print('test')

                pygame.display.update()  # Fenster wird aktualisiert

menu = Menü()
menu.runMenü()

Body:
The __init__ method in Button takes 5 arguments self, x, y, image, scale:

class Button(): #Klasse mit Namen 'Button' erstellen
  def __init__(self, x, y, image, scale): #init Methode definieren

Yet you only pass 1 in the Highscore init method.

Button.__init__(self,)

You'll have to either pass all arguments you defined or remove them from Button.__init__.


问:
how to make pandas dataframe with nested dictionaries after exploded arrays?
I have a two data frames as follow.

```<code>import pandas as pd
import numpy as np
# Create data set.
dataSet1 = {'id': ['A', 'A', 'A','A','B','B','B','C'],
           'id_2': [1, 2, 3, 3, 1,2,3,1],
           'id_3' : [9,13,12,11,9,20,22,13]}
dataSet2 = {'id_2': [1, 1, 1, 1, 1,2,2,2,3,3,4,4],
           'serial_number' : [10,11,12,13,15,11,12,13,20,15,10,15]}
# Create dataframe with data set and named columns.
df_map1 = pd.DataFrame(dataSet1, columns= ['id', 'id_2', 'id_3'])

df_map2 = pd.DataFrame(dataSet2, columns= ['id_2', 'serial_number'])

df_map1

   id id_2 id_3
0   A   1   9
1   A   2   13
2   A   3   12
3   A   3   11
4   B   1   9
5   B   2   20
6   B   3   22
7   C   1   13

  id_2  serial_number
0   1   10
1   1   11
2   1   12
3   1   13
4   1   15
5   2   11
6   2   12
7   2   13
8   3   20
9   3   15
10  4   10
11  4   15
</code>```

such that id follow by id_2 and id_3.

I created dictionary for mapping for df_map1 so we know what's going on and same for df_map2.

```<code>mapping_dict = {}
for lst in df_map1.values:

    leaf = mapping_dict
    for path in lst[:-2]:

        leaf = leaf.setdefault(path, {})
    leaf.setdefault(lst[-2], list()).append(lst[-1])

{'A': {1: [9], 2: [13], 3: [12, 11]},
 'B': {1: [9], 2: [20], 3: [22]},
 'C': {1: [13]}}

df_map2 = df_map2[df_map2['id_2'].isin(df_map1['id_2'].unique().tolist())]

{1: [10, 11, 12, 13, 15], 2: [11, 12, 13], 3: [20, 15]}

</code>```

now we defined our 2 mappings out of df_map1 and df_map2
what i want to do is, based on these dictionaries,

ie)

```<code>{'A' : {1: [9] } <--- from map1

{1: [10, 11, 12, 13, 15]} <--- from map2
</code>```

such that it becomes '9' : [10,11,12,13,15],
and create array that creates random number from 0 to 2 for 4 or n number of columns of arrays that looks like the following.

DESIRED ARRAY : ( basically exploding, and each column represent as sequence that restarts for each combination)

```<code>1st row : 9 | 10 [ 2, 1, 2, 1]
2nd row : 9 | 11 [ 0, 1, 0, 2]
3rd row : 9 | 12 [ 0, 0, 0, 1]
4th row : 9 | 13 [ 0, 2, 2, 2]
5th row : 9 | 15 [ 0, 1, 1, 2]
</code>```

and turns this back to pandas Dataframe which will look like this

```<code>   id_3 serial_number   value    sequence
0   9      10            2          1
1   9      10            1          2
2   9      10            2          3
3   9      10            1          4
4   9      11            0          1
5   9      11            1          2
6   9      11            0          3
7   9      11            2          4
</code>```

this is just an example of regards to this mapping

```<code>{'A' : {1: [9] } <--- from map1

{1: [10, 11, 12, 13, 15]} <--- from map2
</code>```

if we have this case :

```<code>3: [12, 11]   <--- from map1
3: [20, 15]   <--- from map2

it will become
{'12' : [20,15], '11' : [20,15] }
</code>```

答:
Yes, we can skip the intermediate dictionaries and use mergefor your mapping steps.

```<code>import numpy as np
np.random.seed(2)

rand_num_min = 0
rand_num_max = 2
rand_num_len = 4
</code>```

Here comes the merge

```<code>step1 = df_map1.merge(df_map2, on='id_2', how='left')
</code>```

Then we generate a list of 4 random numbers for each row,

```<code>step1['value'] = list(np.random.randint(rand_num_min, rand_num_max+1, (len(step1), rand_num_len)))
</code>```

and explode each list to multiple rows

```<code>step2 = step1.explode('value')
</code>```

Exploded rows share the same index from before they are exploded, so we can use that with groupby and cumcount to assign the sequence

```<code>step2['sequence'] = step2.groupby(step2.index).cumcount()+1
</code>```

Lastly, take care the formatting.

```<code>step2.reset_index(drop=True).drop(columns=['id', 'id_2'])
</code>```

Body:
I have a two data frames as follow.

import pandas as pd
import numpy as np
# Create data set.
dataSet1 = {'id': ['A', 'A', 'A','A','B','B','B','C'],
           'id_2': [1, 2, 3, 3, 1,2,3,1],
           'id_3' : [9,13,12,11,9,20,22,13]}
dataSet2 = {'id_2': [1, 1, 1, 1, 1,2,2,2,3,3,4,4],
           'serial_number' : [10,11,12,13,15,11,12,13,20,15,10,15]}
# Create dataframe with data set and named columns.
df_map1 = pd.DataFrame(dataSet1, columns= ['id', 'id_2', 'id_3'])

df_map2 = pd.DataFrame(dataSet2, columns= ['id_2', 'serial_number'])

df_map1

   id id_2 id_3
0   A   1   9
1   A   2   13
2   A   3   12
3   A   3   11
4   B   1   9
5   B   2   20
6   B   3   22
7   C   1   13

  id_2  serial_number
0   1   10
1   1   11
2   1   12
3   1   13
4   1   15
5   2   11
6   2   12
7   2   13
8   3   20
9   3   15
10  4   10
11  4   15

such that id follow by id_2 and id_3.

I created dictionary for mapping for df_map1 so we know what's going on and same for df_map2.

mapping_dict = {}
for lst in df_map1.values:

    leaf = mapping_dict
    for path in lst[:-2]:

        leaf = leaf.setdefault(path, {})
    leaf.setdefault(lst[-2], list()).append(lst[-1])

{'A': {1: [9], 2: [13], 3: [12, 11]},
 'B': {1: [9], 2: [20], 3: [22]},
 'C': {1: [13]}}

df_map2 = df_map2[df_map2['id_2'].isin(df_map1['id_2'].unique().tolist())]

{1: [10, 11, 12, 13, 15], 2: [11, 12, 13], 3: [20, 15]}

now we defined our 2 mappings out of df_map1 and df_map2
what i want to do is, based on these dictionaries,

ie)

{'A' : {1: [9] } <--- from map1

{1: [10, 11, 12, 13, 15]} <--- from map2

such that it becomes '9' : [10,11,12,13,15],
and create array that creates random number from 0 to 2 for 4 or n number of columns of arrays that looks like the following.

DESIRED ARRAY : ( basically exploding, and each column represent as sequence that restarts for each combination)

1st row : 9 | 10 [ 2, 1, 2, 1]
2nd row : 9 | 11 [ 0, 1, 0, 2]
3rd row : 9 | 12 [ 0, 0, 0, 1]
4th row : 9 | 13 [ 0, 2, 2, 2]
5th row : 9 | 15 [ 0, 1, 1, 2]

and turns this back to pandas Dataframe which will look like this

   id_3 serial_number   value    sequence
0   9      10            2          1
1   9      10            1          2
2   9      10            2          3
3   9      10            1          4
4   9      11            0          1
5   9      11            1          2
6   9      11            0          3
7   9      11            2          4

this is just an example of regards to this mapping

{'A' : {1: [9] } <--- from map1

{1: [10, 11, 12, 13, 15]} <--- from map2

if we have this case :

3: [12, 11]   <--- from map1
3: [20, 15]   <--- from map2

it will become
{'12' : [20,15], '11' : [20,15] }

Body:
Yes, we can skip the intermediate dictionaries and use mergefor your mapping steps.

import numpy as np
np.random.seed(2)

rand_num_min = 0
rand_num_max = 2
rand_num_len = 4

Here comes the merge

step1 = df_map1.merge(df_map2, on='id_2', how='left')

Then we generate a list of 4 random numbers for each row,

step1['value'] = list(np.random.randint(rand_num_min, rand_num_max+1, (len(step1), rand_num_len)))

and explode each list to multiple rows

step2 = step1.explode('value')

Exploded rows share the same index from before they are exploded, so we can use that with groupby and cumcount to assign the sequence

step2['sequence'] = step2.groupby(step2.index).cumcount()+1

Lastly, take care the formatting.

step2.reset_index(drop=True).drop(columns=['id', 'id_2'])


答:
You should read the json file and then loop over the dictionary to find matching for the given input</p>
```<code>def find_key_name_by_value(json_input, key_to_find):
    result = []
    for key, value in input.items():
        if key_to_find in value:
            result.append(key)
    return result

json_input = {
   "Parent1": ["Child1", "Child2","Child5"],
   "Parent2": ["Child3", "Child4","Child5"]
    }
result = find_key_name_by_value(json_input, "Child4")
print(result)
</code>```

Title: How to traverse a json file and find the key name using value?

Body:
You should read the json file and then loop over the dictionary to find matching for the given input

def find_key_name_by_value(json_input, key_to_find):
    result = []
    for key, value in input.items():
        if key_to_find in value:
            result.append(key)
    return result

json_input = {
   "Parent1": ["Child1", "Child2","Child5"],
   "Parent2": ["Child3", "Child4","Child5"]
    }
result = find_key_name_by_value(json_input, "Child4")
print(result)


问:
Microsoft.Toolkit.Forms.UI.Controls Could not find Windows Runtime type 'Microsoft.Toolkit.Win32.UI.XamlHost.IXamlMetadataContainer'
I have created a new "Windows Forms App":

Now I install the Microsoft.Toolkit.Forms.UI.Controls from NuGet.

It requires these dependencies:

After clicking "I accept", the next thing that happens is that an error message "Failed to lauch the design tools server process." is shown:

I select the Form1 designer in the tabs, and the ToolBox now shows the new tools:

However, the designer is gone, and when I try to bring it up again, the message "This item does not support previewing." appears each time I click Form1.vb -> View Designer:

I have repeated the process several times.

When I switch from Debug x86 to Debug AnyCPU, I can open up the designer again.

However, when I then try to drag one of the tools onto the form, an error occurs:

"Failed to create component 'InkCanvas'. The error message follows: 'Microsoft.DotnetNet.DesignTools.Client.DesignToolsServerException: Could not find Windows Runtime type 'Microsoft.Toolkit.Win32.UI.XamlHost.IXamlMetadataContainer'.

I am stuck.

答:
It works if I instantiate the control by code instead of dragging it from the ToolBox.

So perhaps a compatiblity problem with WinForms designer?

```<code>Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim f As New Microsoft.Toolkit.Forms.UI.Controls.InkCanvas
        With f
            .Size = New Size(400, 100)
            .Location = New Point(20, 20)
        End With

        AddHandler f.TextChanged, AddressOf Ink_Changed
        Me.Controls.Add(f)

    End Sub

    Friend Sub Ink_Changed(sender As Object, e As EventArgs)
        'Write code here.
    End Sub
End Class
</code>```

Body:
It works if I instantiate the control by code instead of dragging it from the ToolBox.

So perhaps a compatiblity problem with WinForms designer?

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim f As New Microsoft.Toolkit.Forms.UI.Controls.InkCanvas
        With f
            .Size = New Size(400, 100)
            .Location = New Point(20, 20)
        End With

        AddHandler f.TextChanged, AddressOf Ink_Changed
        Me.Controls.Add(f)

    End Sub

    Friend Sub Ink_Changed(sender As Object, e As EventArgs)
        'Write code here.
    End Sub
End Class


问:
How to make comments multiple lines and one line in .wbt files used as world files in WeBots
In WeBots and using programs with ROS2 you need to use world files with the .wbt extensions.

Does someone know how to comment one line or multiple lines ?

Thanks.

答: Yes, you can use the # character in front of a line to comment it, like in Python.


问:
How can I implement a list of links in Flex?
I have an Array of string which represents links.  I want to display them in a list and make them work like links. How do I do that?</p>

答:
You could create a list with LinkButton as the itemRenderer.
You would also need to add event listeners to the list to actually do navigation. Use navigateToURL to run the link.
MXML for the list:

```<code><mx:List id="myList"
    itemRenderer="mx.controls.LinkButton"
    click="navigateToURL(new URLRequest(myList.selectedItem.text))">
</mx:List>
</code>```

Then in the actionscript part (Or you could set this in the MXML too if you'd like).

```<code>myList.dataProvider = arrayOfLinkStrings;
</code>```

OwnerDisplayName: Chen Kinnrot

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie

Body:
You could create a list with LinkButton as the itemRenderer.
You would also need to add event listeners to the list to actually do navigation. Use navigateToURL to run the link.
MXML for the list:

<mx:List id="myList"
    itemRenderer="mx.controls.LinkButton"
    click="navigateToURL(new URLRequest(myList.selectedItem.text))">
</mx:List>

Then in the actionscript part (Or you could set this in the MXML too if you'd like).

myList.dataProvider = arrayOfLinkStrings;

OwnerDisplayName: CookieOfFortune

LastEditorDisplayName: CookieOfFortune


问:
How to ensure my regular expression does not match too much
A file has few words with numbers in the begining of them. i want to extract a particular no line.when given 1, it extracts line 1 also with 11, 21

FILE.txt has contents:

```
1.sample
lines of
2.sentences
present in
...
...
10.the
11.file
```

when Executed pro 1 file.txt
gives results from line 1,10 and also from line 11
as these three results have 1 in their string. i.e

Output of the script:

```
1.sample
10.the
11.file
```

Expected output: the output which i am expecting
is only line 1 contents and not the line 10 or line 11 contents.
i.e

Expected output:

```1.sample```

My current code:

```<code>proc pro { pattern args} {

   set file [open $args r]
   set lnum 0
   set occ 0
   while {[gets $file line] >=0} {
      incr lnum
      if {[regexp $pattern $line]} {
          incr occ
          puts "The pattern is present in line: $lnum"
          puts "$line"
      } else {
         puts "not found"
      }
   }
   puts "total number of occurencese : $occ"
   close $file
}
</code>```

the program is working fine but the thing is i am retrieving lines that i dont want to along with the expected line. As the number (1) which i want to retrieve is present in the other strings such as 11, 21, 14 etc these lines are also getting printed.

kindly tolerate my unclear way of explaining the question.

答:
If what you're looking to do is as constrained as what you're describing, why not just use something like</p>

```<code>if { [string range $line 0 [string length $pattern]] eq "${pattern}." } {
    ...
}
</code>```

Body:
A file has few words with numbers in the begining of them. i want to extract a particular no line.when given 1, it extracts line 1 also with 11, 21

FILE.txt has contents:

1.sample
lines of
2.sentences
present in
...
...
10.the
11.file

when Executed pro 1 file.txt
gives results from line 1,10 and also from line 11
as these three results have 1 in their string. i.e

Output of the script:

1.sample
10.the
11.file

Expected output: the output which i am expecting
is only line 1 contents and not the line 10 or line 11 contents.
i.e

Expected output:

1.sample

My current code:

proc pro { pattern args} {

   set file [open $args r]
   set lnum 0
   set occ 0
   while {[gets $file line] >=0} {
      incr lnum
      if {[regexp $pattern $line]} {
          incr occ
          puts "The pattern is present in line: $lnum"
          puts "$line"
      } else {
         puts "not found"
      }
   }
   puts "total number of occurencese : $occ"
   close $file
}

the program is working fine but the thing is i am retrieving lines that i dont want to along with the expected line. As the number (1) which i want to retrieve is present in the other strings such as 11, 21, 14 etc these lines are also getting printed.

kindly tolerate my unclear way of explaining the question.

Body:
If what you're looking to do is as constrained as what you're describing, why not just use something like

if { [string range $line 0 [string length $pattern]] eq "${pattern}." } {
    ...
}


问:
How to create custom paginator in django
I'm trying to use django built-in paginator but it's not working cuz I'm not using database storage object I'm creating a website with other api...

heres my code:

```<code>def index(request):
    response = requests.get("https://www.hetzner.com/a_hz_serverboerse/live_data.json")
    data = response.json()
    p = Paginator(data, 3)
    pn = request.GET.get('page')
    print(pn, p, data)
    page_obj = p.get_page(pn)

    context = {
        'data': data,
        'page_obj': page_obj
    }
    return render(request, 'index.html', context)
</code>```

do i need to create custom paginator if so how should i? or is there solution?

答:
https://docs.djangoproject.com/en/4.0/topics/pagination/#example
You can give any list to the paginator.

The problem was that the response from the API did not return a list, but an object where the list was under the servers key.
Solution:

```<code>
def index(request):
    response = requests.get("https://www.hetzner.com/a_hz_serverboerse/live_data.json")
    data = response.json()['server']
    p = Paginator(data, 3)
    pn = request.GET.get('page')
    print(pn, p, data)
    page_obj = p.get_page(pn)

    context = {
        'data': data,
        'page_obj': page_obj
    }
    return render(request, 'index.html', context)
</code>```

Body:
I'm trying to use django built-in paginator but it's not working cuz I'm not using database storage object I'm creating a website with other api...

heres my code:

def index(request):
    response = requests.get("https://www.hetzner.com/a_hz_serverboerse/live_data.json")
    data = response.json()
    p = Paginator(data, 3)
    pn = request.GET.get('page')
    print(pn, p, data)
    page_obj = p.get_page(pn)

    context = {
        'data': data,
        'page_obj': page_obj
    }
    return render(request, 'index.html', context)

do i need to create custom paginator if so how should i? or is there solution?

Body:
https://docs.djangoproject.com/en/4.0/topics/pagination/#example
You can give any list to the paginator.

The problem was that the response from the API did not return a list, but an object where the list was under the servers key.
Solution:

def index(request):
    response = requests.get("https://www.hetzner.com/a_hz_serverboerse/live_data.json")
    data = response.json()['server']
    p = Paginator(data, 3)
    pn = request.GET.get('page')
    print(pn, p, data)
    page_obj = p.get_page(pn)

    context = {
        'data': data,
        'page_obj': page_obj
    }
    return render(request, 'index.html', context)


问:
Giving error when using Provider state management in Flutter
I am trying to increase counter when app call init and using provider to change the state of counter but getting this error i don't understand why i have made the listen to false but no solved kindly help

```<code>import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:providerpractice/counter.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int count = 0;
  Timer? timer;

  @override
  void initState() {
    super.initState();

    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      var pro = Provider.of<Counter>(context, listen: false);
      pro.addCounter();
    });
  }

  @override
  Widget build(BuildContext context) {
    print("build" + count.toString());
    return Scaffold(
      appBar: AppBar(
        title: Text("Provider State Management"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Consumer<Counter>(builder: ((context, value, child) {
              return Text(
                value.counter.toString(),
                style: TextStyle(fontSize: 30),
              );
            }))
          ],
        ),
      ),
    );
  }
}
</code>```

答:
I think the error you're getting is a result of the fact that you do not have any logic to dispose of your active work. Try implementing something in onDispose().

You could also elaborate more on the error you're getting. There is no mention of the error type or statement in your question.

Body:
I am trying to increase counter when app call init and using provider to change the state of counter but getting this error i don't understand why i have made the listen to false but no solved kindly help

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:providerpractice/counter.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int count = 0;
  Timer? timer;

  @override
  void initState() {
    super.initState();

    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      var pro = Provider.of<Counter>(context, listen: false);
      pro.addCounter();
    });
  }

  @override
  Widget build(BuildContext context) {
    print("build" + count.toString());
    return Scaffold(
      appBar: AppBar(
        title: Text("Provider State Management"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Consumer<Counter>(builder: ((context, value, child) {
              return Text(
                value.counter.toString(),
                style: TextStyle(fontSize: 30),
              );
            }))
          ],
        ),
      ),
    );
  }
}


问:
Trying to Create a File from Blob but the Output file has Invalid Size
I am creating a canvas to rotate an image and creating a blob. But I need it as a file to upload it to server.

```<code>return new Promise((resolve, reject) => {
        canvas.toBlob(blob => {
            // returning an error
            if (!blob) {
                reject(new Error('Canvas is empty'));
                return;
            }
            // blob.name = fileName;
            // creating a Object URL representing the Blob object given
            const rotatedImageUrl = window.URL.createObjectURL(blob);
            resolve(rotatedImageUrl);
        }, 'image/jpeg');
    });
</code>```

I am trying to create a file from the blob . I'm able to create it by using this snippet.

```<code>const rotatedFile = new File([img], originalFile.name, {
        type: originalFile.type,
    });
</code>```

But the problem is generated file size is only 58 byte.

```<code>lastModified: 1644577677380
lastModifiedDate: Fri Feb 11 2022 17:07:57 GMT+0600 (Bangladesh Standard Time) {}
name: "IMG_4792.JPG"
size: 58
type: "image/jpeg"
webkitRelativePath: ""
</code>```

I think the image is corrupted somehow.
Initially I thought canvas is somehow corrupting my image but I have also tried to create a file from an uploaded file converted to blob. That also gave me the same output. File size is not correct.

```<code>const file = e.target.files[0];
const blobUrl = URL.createObjectURL(file);
const generatedFile = new File([blobUrl], 'untitled', {
            type: file.type,
        });

</code>```

Is there any solution? How can I properly create the file from the blob?

答:
Why are you using the createObjectURL ?

You should resolve the blob directly resolve(blob); and then the file will correctly represent the image, instead of representing the objectURL.

What you are seeing is the length of the generated url. Something like "blob:https://........'

Body:
I am creating a canvas to rotate an image and creating a blob. But I need it as a file to upload it to server.

return new Promise((resolve, reject) => {
        canvas.toBlob(blob => {
            // returning an error
            if (!blob) {
                reject(new Error('Canvas is empty'));
                return;
            }
            // blob.name = fileName;
            // creating a Object URL representing the Blob object given
            const rotatedImageUrl = window.URL.createObjectURL(blob);
            resolve(rotatedImageUrl);
        }, 'image/jpeg');
    });

I am trying to create a file from the blob . I'm able to create it by using this snippet.

const rotatedFile = new File([img], originalFile.name, {
        type: originalFile.type,
    });

But the problem is generated file size is only 58 byte.

lastModified: 1644577677380
lastModifiedDate: Fri Feb 11 2022 17:07:57 GMT+0600 (Bangladesh Standard Time) {}
name: "IMG_4792.JPG"
size: 58
type: "image/jpeg"
webkitRelativePath: ""

I think the image is corrupted somehow.
Initially I thought canvas is somehow corrupting my image but I have also tried to create a file from an uploaded file converted to blob. That also gave me the same output. File size is not correct.

const file = e.target.files[0];
const blobUrl = URL.createObjectURL(file);
const generatedFile = new File([blobUrl], 'untitled', {
            type: file.type,
        });

Is there any solution? How can I properly create the file from the blob?


问:
Is there any Customizable Sniff Properties for classes/traits/interfaces?
is there any Customizable Sniff Properties for classes/traits/interfaces to do the followings;

not allow a blank line before the first content

One blank line after the last content

I am expecting a rule for something like this.

example

Valid code

```<code>Class Example()
{
  /** Content */

}
</code>```

Invalid Code: After the content it does not have a blank line & before the content there is a space allowed

```<code>Class Example()
{

 /** Content */
}
</code>```

答:
Please refer Squiz.WhiteSpace.FunctionSpacing sniff.

Not completely it matches, but as most classes will have functions at the end, the "One line after last" can be enforced and if the class content starts with a function, the "No blank line before first" as well.

Refererance: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Customisable-Sniff-Properties#squizwhitespacefunctionspacing

found this solution form different source

Body:
is there any Customizable Sniff Properties for classes/traits/interfaces to do the followings;

not allow a blank line before the first content

One blank line after the last content

I am expecting a rule for something like this.

example

Valid code

Class Example()
{
  /** Content */

}

Invalid Code: After the content it does not have a blank line & before the content there is a space allowed

Class Example()
{

 /** Content */
}


问:
How to use Subquery which returned more than one result
My SQL query

```<code>UPDATE Task SET Done = 1 WHERE (ID = (SELECT ID FROM User WHERE UserName = @UserName)
</code>```

I tried and got an error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression. The statement has been terminated.

Is there any possible way to do that (for example a for loop)? Thanks

答:
How would a row's ID be equal to more than one value?

That doesn't make sense, which is why writing such a query isn't possible.

Checking if the ID is in a set would make sense, though...

...WHERE ID IN (SELECT ID...

Body:
My SQL query

UPDATE Task SET Done = 1 WHERE (ID = (SELECT ID FROM User WHERE UserName = @UserName)

I tried and got an error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression. The statement has been terminated.

Is there any possible way to do that (for example a for loop)? Thanks


问:
How to connect mqtt with websocket in c#?
I tried use MQTTnet to connect mqtt.

But seems not worked, it would show the error message:

Unable to connect the remote server, the request was aborted: Could not create SSL/TLS secure channel.

I also found error message on windows event:

A fatal alert was received from the remote endpoint. The TLS protocol defined fatal alert code is 40.

```<code>using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Options;

public override void Run()
{
    var option = new MqttClientOptionsBuilder()
                    .WithWebSocketServer("wss://mymqttserver:443")
                    .WithClientId(Guid.NewGuid().ToString())
                    .WithTls(new MqttClientOptionsBuilderTlsParameters()
                    {
                        AllowUntrustedCertificates = true,
                        UseTls = true,
                        SslProtocol = SslProtocols.Tls12,
                        CertificateValidationCallback = delegate { return true; },
                    })
                    .WithCleanSession()
                    .Build();
    var mqtt = new MqttFactory().CreateMqttClient() as MqttClient;
    mqtt.ConnectAsync(option).Wait();

    string convertMsg = JsonConvert.SerializeObject("Mqtt Connect Successfully!!");

    var appMsg = new MqttApplicationMessage();
    appMsg.Payload = Encoding.UTF8.GetBytes(convertMsg);
    appMsg.Topic = "myTopic";
    appMsg.QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce;
    appMsg.Retain = false;

    mqttClient.PublishAsync(appMsg).Wait();
}
</code>```

I also tried connect my mqtt server with third party application.

It can connect successfully, so my mqtt server should be okay.

But I don't know why I can't use c# to connect.

答:
In the line

```<code>    .WithWebSocketServer("wss://mymqttserver:443")
</code>```

You must remove the "wss://" because that is already being specified using the method ".WithWebSocketServer". So, you would have

```<code>   .WithWebSocketServer("mymqttserver:443")
</code>```

Just use the server and the port.

Body:
I tried use MQTTnet to connect mqtt.

But seems not worked, it would show the error message:

Unable to connect the remote server, the request was aborted: Could not create SSL/TLS secure channel.

I also found error message on windows event:

A fatal alert was received from the remote endpoint. The TLS protocol defined fatal alert code is 40.

using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Options;

public override void Run()
{
    var option = new MqttClientOptionsBuilder()
                    .WithWebSocketServer("wss://mymqttserver:443")
                    .WithClientId(Guid.NewGuid().ToString())
                    .WithTls(new MqttClientOptionsBuilderTlsParameters()
                    {
                        AllowUntrustedCertificates = true,
                        UseTls = true,
                        SslProtocol = SslProtocols.Tls12,
                        CertificateValidationCallback = delegate { return true; },
                    })
                    .WithCleanSession()
                    .Build();
    var mqtt = new MqttFactory().CreateMqttClient() as MqttClient;
    mqtt.ConnectAsync(option).Wait();

    string convertMsg = JsonConvert.SerializeObject("Mqtt Connect Successfully!!");

    var appMsg = new MqttApplicationMessage();
    appMsg.Payload = Encoding.UTF8.GetBytes(convertMsg);
    appMsg.Topic = "myTopic";
    appMsg.QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce;
    appMsg.Retain = false;

    mqttClient.PublishAsync(appMsg).Wait();
}

I also tried connect my mqtt server with third party application.

It can connect successfully, so my mqtt server should be okay.

But I don't know why I can't use c# to connect.

Body:
In the line

    .WithWebSocketServer("wss://mymqttserver:443")

You must remove the "wss://" because that is already being specified using the method ".WithWebSocketServer". So, you would have

   .WithWebSocketServer("mymqttserver:443")

Just use the server and the port.


问:
sqlite selection error
I got this code in one of my methods. It should check if the string is already in the database and if it is the db entry gets updated. If it is not there I catch the exception and just create the entry.

```<code>String s="hallo";

try {
   Cursor c1 = dba.fetchSubject(s);
   dba.updateSubject(c1.getLong(c1.getColumnIndex(DbAdapter.KEY_ROWID)), s, t, r);
} catch (SQLException e){
   dba.createSubject(s, t, r);
}
</code>```

The problem is fetchSubject allway throws an Exception.

I use a similar method to get a db entry by a rowId instead of a String, which is working:

```<code>public Cursor fetchSubject(long rowId) throws SQLException {
    Cursor mCursor = database.query(true, DATABASE_TABLE2, new String[] {
            KEY_ROWID, KEY_SUBJECT, KEY_TEACHER, KEY_ROOM}, KEY_ROWID
            + "=" + rowId, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}
</code>```

The method called on top:

```<code>public Cursor fetchSubject(String subject) throws SQLException {
    Cursor mCursor = database.query(true, DATABASE_TABLE2, new String[] {
            KEY_ROWID, KEY_SUBJECT, KEY_TEACHER, KEY_ROOM}, KEY_SUBJECT
            + "=" + subject, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}
</code>```

The error:

```<code> sqlite returned: error code = 1, msg = no such column: hallo
</code>```

I don't know where my error is. Isn't it possible to use a string at the selection parameter?

答:
Try adding single quotes around hallo

```<code>String s = "'hallo'";
</code>```

Essentially what you're doing is telling your query: select blah blah blah from TABLE where subject = hallo. Since hallo isn't surrounded by quotes, it is trying to find a variable / column with that name. When we surround it with quotes, we are saying that we are looking for the string within these quotes, rather than a variable.

Think of it like normal programming..

```<code>String s = hallo;
</code>```

is completely different than

```<code>String s = "hallo";
</code>```

Title: sqlite selection error

Body:
I got this code in one of my methods. It should check if the string is already in the database and if it is the db entry gets updated. If it is not there I catch the exception and just create the entry.

String s="hallo";

try {
   Cursor c1 = dba.fetchSubject(s);
   dba.updateSubject(c1.getLong(c1.getColumnIndex(DbAdapter.KEY_ROWID)), s, t, r);
} catch (SQLException e){
   dba.createSubject(s, t, r);
}

The problem is fetchSubject allway throws an Exception.

I use a similar method to get a db entry by a rowId instead of a String, which is working:

public Cursor fetchSubject(long rowId) throws SQLException {
    Cursor mCursor = database.query(true, DATABASE_TABLE2, new String[] {
            KEY_ROWID, KEY_SUBJECT, KEY_TEACHER, KEY_ROOM}, KEY_ROWID
            + "=" + rowId, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

The method called on top:

public Cursor fetchSubject(String subject) throws SQLException {
    Cursor mCursor = database.query(true, DATABASE_TABLE2, new String[] {
            KEY_ROWID, KEY_SUBJECT, KEY_TEACHER, KEY_ROOM}, KEY_SUBJECT
            + "=" + subject, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

The error:

 sqlite returned: error code = 1, msg = no such column: hallo

I don't know where my error is. Isn't it possible to use a string at the selection parameter?

Body:
Try adding single quotes around hallo

String s = "'hallo'";

Essentially what you're doing is telling your query: select blah blah blah from TABLE where subject = hallo. Since hallo isn't surrounded by quotes, it is trying to find a variable / column with that name. When we surround it with quotes, we are saying that we are looking for the string within these quotes, rather than a variable.

Think of it like normal programming..

String s = hallo;

is completely different than

String s = "hallo";


问:
Is there any multimap with different values of different object for one key in java-redis?
My application requires a multivaluemap to store in redis cache with a key having 2 different objects saying object1 and object2. Map can return all the values or a single value based on type parameter as in get(key, type).
Couldn't find such feature in either reddison or jedis. Is there any other library providing this data structure or I would have to implement my own?</p>

答: As I know, there is no this kind of data structure in Redis, you have to do a little design by yourself, using extra keys to store extra information.</p>