问:
how to take rms without considering extreme points
I center each point on my graph and take the rms with the points that are within 8's of that centered point. However, the points at the ends skew my results. I would like to know how to disregard these extreme points when removing the rms but without disregarding them in the total analysis

```<code>

</code>```

my code is

```<code>from scipy import spatial

# arvore dos dados(pontos azuis)
points2 = np.c_[x2.ravel(), y2.ravel(), z2.ravel()]

# pontos de contagens(pontos vermelhos)
points3 = np.c_[x3.ravel(), y3.ravel(), z3.ravel()]

# construo a arvore dos pontos azuis
tree = spatial.KDTree(points3)

# contagem usando os pontos vermelhos como centro de contagem
I = tree.query_ball_point(points3, 8)
x = np.array(points3[:, 0])
y = np.array(points3[:, 1])

sig8 = []
for i in range(len(I)):
    # massa HI dos pontos de contagem
    Mi = m2[I[i]]
    sig8.append(np.sqrt(np.var(Mi)))

sig8 = np.array(sig8)

ax = plt.subplots(figsize=(10, 6), dpi=80)

plt.hist(sig8, bins=40)
print(np.mean(sig8))
</code>```

Body:
I center each point on my graph and take the rms with the points that are within 8's of that centered point. However, the points at the ends skew my results. I would like to know how to disregard these extreme points when removing the rms but without disregarding them in the total analysis

my code is

from scipy import spatial

# arvore dos dados(pontos azuis)
points2 = np.c_[x2.ravel(), y2.ravel(), z2.ravel()]

# pontos de contagens(pontos vermelhos)
points3 = np.c_[x3.ravel(), y3.ravel(), z3.ravel()]

# construo a arvore dos pontos azuis
tree = spatial.KDTree(points3)

# contagem usando os pontos vermelhos como centro de contagem
I = tree.query_ball_point(points3, 8)
x = np.array(points3[:, 0])
y = np.array(points3[:, 1])

sig8 = []
for i in range(len(I)):
    # massa HI dos pontos de contagem
    Mi = m2[I[i]]
    sig8.append(np.sqrt(np.var(Mi)))

sig8 = np.array(sig8)

ax = plt.subplots(figsize=(10, 6), dpi=80)

plt.hist(sig8, bins=40)
print(np.mean(sig8))


来源: stackexchange

问:
Filter Object records where multiple Types are involved but only one type has additional condition
I'm trying to extract data from one Object called Account using SOQL and have multiple Account.Types to be extracted, but need to further filter one type with additional condition where branch id != null
Running this SOQL query but it throws an error on unexpected '(' Please help.

Select Id, Type, BranchId from Account
where Type in (('retail') or (('consultant') and BranchId != null))

Expecting to see output as (All Account records where account.type = Retail) + (all account records where Account.Type = (consultant and Account.Branchid for consultant records is not null))

ContentLicense: CC BY-SA 4.0


问:
Callback with int argument from Native Android on Flutter
I am trying to receive a callback from Android Native on my Flutter app. Nevertheless, it seems to be working. So far, my implementation looks like the following:

Invoking method from Android side

Firstly I have implemented a method call in order to send the values which I require on Dart

```<code>int length = 1234;

handler.post(() -> {
    if (channel != null) {
        channel.invokeMethod("onDone", length);
    }
});
</code>```

Receive the callback on dart side

Secondly, I have implemented a platform handler in order to receive those calls. Nevertheless, I believe that the map is failing (but I am not receiving any error message)

```<code>// Receive callbacks from native platform
Future platformCallHandler(MethodCall call) async {
  switch (call.method) {
    // Case called when synthesization of an audio cue has been completed
    case "onDone":

      final args = call.arguments as Map<dynamic, dynamic>;
      break;
  }
}

</code>```

Am I missing something? I receive the call on onDone method but I can not get access to the argument.

I would be expecting to get my int as an argument

Body:
I am trying to receive a callback from Android Native on my Flutter app. Nevertheless, it seems to be working. So far, my implementation looks like the following:

Invoking method from Android side

Firstly I have implemented a method call in order to send the values which I require on Dart

int length = 1234;

handler.post(() -> {
    if (channel != null) {
        channel.invokeMethod("onDone", length);
    }
});

Receive the callback on dart side

Secondly, I have implemented a platform handler in order to receive those calls. Nevertheless, I believe that the map is failing (but I am not receiving any error message)

// Receive callbacks from native platform
Future platformCallHandler(MethodCall call) async {
  switch (call.method) {
    // Case called when synthesization of an audio cue has been completed
    case "onDone":

      final args = call.arguments as Map<dynamic, dynamic>;
      break;
  }
}

Am I missing something? I receive the call on onDone method but I can not get access to the argument.

I would be expecting to get my int as an argument


问:
Pandas DataFrame query in sorting data
I am trying to sort a pandas dataframe. The data looks like-

year
state
district
Party
rank
share in votes

2010
haryana
kaithal
Winner
1
40.12

2010
haryana
kaithal
bjp
2
30.52

2010
haryana
kaithal
NOTA
3
29

2010
goa
panji
Winner
3
10

2010
goa
panji
INC
2
40

2010
goa
panji
BJP
1
50

2013
up
meerut
Winner
2
40

2013
up
meerut
SP
1
60

2015
haryana
kaithal
Winner
2
15

2015
haryana
kaithal
BJP
3
35

2015
haryana
kaithal
INC
1
50

This data is for multiple states for multiple years.
In this dataset, there are multiple values for each district. I want to calculate the margin of share for each district in this manner. I have tried this, but not able to write fully. I am not able to write code for defining the margin of share and get a dataframe with only one (margin of share) value corresponding to each district instead of party wise shares.

```<code>for year in df['YEAR']:
 for state in df['STATE']:
    for district in df['DISTRICT']:
        for rank in df['RANK']:
            for party in df['PARTY']:
                if rank==1 and party=='WINNER':
</code>```

then margin of share =Share of Winner-Share of party at rank 2. If share WINNER does not have rank 1 then Margin of Share= share of winner - share of party at rank 1.

I am basically trying to get this output-

```<code>|      year     |     state   |district| margin of share|
|---------------|-------------|--------|----------------|
|          2010    |     haryana       |kaithal| 9.6|
|          2010    |     goa       |panji| -40|
|          2010    |     up       |kaithal| -20|
|          2015   |     haryana      |kaithal| -35|
</code>```

I wish to have create a different data frame with columns Year, State, District and margin of SHARE.

Title: Pandas DataFrame query in sorting data

Body:
I am trying to sort a pandas dataframe. The data looks like-

year
state
district
Party
rank
share in votes

2010
haryana
kaithal
Winner
1
40.12

2010
haryana
kaithal
bjp
2
30.52

2010
haryana
kaithal
NOTA
3
29

2010
goa
panji
Winner
3
10

2010
goa
panji
INC
2
40

2010
goa
panji
BJP
1
50

2013
up
meerut
Winner
2
40

2013
up
meerut
SP
1
60

2015
haryana
kaithal
Winner
2
15

2015
haryana
kaithal
BJP
3
35

2015
haryana
kaithal
INC
1
50

This data is for multiple states for multiple years.
In this dataset, there are multiple values for each district. I want to calculate the margin of share for each district in this manner. I have tried this, but not able to write fully. I am not able to write code for defining the margin of share and get a dataframe with only one (margin of share) value corresponding to each district instead of party wise shares.

for year in df['YEAR']:
 for state in df['STATE']:
    for district in df['DISTRICT']:
        for rank in df['RANK']:
            for party in df['PARTY']:
                if rank==1 and party=='WINNER':

then margin of share =Share of Winner-Share of party at rank 2. If share WINNER does not have rank 1 then Margin of Share= share of winner - share of party at rank 1.

I am basically trying to get this output-

|      year     |     state   |district| margin of share|
|---------------|-------------|--------|----------------|
|          2010    |     haryana       |kaithal| 9.6|
|          2010    |     goa       |panji| -40|
|          2010    |     up       |kaithal| -20|
|          2015   |     haryana      |kaithal| -35|

I wish to have create a different data frame with columns Year, State, District and margin of SHARE.


问:
Calculate size of custom collectionView cell at run time with typing text
I have made custom cell and reusable with typingIndicator data source method of MessageKit. I want to calculate size of the custom cell and update the height with the actual text of typed by another user. Can you help me with the below UI?


问:
Replace unique values of dataframe with another list or dataframe
i have a column in a dataframe with these unique values by using this line

df['REASON.FOR.DISCHARGE'].unique()

output:

Since there are 14 unique values. I want to replace all of them with an assigned number.
Like,

Medical Decision = 1,

patient Decision = 2,

I tried this code but get an error.

```<code>df1 = df
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
df2 = pd.DataFrame(a)

for i in df1:
    df1['REASON.FOR.DISCHARGE'].unique()
    df1['REASON.FOR.DISCHARGE'] = df1['REASON.FOR.DISCHARGE'].replace(df1[i], df2[i])

</code>```

Help would be much appreciated.

Thanks!!

Body:
i have a column in a dataframe with these unique values by using this line

df['REASON.FOR.DISCHARGE'].unique()

output:

Since there are 14 unique values. I want to replace all of them with an assigned number.
Like,

Medical Decision = 1,

patient Decision = 2,

I tried this code but get an error.

df1 = df
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
df2 = pd.DataFrame(a)

for i in df1:
    df1['REASON.FOR.DISCHARGE'].unique()
    df1['REASON.FOR.DISCHARGE'] = df1['REASON.FOR.DISCHARGE'].replace(df1[i], df2[i])

Help would be much appreciated.

Thanks!!


问:
Slowly changing side input stops working with larger dataset
EDIT:  As far as I can tell, all the elements are added. I tried adding a reshuffle and missing with the sequence but no luck.  I added more of my source code here:  https://github.com/nathan-smit/dataflowpipelinecode

I'm currently using Apache Beam SDK for Java 2.42.0 on Google Cloud Dataflow. I have a slowly changing side input that I'm reading in from a BigQuery table.  This is what the side input looks like:

```<code>        final PCollectionView<Map<String, String>> skus = pipeline
                // Emitted long data trigger this batch read BigQuery client job.
                .apply(String.format("Read big query central sku table.  Updating every %s hours", 10),
                        GenerateSequence.from(0).withRate(1, Duration.standardHours(10)))
                .apply(
                        Window.<Long>into(new GlobalWindows())
                                .triggering(Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane()))
                                .discardingFiredPanes()) // Caching results as Map.

                .apply(new ReadSlowChangingBigQueryTable("Read BigQuery SKU Table", query,
                        "sku_id",
                        "sku_code"))
                // Caching results as Map.
                .apply("Sku View As Map", View.asMap());
</code>```

"ReadSlowChangingBigQueryTable" fetches two columns and returns these as KV pairs.

```<code>                for (FieldValueList row : result.iterateAll()) {
                    String keyInstance = row.get(key).getStringValue();
                    String valueInstance = row.get(value).getStringValue();

                    c.output(KV.of(keyInstance, valueInstance));
                }
</code>```

I'm using this side input as a lookup which looks like the below where I'm looking up a corresponding code for this id.  I was running this with 10000 rows from BigQuery without issue, however, as I've tried to add more rows it seems that my lookup stops working even though the absolute amount of data for all rows (500k rows) is +- 15mb i.e. when I try to enrich the row skuTable.get(sku) returns null.

Is there a better way to do what I'm attempting here? I'm uncertain if the pipeline is just slow or if it'll never complete as all of the elements are placed in the view as map step, but the lookup doesn't return the expected result.

```<code>   @ProcessElement
    public void ProcessElement(ProcessContext c) {

        skuTable = c.sideInput(skus);
        String sku = c.element().getSku();

        if (skuTable.containsKey(sku)) {
          c.output(
            new BranchCompanySkuTransactionValue(
              c.element().getBranch(),
              c.element().getCompany(),
              skuTable.get(sku),
              c.element().getTransactionId(),
              c.element().getTable(),
              c.element().getOp(),
              c.element().getTs_ms(),
              c.element().getValue()
            )
          );
        }
  }
</code>```

Edit:  There is also this recommendation in the Dataflow console

Body:
EDIT:  As far as I can tell, all the elements are added. I tried adding a reshuffle and missing with the sequence but no luck.  I added more of my source code here:  https://github.com/nathan-smit/dataflowpipelinecode

I'm currently using Apache Beam SDK for Java 2.42.0 on Google Cloud Dataflow. I have a slowly changing side input that I'm reading in from a BigQuery table.  This is what the side input looks like:

        final PCollectionView<Map<String, String>> skus = pipeline
                // Emitted long data trigger this batch read BigQuery client job.
                .apply(String.format("Read big query central sku table.  Updating every %s hours", 10),
                        GenerateSequence.from(0).withRate(1, Duration.standardHours(10)))
                .apply(
                        Window.<Long>into(new GlobalWindows())
                                .triggering(Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane()))
                                .discardingFiredPanes()) // Caching results as Map.

                .apply(new ReadSlowChangingBigQueryTable("Read BigQuery SKU Table", query,
                        "sku_id",
                        "sku_code"))
                // Caching results as Map.
                .apply("Sku View As Map", View.asMap());

"ReadSlowChangingBigQueryTable" fetches two columns and returns these as KV pairs.

                for (FieldValueList row : result.iterateAll()) {
                    String keyInstance = row.get(key).getStringValue();
                    String valueInstance = row.get(value).getStringValue();

                    c.output(KV.of(keyInstance, valueInstance));
                }

I'm using this side input as a lookup which looks like the below where I'm looking up a corresponding code for this id.  I was running this with 10000 rows from BigQuery without issue, however, as I've tried to add more rows it seems that my lookup stops working even though the absolute amount of data for all rows (500k rows) is +- 15mb i.e. when I try to enrich the row skuTable.get(sku) returns null.

Is there a better way to do what I'm attempting here? I'm uncertain if the pipeline is just slow or if it'll never complete as all of the elements are placed in the view as map step, but the lookup doesn't return the expected result.

   @ProcessElement
    public void ProcessElement(ProcessContext c) {

        skuTable = c.sideInput(skus);
        String sku = c.element().getSku();

        if (skuTable.containsKey(sku)) {
          c.output(
            new BranchCompanySkuTransactionValue(
              c.element().getBranch(),
              c.element().getCompany(),
              skuTable.get(sku),
              c.element().getTransactionId(),
              c.element().getTable(),
              c.element().getOp(),
              c.element().getTs_ms(),
              c.element().getValue()
            )
          );
        }
  }

Edit:  There is also this recommendation in the Dataflow console


问:
How to block downloadable pdf at checkout wordpress/woocommerce?
I have made a bookshop with wordpress and woocommerce. On each product page I have embedded a pdf sample of the book using this code.

```<code>[pdf-embedder url=""]

<form class="pdf-download" action=""><input type="submit"
value="Sample!" /></form>
</code>```

Which I put in the product description. To generate the pdf link I use downloadable in product data. I can't use the link from add media as it will link the pdf not embed it. However, when a customer buys a book they also get given the pdf which is causing some confusion. I want to avoid changing how I embed the pdf(if possible) as I manually add the books and it would mean having to go back through each product and changing it. Could I custom code something to block the downloadable feature at the checkout?

I've tried setting the limit and expiry to 0 nothing changed.

Body:
I have made a bookshop with wordpress and woocommerce. On each product page I have embedded a pdf sample of the book using this code.

[pdf-embedder url=""]

<form class="pdf-download" action=""><input type="submit"
value="Sample!" /></form>

Which I put in the product description. To generate the pdf link I use downloadable in product data. I can't use the link from add media as it will link the pdf not embed it. However, when a customer buys a book they also get given the pdf which is causing some confusion. I want to avoid changing how I embed the pdf(if possible) as I manually add the books and it would mean having to go back through each product and changing it. Could I custom code something to block the downloadable feature at the checkout?

I've tried setting the limit and expiry to 0 nothing changed.


问:
I have a dataframe of Tweets. How can I search these Tweets for words that are more or less country names or region names?
I have a pandas dataframe of Tweets that looks like this:

```<code>    sentiment                   id                      date                                               text
0           0  1598826356309364736 2022-12-02 23:48:02+00:00  I love a man who believes in dancing with the ...
1           0  1598825548931006465 2022-12-02 23:44:50+00:00  Super empty hotels Lots of vacationing boomers...
2           0  1598823439460073474 2022-12-02 23:36:27+00:00  Charlen60403930 HustusMichael Yugoslavians do ...
3           0  1598822560724312065 2022-12-02 23:32:57+00:00  ramchrisali elonmusk No He 's trying to distra...
4           0  1598814115664994307 2022-12-02 22:59:24+00:00  DougBookwriter2 _TimSwain_ LindseyGrahamSC Wri...
..        ...                  ...                       ...                                                ...
995         0  1596399988464308225 2022-11-26 07:06:31+00:00  `` we 're all messed up perfectly imperfect pe...
996         0  1596398693447598080 2022-11-26 07:01:22+00:00  sorry but if you make safety school comments y...
997         0  1596391055494189057 2022-11-26 06:31:01+00:00  Just watched a video of Jessie J singing “ ext...
998         0  1596390875667611651 2022-11-26 06:30:18+00:00  itsJeffTiedrich I have a question How many ill...
999         0  1596379074221723648 2022-11-26 05:43:25+00:00  Pro-democracy people from a village of Kani Tw...
</code>```

Is there way that I can search the text of each tweet for country or region names that might have misspellings, or different endings?

Ex: If I was searching for Republic of Korea, matches would be anything like South Korean, souTh korian, s. korean. It doesn't need to be 100% accurate.

My goal is to delete all tweets that don't mention a country or region, so any way that could be accomplished would be good.

Body:
I have a pandas dataframe of Tweets that looks like this:

    sentiment                   id                      date                                               text
0           0  1598826356309364736 2022-12-02 23:48:02+00:00  I love a man who believes in dancing with the ...
1           0  1598825548931006465 2022-12-02 23:44:50+00:00  Super empty hotels Lots of vacationing boomers...
2           0  1598823439460073474 2022-12-02 23:36:27+00:00  Charlen60403930 HustusMichael Yugoslavians do ...
3           0  1598822560724312065 2022-12-02 23:32:57+00:00  ramchrisali elonmusk No He 's trying to distra...
4           0  1598814115664994307 2022-12-02 22:59:24+00:00  DougBookwriter2 _TimSwain_ LindseyGrahamSC Wri...
..        ...                  ...                       ...                                                ...
995         0  1596399988464308225 2022-11-26 07:06:31+00:00  `` we 're all messed up perfectly imperfect pe...
996         0  1596398693447598080 2022-11-26 07:01:22+00:00  sorry but if you make safety school comments y...
997         0  1596391055494189057 2022-11-26 06:31:01+00:00  Just watched a video of Jessie J singing “ ext...
998         0  1596390875667611651 2022-11-26 06:30:18+00:00  itsJeffTiedrich I have a question How many ill...
999         0  1596379074221723648 2022-11-26 05:43:25+00:00  Pro-democracy people from a village of Kani Tw...

Is there way that I can search the text of each tweet for country or region names that might have misspellings, or different endings?

Ex: If I was searching for Republic of Korea, matches would be anything like South Korean, souTh korian, s. korean. It doesn't need to be 100% accurate.

My goal is to delete all tweets that don't mention a country or region, so any way that could be accomplished would be good.


问:
Checking Java minor version on Ubuntu server
I have Ununtu server with OpenJDK.
When I check Java version from shell, I get this:

```<code># java -version
openjdk version "18.0.2-ea" 2022-07-19
OpenJDK Runtime Environment (build 18.0.2-ea+9-Ubuntu-222.04)
OpenJDK 64-Bit Server VM (build 18.0.2-ea+9-Ubuntu-222.04, mixed mode, sharing)
</code>```

I don't know how to check is there any minor Java versions upgrades available (for example 18.0.5 or 18.1.0) which means not Java 19 or any other major versions.

Every attempt to search around for magic apt-get command ends with instructions on installing Java, not checking minor versions and upgrading minor versions.

Body:
I have Ununtu server with OpenJDK.
When I check Java version from shell, I get this:

# java -version
openjdk version "18.0.2-ea" 2022-07-19
OpenJDK Runtime Environment (build 18.0.2-ea+9-Ubuntu-222.04)
OpenJDK 64-Bit Server VM (build 18.0.2-ea+9-Ubuntu-222.04, mixed mode, sharing)

I don't know how to check is there any minor Java versions upgrades available (for example 18.0.5 or 18.1.0) which means not Java 19 or any other major versions.

Every attempt to search around for magic apt-get command ends with instructions on installing Java, not checking minor versions and upgrading minor versions.


问:
how to use retrofit to post a custom list to server
I use phpMyAdmin to make cart activity at first :
1- I want to get all quntity from reyclerview and set sum to cart activty .
2- i want to post all items in cart to server .
I can post only 1 item but when i use loop to post all items it get error .</p>


问:
javascript string method lastIndexOf()
I've been checking the lastIndexOf() method. Can someone explain the fourth case? The result is a bit strange, it shouldn't be -1 right?

let study = "javascript";
console.log(study.length); // 10
// search chr only
console.log(study.lastIndexOf('t')); // 9; 't' is found at index 9
console.log(study.lastIndexOf('v')); // 2; 'v' is found at index 2
console.log(study.lastIndexOf()); // -1; [empty] is not found
console.log(study.lastIndexOf("")); // 10; [nothing] is found at index 10, strange result
console.log(study.lastIndexOf(" ")); // -1; space is not found```

Title: javascript string method lastIndexOf()


问:
Error negotiating V4L2 H264 output over UVC USB webcam
I'm trying to connect a DJI Osmo Action 3 in USB webcam mode to a Linux video pipeline. The camera supports both MJPG and H264:

```<code>$ v4l2-ctl -d /dev/video1 --list-formats-ext
ioctl: VIDIOC_ENUM_FMT
        Type: Video Capture

        [0]: 'MJPG' (Motion-JPEG, compressed)
                Size: Discrete 1280x720
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 1920x1080
                        Interval: Discrete 0.033s (30.000 fps)
        [1]: 'H264' (H.264, compressed)
                Size: Discrete 1280x720
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 1920x1080
                        Interval: Discrete 0.033s (30.000 fps)
</code>```

The MJPG output appears to be much lower quality than the H264 output, so I want to negotiate the latter. I believe the camera is able to output H264 on Windows because the output is much higher quality and the device does not support setting the JPEG compression level:

```<code>$ v4l2-ctl --all -d /dev/video1
Driver Info:
        Driver name      : uvcvideo
        Card type        : OsmoAction3: OsmoAction3
        Bus info         : usb-xhci-hcd.11.auto-1
        Driver version   : 5.10.66
        Capabilities     : 0x84a00001
                Video Capture
                Metadata Capture
                Streaming
                Extended Pix Format
                Device Capabilities
        Device Caps      : 0x04200001
                Video Capture
                Streaming
                Extended Pix Format
Media Driver Info:
        Driver name      : uvcvideo
        Model            : OsmoAction3: OsmoAction3
        Serial           : 123456789ABCDEF
        Bus info         : usb-xhci-hcd.11.auto-1
        Media version    : 5.10.66
        Hardware revision: 0x00000504 (1284)
        Driver version   : 5.10.66
Interface Info:
        ID               : 0x03000002
        Type             : V4L Video
Entity Info:
        ID               : 0x00000001 (1)
        Name             : OsmoAction3: OsmoAction3
        Function         : V4L2 I/O
        Flags         : default
        Pad 0x01000007   : 0: Sink
          Link 0x0200000d: from remote pad 0x100000a of entity 'Processing 2': Data, Enabled, Immutable
Priority: 2
Video input : 0 (Camera 1: ok)
Format Video Capture:
        Width/Height      : 1920/1080
        Pixel Format      : 'MJPG' (Motion-JPEG)
        Field             : None
        Bytes per Line    : 0
        Size Image        : 4147200
        Colorspace        : Default
        Transfer Function : Default (maps to Rec. 709)
        YCbCr/HSV Encoding: Default (maps to ITU-R 601)
        Quantization      : Default (maps to Full Range)
        Flags             :
Crop Capability Video Capture:
        Bounds      : Left 0, Top 0, Width 1920, Height 1080
        Default     : Left 0, Top 0, Width 1920, Height 1080
        Pixel Aspect: 1/1
Selection Video Capture: crop_default, Left 0, Top 0, Width 1920, Height 1080, Flags:
Selection Video Capture: crop_bounds, Left 0, Top 0, Width 1920, Height 1080, Flags:
Streaming Parameters Video Capture:
        Capabilities     : timeperframe
        Frames per second: 30.000 (30/1)
        Read buffers     : 0
</code>```

However, pulling video via H264 doesn't seem to work correctly with the UVC driver:

```<code>$ gst-launch-1.0 -vvv v4l2src device=/dev/video1 ! video/x-h264 ! fakesink
...
ERROR: from element /GstPipeline:pipeline0/GstV4l2Src:v4l2src0: Video device did not suggest any buffer size.
...
</code>```

And same with v4l2-ctl:

```<code>$ v4l2-ctl -d /dev/video1 --set-fmt-video width=1920,height=1080,pixelformat=MJPG --stream-mmap --stream-count=50
<<<<<<<<<<<<<<<<<<<<<<<<<^C
$ v4l2-ctl -d /dev/video1 --set-fmt-video width=1920,height=1080,pixelformat=H264 --stream-mmap --stream-count=50
                VIDIOC_REQBUFS returned -1 (Invalid argument)
</code>```

I'm running kernel 5.10.66 and I do get a pretty nasty stack trace in dmesg:

```<code>[3445509.809183] WARNING: CPU: 1 PID: 125186 at drivers/media/common/videobuf2/videobuf2-core.c:806 vb2_core_reqbufs+0x2a4/0x380
[3445509.809188] Modules linked in: bcmdhd
[3445509.809200] CPU: 1 PID: 125186 Comm: v4l2-ctl Tainted: G        W         5.10.66 #1
[3445509.809204] Hardware name: RK3588 MINIPC-MIZHUO LP4x V1.0 BlueBerry Board (DT)
[3445509.809210] pstate: 20400009 (nzCv daif +PAN -UAO -TCO BTYPE=--)
[3445509.809216] pc : vb2_core_reqbufs+0x2a4/0x380
[3445509.809221] lr : vb2_core_reqbufs+0x278/0x380
[3445509.809225] sp : ffffffc017deba90
[3445509.809229] x29: ffffffc017deba90 x28: ffffffc0112b40e0
[3445509.809235] x27: ffffff80429d0400 x26: 0000000000000000
[3445509.809241] x25: ffffff80c35c4018 x24: 0000000000000000
[3445509.809248] x23: ffffff80c35c4720 x22: ffffffc017debd18
[3445509.809254] x21: 0000000000000001 x20: 0000000000000000
[3445509.809260] x19: ffffff80c35c46b8 x18: 0000000000000000
[3445509.809266] x17: 0000000000000000 x16: 0000000000000000
[3445509.809272] x15: 0000000000000000 x14: 0000000000000000
[3445509.809278] x13: 0000000000000000 x12: 0000000000000000
[3445509.809284] x11: 0000000000000000 x10: 0000000000000000
[3445509.809290] x9 : ffffffc010ba5750 x8 : ffffffc010b73428
[3445509.809296] x7 : 0000000000000000 x6 : 0000000000000000
[3445509.809302] x5 : ffffffc010c0d1cc x4 : ffffff80c35c4720
[3445509.809308] x3 : 0000000000000001 x2 : ffffffc017debae4
[3445509.809314] x1 : 0000000000000000 x0 : 0000000000000001
[3445509.809320] Call trace:
[3445509.809325]  vb2_core_reqbufs+0x2a4/0x380
[3445509.809331]  vb2_reqbufs+0x54/0x70
[3445509.809338]  uvc_request_buffers+0x40/0x6c
[3445509.809345]  uvc_ioctl_reqbufs+0x58/0x9c
[3445509.809350]  v4l_reqbufs+0x58/0x6c
[3445509.809354]  __video_do_ioctl+0x258/0x384
[3445509.809359]  video_usercopy+0x23c/0x490
</code>```

So it seems like the uvcvideo driver isn't compatible with H264 output? Is that true? Is there a webcam driver that supports H264 output in Linux?

Body:
I'm trying to connect a DJI Osmo Action 3 in USB webcam mode to a Linux video pipeline. The camera supports both MJPG and H264:

$ v4l2-ctl -d /dev/video1 --list-formats-ext
ioctl: VIDIOC_ENUM_FMT
        Type: Video Capture

        [0]: 'MJPG' (Motion-JPEG, compressed)
                Size: Discrete 1280x720
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 1920x1080
                        Interval: Discrete 0.033s (30.000 fps)
        [1]: 'H264' (H.264, compressed)
                Size: Discrete 1280x720
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 1920x1080
                        Interval: Discrete 0.033s (30.000 fps)

The MJPG output appears to be much lower quality than the H264 output, so I want to negotiate the latter. I believe the camera is able to output H264 on Windows because the output is much higher quality and the device does not support setting the JPEG compression level:

$ v4l2-ctl --all -d /dev/video1
Driver Info:
        Driver name      : uvcvideo
        Card type        : OsmoAction3: OsmoAction3
        Bus info         : usb-xhci-hcd.11.auto-1
        Driver version   : 5.10.66
        Capabilities     : 0x84a00001
                Video Capture
                Metadata Capture
                Streaming
                Extended Pix Format
                Device Capabilities
        Device Caps      : 0x04200001
                Video Capture
                Streaming
                Extended Pix Format
Media Driver Info:
        Driver name      : uvcvideo
        Model            : OsmoAction3: OsmoAction3
        Serial           : 123456789ABCDEF
        Bus info         : usb-xhci-hcd.11.auto-1
        Media version    : 5.10.66
        Hardware revision: 0x00000504 (1284)
        Driver version   : 5.10.66
Interface Info:
        ID               : 0x03000002
        Type             : V4L Video
Entity Info:
        ID               : 0x00000001 (1)
        Name             : OsmoAction3: OsmoAction3
        Function         : V4L2 I/O
        Flags         : default
        Pad 0x01000007   : 0: Sink
          Link 0x0200000d: from remote pad 0x100000a of entity 'Processing 2': Data, Enabled, Immutable
Priority: 2
Video input : 0 (Camera 1: ok)
Format Video Capture:
        Width/Height      : 1920/1080
        Pixel Format      : 'MJPG' (Motion-JPEG)
        Field             : None
        Bytes per Line    : 0
        Size Image        : 4147200
        Colorspace        : Default
        Transfer Function : Default (maps to Rec. 709)
        YCbCr/HSV Encoding: Default (maps to ITU-R 601)
        Quantization      : Default (maps to Full Range)
        Flags             :
Crop Capability Video Capture:
        Bounds      : Left 0, Top 0, Width 1920, Height 1080
        Default     : Left 0, Top 0, Width 1920, Height 1080
        Pixel Aspect: 1/1
Selection Video Capture: crop_default, Left 0, Top 0, Width 1920, Height 1080, Flags:
Selection Video Capture: crop_bounds, Left 0, Top 0, Width 1920, Height 1080, Flags:
Streaming Parameters Video Capture:
        Capabilities     : timeperframe
        Frames per second: 30.000 (30/1)
        Read buffers     : 0

However, pulling video via H264 doesn't seem to work correctly with the UVC driver:

$ gst-launch-1.0 -vvv v4l2src device=/dev/video1 ! video/x-h264 ! fakesink
...
ERROR: from element /GstPipeline:pipeline0/GstV4l2Src:v4l2src0: Video device did not suggest any buffer size.
...

And same with v4l2-ctl:

$ v4l2-ctl -d /dev/video1 --set-fmt-video width=1920,height=1080,pixelformat=MJPG --stream-mmap --stream-count=50
<<<<<<<<<<<<<<<<<<<<<<<<<^C
$ v4l2-ctl -d /dev/video1 --set-fmt-video width=1920,height=1080,pixelformat=H264 --stream-mmap --stream-count=50
                VIDIOC_REQBUFS returned -1 (Invalid argument)

I'm running kernel 5.10.66 and I do get a pretty nasty stack trace in dmesg:

[3445509.809183] WARNING: CPU: 1 PID: 125186 at drivers/media/common/videobuf2/videobuf2-core.c:806 vb2_core_reqbufs+0x2a4/0x380
[3445509.809188] Modules linked in: bcmdhd
[3445509.809200] CPU: 1 PID: 125186 Comm: v4l2-ctl Tainted: G        W         5.10.66 #1
[3445509.809204] Hardware name: RK3588 MINIPC-MIZHUO LP4x V1.0 BlueBerry Board (DT)
[3445509.809210] pstate: 20400009 (nzCv daif +PAN -UAO -TCO BTYPE=--)
[3445509.809216] pc : vb2_core_reqbufs+0x2a4/0x380
[3445509.809221] lr : vb2_core_reqbufs+0x278/0x380
[3445509.809225] sp : ffffffc017deba90
[3445509.809229] x29: ffffffc017deba90 x28: ffffffc0112b40e0
[3445509.809235] x27: ffffff80429d0400 x26: 0000000000000000
[3445509.809241] x25: ffffff80c35c4018 x24: 0000000000000000
[3445509.809248] x23: ffffff80c35c4720 x22: ffffffc017debd18
[3445509.809254] x21: 0000000000000001 x20: 0000000000000000
[3445509.809260] x19: ffffff80c35c46b8 x18: 0000000000000000
[3445509.809266] x17: 0000000000000000 x16: 0000000000000000
[3445509.809272] x15: 0000000000000000 x14: 0000000000000000
[3445509.809278] x13: 0000000000000000 x12: 0000000000000000
[3445509.809284] x11: 0000000000000000 x10: 0000000000000000
[3445509.809290] x9 : ffffffc010ba5750 x8 : ffffffc010b73428
[3445509.809296] x7 : 0000000000000000 x6 : 0000000000000000
[3445509.809302] x5 : ffffffc010c0d1cc x4 : ffffff80c35c4720
[3445509.809308] x3 : 0000000000000001 x2 : ffffffc017debae4
[3445509.809314] x1 : 0000000000000000 x0 : 0000000000000001
[3445509.809320] Call trace:
[3445509.809325]  vb2_core_reqbufs+0x2a4/0x380
[3445509.809331]  vb2_reqbufs+0x54/0x70
[3445509.809338]  uvc_request_buffers+0x40/0x6c
[3445509.809345]  uvc_ioctl_reqbufs+0x58/0x9c
[3445509.809350]  v4l_reqbufs+0x58/0x6c
[3445509.809354]  __video_do_ioctl+0x258/0x384
[3445509.809359]  video_usercopy+0x23c/0x490

So it seems like the uvcvideo driver isn't compatible with H264 output? Is that true? Is there a webcam driver that supports H264 output in Linux?


问:
Trouble downloading table from Excel to BQ
I'm trying to import a table in SQL using a .csv file from Excel but keep getting this error message, " Error detected while parsing row starting at position: 0. Error: Bad character (ASCII 0) encountered." I am completely stumped, tried Google and even YouTube for help and nothing. Thanks in advance!
I tried loading via Google Sheets and Excel, I've changed the file type to UTF-8 in Excel and still the same error code.</p>


问:
How do I stop images from looping using Image Picker?
In a class I took he said pickedImages is looping, so I'm not sure if the problem is in uploadMultipleImages function where pickedImages is used or if the problem is in the function loadImages.

The functions are a bit beyond my understanding. What I'm trying to do is have each card show different images. I'm not sure what needs to change.

Functions:

```<code>  File? imageFile;
  String? fileName;

  Future<void> uploadMultipleImages() async {
    final picker = ImagePicker();
    final List<XFile>? pickedImages = await picker.pickMultiImage();
    if (pickedImages == null) {
      return null;
    }
    setState(() {
      loading = true;
    });
    await Future.forEach(pickedImages, (XFile image) async {
      fileName = image.name;
      imageFile = File(image.path);

      try {
        await firebaseStorage.ref(fileName).putFile(imageFile!);
      } on FirebaseException catch (e) {
        print(e);
      }
    });

    setState(() {
      loading = false;
    });

    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("All images uploaded successfully")));
  }
</code>```
```<code>  Future<List> loadImages() async {
    List<Map> files = [];
    final ListResult result = await firebaseStorage.ref().listAll();
    final List<Reference> allFiles = result.items;
    await Future.forEach(allFiles, (Reference file) async {
      final String fileUrl = await file.getDownloadURL();
      files.add({
        "url": fileUrl,
        "path": file.fullPath,
      });
    });
    print(files);
    return files;
  }
</code>```

Here I use loadImages:

```<code> body: StreamBuilder(
          stream: FirebaseFirestore.instance
              .collection("notes")
              .where('userId', isEqualTo: user.uid)
              .snapshots(),
          builder: (context, AsyncSnapshot streamSnapshot) {
            if (streamSnapshot.hasData) {
              if (streamSnapshot.data.docs.length > 0) {
                return ListView.builder(
                    itemCount: streamSnapshot.data.docs.length ?? 0,
                    itemBuilder: (context, index) {
                      final NoteModel note =
                          NoteModel.fromJson(streamSnapshot.data.docs[index]);
                      return Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(15.0),
                        ),
                        margin:
                            const EdgeInsets.only(top: 18, left: 15, right: 15),
                        child: Column(children: [
                          SizedBox(
                            height: 210,
                            child: Expanded(
                              child: FutureBuilder(
                                  future: loadImages(),
                                  builder: (context, AsyncSnapshot snapshot) {
                                    if (snapshot.connectionState ==
                                        ConnectionState.waiting) {
                                      return const Center(
                                        child: CircularProgressIndicator(),
                                      );
                                    }
                                    return Swiper(
                                        loop: false,
                                        pagination: SwiperPagination(
                                          alignment: Alignment.bottomRight,
                                          builder: DotSwiperPaginationBuilder(
                                              activeSize: 7,
                                              size: 6,
                                              color: Colors.grey[100],
                                              activeColor: Colors.grey[600]),
                                        ),
                                        scrollDirection: Axis.horizontal,
                                        itemCount: snapshot.data.length ?? 0,
                                        itemBuilder: (context, index) {
                                          final Map image =
                                              snapshot.data[index];
                                          return Padding(
                                              padding:
                                                  const EdgeInsets.all(0.0),
                                              child: Column(
                                                children: [
                                                  Card(
                                                    child: SizedBox(
                                                      height: 200,
                                                      child: SizedBox(
                                                        height: MediaQuery.of(
                                                                context)
                                                            .size
                                                            .height,
                                                        width: MediaQuery.of(
                                                                context)
                                                            .size
                                                            .width,
                                                        child: ClipRRect(
                                                          borderRadius:
                                                              const BorderRadius
                                                                      .only(
                                                                  topLeft: Radius
                                                                      .circular(
                                                                          15),
                                                                  topRight: Radius
                                                                      .circular(
                                                                          15)),
                                                          child:
                                                              CachedNetworkImage(
                                                            fit: BoxFit.cover,
                                                            imageUrl:
                                                                image['url'],
                                                            placeholder: (context,
                                                                    url) =>
                                                                Image.asset(
                                                                    'assets/placeholder.jpg'),
                                                            errorWidget: (context,
                                                                    url,
                                                                    error) =>
                                                                const Icon(Icons
                                                                    .error),
                                                          ),
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ));
                                        });
                                  }),
                            ),
                          ),
</code>```

Please let me know if you need to see more code.

Any help is appreciated!

Body:
In a class I took he said pickedImages is looping, so I'm not sure if the problem is in uploadMultipleImages function where pickedImages is used or if the problem is in the function loadImages.

The functions are a bit beyond my understanding. What I'm trying to do is have each card show different images. I'm not sure what needs to change.

Functions:

  File? imageFile;
  String? fileName;

  Future<void> uploadMultipleImages() async {
    final picker = ImagePicker();
    final List<XFile>? pickedImages = await picker.pickMultiImage();
    if (pickedImages == null) {
      return null;
    }
    setState(() {
      loading = true;
    });
    await Future.forEach(pickedImages, (XFile image) async {
      fileName = image.name;
      imageFile = File(image.path);

      try {
        await firebaseStorage.ref(fileName).putFile(imageFile!);
      } on FirebaseException catch (e) {
        print(e);
      }
    });

    setState(() {
      loading = false;
    });

    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("All images uploaded successfully")));
  }

  Future<List> loadImages() async {
    List<Map> files = [];
    final ListResult result = await firebaseStorage.ref().listAll();
    final List<Reference> allFiles = result.items;
    await Future.forEach(allFiles, (Reference file) async {
      final String fileUrl = await file.getDownloadURL();
      files.add({
        "url": fileUrl,
        "path": file.fullPath,
      });
    });
    print(files);
    return files;
  }

Here I use loadImages:

 body: StreamBuilder(
          stream: FirebaseFirestore.instance
              .collection("notes")
              .where('userId', isEqualTo: user.uid)
              .snapshots(),
          builder: (context, AsyncSnapshot streamSnapshot) {
            if (streamSnapshot.hasData) {
              if (streamSnapshot.data.docs.length > 0) {
                return ListView.builder(
                    itemCount: streamSnapshot.data.docs.length ?? 0,
                    itemBuilder: (context, index) {
                      final NoteModel note =
                          NoteModel.fromJson(streamSnapshot.data.docs[index]);
                      return Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(15.0),
                        ),
                        margin:
                            const EdgeInsets.only(top: 18, left: 15, right: 15),
                        child: Column(children: [
                          SizedBox(
                            height: 210,
                            child: Expanded(
                              child: FutureBuilder(
                                  future: loadImages(),
                                  builder: (context, AsyncSnapshot snapshot) {
                                    if (snapshot.connectionState ==
                                        ConnectionState.waiting) {
                                      return const Center(
                                        child: CircularProgressIndicator(),
                                      );
                                    }
                                    return Swiper(
                                        loop: false,
                                        pagination: SwiperPagination(
                                          alignment: Alignment.bottomRight,
                                          builder: DotSwiperPaginationBuilder(
                                              activeSize: 7,
                                              size: 6,
                                              color: Colors.grey[100],
                                              activeColor: Colors.grey[600]),
                                        ),
                                        scrollDirection: Axis.horizontal,
                                        itemCount: snapshot.data.length ?? 0,
                                        itemBuilder: (context, index) {
                                          final Map image =
                                              snapshot.data[index];
                                          return Padding(
                                              padding:
                                                  const EdgeInsets.all(0.0),
                                              child: Column(
                                                children: [
                                                  Card(
                                                    child: SizedBox(
                                                      height: 200,
                                                      child: SizedBox(
                                                        height: MediaQuery.of(
                                                                context)
                                                            .size
                                                            .height,
                                                        width: MediaQuery.of(
                                                                context)
                                                            .size
                                                            .width,
                                                        child: ClipRRect(
                                                          borderRadius:
                                                              const BorderRadius
                                                                      .only(
                                                                  topLeft: Radius
                                                                      .circular(
                                                                          15),
                                                                  topRight: Radius
                                                                      .circular(
                                                                          15)),
                                                          child:
                                                              CachedNetworkImage(
                                                            fit: BoxFit.cover,
                                                            imageUrl:
                                                                image['url'],
                                                            placeholder: (context,
                                                                    url) =>
                                                                Image.asset(
                                                                    'assets/placeholder.jpg'),
                                                            errorWidget: (context,
                                                                    url,
                                                                    error) =>
                                                                const Icon(Icons
                                                                    .error),
                                                          ),
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ));
                                        });
                                  }),
                            ),
                          ),

Please let me know if you need to see more code.

Any help is appreciated!


问:
How to use IIFE in Storybook.js MDX?
How can I write a function that is immediately executed when using MDX in Storybook.js?

Simply providing call:

```<code>{(function () {
  console.log("Hello");
})()}
</code>```

... causes it to appear as text in the body of the document, instead of executing.

What is the best method to define a function in this way?

Title: How to use IIFE in Storybook.js MDX?

Body:
How can I write a function that is immediately executed when using MDX in Storybook.js?

Simply providing call:

{(function () {
  console.log("Hello");
})()}

... causes it to appear as text in the body of the document, instead of executing.

What is the best method to define a function in this way?


问:
Is stelligent/config-lint still functional? Couldn't lint simple YAML type files
Defining the following rule:

```<code>version: 1
description: Rules for ArgoCD-Apps Helm Chart
type: YAML
files:
  - "*.yaml"
resources:
  - type: project
    key: argocd-apps.projects[]
    id: name
</code>```

And it scans a file that contains:

```<code>argocd-apps:
  projects:
    - name: my-project
      description: "My Project"
      sourceRepos:
        - 'https://xxx.xx.yy/my-git-repo.git'
      destinations:
        - namespace: 'my-project'
          server: '*'
          name: '*'
      clusterResourceWhitelist:
        - group: '*'
          kind: '*'
</code>```

But didn't find any resources:

```<code>Found variables []
{
  "FilesScanned": [
    "y/x/Chart.yaml",
    "y/z/values.yaml",
    "y/w/Chart.yaml",
    "y/x/values.yaml"
  ],
  "Violations": [],
  "ResourcesScanned": []
}
</code>```

But couldn't load any resources. Spent some time on this, and noticed this project was last committed 2 years ago... Have I missed something?

Body:
Defining the following rule:

version: 1
description: Rules for ArgoCD-Apps Helm Chart
type: YAML
files:
  - "*.yaml"
resources:
  - type: project
    key: argocd-apps.projects[]
    id: name

And it scans a file that contains:

argocd-apps:
  projects:
    - name: my-project
      description: "My Project"
      sourceRepos:
        - 'https://xxx.xx.yy/my-git-repo.git'
      destinations:
        - namespace: 'my-project'
          server: '*'
          name: '*'
      clusterResourceWhitelist:
        - group: '*'
          kind: '*'

But didn't find any resources:

Found variables []
{
  "FilesScanned": [
    "y/x/Chart.yaml",
    "y/z/values.yaml",
    "y/w/Chart.yaml",
    "y/x/values.yaml"
  ],
  "Violations": [],
  "ResourcesScanned": []
}

But couldn't load any resources. Spent some time on this, and noticed this project was last committed 2 years ago... Have I missed something?


问:
MongoDB Charts date() not updating
I am using MongoDB charts and one of parameter I am trying to calculate is the day difference between a customer's PO date and today's date.

What I did was to add a calculated field called Today Date with the following expression:

```<code>{$toDate:Date()}
</code>```

and then I have a separate calculated field called Days Difference with the following expression:

```<code>{$dateDiff:{
      endDate: "$Delivery Date",
      startDate: "$Today Date",
      unit: "day"}
}

</code>```

For some reason, it only works the first time I tried it and the Today Date calculated field is always stuck at the first date that I have saved the field. Are there any ways to update this calculated field to always measure today's date?

I tried this also but to no avail

```<code>{$dateDiff:{
      endDate: "$Delivery Date",
      startDate: {$toDate: Date()},
      unit: "day"}
}

</code>```

Title: MongoDB Charts date() not updating

Body:
I am using MongoDB charts and one of parameter I am trying to calculate is the day difference between a customer's PO date and today's date.

What I did was to add a calculated field called Today Date with the following expression:

{$toDate:Date()}

and then I have a separate calculated field called Days Difference with the following expression:

{$dateDiff:{
      endDate: "$Delivery Date",
      startDate: "$Today Date",
      unit: "day"}
}

For some reason, it only works the first time I tried it and the Today Date calculated field is always stuck at the first date that I have saved the field. Are there any ways to update this calculated field to always measure today's date?

I tried this also but to no avail

{$dateDiff:{
      endDate: "$Delivery Date",
      startDate: {$toDate: Date()},
      unit: "day"}
}


问:
Apache server - multiple domains to forward to single hosted multi-tenant application
Is it possible with Apache:

```
domain1.com forward to http://localhost:8080/multitenantApp/client1
domain2.com forward to http://localhost:8080/multitenantApp/client2
domain3.com forward to http://localhost:8080/multitenantApp/client3
domain4.com forward to http://localhost:8080/multitenantApp/client4

etc----
```

If someone has clue please do share.

Body:
Is it possible with Apache:

domain1.com forward to http://localhost:8080/multitenantApp/client1
domain2.com forward to http://localhost:8080/multitenantApp/client2
domain3.com forward to http://localhost:8080/multitenantApp/client3
domain4.com forward to http://localhost:8080/multitenantApp/client4

etc----

If someone has clue please do share.


问:
Having trouble using howler
The music plays and then does not pause. Also, when I play the music instead of playing from start it plays double. Here is the screenshot of the page

below I am attaching the code, please can someone help me use howler correctly?

p.s ignore the backend code get request

```<code>import React, { useState } from "react";
import "./LikedSongs.css";
import Sidebar from "./Sidebar";
import { useEffect } from "react";
import axios from "axios";
import { Howl } from "howler";

function Song(props) {
  function handleSong(e) {
    e.preventDefault();
    props.handleSongClick(props.song);
  }

  return (
    <div>
      <li className="songItem" onClick={handleSong}>
        <span>{props.song.count}</span>
        <h5>
          {props.song.songname}
          <div className="subtitle">{props.song.artistname}</div>
        </h5>
        <div className="album">{props.song.Albumname}</div>
      </li>
    </div>
  );
}

const initialValueOfSongs = [
  {
    songname: "On my way",
    artistname: "Alan Walker",
    Albumname: "On my way",
    songlink:
      "https://dl.dropboxusercontent.com/s/rfz0s49idtk3rhl/Canon%20In%20D.mp3?dl=0",
  },
  {
    songname: "Aitebar",
    artistname: "Abdullah Qureshi",
    Albumname: "Aitebar",
  },
  {
    songname: "On my way",
    artistname: "Alan Walker",
    Albumname: "On my way",
  },
  {
    songname: "On my way",
    artistname: "Alan Walker",
    Albumname: "On my way",
  },
  {
    songname: "On my way",
    artistname: "Alan Walker",
    Albumname: "On my way",
  },
];

export default function LikedSongs() {
  const [selectedSong, setSelectedSong] = useState(initialValueOfSongs[0]);
  const [songs, setSongs] = useState(initialValueOfSongs);
  const [play, setPlay] = useState(require("./playbutton.png"));

  var src = selectedSong.songlink;
  var sound = new Howl({
    src,
    html5: true,
    preload: true,
    loop: true,
  });

  useEffect(() => {
    fetchdata();
  }, []);

  const callMySound = () => {
    sound.play();
    setPlay(require("./pause.png"));
  };

  const handleplay= ()=>{
    if(play===require("./pause.png")){
      sound.pause()
      setPlay(require("./playbutton.png"))
    }
    else{
      sound.play()
      setPlay(require("./pause.png"))
    }
  }

  async function fetchdata() {
    const response = await axios.get("http://localhost:5000/songs");
    const songs = response.data;
    var count = 1;
    songs.forEach((song) => {
      song["count"] = count;
      count++;
    });
    setSongs(songs);
  }

  const handleSongClick = (song) => {
    setSelectedSong(song);
    callMySound();
    console.log(sound);
  };

  return (
    <div className="songsbody">
      <Sidebar />
      <div className="listsongs">
        <li className="songItem top">
          <span>#</span>
          <h5>Song name</h5>
          <div className="album">Album name</div>
        </li>
        {songs &&
          songs.map((song) => (
            <Song
              key={song.count}
              song={song}
              handleSongClick={handleSongClick}
            />
          ))}
      </div>
      <div className="footer">
        <div className="footer_left">
          <img
            className="footer_albumLogo"
            src="https://i1.sndcdn.com/artworks-aHWeKTP05eBf-0-t500x500.jpg"
            alt=""
          />

          <div className="footer_songInfo">
            <h6>{selectedSong.songname}</h6>
            <p>{selectedSong.artistname}</p>
          </div>
        </div>

        <div className="footer_center">
          <img className="shuffle" src={require("./shuffle.png")} alt="" />
          <img className="back" src={require("./back.png")} alt="" />
          <img className="playbutton" src={play} alt="" onClick={handleplay}/>
          {/* <img className="pause" src={require("./pause.png")} alt=""/> */}
          <img className="next" src={require("./next.png")} alt="" />
          <img className="repeat" src={require("./repeat.png")} alt="" />
        </div>

        <div className="footer_right">
          <img className="volume" src={require("./volume.png")} alt="" />
        </div>
      </div>
    </div>
  );
}

</code>```

I tried a bunch of functions and methods, making the new howl global etc, but doesnt work correctly. Also, I am new to reactjs, hence may not know the correct way to do this.

Title: Having trouble using howler

Body:
The music plays and then does not pause. Also, when I play the music instead of playing from start it plays double. Here is the screenshot of the page

below I am attaching the code, please can someone help me use howler correctly?

p.s ignore the backend code get request

import React, { useState } from "react";
import "./LikedSongs.css";
import Sidebar from "./Sidebar";
import { useEffect } from "react";
import axios from "axios";
import { Howl } from "howler";

function Song(props) {
  function handleSong(e) {
    e.preventDefault();
    props.handleSongClick(props.song);
  }

  return (

        {props.song.count}

          {props.song.songname}

{props.song.artistname}

{props.song.Albumname}

  );
}

const initialValueOfSongs = [
  {
    songname: "On my way",
    artistname: "Alan Walker",
    Albumname: "On my way",
    songlink:
      "https://dl.dropboxusercontent.com/s/rfz0s49idtk3rhl/Canon%20In%20D.mp3?dl=0",
  },
  {
    songname: "Aitebar",
    artistname: "Abdullah Qureshi",
    Albumname: "Aitebar",
  },
  {
    songname: "On my way",
    artistname: "Alan Walker",
    Albumname: "On my way",
  },
  {
    songname: "On my way",
    artistname: "Alan Walker",
    Albumname: "On my way",
  },
  {
    songname: "On my way",
    artistname: "Alan Walker",
    Albumname: "On my way",
  },
];

export default function LikedSongs() {
  const [selectedSong, setSelectedSong] = useState(initialValueOfSongs[0]);
  const [songs, setSongs] = useState(initialValueOfSongs);
  const [play, setPlay] = useState(require("./playbutton.png"));

  var src = selectedSong.songlink;
  var sound = new Howl({
    src,
    html5: true,
    preload: true,
    loop: true,
  });

  useEffect(() => {
    fetchdata();
  }, []);

  const callMySound = () => {
    sound.play();
    setPlay(require("./pause.png"));
  };

  const handleplay= ()=>{
    if(play===require("./pause.png")){
      sound.pause()
      setPlay(require("./playbutton.png"))
    }
    else{
      sound.play()
      setPlay(require("./pause.png"))
    }
  }

  async function fetchdata() {
    const response = await axios.get("http://localhost:5000/songs");
    const songs = response.data;
    var count = 1;
    songs.forEach((song) => {
      song["count"] = count;
      count++;
    });
    setSongs(songs);
  }

  const handleSongClick = (song) => {
    setSelectedSong(song);
    callMySound();
    console.log(sound);
  };

  return (

      <Sidebar />

          #

Song name

Album name

        {songs &&
          songs.map((song) => (
            <Song
              key={song.count}
              song={song}
              handleSongClick={handleSongClick}
            />
          ))}

{selectedSong.songname}

{selectedSong.artistname}

          {/*  */}

  );
}

I tried a bunch of functions and methods, making the new howl global etc, but doesnt work correctly. Also, I am new to reactjs, hence may not know the correct way to do this.


问:
Align-items-stretch Bootstrap 5 cards not working
I'm trying to create a series of Bootstrap 5 cards based on variable data using a Jinja for loop. When they plot on the site, they are not uniform height as I'd hoped. Is there a way to fix this code so that each card on each row appears as the same height? It looks correct on the widest page setting, but shrinking causes the alignment to stop working.

    {% for emergency in active_emergencies %}

{{emergency.Emergency.emergency_name}}

    {% endfor %}

```

I've tried fiddling with the Bootstrap classes that would (ostensibly) set this to be the same size. I can't figure out why it isn't working.

Body:
I'm trying to create a series of Bootstrap 5 cards based on variable data using a Jinja for loop. When they plot on the site, they are not uniform height as I'd hoped. Is there a way to fix this code so that each card on each row appears as the same height? It looks correct on the widest page setting, but shrinking causes the alignment to stop working.

    {% for emergency in active_emergencies %}

{{emergency.Emergency.emergency_name}}

    {% endfor %}

I've tried fiddling with the Bootstrap classes that would (ostensibly) set this to be the same size. I can't figure out why it isn't working.


问:
Regex to match comments in an INF file
While designing a Regex to match comments in an INF file ( its formal syntax definition is here ), I came across an insurmountable (to me) problem where a mismatch is occurring when an opening left square bracket is wrongly paired with a double quote (dquote).

Here is a brief description of the comment syntax in the INF file:

Note ; A comment starts with a semicolon and continues untill the EOL

A string begins with an odd dquote "and terminates at the next dquote" ...or at the EOL.

Unbalanced dquotes "are implicitly closed by the EOL .i.e. ;this is not a comment.

A semicolon ";inside a string" loses its power to initiate a comment.

...however, an even number of dquotes "" before the semicolon ;does not disable its power to
initiate a comment

A string can contain a dquote when such dquote is escaped with another dquote, in other words - "doubled dquote""."

Inside a string "the semicolon ; a backslash \ and square brackets ][ are treated just like regular characters"

;From the comment-initiating semicolon to the EOL, the other semicolons; the line continuation backslash, the dquotes """ and square brackets ][ are treated just like regular characters. \

A semicolon [inside;] square brackets does not initiate a comment; but outside - it does.

A left square bracket [ before the semicolon ; disables its comment initiating function; too.

Neither nested nor unbalanced square brackets occur in the input unless they are inside a string.

The line continuation sequence (backslash+newline) does not work:

inside ;comments\

between the left square bracket [ and EOL \

between an unbalanced dquote and EOL "\

between balanced dquotes"\

;nice try"

( unbalanced and nested square brackets do not occur in the input unless they are inside a string )

Here is my c# (.NET flavor) Regex to match the comments:

```<code>(?:^|(?<=\n))(?>(?:[^;""\[\n]*[""\[][^""\]\n]*[""\]])*)(?>[^;""\[\n;]*)(;.*?)(?:\n|$)
</code>```

See its simulation here (click "List" in the left panel) to get a list of matches.

From the text of the syntax description above, my Regex pattern generates the following matches denoted in green color:

However my Regex fails with the following input:

A semicolon [inside";] square brackets" does not initiate a comment; but outside - it does.

The expected match is at the second semicolon, but it matches at the first semicolon because the left square bracket is wrongly paired to the first dquote.

QUESTION: How to repair this Regex so only a right square bracket can pair&close a left square bracket ?

Title: Regex to match comments in an INF file

Body:
While designing a Regex to match comments in an INF file ( its formal syntax definition is here ), I came across an insurmountable (to me) problem where a mismatch is occurring when an opening left square bracket is wrongly paired with a double quote (dquote).

Here is a brief description of the comment syntax in the INF file:

Note ; A comment starts with a semicolon and continues untill the EOL

A string begins with an odd dquote "and terminates at the next dquote" ...or at the EOL.

Unbalanced dquotes "are implicitly closed by the EOL .i.e. ;this is not a comment.

A semicolon ";inside a string" loses its power to initiate a comment.

...however, an even number of dquotes "" before the semicolon ;does not disable its power to
initiate a comment

A string can contain a dquote when such dquote is escaped with another dquote, in other words - "doubled dquote""."

Inside a string "the semicolon ; a backslash \ and square brackets ][ are treated just like regular characters"

;From the comment-initiating semicolon to the EOL, the other semicolons; the line continuation backslash, the dquotes """ and square brackets ][ are treated just like regular characters. \

A semicolon [inside;] square brackets does not initiate a comment; but outside - it does.

A left square bracket [ before the semicolon ; disables its comment initiating function; too.

Neither nested nor unbalanced square brackets occur in the input unless they are inside a string.

The line continuation sequence (backslash+newline) does not work:

inside ;comments\

between the left square bracket [ and EOL \

between an unbalanced dquote and EOL "\

between balanced dquotes"\

;nice try"

( unbalanced and nested square brackets do not occur in the input unless they are inside a string )

Here is my c# (.NET flavor) Regex to match the comments:

(?:^|(?<=\n))(?>(?:[^;""\[\n]*[""\[][^""\]\n]*[""\]])*)(?>[^;""\[\n;]*)(;.*?)(?:\n|$)

See its simulation here (click "List" in the left panel) to get a list of matches.

From the text of the syntax description above, my Regex pattern generates the following matches denoted in green color:

However my Regex fails with the following input:

A semicolon [inside";] square brackets" does not initiate a comment; but outside - it does.

The expected match is at the second semicolon, but it matches at the first semicolon because the left square bracket is wrongly paired to the first dquote.

QUESTION: How to repair this Regex so only a right square bracket can pair&close a left square bracket ?


问:
Make div disappear when clicking anywhere outside of it?
I am trying to make my div element disappear when clicking anywhere out side of it. The div is created when clicking a path from my SVG element and is supposed to close and open a new one when clicking the another path in the SVG. I think I may have set this up wrong and have been trying to figure out the most effective way to get it working. The div that has been created will hold an X button that will close the div and reload the page to bring back the styling options. Would that be the best way to go about this because I am thinking that may not be the most efficient way to do this.

```<code>$(document).ready(function(){
    $("#SVGGraphic").load("/src/Areas-of-Focus.svg", function(event){
        $("#SVGGraphic svg").css("height", "1000", "width", "1000px");

        console.log("loaded successfully")

        $("path").on("click", function(evt) {
            var parsedStringArray = evt.target.id.split('_');
            var pathID = ("#" + (evt.target.id))
            console.log(parsedStringArray);
            areaOfFocusBody(parsedStringArray[0]);
            colorChanger(pathID);
        });
    })
})
</code>```
```<code>function colorChanger(pathName){
    $("path").css("filter", "opacity(25%)")
    $("circle").css("filter", "opacity(25%)")
    $(pathName).css("fill", "#f1562c")
    $(pathName).css("filter", "opacity(100%)")
}

function areaOfFocusBody(areaOfFocus) {
    $("#DOM").append(`
    <div class="textbox" id="menucontainer">
        <span id="close" onclick="this.parentNode.remove(); location.reload(); return false;" class="btn btn-default large">
            <img src="/src/Esc X.svg" height="33" width="33"></img>
        </span>
        <h2>${focusCard[areaOfFocus]?.title ?? 'none'}</h2>
        <div class="card-body" id="card-div">
            <p class="card-body" style="padding: 1rem">${focusCard[areaOfFocus]?.body ?? 'none'}</p>
            <div class="container">
                <div class="row">
                    <div class="col text-center" style="padding-bottom: 1rem;">
                        <a target="_blank" rel="noopener noreferrer" href="${focusCard[areaOfFocus]?.url ?? 'none'}">
                            <button class="btn btn-primary" role="button">
                                Show Employees in this Section <img src="/src/opens-new-tab-arrow.svg" height="20">
                            </button>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>`)
}
</code>```

Before Click Event
After Click Event

Body:
I am trying to make my div element disappear when clicking anywhere out side of it. The div is created when clicking a path from my SVG element and is supposed to close and open a new one when clicking the another path in the SVG. I think I may have set this up wrong and have been trying to figure out the most effective way to get it working. The div that has been created will hold an X button that will close the div and reload the page to bring back the styling options. Would that be the best way to go about this because I am thinking that may not be the most efficient way to do this.

$(document).ready(function(){
    $("#SVGGraphic").load("/src/Areas-of-Focus.svg", function(event){
        $("#SVGGraphic svg").css("height", "1000", "width", "1000px");

        console.log("loaded successfully")

        $("path").on("click", function(evt) {
            var parsedStringArray = evt.target.id.split('_');
            var pathID = ("#" + (evt.target.id))
            console.log(parsedStringArray);
            areaOfFocusBody(parsedStringArray[0]);
            colorChanger(pathID);
        });
    })
})

function colorChanger(pathName){
    $("path").css("filter", "opacity(25%)")
    $("circle").css("filter", "opacity(25%)")
    $(pathName).css("fill", "#f1562c")
    $(pathName).css("filter", "opacity(100%)")
}

function areaOfFocusBody(areaOfFocus) {
    $("#DOM").append(`

${focusCard[areaOfFocus]?.title ?? 'none'}

${focusCard[areaOfFocus]?.body ?? 'none'}

                            <button class="btn btn-primary" role="button">
                                Show Employees in this Section
                            </button>

`)
}

Before Click Event
After Click Event


问:
How to close the MS Access auto dialer after 5 seconds
When I use the MS Access Auto Dialer it opens the form, but a user must press the "Hang UP" button to close the form.  How can I have the form close after a 5 second delay?

```<code>Sub CallCandidate(PhoneNumber As String, HangUpDelay As Integer)
    On Error GoTo Err_CallCandidate

    Application.Run "utility.wlib_AutoDial", PhoneNumber

Exit_CallCandidate:
    Exit Sub

Err_CallCandidate:
    MsgBox Err.Description
    Resume Exit_CallCandidate

End Sub
</code>```

I would like the passed integer "HangUpDelay" to be the delay time before it hangs up and closes the form; so, in essence, automatically executing the "Hang Up" button being pressed.

Body:
When I use the MS Access Auto Dialer it opens the form, but a user must press the "Hang UP" button to close the form.  How can I have the form close after a 5 second delay?

Sub CallCandidate(PhoneNumber As String, HangUpDelay As Integer)
    On Error GoTo Err_CallCandidate

    Application.Run "utility.wlib_AutoDial", PhoneNumber

Exit_CallCandidate:
    Exit Sub

Err_CallCandidate:
    MsgBox Err.Description
    Resume Exit_CallCandidate

End Sub

I would like the passed integer "HangUpDelay" to be the delay time before it hangs up and closes the form; so, in essence, automatically executing the "Hang Up" button being pressed.


问:
How do I get multiple Modal instances to properly function in one page?
I'm creating a team page with modal popups for bio.

I'm using Hugo with Babel JS as the framework. There is no bootstrap on this project.

HTML

```<code><div class="team-ui">
{{ with .Params.executive_team }}
   {{ range . }}
      {{ partial "components/modalTeammate.html" . }}
   {{ end }}
{{ end }}
</div>

{{ with .Params.executive_team }}
   {{ range . }}
      {{ partial "components/modalTeammateBio.html" . }}
   {{ end }}
{{ end }}
</code>```

modalTeammate.html

```<code><div class="teammate-card trigger" data-id="#myBio-{{ .modal_id }}" data-toggle="modal" data-target="myBio-{{ .modal_id }}" id="trigger">
    <img src="{{ if .img_overwrite }}/uploads/headshot-{{ .img_overwrite }}.png{{ else }}/uploads/headshot-{{ .name }}.png{{ end }}" alt="{{ .name }} | {{ .job_title }}" loading="lazy" class="teammate-img">
    <p class="teammate-name">{{ .name }}</p>
    <p class="teammate-jobtitle">{{ .job_title }}</p>
</div>
</code>```

modalTeammateBio.html

```<code><div class="modal myBio-{{ .modal_id }}" tabindex="-1" role="dialog" aria-hidden="true" id="myBio-{{ .modal_id }}">
    <div class="modal-content">
        <div class="modal-body">
            <div class="bio-box">
                <div class="bio-box-sidebar">
                    <img src="{{ if .img_overwrite }}/uploads/headshot-{{ .img_overwrite }}.png{{ else }}/uploads/headshot-{{ .name }}.png{{ end }}" alt="{{ .name }} | {{ .job_title }}" loading="lazy" class="teammate-img">
                    <p class="teammate-name">{{ .name }}</p>
                    <p class="teammate-jobtitle">{{ if .job_title_long }}{{ .job_title_long }}{{ else }}{{ .job_title }}{{ end }}</p>
                </div>
                <div class="bio-box-content">
                {{ with .bio }}
                    {{ range . }}
                    <p class="has-margin-bottom-half">{{ .p }}</p>
                    {{ end }}
                {{ end }}
                </div>
                <button class="modal-close is-large" aria-label="close"></button>
            </div>
        </div>
    </div>
</div>
</code>```

Current JS

```<code>var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var videoID = trigger.getAttribute('data-id');
var closeButton = document.querySelector(".modal-close");

// YouTube Player API Reference
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: videoID
    });
}

function toggleModal(e) {
    if (!modal.classList.contains("is-active")) {
        modal.classList.add("is-active");
        player.playVideo()
    }
    else {
        modal.classList.remove("is-active");
        player.pauseVideo()
    }
}

function windowOnClick(e) {
    if (e.target === modal) {
        toggleModal();
    }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
</code>```

I know I'm missing something, but I'm not sure what else I can do.

I'm using this oringal code as an example and a base.

```<code><a href="#" data-id="{{.Get "youtube"}}" class="button is-warning trigger" data-toggle="modal" id="trigger">Watch the Video</a>
<div class="modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-content">
        <div class="modal-body" id="player">
            Content
        </div>
    </div>
    <button class="modal-close is-large" aria-label="close"></button>
</div>

<script src="/js/modal.js"></script>
</code>```

Body:
I'm creating a team page with modal popups for bio.

I'm using Hugo with Babel JS as the framework. There is no bootstrap on this project.

HTML

{{ with .Params.executive_team }}
   {{ range . }}
      {{ partial "components/modalTeammate.html" . }}
   {{ end }}
{{ end }}

{{ with .Params.executive_team }}
   {{ range . }}
      {{ partial "components/modalTeammateBio.html" . }}
   {{ end }}
{{ end }}

modalTeammate.html

{{ .name }}

{{ .job_title }}

modalTeammateBio.html

{{ .name }}

{{ if .job_title_long }}{{ .job_title_long }}{{ else }}{{ .job_title }}{{ end }}

                {{ with .bio }}
                    {{ range . }}

{{ .p }}

                    {{ end }}
                {{ end }}

                <button class="modal-close is-large" aria-label="close"></button>

Current JS

var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var videoID = trigger.getAttribute('data-id');
var closeButton = document.querySelector(".modal-close");

// YouTube Player API Reference
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: videoID
    });
}

function toggleModal(e) {
    if (!modal.classList.contains("is-active")) {
        modal.classList.add("is-active");
        player.playVideo()
    }
    else {
        modal.classList.remove("is-active");
        player.pauseVideo()
    }
}

function windowOnClick(e) {
    if (e.target === modal) {
        toggleModal();
    }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);

I know I'm missing something, but I'm not sure what else I can do.

I'm using this oringal code as an example and a base.

Watch the Video

            Content

    <button class="modal-close is-large" aria-label="close"></button>


问:
Wordpress plugin with custom post type-- how use templates from the plugin for both single post and front page views
I've written a simple Wordpress plugin that creates a custom post type (called a "river", it displays images of book covers).

I originally kept the templates for the rivers in my main theme file and followed the standard hierarchy by making a template named single-river.php, which works. I also showed the rivers interspersed with regular posts on the front page of my website by putting this inside the loop in index.php:

```<code>if (get_post_type() == 'post') {
    get_template_part( 'template-parts/content');
elseif (get_post_type() == 'river' {
    get_template_part( 'template-parts/river');
}
</code>```

I'm adding some features to the plugin, and as part of that i'd like to move all the river-related code inside the plugin instead of having it scattered around.

Adding this code to my plugin works for displaying a single river on its own page:

```<code>add_filter( 'template_include', 'river_template', 99);

function river_template($template) {
    if (get_post_type($post) == 'river' ) {
        $file_name = 'single-river.php';
        $template = dirname( __FILE__ ) . '/template/' . $file_name;
    }
    return $template;
}
</code>```

What's the right way to specify a template part for rivers displayed on the front page/other list pages that display multiple posts, if i'm not using get_template_part in the loop? I've tried is_front_page() in the template_include filter without success and I'm not sure why that doesn't work.

Body:
I've written a simple Wordpress plugin that creates a custom post type (called a "river", it displays images of book covers).

I originally kept the templates for the rivers in my main theme file and followed the standard hierarchy by making a template named single-river.php, which works. I also showed the rivers interspersed with regular posts on the front page of my website by putting this inside the loop in index.php:

if (get_post_type() == 'post') {
    get_template_part( 'template-parts/content');
elseif (get_post_type() == 'river' {
    get_template_part( 'template-parts/river');
}

I'm adding some features to the plugin, and as part of that i'd like to move all the river-related code inside the plugin instead of having it scattered around.

Adding this code to my plugin works for displaying a single river on its own page:

add_filter( 'template_include', 'river_template', 99);

function river_template($template) {
    if (get_post_type($post) == 'river' ) {
        $file_name = 'single-river.php';
        $template = dirname( __FILE__ ) . '/template/' . $file_name;
    }
    return $template;
}

What's the right way to specify a template part for rivers displayed on the front page/other list pages that display multiple posts, if i'm not using get_template_part in the loop? I've tried is_front_page() in the template_include filter without success and I'm not sure why that doesn't work.


问:
How to speed up the check for duplicate rows when using the Python library dataset?
How can the is_duplicate_free(table) function change, so it runs significantly faster? It performs poorly on life-sized tables. Currently, the following test program takes 45 seconds on my workstation.

I know faster ways on some specific database engines, but despite rereading the documentation [https://dataset.readthedocs.io/en/latest/] and googling, I can't find a database-agnostic speed-up for the dataset library.

```<code>import dataset      # https://dataset.readthedocs.io
import random
import string
import time

def is_duplicate_free(table) -> bool:
    """ Is the table free of duplicates, True or False? """
    # TODO Speed up; perhaps use the database engine to count.
    # TODO With the dataset library currently, we use SQLite and PostgreSQL, ideally, remain database agnostic.
    # TODO Be compatible with current versions of Python 3.
    count = 0
    columns = table.columns
    columns.remove('id')    # Ignore the automatic serial id. TODO Also, cope none or some other primary key.
    for _row in table.distinct(*columns):
        count += 1
    return count == len(table)

def main() -> None:
    start_time = time.time()

    db = dataset.connect(f"sqlite:///database.db")

    # create a table or clear it if it already exists
    table = db.create_table('table')
    columns = [*string.ascii_lowercase]
    table.delete()
    assert is_duplicate_free(table)

    # insert unique rows
    row = [random.randint(0, 9) for _ in range(len(columns))]
    for _ in range(1000):
        row[random.randint(0, len(columns) - 1)] += 1
        table.insert(dict(zip(columns, row)))
        assert is_duplicate_free(table)

    # insert a duplicate row
    table.insert(dict(zip(columns, row)))
    assert not is_duplicate_free(table)

    # insert more unique rows
    row = [random.randint(0, 9) for _ in range(len(columns))]
    for _ in range(500):
        row[random.randint(0, len(columns) - 1)] += 1
        table.insert(dict(zip(columns, row)))
        assert not is_duplicate_free(table)

    db.close()

    print (f"elapsed time: {time.time() - start_time:.2f} seconds")

if __name__ == "__main__":
    main()

</code>```

Body:
How can the is_duplicate_free(table) function change, so it runs significantly faster? It performs poorly on life-sized tables. Currently, the following test program takes 45 seconds on my workstation.

I know faster ways on some specific database engines, but despite rereading the documentation [https://dataset.readthedocs.io/en/latest/] and googling, I can't find a database-agnostic speed-up for the dataset library.

import dataset      # https://dataset.readthedocs.io
import random
import string
import time

def is_duplicate_free(table) -> bool:
    """ Is the table free of duplicates, True or False? """
    # TODO Speed up; perhaps use the database engine to count.
    # TODO With the dataset library currently, we use SQLite and PostgreSQL, ideally, remain database agnostic.
    # TODO Be compatible with current versions of Python 3.
    count = 0
    columns = table.columns
    columns.remove('id')    # Ignore the automatic serial id. TODO Also, cope none or some other primary key.
    for _row in table.distinct(*columns):
        count += 1
    return count == len(table)

def main() -> None:
    start_time = time.time()

    db = dataset.connect(f"sqlite:///database.db")

    # create a table or clear it if it already exists
    table = db.create_table('table')
    columns = [*string.ascii_lowercase]
    table.delete()
    assert is_duplicate_free(table)

    # insert unique rows
    row = [random.randint(0, 9) for _ in range(len(columns))]
    for _ in range(1000):
        row[random.randint(0, len(columns) - 1)] += 1
        table.insert(dict(zip(columns, row)))
        assert is_duplicate_free(table)

    # insert a duplicate row
    table.insert(dict(zip(columns, row)))
    assert not is_duplicate_free(table)

    # insert more unique rows
    row = [random.randint(0, 9) for _ in range(len(columns))]
    for _ in range(500):
        row[random.randint(0, len(columns) - 1)] += 1
        table.insert(dict(zip(columns, row)))
        assert not is_duplicate_free(table)

    db.close()

    print (f"elapsed time: {time.time() - start_time:.2f} seconds")

if __name__ == "__main__":
    main()


问:
How to Strip 2D Numpy Arrays with Try Exception Methods in python
Inside a function name Strip_array() I have a np array (4 * 5) like bellows. Here condition is I need to apply try and exception methods inside function if my input np array dimensions less than (3 * 3)
it will call exceptions methods an shows a error message. So condition is minimum np array size would be (3 * 3).

A Sample array

```<code>array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
</code>```

Then, Output would be like last 2 columns

Output-

```<code>array([[3, 4],
       [8, 9],
       [13, 14],
       [18, 19]])
</code>```

Body:
Inside a function name Strip_array() I have a np array (4 * 5) like bellows. Here condition is I need to apply try and exception methods inside function if my input np array dimensions less than (3 * 3)
it will call exceptions methods an shows a error message. So condition is minimum np array size would be (3 * 3).

A Sample array

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

Then, Output would be like last 2 columns

Output-

array([[3, 4],
       [8, 9],
       [13, 14],
       [18, 19]])


问:
Error on Publish Quality Gate Result in Azure DevOps Release pipeline
In my particular case I have to run the sonar analysis in the release, I can’t do it in the pipeline because it depends on the environment.
I have been using sonar in azure devops for several years but always running sonar from the pipeline
In this very special case I have to run the sonar in the release and this is where the error occurs.

Error in: Publish Quality Gate Result:
##[error]The "path" argument must be of type string. Received type undefined

enter image description here

enter image description here

Run Code Analysis: no Warning and no error:
enter image description here

if i run it manually on my pc it works fine:

sonar-scanner.bat -D"sonar.projectKey=SQLAA" -D"sonar.sources=Develop" -D"sonar.host.url=https://sssss.ssss.uuuu" -D"sonar.login=nnnnnnnnnnnn" -D"sonar.sql.dialect=tsql" -D"sonar.language=sql" -D"sonar.exclusions=DefinitionName/**" -D"sonar.scm.disabled=true" -D"sonar.verbose=true"

I use standalone scanner

is a simple release
enter image description here
It was tried as seen in the images, but it gives an error


问:
How to find a row where a value in the cell matches a value in a different cell?
I have a large table of items. The first column of the table is part number - this might be fully numerical (e.g. 605042) or it could be alphanumeric (XD-5201). The user inputs the part number into the cells.

I have a VBA code where I want the user to be able to enter a part number into a separate cell, run the code, and the row in the table with that matching part number will be deleted. So firstly I need to identify the row in the table that match the input cell value.

```<code>Dim deletePartRow As Integer
Dim deletePartColumn As Integer
Dim deletePartNumber As String
Dim topRowDelete As Long

deletePartRow = 14     'Defines the input cell for the user
deletePartColumn = 14  'Defines the input cell for the user

deletePartNumber = Cells(deletePartRow, deletePartColumn)  'Defines variable with user input part number

topRowDelete = Range("C:C").Find(deletePartNumber).Row   'Define the row that contains the part number
</code>```

I would expect topRowDelete to return the Row where the matching part number is found, but instead I get a Run-time error 91: Object variable or With block variable not set.

What am I doing wrong?

Thanks

Body:
I have a large table of items. The first column of the table is part number - this might be fully numerical (e.g. 605042) or it could be alphanumeric (XD-5201). The user inputs the part number into the cells.

I have a VBA code where I want the user to be able to enter a part number into a separate cell, run the code, and the row in the table with that matching part number will be deleted. So firstly I need to identify the row in the table that match the input cell value.

Dim deletePartRow As Integer
Dim deletePartColumn As Integer
Dim deletePartNumber As String
Dim topRowDelete As Long

deletePartRow = 14     'Defines the input cell for the user
deletePartColumn = 14  'Defines the input cell for the user

deletePartNumber = Cells(deletePartRow, deletePartColumn)  'Defines variable with user input part number

topRowDelete = Range("C:C").Find(deletePartNumber).Row   'Define the row that contains the part number

I would expect topRowDelete to return the Row where the matching part number is found, but instead I get a Run-time error 91: Object variable or With block variable not set.

What am I doing wrong?

Thanks


问:
Gelf logging with docker-compose
I've googled the f out of this.

here is the log driver config for my docker container in the compose file

```<code>       driver: gelf
       options:
          gelf-address: "http://graylog:12201"
</code>```

I created a GELF HTTP input in the admin console.
I know that graylog is accessible at 12201, because if I ssh into a container and run

curl -X POST -H 'Content-Type: application/json' -d '{ "version": "1.1", "host": "example.org", "short_message": "A short message", "level": 5, "_some_info": "test" }' 'http://graylog:12201/gelf'

Then I can see the log message.

The problem is, it seems like I have to add the /gelf to the address, but docker complains if I try to do that. But no other curl commands work without it, and I can't seem to get it to work with TCP or UDP at all. So.... what am I doing wrong?

Title: Gelf logging with docker-compose

Body:
I've googled the f out of this.

here is the log driver config for my docker container in the compose file

       driver: gelf
       options:
          gelf-address: "http://graylog:12201"

I created a GELF HTTP input in the admin console.
I know that graylog is accessible at 12201, because if I ssh into a container and run

curl -X POST -H 'Content-Type: application/json' -d '{ "version": "1.1", "host": "example.org", "short_message": "A short message", "level": 5, "_some_info": "test" }' 'http://graylog:12201/gelf'

Then I can see the log message.

The problem is, it seems like I have to add the /gelf to the address, but docker complains if I try to do that. But no other curl commands work without it, and I can't seem to get it to work with TCP or UDP at all. So.... what am I doing wrong?


问:
URL rewrite http to https not working for WCF web application in IIS
I have added URL rewrite for Http to Https for website. But website has many web applications and URL rewriting is not working for web applications. It is showing 404 error

followed this url for http tp https https://www.ssl.com/how-to/redirect-http-to-https-with-windows-iis-10/

added rule to default website. but rule not working for web applications. How to apply rule to web applications too?

https://www.xyz1.com has url. I can see rule on web.config

https://www.xyz1.com/subsite/Testweb.svc - not working. rule not found in web.config