问:
Why is my Bitmap null when feeding through tensorflow pipeline?
Using an AR glass' API to get its camera frames to do object detection

I tried converting the frames ( Byte Buffer ) to a bitmap and feeding it into my object detection pipeline. I realised there was no detection going on and debugged to find my bitmap is being read as null. Is it possible to input the bytebuffer straight to the interpreter and do object detection? if not my byte is valid and tested just converting to bitmap returns a toast messafe that is invalid and null.

```<code>package com.example.jjsdkcameratest;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.nio.ByteBuffer;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.FileUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.widget.Button;

import com.example.jjsdkcameratest.ml.SsdMobilenetV11Metadata1;
import com.jorjin.jjsdk.camera.CameraManager;
import com.jorjin.jjsdk.camera.FrameListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.Toast;

import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.common.FileUtil;
import org.tensorflow.lite.support.image.ImageProcessor;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.image.ops.ResizeOp;
import org.tensorflow.lite.support.image.ImageProcessor;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends Activity {

    private CameraManager cameraManager;
    private SurfaceView cameraSurface;
    private Context context;
    private ImageView imageView;
    private SsdMobilenetV11Metadata1 model;
    private ImageProcessor imageProcessor;
    private Paint paint;
    private List<String> labels;
    private List<Integer> colors = Arrays.asList(Color.BLUE, Color.GREEN, Color.CYAN, Color.GRAY, Color.BLACK, Color.DKGRAY, Color.MAGENTA, Color.YELLOW, Color.RED);

    private FrameListener frameListener = (buffer, width, height, format) -> {

        // Access the data buffer of the previewing frame here
        byte[] bytes = buffer.array();
        if (bytes == null || bytes.length == 0) {
            Log.e("MainActivity", "Frame data is invalid or empty");
            Toast.makeText(context, "Error: Frame data not valid", Toast.LENGTH_SHORT).show();
            return;
        }

        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            if (bitmap == null) {
                Log.e("MainActivity", "Failed to decode frame data into a bitmap");
                Toast.makeText(context, "Error: Failed to decode frame data into a bitmap", Toast.LENGTH_SHORT).show();

            }

            // Creates inputs for reference.
        try {
            TensorImage image = TensorImage.fromBitmap(bitmap);
            image = imageProcessor.process(image);
            // Runs model inference and gets result.
            SsdMobilenetV11Metadata1.Outputs outputs = model.process(image);
            float[] locations = outputs.getLocationsAsTensorBuffer().getFloatArray();
            float[] classes = outputs.getClassesAsTensorBuffer().getFloatArray();
            float[] scores = outputs.getScoresAsTensorBuffer().getFloatArray();
            float[] numberOfDetections = outputs.getNumberOfDetectionsAsTensorBuffer().getFloatArray();

            Bitmap mutable = bitmap.copy(Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(mutable);

            int h = mutable.getHeight();
            int w = mutable.getWidth();

            paint.setTextSize(h/15f);
            paint.setStrokeWidth(h/85f);

            int x = 0;

            for (int index = 0; index < scores.length; index++) {
                float fl = scores[index];
                x = index;
                x *= 4;

                if (fl > 0.5) {
                    paint.setColor(colors.get(index));
                    paint.setStyle(Paint.Style.STROKE);
                    canvas.drawRect(new RectF(locations[x+1]*w, locations[x]*h, locations[x+3]*w, locations[x+2]*h), paint);
                    paint.setStyle(Paint.Style.FILL);
                    canvas.drawText(labels.get((int) classes[index]) + " " + Float.toString(fl), locations[x+1]*w, locations[x]*h, paint);
                }
            }
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }

        } catch (NullPointerException npe) {
            Log.e("MainActivity", "Null pointer exception occurred", npe);
            Toast.makeText(this, "Null pointer exception occurred", Toast.LENGTH_SHORT);
        }

    };

    public ImageView getImageView() {
        if (imageView == null) {
            imageView = findViewById(R.id.image_view);
        }
        return imageView;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            labels = FileUtil.loadLabels(this, "labels.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        context = this;
        getImageView();
        cameraSurface = findViewById(R.id.surface_camera);
        cameraManager = new CameraManager(context);
        cameraManager.addSurfaceHolder(cameraSurface.getHolder());
        cameraManager.setCameraFrameListener(frameListener);
        cameraManager.setResolutionIndex(0);
        cameraManager.startCamera(CameraManager.COLOR_FORMAT_RGBA);
        imageProcessor = new ImageProcessor.Builder().add(new ResizeOp(300, 300, ResizeOp.ResizeMethod.BILINEAR)).build();
        try {
            SsdMobilenetV11Metadata1 model = SsdMobilenetV11Metadata1.newInstance(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Releases model resources if no longer used.
        model.close();
        cameraManager.stopCamera();
    }
}

</code>```

Body:
Using an AR glass' API to get its camera frames to do object detection

I tried converting the frames ( Byte Buffer ) to a bitmap and feeding it into my object detection pipeline. I realised there was no detection going on and debugged to find my bitmap is being read as null. Is it possible to input the bytebuffer straight to the interpreter and do object detection? if not my byte is valid and tested just converting to bitmap returns a toast messafe that is invalid and null.

package com.example.jjsdkcameratest;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.nio.ByteBuffer;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.FileUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.widget.Button;

import com.example.jjsdkcameratest.ml.SsdMobilenetV11Metadata1;
import com.jorjin.jjsdk.camera.CameraManager;
import com.jorjin.jjsdk.camera.FrameListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.Toast;

import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.common.FileUtil;
import org.tensorflow.lite.support.image.ImageProcessor;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.image.ops.ResizeOp;
import org.tensorflow.lite.support.image.ImageProcessor;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends Activity {

    private CameraManager cameraManager;
    private SurfaceView cameraSurface;
    private Context context;
    private ImageView imageView;
    private SsdMobilenetV11Metadata1 model;
    private ImageProcessor imageProcessor;
    private Paint paint;
    private List<String> labels;
    private List<Integer> colors = Arrays.asList(Color.BLUE, Color.GREEN, Color.CYAN, Color.GRAY, Color.BLACK, Color.DKGRAY, Color.MAGENTA, Color.YELLOW, Color.RED);

    private FrameListener frameListener = (buffer, width, height, format) -> {

        // Access the data buffer of the previewing frame here
        byte[] bytes = buffer.array();
        if (bytes == null || bytes.length == 0) {
            Log.e("MainActivity", "Frame data is invalid or empty");
            Toast.makeText(context, "Error: Frame data not valid", Toast.LENGTH_SHORT).show();
            return;
        }

        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            if (bitmap == null) {
                Log.e("MainActivity", "Failed to decode frame data into a bitmap");
                Toast.makeText(context, "Error: Failed to decode frame data into a bitmap", Toast.LENGTH_SHORT).show();

            }

            // Creates inputs for reference.
        try {
            TensorImage image = TensorImage.fromBitmap(bitmap);
            image = imageProcessor.process(image);
            // Runs model inference and gets result.
            SsdMobilenetV11Metadata1.Outputs outputs = model.process(image);
            float[] locations = outputs.getLocationsAsTensorBuffer().getFloatArray();
            float[] classes = outputs.getClassesAsTensorBuffer().getFloatArray();
            float[] scores = outputs.getScoresAsTensorBuffer().getFloatArray();
            float[] numberOfDetections = outputs.getNumberOfDetectionsAsTensorBuffer().getFloatArray();

            Bitmap mutable = bitmap.copy(Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(mutable);

            int h = mutable.getHeight();
            int w = mutable.getWidth();

            paint.setTextSize(h/15f);
            paint.setStrokeWidth(h/85f);

            int x = 0;

            for (int index = 0; index < scores.length; index++) {
                float fl = scores[index];
                x = index;
                x *= 4;

                if (fl > 0.5) {
                    paint.setColor(colors.get(index));
                    paint.setStyle(Paint.Style.STROKE);
                    canvas.drawRect(new RectF(locations[x+1]*w, locations[x]*h, locations[x+3]*w, locations[x+2]*h), paint);
                    paint.setStyle(Paint.Style.FILL);
                    canvas.drawText(labels.get((int) classes[index]) + " " + Float.toString(fl), locations[x+1]*w, locations[x]*h, paint);
                }
            }
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }

        } catch (NullPointerException npe) {
            Log.e("MainActivity", "Null pointer exception occurred", npe);
            Toast.makeText(this, "Null pointer exception occurred", Toast.LENGTH_SHORT);
        }

    };

    public ImageView getImageView() {
        if (imageView == null) {
            imageView = findViewById(R.id.image_view);
        }
        return imageView;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            labels = FileUtil.loadLabels(this, "labels.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        context = this;
        getImageView();
        cameraSurface = findViewById(R.id.surface_camera);
        cameraManager = new CameraManager(context);
        cameraManager.addSurfaceHolder(cameraSurface.getHolder());
        cameraManager.setCameraFrameListener(frameListener);
        cameraManager.setResolutionIndex(0);
        cameraManager.startCamera(CameraManager.COLOR_FORMAT_RGBA);
        imageProcessor = new ImageProcessor.Builder().add(new ResizeOp(300, 300, ResizeOp.ResizeMethod.BILINEAR)).build();
        try {
            SsdMobilenetV11Metadata1 model = SsdMobilenetV11Metadata1.newInstance(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Releases model resources if no longer used.
        model.close();
        cameraManager.stopCamera();
    }
}


来源: stackexchange

问:
Searching for documents to get links
This script goes to a website, enters a name, and clicks search just fine. Once it gets through the initial search, I need to find all the documents that contain a certain word such as "deed", then find the link that goes with that "deed", then put the links inside a pdf, and save the file.

I can't provide an XPath because each time you have a document they have their own path. So I'm trying to get it to scrap the page and locate them all.

Right now when it prints, it just returns empty. I know it's the XPaths but cant figure it out..

Any thoughts on how I can fix this?

while True:

    # Find the rows that contain the word "deed" in the 4th column
    row_elements = driver.find_elements(by=By.XPATH, value='//table[@id="f"]//tr[td[contains(text(), "deed")]]')

    # Extract the links from the rows
    links = [row.find_element(by=By.XPATH, value='.//td[1]/a').get_attribute("href") for row in row_elements]
    print(links)

    # Iterate through the links and download the PDFs
    for link in links:
        # Get the PDF content from the link
        response = requests.get(link)

        # Create a PDF file object from the PDF content
        file = io.BytesIO(response.content)

        # Create a PDF reader object
        reader = P

# Close the web browser
driver.close()
```

ContentLicense: CC BY-SA 4.0

Title: Searching for documents to get links


问:
Get Data from another activity to App Widget with intent
Hi I have an Activity 1 which needs to send data to Appwidget (widget) which has a image view.

For sending data between activites i know that we can use intent.putExtra("mydata", dataString)

I send image from my adapter to my widget class but my image doesn't show up how can i fix that?

This is my adapter class I am sending data to adapter class

```<code> var intent=Intent(holder.itemView.context,AppWidgetBroadcast::class.java)
        intent.putExtra("myimagedataWD",arraylist.get(position).imageimage)
</code>```

This is my widget provider class

```<code>class AppWidgetBroadcast() : AppWidgetProvider() {

    private lateinit var imageuri:String
    private lateinit var parseUri:Uri

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {

        appWidgetIds.forEach { appWidgetId ->
            // Create an Intent to launch ExampleActivity.
            val pendingIntent: PendingIntent = PendingIntent.getActivity(
                /* context = */ context,
                /* requestCode = */  0,
                /* intent = */ Intent(context, WidgetDetailsActivity::class.java),
                /* flags = */ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )
            val views: RemoteViews = RemoteViews(context.packageName,R.layout.activity_widget_details).apply {
                setOnClickPendingIntent(R.id.fullImageWidget, pendingIntent)

            }

                try {

                    var bitmap: Bitmap =

                        Glide.with(context)
                            .asBitmap()
                            .load(parseUri)
                            .submit(250, 250)
                            .get()
                    views.setImageViewBitmap(R.id.fullImageWidget,bitmap)

                } catch (e: Exception) {
                    e.printStackTrace()
                }

            val id: Int = context.resources.getIdentifier(
                "name",
                null,
                null
            )

            appWidgetManager.updateAppWidget(appWidgetId, views)

        }
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        super.onReceive(context, intent)
        if (intent != null) {

            imageuri= intent.getStringExtra("myimagedataWD")!!
            parseUri= Uri.parse(imageuri)
        }
    }
}
</code>```

Body:
Hi I have an Activity 1 which needs to send data to Appwidget (widget) which has a image view.

For sending data between activites i know that we can use intent.putExtra("mydata", dataString)

I send image from my adapter to my widget class but my image doesn't show up how can i fix that?

This is my adapter class I am sending data to adapter class

 var intent=Intent(holder.itemView.context,AppWidgetBroadcast::class.java)
        intent.putExtra("myimagedataWD",arraylist.get(position).imageimage)

This is my widget provider class

class AppWidgetBroadcast() : AppWidgetProvider() {

    private lateinit var imageuri:String
    private lateinit var parseUri:Uri

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {

        appWidgetIds.forEach { appWidgetId ->
            // Create an Intent to launch ExampleActivity.
            val pendingIntent: PendingIntent = PendingIntent.getActivity(
                /* context = */ context,
                /* requestCode = */  0,
                /* intent = */ Intent(context, WidgetDetailsActivity::class.java),
                /* flags = */ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )
            val views: RemoteViews = RemoteViews(context.packageName,R.layout.activity_widget_details).apply {
                setOnClickPendingIntent(R.id.fullImageWidget, pendingIntent)

            }

                try {

                    var bitmap: Bitmap =

                        Glide.with(context)
                            .asBitmap()
                            .load(parseUri)
                            .submit(250, 250)
                            .get()
                    views.setImageViewBitmap(R.id.fullImageWidget,bitmap)

                } catch (e: Exception) {
                    e.printStackTrace()
                }

            val id: Int = context.resources.getIdentifier(
                "name",
                null,
                null
            )

            appWidgetManager.updateAppWidget(appWidgetId, views)

        }
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        super.onReceive(context, intent)
        if (intent != null) {

            imageuri= intent.getStringExtra("myimagedataWD")!!
            parseUri= Uri.parse(imageuri)
        }
    }
}


问:
Unable to adjust font sizes and other params in matplotlib (scatterplot)
I spent hours researching this question on Google and found tons of answers. I actually have some pieces of code that work as expected. But today, I spent hours trying to change font sizes to no avail.

Here is my imports:

```<code>import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import colors
from matplotlib import cm # color maps
</code>```

Now the code to produce the scatterplot:

```<code>SMALL_SIZE = 0
MEDIUM_SIZE = 0
BIGGER_SIZE = 0

fig = plt.figure(figsize =(6, 4), dpi=120)
axes = plt.axes()
plt.scatter(npdata[:,1], npdata[:,0], c=npdata[:,2], s=8, cmap=cm.coolwarm,edgecolors='black',linewidth=0.3, alpha=0.8)
plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title
mpl.rc('xtick', labelsize=0)
mpl.rc('ytick', labelsize=0)
cs = plt.contourf(yc, xc, zgridt,cmap='coolwarm',levels=16)
cbar = plt.colorbar(cs)

plt.show()
</code>```

I set everything to a size of zero, but whatever the size, nothing changes except the size of the font on the right bar.

Here is the plot:

I am wondering what is wrong in my code.

Body:
I spent hours researching this question on Google and found tons of answers. I actually have some pieces of code that work as expected. But today, I spent hours trying to change font sizes to no avail.

Here is my imports:

import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import colors
from matplotlib import cm # color maps

Now the code to produce the scatterplot:

SMALL_SIZE = 0
MEDIUM_SIZE = 0
BIGGER_SIZE = 0

fig = plt.figure(figsize =(6, 4), dpi=120)
axes = plt.axes()
plt.scatter(npdata[:,1], npdata[:,0], c=npdata[:,2], s=8, cmap=cm.coolwarm,edgecolors='black',linewidth=0.3, alpha=0.8)
plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title
mpl.rc('xtick', labelsize=0)
mpl.rc('ytick', labelsize=0)
cs = plt.contourf(yc, xc, zgridt,cmap='coolwarm',levels=16)
cbar = plt.colorbar(cs)

plt.show()

I set everything to a size of zero, but whatever the size, nothing changes except the size of the font on the right bar.

Here is the plot:

I am wondering what is wrong in my code.


问:
How can I get the eBay API to return list of current eBay Promotional Offers for my seller account?
If you are an eBay seller and have enabled the Seller Hub dashboard, you could scroll down and see a section named "Promotional Offers".  For example, mine may say:

```<code>Promotional offers

Additional Fixed Price Free Insertions in Select Categories
Additional fixed price insertions in select categories.
Start:Jan 1, 2023 at 12:00am PST    End:End:Feb 1, 2023 at 12:00am PST
Used/Left: 6, 49994 ebay.com

Premium Store Subscription – 10,000 Fixed Price Listings
Pay no insertion fees for 10,000 listings
Start:Jan 1, 2023 at 12:00am PST    End:End:Feb 1, 2023 at 12:00am PST
Used/Left: 48, 9952 ebay.com

List auction-style FREE, up to 500 in select categories
Pay no insertion fee for 500 auction-style listings in collectible and fashion categories.
Start:Jan 1, 2023 at 12:00am PST    End:End:Feb 1, 2023 at 12:00am PST
Used/Left: 0, 500 ebay.com
</code>```

I have been unable to find any API call in the eBay developer docs yet which specifically can pull these promotional offers programmatically for me.

Is there any way to do this?  I'd hate to resort to some lame scraping-my-ebay-dashboard solution for this...

Body:
If you are an eBay seller and have enabled the Seller Hub dashboard, you could scroll down and see a section named "Promotional Offers".  For example, mine may say:

Promotional offers

Additional Fixed Price Free Insertions in Select Categories
Additional fixed price insertions in select categories.
Start:Jan 1, 2023 at 12:00am PST    End:End:Feb 1, 2023 at 12:00am PST
Used/Left: 6, 49994 ebay.com

Premium Store Subscription – 10,000 Fixed Price Listings
Pay no insertion fees for 10,000 listings
Start:Jan 1, 2023 at 12:00am PST    End:End:Feb 1, 2023 at 12:00am PST
Used/Left: 48, 9952 ebay.com

List auction-style FREE, up to 500 in select categories
Pay no insertion fee for 500 auction-style listings in collectible and fashion categories.
Start:Jan 1, 2023 at 12:00am PST    End:End:Feb 1, 2023 at 12:00am PST
Used/Left: 0, 500 ebay.com

I have been unable to find any API call in the eBay developer docs yet which specifically can pull these promotional offers programmatically for me.

Is there any way to do this?  I'd hate to resort to some lame scraping-my-ebay-dashboard solution for this...


问:
Bidirectional with Repeater On Post Object
```<code><?php
if( have_rows('repeater_field_name')): // check for repeater fields ?>
<?php while ( have_rows('repeater_field_name')) : the_row(); // loop through the repeater fields ?>

    <?php // set up post object
        $post_object = get_sub_field('test');
        if( $post_object ) :
        $post = $post_object;
        setup_postdata($post);
    ?>

        <?php the_title(); ?>
        <?php the_post_thumbnail(); ?>
        <?php // whatever post stuff you want goes here ?>

    <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>

<?php endif; ?>
<?php endwhile; ?>

</div>
<!-- End Repeater -->
<?php endif; ?>
</code>```

Hi, Im trying my best to add an Bidirectional inside a repeater. Can anyone help me? this is my query.

This is the query i want to inside above the code idk if possible but im hoping..

```<code>$related_articles = get_posts(array(
    'post_type' => 'book',
    'meta_query' => array(
        array(
            'key' => 'relationship_field', // name of custom field
            'value' => '"' . get_the_ID() . '"',
            'compare' => 'LIKE'
        )
    )
));
</code>```

Body:
<?php
if( have_rows('repeater_field_name')): // check for repeater fields ?>
<?php while ( have_rows('repeater_field_name')) : the_row(); // loop through the repeater fields ?>

    <?php // set up post object
        $post_object = get_sub_field('test');
        if( $post_object ) :
        $post = $post_object;
        setup_postdata($post);
    ?>

        <?php the_title(); ?>
        <?php the_post_thumbnail(); ?>
        <?php // whatever post stuff you want goes here ?>

    <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>

<?php endif; ?>
<?php endwhile; ?>

<?php endif; ?>

Hi, Im trying my best to add an Bidirectional inside a repeater. Can anyone help me? this is my query.

This is the query i want to inside above the code idk if possible but im hoping..

$related_articles = get_posts(array(
    'post_type' => 'book',
    'meta_query' => array(
        array(
            'key' => 'relationship_field', // name of custom field
            'value' => '"' . get_the_ID() . '"',
            'compare' => 'LIKE'
        )
    )
));


问:
How to properly close vertx and vertx mysqlclient on jakartaee application?
I use vertx and vertx mysql client in a jakartaEE10 application. I used netbeans to write code, it auto reloads once I make change by redeploying the war file in TomEE. This used to work fine in java ee 7 app (I used only Tomcat9 there, not TomEE).

I closed vertx and mysqlclient. I tried closing in @Disposes, and then tried closing contextDestroyed method of ServletContextLisener. I can see the code triggers. But the next time app loads it doesnt seem to load properly. Every vertx call blocks.

Is there anything more should I do please let me know.

I am getting following error in logs.

```<code>08-Jan-2023 12:24:47.937 WARNING [main] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [app] appears to have started a thread named [vertx-blocked-thread-checker] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [app] appears to have started a thread named [vert.x-eventloop-thread-0] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.base@17.0.5/sun.nio.ch.KQueue.poll(Native Method)
</code>```

I would love to provide more information if needed. Plese let me know.

Edit 1:
I was blocking on @postconstruct to load config from database. I spawned a new thread to execute the blocking code. Now it runs fine, not sure how postconstruct thread is linked to event loop thread. This still blocks postconstruct method by calling Thread.join() but somehow it works.

Body:
I use vertx and vertx mysql client in a jakartaEE10 application. I used netbeans to write code, it auto reloads once I make change by redeploying the war file in TomEE. This used to work fine in java ee 7 app (I used only Tomcat9 there, not TomEE).

I closed vertx and mysqlclient. I tried closing in @Disposes, and then tried closing contextDestroyed method of ServletContextLisener. I can see the code triggers. But the next time app loads it doesnt seem to load properly. Every vertx call blocks.

Is there anything more should I do please let me know.

I am getting following error in logs.

08-Jan-2023 12:24:47.937 WARNING [main] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [app] appears to have started a thread named [vertx-blocked-thread-checker] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [app] appears to have started a thread named [vert.x-eventloop-thread-0] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.base@17.0.5/sun.nio.ch.KQueue.poll(Native Method)

I would love to provide more information if needed. Plese let me know.

Edit 1:
I was blocking on @postconstruct to load config from database. I spawned a new thread to execute the blocking code. Now it runs fine, not sure how postconstruct thread is linked to event loop thread. This still blocks postconstruct method by calling Thread.join() but somehow it works.


问:
Best solution to transcode mp3s (lower bitrate) and stream on the fly
I have a large repo of mp3s on my LAMP server (I think it's a Debian VPS now) and currently I use a crude flash based mp3 player that "streams" the mp3s directly from my server. I am implementing an HTML5 player but I feel this is a similar to my flash integration (and this is slightly besides the point of this question)

This question is about how I should start molding my delivery to limit bandwidth - connection speed isn't entirely an issue (although should be reasonable) but my bandwidth costs are flying now and I need to take measures to limit stream quality (transcode down to 128)

Ideally I'd like to avoid RTMP so I can use my shiny new soundmanager2(html5) plugin for mobile etc, and as such I've been looking into this article here - http://www.metabrew.com/article/transcoding-http-mp3-streaming-proxy-in-bash which details how to create a proxy to on-the-fly transcode bitrate and serve new files.

I am fairly new to this arena and am open to all solutions! Thanks!

P.S I am open to 3rd party services - affordable ones at least :)

Possible Solutions (on SO)

reduce bandwidth streaming mp3s php

ContentLicense: CC BY-SA 3.0


问:
Centos 8 apache test page
I have a clean instalation of centos 8 server with the LAMP services installed.However I can only access the apache test page on the machine and not from the network.When trying to open the page the browser shows error in connetion.I have an old server running Centos 6 which everything is running fine. even switching the IPs of the servers the new server still cannot open the page.

What i have done so far

Configure httpd.conf to listen on port 80 on the ip address of the server.

Temporarily disabled server firewall.

When i check the apache logs i can only see the logs from when i access on the machine, nothing  is generated when i try to access on the browser.

Copied the http.conf file from the old server to the new server to no avail

Can someone point me in the right direction.

Title: Centos 8 apache test page


问:
How to avoid redirect when using google app scripts to send react form data to a google sheet?
Currently, I am trying to have a simple form send its data to a google sheet to make it easier for the owner of the website to see their responses. Im trying to use google app scripts following a tutorial online, but once the data is submitted I am redirected to the successful JSON response.

Going off of another post:

How to avoid redirection in google-sheet app script

Another User said to avoid using Content service, but i couldn't find an alternative. I have attached my google scripts code below and the component that handles my form logic.

Form component:

```<code>import React from "react"

import { useState } from "react";
export default function Form(props) {
  const [data, setData] = useState({
    name: " ",
    company: "",
    service: "",
    contact: "",
    technician: "",
  });
  const { name, company, service, contact, technician } = data;

  const handleChange = (e) => {
    setData({ ...data, [e.target.name]: e.target.value });
  };

  return (
    <div className="form-container">
      <form
      action="<my google scripts api endpoint"
      method="POST"
      >
        <div className="form-group">
          <h3 className="form-header">Service Inquiry</h3>
          <label className="input-label">Name:</label>
          <textarea
            type="text"
            name="name"
            value={name}
            onChange={handleChange}
            required
            className="input"
            rows="1"
          ></textarea>
        </div>

        <div className="form-group">
          <label className="input-label">Company Name:</label>
          <textarea
            type="text"
            name="company"
            value={company}
            onChange={handleChange}
            required
            className="input"
            rows="1"
          ></textarea>
        </div>
        <div className="form-group">
          <label className="input-label">What can we do for you?</label>

          <textarea
            type="text"
            name="service"
            value={service}
            onChange={handleChange}
            required
            className="input"
            rows="5"
            cols="50"
          ></textarea>
        </div>
        <div className="form-group">
          <label className="input-label">
            Please leave a way for us to contact you:
          </label>
          <textarea
            type="text"
            name="contact"
            value={contact}
            onChange={handleChange}
            placeholder="Email or Phone"
            className="input"
            rows="1"
          ></textarea>
        </div>
        <div className="form-group">
          <label className="input-label">Request Specific Technician:</label>
          <textarea
            type="text"
            name="technician"
            value={technician}
            onChange={handleChange}
            className="input"
            rows="1"
            placeholder="*optional"
          ></textarea>

          <p className="footnote">
            *if you would like a specific technician, please specify
          </p>
          <input type="submit" value="Send" className="submit-button" />
        </div>
      </form>
    </div>
  );
}
</code>```

Google App Scripts:

```<code>// Original code from https://github.com/jamiewilson/form-to-google-sheets
// Updated for 2021 and ES6 standards

const sheetName = 'Sheet1'
const scriptProp = PropertiesService.getScriptProperties()

function initialSetup () {
  const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  const lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    const doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    const sheet = doc.getSheetByName(sheetName)

    const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    const nextRow = sheet.getLastRow() + 1

    const newRow = headers.map(function(header) {
      return header === 'Date' ? new Date() : e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}
</code>```

What I am receiving after the form is submitted:

I would just like to avoid the redirection to the JSON.

Body:
Currently, I am trying to have a simple form send its data to a google sheet to make it easier for the owner of the website to see their responses. Im trying to use google app scripts following a tutorial online, but once the data is submitted I am redirected to the successful JSON response.

Going off of another post:

How to avoid redirection in google-sheet app script

Another User said to avoid using Content service, but i couldn't find an alternative. I have attached my google scripts code below and the component that handles my form logic.

Form component:

import React from "react"

import { useState } from "react";
export default function Form(props) {
  const [data, setData] = useState({
    name: " ",
    company: "",
    service: "",
    contact: "",
    technician: "",
  });
  const { name, company, service, contact, technician } = data;

  const handleChange = (e) => {
    setData({ ...data, [e.target.name]: e.target.value });
  };

  return (

      <form
      action="<my google scripts api endpoint"
      method="POST"
      >

Service Inquiry

          Name:
          <textarea
            type="text"
            name="name"
            value={name}
            onChange={handleChange}
            required
            className="input"
            rows="1"
          ></textarea>

          Company Name:
          <textarea
            type="text"
            name="company"
            value={company}
            onChange={handleChange}
            required
            className="input"
            rows="1"
          ></textarea>

          What can we do for you?

          <textarea
            type="text"
            name="service"
            value={service}
            onChange={handleChange}
            required
            className="input"
            rows="5"
            cols="50"
          ></textarea>

            Please leave a way for us to contact you:

          <textarea
            type="text"
            name="contact"
            value={contact}
            onChange={handleChange}
            placeholder="Email or Phone"
            className="input"
            rows="1"
          ></textarea>

          Request Specific Technician:
          <textarea
            type="text"
            name="technician"
            value={technician}
            onChange={handleChange}
            className="input"
            rows="1"
            placeholder="*optional"
          ></textarea>

            *if you would like a specific technician, please specify

          <input type="submit" value="Send" className="submit-button" />

      </form>

  );
}

Google App Scripts:

// Original code from https://github.com/jamiewilson/form-to-google-sheets
// Updated for 2021 and ES6 standards

const sheetName = 'Sheet1'
const scriptProp = PropertiesService.getScriptProperties()

function initialSetup () {
  const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  const lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    const doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    const sheet = doc.getSheetByName(sheetName)

    const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    const nextRow = sheet.getLastRow() + 1

    const newRow = headers.map(function(header) {
      return header === 'Date' ? new Date() : e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

What I am receiving after the form is submitted:

I would just like to avoid the redirection to the JSON.


问:
Reading nested collection QueryDSL
I am using queryDSL to fetch the inner collection of data and failed to do so. My entities are

```<code> @Entity
 @Table(name = "countries")
 @Setter
 @Getter
 public class Country {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long countryId;

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

    @Column(name = "data")
    private String data;

    @OneToOne(mappedBy = "country")
    private State stateJoin;

}
</code>```

@Entity
@Table(name = "states")
@Setter
@Getter
public class State {

```<code>  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Long stateId;

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

  @Column(name = "count")
  private String count;

  @Column(name = "co_id")
  private Long countryId;

  @OneToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "co_id", referencedColumnName = "id", updatable = false, insertable = false)
  private Country country;

  @OneToMany(cascade = CascadeType.ALL)
  @JoinColumn(name = "state_id", referencedColumnName = "id")
  private Set<Town> towns;
</code>```

}

```<code>@Entity
@Table(name = "towns")
@Setter
@Getter
public class Town {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "town_id")
    private Long townId;

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

    @Column(name = "people_count")
    private String peopleCount;

    @Column(name = "st_id")
    private Long stateId;
}
</code>```

and in querydsl i am trying below query and always failing to retrieve inner collection towns

```<code>List<Expression> childGroup = new ArrayList<>();

query.from(countries);

childGroup.addAll(Arrays.asList(countries.name, countries.data, countries.stateJoin));

query.join(countries.stateJoin, State);
childGroup.add(Projections.bean(State.class, name, count, town)
                .as((Path) countries.stateJoin));

            OR

childGroup.add(Projections.bean(State.class, name, count, list(town)).as((Path) countries.stateJoin));

query.select(fields);
query.where();

final Map<? extends Number, ? extends Object> t =
        (Map<? extends Number, ? extends Object>)
            query
                .limit(pageRequest.getPageSize())
                .offset(pageRequest.getOffset())
                .distinct()
                .transform(
                    GroupBy.groupBy(groupByPath)
                        .as(Projections.bean(Countris.class, childGroup.toArray(new Expression[0]))));

</code>```

while executing the above line exactly i am getting always SQLSyntax error as i see the underlying SQL is with

```<code>. as towns
</code>```

Can some one help me how to read the nested collection formed by JPA join?

Title: Reading nested collection QueryDSL

Body:
I am using queryDSL to fetch the inner collection of data and failed to do so. My entities are

 @Entity
 @Table(name = "countries")
 @Setter
 @Getter
 public class Country {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long countryId;

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

    @Column(name = "data")
    private String data;

    @OneToOne(mappedBy = "country")
    private State stateJoin;

}

@Entity
@Table(name = "states")
@Setter
@Getter
public class State {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Long stateId;

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

  @Column(name = "count")
  private String count;

  @Column(name = "co_id")
  private Long countryId;

  @OneToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "co_id", referencedColumnName = "id", updatable = false, insertable = false)
  private Country country;

  @OneToMany(cascade = CascadeType.ALL)
  @JoinColumn(name = "state_id", referencedColumnName = "id")
  private Set<Town> towns;

}

@Entity
@Table(name = "towns")
@Setter
@Getter
public class Town {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "town_id")
    private Long townId;

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

    @Column(name = "people_count")
    private String peopleCount;

    @Column(name = "st_id")
    private Long stateId;
}

and in querydsl i am trying below query and always failing to retrieve inner collection towns

List<Expression> childGroup = new ArrayList<>();

query.from(countries);

childGroup.addAll(Arrays.asList(countries.name, countries.data, countries.stateJoin));

query.join(countries.stateJoin, State);
childGroup.add(Projections.bean(State.class, name, count, town)
                .as((Path) countries.stateJoin));

            OR

childGroup.add(Projections.bean(State.class, name, count, list(town)).as((Path) countries.stateJoin));

query.select(fields);
query.where();

final Map<? extends Number, ? extends Object> t =
        (Map<? extends Number, ? extends Object>)
            query
                .limit(pageRequest.getPageSize())
                .offset(pageRequest.getOffset())
                .distinct()
                .transform(
                    GroupBy.groupBy(groupByPath)
                        .as(Projections.bean(Countris.class, childGroup.toArray(new Expression[0]))));

while executing the above line exactly i am getting always SQLSyntax error as i see the underlying SQL is with

. as towns

Can some one help me how to read the nested collection formed by JPA join?


问:
Why does shap Explainer give KeyError: 'class0'?
I have a pytorch text multiclass classifier model based on a XLMR based architecture. Due to IP reasons I can't share the architecture code. I have tried putting as much detail as I can. Please point out if more information is needed. But it outputs 28 classes from 'class0' to 'class27' with probability scores that add to 1.

I am trying to use shap package to explain the results. I have wrapped my model into huggingface's custom pipeline object and I get the following output for 1 input text:

```<code>pipe = CustomPipeline(model = model, tokenizer = base_tokenizer)
output = pipe(list_of_inputs) # list_of_inputs = ['this is test input']
</code>```

Output:

```<code>[[{"label": "class0","score": 0.01500235591083765},{"label": "class1","score": 0.001698049483820796},{"label": "class2","score": 0.0019644589629024267},{"label": "class3","score": 0.0004418794414959848},{"label": "class4","score": 5.9095666074426845e-05},{"label": "class5","score": 0.0007908751722425222},{"label": "class6","score": 0.002379569923505187},{"label": "class7","score": 0.0035733324475586414},{"label": "class8","score": 0.0014360857894644141},{"label": "class9","score": 0.0007365105557255447},{"label": "class10","score": 0.0014471099711954594},{"label": "class11","score": 0.0011013210751116276},{"label": "class12","score": 0.0010048456024378538},{"label": "class13","score": 0.000885132874827832},{"label": "class14","score": 0.0022015925496816635},{"label": "class15","score": 0.0013197452062740922},{"label": "class16","score": 0.0037292027845978737},{"label": "class17","score": 0.004212632775306702},{"label": "class18","score": 0.9481304287910461},{"label": "class19","score": 0.001469381619244814},{"label": "class20","score": 0.0009713817853480577},{"label": "class21","score": 0.0018773127812892199},{"label": "class22","score": 0.0009251375449821353},{"label": "class23","score": 0.0007248060428537428},{"label": "class24","score": 0.00031718137324787676},{"label": "class25","score": 0.0011144360760226846},{"label": "class26","score": 0.0002294857840752229},{"label": "class27","score": 0.00025681318948045373}]]
</code>```

The output is in same format as the notebook specified by shap package.

Now, when I try to use shap Explainer:

```<code>pipe = UDTMPipeline(model = model, tokenizer = base_tokenizer)
explainer = shap.Explainer(pipe)
shap_values = explainer(list_of_inputs)
shap.plots.text(shap_values)
</code>```

Error:

```<code>File "C:\pipeline.py", line 104, in udtm_xai
shap_values = explainer(query_data)
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\explainers\_partition.py", line 136, in __call__
return super().__call__(
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\explainers\_explainer.py", line 266, in __call__
row_result = self.explain_row(
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\explainers\_partition.py", line 161, in explain_row
self._curr_base_value = fm(m00.reshape(1, -1), zero_index=0)[0] # the zero index param tells the masked model what the baseline is
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\utils\_masked_model.py", line 67, in __call__
return self._full_masking_call(masks, batch_size=batch_size)
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\utils\_masked_model.py", line 144, in _full_masking_call
outputs = self.model(*joined_masked_inputs)
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\models\_transformers_pipeline.py", line 35, in __call__
output[i, self.label2id[obj["label"]]] = sp.special.logit(obj["score"]) if self.rescale_to_logits else obj["score"]
KeyError: 'class0'
</code>```

The code is unable to find 'class0'. In the postprocess function of pipeline class, I read a file containing label mappings, obtain the softmax scores from _forward function of pipeline class and create a dictionary in the final format to send as output:

```<code>class CustomPipeline(Pipeline): # Ignore no indentation below, formatting issue in stackoverflow
def _sanitize_parameters(self, **kwargs):
    self.mapping_json = json.loads(open("mapping_file.json", "r", encoding = "utf-8").read().strip())

    return {}, {}, {}

def preprocess(self, inputs):
    inputs_df = pd.DataFrame([inputs], columns = ["Query"])
    inference_dataloader = getInferenceDataloader(inputs_df, self.tokenizer, batch_size = 16)
    return inference_dataloader

def softmax_with_temp(self, input, t):
    ex = torch.exp(input/t)
    sum = torch.sum(ex,0)
    return ex / sum

def _forward(self, model_inputs):
    if torch.cuda.is_available():
        device = torch.device('cuda')
    else:
        device = torch.device('cpu')
    final_pred_labels = []
    final_scores = []
    batch_count = 0
    self.model.eval()
    for batch in model_inputs:
        batch_count += 1
        b_input_ids = batch[0].to(device)
        b_input_mask = batch[1].to(device)
        b_input_task = torch.full((b_input_ids.shape[0],), -1, dtype=torch.int32).to(device)
        with torch.no_grad():
            result = self.model((b_input_ids, b_input_mask, b_input_task))
        logits = result
        logits = logits.detach().cpu().numpy()
        pred_softmax_t = self.softmax_with_temp(torch.from_numpy(logits[0]), 2).numpy()
    return pred_softmax_t

def postprocess(self, model_outputs):
    output_list = [{"label":"class0", "score":float(model_outputs[0])}]
    index = 1
    for label in self.mapping_json.keys(): #self.mapping_json contains label names that has been read from a file
        output_list.append({"label":label, "score":float(model_outputs[index])}) #model_outputs is a list of 28 floating scores
        index += 1
    return output_list
</code>```

Am I missing some to define any label based variable which is why I am getting 'class0' key error?

Body:
I have a pytorch text multiclass classifier model based on a XLMR based architecture. Due to IP reasons I can't share the architecture code. I have tried putting as much detail as I can. Please point out if more information is needed. But it outputs 28 classes from 'class0' to 'class27' with probability scores that add to 1.

I am trying to use shap package to explain the results. I have wrapped my model into huggingface's custom pipeline object and I get the following output for 1 input text:

pipe = CustomPipeline(model = model, tokenizer = base_tokenizer)
output = pipe(list_of_inputs) # list_of_inputs = ['this is test input']

Output:

[[{"label": "class0","score": 0.01500235591083765},{"label": "class1","score": 0.001698049483820796},{"label": "class2","score": 0.0019644589629024267},{"label": "class3","score": 0.0004418794414959848},{"label": "class4","score": 5.9095666074426845e-05},{"label": "class5","score": 0.0007908751722425222},{"label": "class6","score": 0.002379569923505187},{"label": "class7","score": 0.0035733324475586414},{"label": "class8","score": 0.0014360857894644141},{"label": "class9","score": 0.0007365105557255447},{"label": "class10","score": 0.0014471099711954594},{"label": "class11","score": 0.0011013210751116276},{"label": "class12","score": 0.0010048456024378538},{"label": "class13","score": 0.000885132874827832},{"label": "class14","score": 0.0022015925496816635},{"label": "class15","score": 0.0013197452062740922},{"label": "class16","score": 0.0037292027845978737},{"label": "class17","score": 0.004212632775306702},{"label": "class18","score": 0.9481304287910461},{"label": "class19","score": 0.001469381619244814},{"label": "class20","score": 0.0009713817853480577},{"label": "class21","score": 0.0018773127812892199},{"label": "class22","score": 0.0009251375449821353},{"label": "class23","score": 0.0007248060428537428},{"label": "class24","score": 0.00031718137324787676},{"label": "class25","score": 0.0011144360760226846},{"label": "class26","score": 0.0002294857840752229},{"label": "class27","score": 0.00025681318948045373}]]

The output is in same format as the notebook specified by shap package.

Now, when I try to use shap Explainer:

pipe = UDTMPipeline(model = model, tokenizer = base_tokenizer)
explainer = shap.Explainer(pipe)
shap_values = explainer(list_of_inputs)
shap.plots.text(shap_values)

Error:

File "C:\pipeline.py", line 104, in udtm_xai
shap_values = explainer(query_data)
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\explainers\_partition.py", line 136, in __call__
return super().__call__(
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\explainers\_explainer.py", line 266, in __call__
row_result = self.explain_row(
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\explainers\_partition.py", line 161, in explain_row
self._curr_base_value = fm(m00.reshape(1, -1), zero_index=0)[0] # the zero index param tells the masked model what the baseline is
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\utils\_masked_model.py", line 67, in __call__
return self._full_masking_call(masks, batch_size=batch_size)
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\utils\_masked_model.py", line 144, in _full_masking_call
outputs = self.model(*joined_masked_inputs)
File "C:\Users\Miniconda3\envs\dtlr_udtm\lib\site-packages\shap\models\_transformers_pipeline.py", line 35, in __call__
output[i, self.label2id[obj["label"]]] = sp.special.logit(obj["score"]) if self.rescale_to_logits else obj["score"]
KeyError: 'class0'

The code is unable to find 'class0'. In the postprocess function of pipeline class, I read a file containing label mappings, obtain the softmax scores from _forward function of pipeline class and create a dictionary in the final format to send as output:

class CustomPipeline(Pipeline): # Ignore no indentation below, formatting issue in stackoverflow
def _sanitize_parameters(self, **kwargs):
    self.mapping_json = json.loads(open("mapping_file.json", "r", encoding = "utf-8").read().strip())

    return {}, {}, {}

def preprocess(self, inputs):
    inputs_df = pd.DataFrame([inputs], columns = ["Query"])
    inference_dataloader = getInferenceDataloader(inputs_df, self.tokenizer, batch_size = 16)
    return inference_dataloader

def softmax_with_temp(self, input, t):
    ex = torch.exp(input/t)
    sum = torch.sum(ex,0)
    return ex / sum

def _forward(self, model_inputs):
    if torch.cuda.is_available():
        device = torch.device('cuda')
    else:
        device = torch.device('cpu')
    final_pred_labels = []
    final_scores = []
    batch_count = 0
    self.model.eval()
    for batch in model_inputs:
        batch_count += 1
        b_input_ids = batch[0].to(device)
        b_input_mask = batch[1].to(device)
        b_input_task = torch.full((b_input_ids.shape[0],), -1, dtype=torch.int32).to(device)
        with torch.no_grad():
            result = self.model((b_input_ids, b_input_mask, b_input_task))
        logits = result
        logits = logits.detach().cpu().numpy()
        pred_softmax_t = self.softmax_with_temp(torch.from_numpy(logits[0]), 2).numpy()
    return pred_softmax_t

def postprocess(self, model_outputs):
    output_list = [{"label":"class0", "score":float(model_outputs[0])}]
    index = 1
    for label in self.mapping_json.keys(): #self.mapping_json contains label names that has been read from a file
        output_list.append({"label":label, "score":float(model_outputs[index])}) #model_outputs is a list of 28 floating scores
        index += 1
    return output_list

Am I missing some to define any label based variable which is why I am getting 'class0' key error?


问:
Angular and NestJS file upload progress bar
So, i have a system set up to be able to upload files via Angular to NestJS, but i wanna know the progress of the upload, because its a little annoying that i cant see when it finishes.

Is there any way to do it? Thanks!

Heres my code:

FrontEND: Angular:

```<code>          let formData = new FormData()

          let dateX = cur_day + hours + minutes + seconds; // removed the vars

          formData.append("dest", `${this.chatid}/${this.userData.userid}/${dateX}/`)
          this.draftImages.forEach((fileData: any) => {

            formData.append("file", fileData.file, fileData.name)
            console.log(fileData.file);
          })

          console.log(formData)
          this.http.post<any>("http://localhost:3000/chat/message/dm/uploadImg", formData).subscribe((result) => {
            console.log(result, formData)
            let filesUploaded: any = []
            this.draftImages = []

            Array.from(result).forEach((file: any) => {
              filesUploaded.push(file.destination + file.originalname)
            })

            this.dmService.sendMessage({
              message: message,
              chatid: this.chatid,
              userid: this.userData.userid,
              username: this.userData.username,
              pfp: this.userData.pfp,
              files: filesUploaded
            });

          })
</code>```

BackEND: NestJS:

```<code>  @Post("uploadImg")
  @UseInterceptors(
    AnyFilesInterceptor({
      storage: diskStorage({
        destination: function (req: any, file, cb) {
          console.log(file);

          function mkdirRecursiveSync(path: string) {
            if (!existsSync(path)) {
              mkdirRecursiveSync(dirname(path));
              mkdirSync(path);
            }
          }

          const destPath = `CDN/attachments/${req.body.dest}`;
          mkdirRecursiveSync(destPath);
          console.log(req.body)
          cb(null, destPath);
        },
        filename: function (req, file, cb) {
          console.log(file)
          cb(null, file.originalname);
        },
      }),
    })
  )
  async uploadedFile(@UploadedFiles() file) {
    console.log(file)
    return file;
  }
</code>```

Body:
So, i have a system set up to be able to upload files via Angular to NestJS, but i wanna know the progress of the upload, because its a little annoying that i cant see when it finishes.

Is there any way to do it? Thanks!

Heres my code:

FrontEND: Angular:

          let formData = new FormData()

          let dateX = cur_day + hours + minutes + seconds; // removed the vars

          formData.append("dest", `${this.chatid}/${this.userData.userid}/${dateX}/`)
          this.draftImages.forEach((fileData: any) => {

            formData.append("file", fileData.file, fileData.name)
            console.log(fileData.file);
          })

          console.log(formData)
          this.http.post<any>("http://localhost:3000/chat/message/dm/uploadImg", formData).subscribe((result) => {
            console.log(result, formData)
            let filesUploaded: any = []
            this.draftImages = []

            Array.from(result).forEach((file: any) => {
              filesUploaded.push(file.destination + file.originalname)
            })

            this.dmService.sendMessage({
              message: message,
              chatid: this.chatid,
              userid: this.userData.userid,
              username: this.userData.username,
              pfp: this.userData.pfp,
              files: filesUploaded
            });

          })

BackEND: NestJS:

  @Post("uploadImg")
  @UseInterceptors(
    AnyFilesInterceptor({
      storage: diskStorage({
        destination: function (req: any, file, cb) {
          console.log(file);

          function mkdirRecursiveSync(path: string) {
            if (!existsSync(path)) {
              mkdirRecursiveSync(dirname(path));
              mkdirSync(path);
            }
          }

          const destPath = `CDN/attachments/${req.body.dest}`;
          mkdirRecursiveSync(destPath);
          console.log(req.body)
          cb(null, destPath);
        },
        filename: function (req, file, cb) {
          console.log(file)
          cb(null, file.originalname);
        },
      }),
    })
  )
  async uploadedFile(@UploadedFiles() file) {
    console.log(file)
    return file;
  }


问:
Adding a class into another class's return statement
Im new to react, but I am wondering if there is a solution to creating a nesting class in the return statement of an existing class? Ive tried to look for other solution and had no choice but to ask this here.

Assuming in the return class in App.js:

```<code>import { useRef, useEffect} from "react";
import {  MapContainer } from "./maps";
import { GoogleApiWrapper } from 'google-maps-react';

return (

      <div class="body">
        <div class="background"></div>
        <div class="topnav">
            <input id="seachbar" name="seachbar" type="text" placeholder="Search.." ref={inputRef} ></input>
            <button onclick="document.getElementByName('seachbar').name = ''" class='removeButton'>X</button>
            <button type="submit" class='searchButton'>Search</button>

        </div>
        <br></br>
        <br></br>
        <br></br>
        <div class="content">
          <MapContainer/>
        </div>
      </div>

 );
</code>```

I had tried to add the class inside it but kept getting an error stating that export has to be outside the statement. Is there a function that I can use to nest it inside? Just adding more context I am trying to add in google maps into the div section but the google maps contain 2 different exports.

Assuming in the return class in maps.js:

```<code>export class MapContainer extends Component {
  render() {
    return (
      <Map
        google={this.props.google}
        zoom={14}
        style={mapStyles}
        initialCenter={
          {
            lat: 3.1474767381135407,
            lng: 101.69958884212062
          }
        }
      />
    );
  }
}

export default GoogleApiWrapper({
  apiKey: 'AIzaSyDkXk3MuVjovvaVAnl2wt2j_2ES-INLJ0s'
})(MapContainer);

</code>```

I want to use both the section of the export in order to generate a map from map.js into App.js. However when I call  in App.js after importing. It would say "loading map" but unable to do so.

Body:
Im new to react, but I am wondering if there is a solution to creating a nesting class in the return statement of an existing class? Ive tried to look for other solution and had no choice but to ask this here.

Assuming in the return class in App.js:

import { useRef, useEffect} from "react";
import {  MapContainer } from "./maps";
import { GoogleApiWrapper } from 'google-maps-react';

return (

            <input id="seachbar" name="seachbar" type="text" placeholder="Search.." ref={inputRef} ></input>
            <button onclick="document.getElementByName('seachbar').name = ''" class='removeButton'>X</button>
            <button type="submit" class='searchButton'>Search</button>

          <MapContainer/>

 );

I had tried to add the class inside it but kept getting an error stating that export has to be outside the statement. Is there a function that I can use to nest it inside? Just adding more context I am trying to add in google maps into the div section but the google maps contain 2 different exports.

Assuming in the return class in maps.js:

export class MapContainer extends Component {
  render() {
    return (
      <Map
        google={this.props.google}
        zoom={14}
        style={mapStyles}
        initialCenter={
          {
            lat: 3.1474767381135407,
            lng: 101.69958884212062
          }
        }
      />
    );
  }
}

export default GoogleApiWrapper({
  apiKey: 'AIzaSyDkXk3MuVjovvaVAnl2wt2j_2ES-INLJ0s'
})(MapContainer);

I want to use both the section of the export in order to generate a map from map.js into App.js. However when I call  in App.js after importing. It would say "loading map" but unable to do so.


问:
How to create html report from a view in oracle apex?
I have view which contains some data like the following table.

col a
Col B
col c
col D
col e

999
111
1
abc
3030

444
10

The report which I want to be created in html is the following.

text
999

text
444

text
10

text
abc

text
3030


问:
Looking for extreme minimum grumbel in pYMC
I have been reading up on the Gumbel function in pymc. According to the docs, this looks like the extreme maximum implementation of the function but I am interested in the extreme minimum version. How can I find that in PYMC?

pYMC documentation on function
Wikipedia article discussing the difference


问:
is there any way to change python version in google colab?
How can I change Python version on google colab?
I want to use version 2.7 because I want to use wheel.pep425tags package in my project.


问:
Shopizer getting spring-releases (https://repo.spring.io/libs-release): Not authorized , ReasonPhrase: Unauthorized
when we build and updated Shopizer repository then getting spring-releases (https://repo.spring.io/libs-release): Not authorized , ReasonPhrase: Unauthorized.

version: 3.2.2

Shopizer successfully updates maven dependencies without any authorization.


问:
Camera stream preview work only when touch moving
when i route app (Ionic(Capacitor)) to external website camera stream preview work only when touching

android

```<code>private void loadWebView() {
    // ...
   webView.loadUrl("https://example.com/");
}
</code>```

on example.com js code:

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<body>
    <video id="stream" autoplay playsinline width="200" height="200"></video>
</body>
</html>
<script type="text/javascript">
    navigator.mediaDevices.getUserMedia({video: true}).then((stream) => {
        document.getElementById('stream').srcObject = stream;
    });
</script>
</code>```

on localhost all fine

P.S on a Cordova browser too fine

i try use browser from cordova, but it's hard for me

Body:
when i route app (Ionic(Capacitor)) to external website camera stream preview work only when touching

android

private void loadWebView() {
    // ...
   webView.loadUrl("https://example.com/");
}

on example.com js code:

<!doctype html>

  <meta charset="utf-8">
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">

    <video id="stream" autoplay playsinline width="200" height="200"></video>

on localhost all fine

P.S on a Cordova browser too fine

i try use browser from cordova, but it's hard for me


问:
Sequelize self-referential Many-to-Many relationships are not working
I only found following in Sequelize documentation, but it's not possible to understand how to fetch associations properly.

```<code>Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' })
// This will create the table PersonChildren which stores the ids of the objects.
</code>```

This is the implementation.

```<code>const sequelizePsqlConfig = new Sequelize(
  "postgres://Kavinda Vindika@localhost:5432/hrm_users"
);

export const User = sequelizePsqlConfig.define(
  "users",
  {
    userId: {
      field: "user_id",
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    userName: {
      field: "user_name",
      type: DataTypes.STRING,
    },
    email: { type: DataTypes.STRING, key: "email" },
    department: { type: DataTypes.STRING, key: "department" },
    designation: { type: DataTypes.STRING, key: "designation" },
  },
  {
    timestamps: false,
  }
);

export const User_Associations = sequelizePsqlConfig.define(
  "user_associations",
  {
    id: {
      field: "id",
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    managerId: {
      field: "manager_id",
      type: DataTypes.INTEGER,
    },
    subordinateId: {
      field: "subordinate_id",
      type: DataTypes.INTEGER,
    },
  },
  {
    modelName: "user_associations",
    timestamps: false,
    tableName: "user_associations",
  }
);

User.belongsToMany(User, {
  as: "manager",
  through: "user_associations",
  foreignKey: "manager_id",
  otherKey: "subordinate_id",
});
User.belongsToMany(User, {
  as: "subordinate",
  through: "user_associations",
  foreignKey: "subordinate_id",
  otherKey: "manager_id",
});
</code>```

Then I tried to fetch the data with manager and subordinate details.

```<code>  public async getAllUsers() {
    return User.findAll({
      include: ["manager", "subordinate"],
    });
  }
</code>```

But it failed with following logs. Please assist me on this issue.

```<code>[1] Executing (default): SELECT "users"."user_id" AS "userId", "users"."user_name" AS "userName", "users"."email", "users"."department", "users"."designation", "manager"."user_id" AS "manager.userId", "manager"."user_name" AS "manager.userName", "manager"."email" AS "manager.email", "manager"."department" AS "manager.department", "manager"."designation" AS "manager.designation", "manager->user_associations"."id" AS "manager.user_associations.id", "manager->user_associations"."manager_id" AS "manager.user_associations.managerId", "manager->user_associations"."subordinate_id" AS "manager.user_associations.subordinateId", "manager->user_associations"."manager_id" AS "manager.user_associations.manager_id", "manager->user_associations"."subordinate_id" AS "manager.user_associations.subordinate_id", "subordinate"."user_id" AS "subordinate.userId", "subordinate"."user_name" AS "subordinate.userName", "subordinate"."email" AS "subordinate.email", "subordinate"."department" AS "subordinate.department", "subordinate"."designation" AS "subordinate.designation", "subordinate->user_associations"."id" AS "subordinate.user_associations.id", "subordinate->user_associations"."manager_id" AS "subordinate.user_associations.managerId", "subordinate->user_associations"."subordinate_id" AS "subordinate.user_associations.subordinateId", "subordinate->user_associations"."manager_id" AS "subordinate.user_associations.manager_id", "subordinate->user_associations"."subordinate_id" AS "subordinate.user_associations.subordinate_id" FROM "users" AS "users" LEFT OUTER JOIN ( "user_associations" AS "manager->user_associations" INNER JOIN "users" AS "manager" ON "manager"."user_id" = "manager->user_associations"."subordinate_id") ON "users"."user_id" = "manager->user_associations"."manager_id" LEFT OUTER JOIN ( "user_associations" AS "subordinate->user_associations" INNER JOIN "users" AS "subordinate" ON "subordinate"."user_id" = "subordinate->user_associations"."manager_id") ON "users"."user_id" = "subordinate->user_associations"."subordinate_id";
[1] TypeError: Class constructor model cannot be invoked without 'new'
</code>```

Body:
I only found following in Sequelize documentation, but it's not possible to understand how to fetch associations properly.

Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' })
// This will create the table PersonChildren which stores the ids of the objects.

This is the implementation.

const sequelizePsqlConfig = new Sequelize(
  "postgres://Kavinda Vindika@localhost:5432/hrm_users"
);

export const User = sequelizePsqlConfig.define(
  "users",
  {
    userId: {
      field: "user_id",
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    userName: {
      field: "user_name",
      type: DataTypes.STRING,
    },
    email: { type: DataTypes.STRING, key: "email" },
    department: { type: DataTypes.STRING, key: "department" },
    designation: { type: DataTypes.STRING, key: "designation" },
  },
  {
    timestamps: false,
  }
);

export const User_Associations = sequelizePsqlConfig.define(
  "user_associations",
  {
    id: {
      field: "id",
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    managerId: {
      field: "manager_id",
      type: DataTypes.INTEGER,
    },
    subordinateId: {
      field: "subordinate_id",
      type: DataTypes.INTEGER,
    },
  },
  {
    modelName: "user_associations",
    timestamps: false,
    tableName: "user_associations",
  }
);

User.belongsToMany(User, {
  as: "manager",
  through: "user_associations",
  foreignKey: "manager_id",
  otherKey: "subordinate_id",
});
User.belongsToMany(User, {
  as: "subordinate",
  through: "user_associations",
  foreignKey: "subordinate_id",
  otherKey: "manager_id",
});

Then I tried to fetch the data with manager and subordinate details.

  public async getAllUsers() {
    return User.findAll({
      include: ["manager", "subordinate"],
    });
  }

But it failed with following logs. Please assist me on this issue.

[1] Executing (default): SELECT "users"."user_id" AS "userId", "users"."user_name" AS "userName", "users"."email", "users"."department", "users"."designation", "manager"."user_id" AS "manager.userId", "manager"."user_name" AS "manager.userName", "manager"."email" AS "manager.email", "manager"."department" AS "manager.department", "manager"."designation" AS "manager.designation", "manager->user_associations"."id" AS "manager.user_associations.id", "manager->user_associations"."manager_id" AS "manager.user_associations.managerId", "manager->user_associations"."subordinate_id" AS "manager.user_associations.subordinateId", "manager->user_associations"."manager_id" AS "manager.user_associations.manager_id", "manager->user_associations"."subordinate_id" AS "manager.user_associations.subordinate_id", "subordinate"."user_id" AS "subordinate.userId", "subordinate"."user_name" AS "subordinate.userName", "subordinate"."email" AS "subordinate.email", "subordinate"."department" AS "subordinate.department", "subordinate"."designation" AS "subordinate.designation", "subordinate->user_associations"."id" AS "subordinate.user_associations.id", "subordinate->user_associations"."manager_id" AS "subordinate.user_associations.managerId", "subordinate->user_associations"."subordinate_id" AS "subordinate.user_associations.subordinateId", "subordinate->user_associations"."manager_id" AS "subordinate.user_associations.manager_id", "subordinate->user_associations"."subordinate_id" AS "subordinate.user_associations.subordinate_id" FROM "users" AS "users" LEFT OUTER JOIN ( "user_associations" AS "manager->user_associations" INNER JOIN "users" AS "manager" ON "manager"."user_id" = "manager->user_associations"."subordinate_id") ON "users"."user_id" = "manager->user_associations"."manager_id" LEFT OUTER JOIN ( "user_associations" AS "subordinate->user_associations" INNER JOIN "users" AS "subordinate" ON "subordinate"."user_id" = "subordinate->user_associations"."manager_id") ON "users"."user_id" = "subordinate->user_associations"."subordinate_id";
[1] TypeError: Class constructor model cannot be invoked without 'new'


问:
Scalling flask socket io with redis connecting to only one server port
I have real time chatapplication, unable to scale them.

so i have frontend ngnix which proxy pass to backend ngnix , now backend ngnix will upstream to flasksocket io multiple instance,

```<code>server {
listen 443 ssl;
#server_name xx.xxx.xx.xxx;
client_max_body_size 300M;
ssl_certificate /etc/nginx/ssl/newssl/ssl_bundle.crt;
ssl_certificate_key /etc/nginx/ssl/newssl/example.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'xxx+xxxx+xxxx';
set_real_ip_from 0.0.0.0/0;
real_ip_header X-Real-IP;
real_ip_recursive on;
add_header X-Frame-Options "SAMEORIGIN" ;
add_header Access-Control-Allow-Origin *;

location / {
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                    proxy_set_header Host $http_host;
                    proxy_set_header X-NginX-Proxy true;
                    proxy_redirect off;
                    proxy_read_timeout 120s;
                    proxy_connect_timeout 120s;
                    open_file_cache max=200000 inactive=20s;
                    open_file_cache_valid 65s;
                    open_file_cache_min_uses 2;
                    open_file_cache_errors on;
                    proxy_buffering    on;
                    proxy_buffer_size  128k;
                    proxy_buffers 100  128k;
                    client_max_body_size 0M;
                    proxy_pass http://live_chatnodes;
</code>```

backend ngnix

```<code>server {
            listen 80;
            server_name 10.0.2.9;
            client_max_body_size 300M;
            location / {
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                    proxy_set_header Host $http_host;
                    proxy_set_header X-NginX-Proxy true;
                    proxy_redirect off;
                    proxy_read_timeout 120s;
                    proxy_connect_timeout 120s;
                    open_file_cache max=200000 inactive=20s;
                    open_file_cache_valid 65s;
                    open_file_cache_min_uses 2;
                    open_file_cache_errors on;
                    proxy_buffering    on;
                    proxy_buffer_size  128k;
                    proxy_buffers 100  128k;
                    client_max_body_size 0M;
                    proxy_pass http://live_nodes;
                    }
</code>```

this now pass request to upstream and upstream has 15 nodes, how ever all the request are going to one flasksocket io. which is causing my system go down. and last info upstream has iphash as per flaskcoketio documentation.
all my clients are using vpn so they have static ip as well,

Body:
I have real time chatapplication, unable to scale them.

so i have frontend ngnix which proxy pass to backend ngnix , now backend ngnix will upstream to flasksocket io multiple instance,

server {
listen 443 ssl;
#server_name xx.xxx.xx.xxx;
client_max_body_size 300M;
ssl_certificate /etc/nginx/ssl/newssl/ssl_bundle.crt;
ssl_certificate_key /etc/nginx/ssl/newssl/example.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'xxx+xxxx+xxxx';
set_real_ip_from 0.0.0.0/0;
real_ip_header X-Real-IP;
real_ip_recursive on;
add_header X-Frame-Options "SAMEORIGIN" ;
add_header Access-Control-Allow-Origin *;

location / {
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                    proxy_set_header Host $http_host;
                    proxy_set_header X-NginX-Proxy true;
                    proxy_redirect off;
                    proxy_read_timeout 120s;
                    proxy_connect_timeout 120s;
                    open_file_cache max=200000 inactive=20s;
                    open_file_cache_valid 65s;
                    open_file_cache_min_uses 2;
                    open_file_cache_errors on;
                    proxy_buffering    on;
                    proxy_buffer_size  128k;
                    proxy_buffers 100  128k;
                    client_max_body_size 0M;
                    proxy_pass http://live_chatnodes;

backend ngnix

server {
            listen 80;
            server_name 10.0.2.9;
            client_max_body_size 300M;
            location / {
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                    proxy_set_header Host $http_host;
                    proxy_set_header X-NginX-Proxy true;
                    proxy_redirect off;
                    proxy_read_timeout 120s;
                    proxy_connect_timeout 120s;
                    open_file_cache max=200000 inactive=20s;
                    open_file_cache_valid 65s;
                    open_file_cache_min_uses 2;
                    open_file_cache_errors on;
                    proxy_buffering    on;
                    proxy_buffer_size  128k;
                    proxy_buffers 100  128k;
                    client_max_body_size 0M;
                    proxy_pass http://live_nodes;
                    }

this now pass request to upstream and upstream has 15 nodes, how ever all the request are going to one flasksocket io. which is causing my system go down. and last info upstream has iphash as per flaskcoketio documentation.
all my clients are using vpn so they have static ip as well,


问:
DRF: use to_representation to hide fields
In my app, I want to hide absolute_url in the detail view and content in the list view. I always use different serializers and conditionals in view to achieve this goal. I wanted to know if it is a bad practice to use to_representation here.

serializers.py

```<code>class PostSerializer(serializers.ModelSerializer):
    absolute_url = serializers.SerializerMethodField()

    author = serializers.SlugRelatedField(slug_field="full_name", read_only=True)

    category = serializers.SlugRelatedField(
        queryset=Category.objects.all(),
        slug_field="id",
    )

    def get_absolute_url(self, obj):
        request = self.context.get("request")
        return request.build_absolute_uri(obj.slug)

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        request = self.context.get("request")

        if request.parser_context.get("kwargs").get("slug"):

            rep.pop("absolute_url", None)
        else:
            rep.pop("content", None)

        rep["category"] = CategorySerializer(instance.category).data["name"]

        return rep

    def create(self, validated_data):
        validated_data["author"] = User.objects.get(
            id=self.context.get("request").user.id
        )
        return super().create(validated_data)

    class Meta:
        model = Post
        fields = [
            "id",
            "author",
            "category",
            "title",
            "slug",
            "content",
            "status",
            "image",
            "absolute_url",
            "created_at",
            "updated_at",
            "published_at",
        ]
        read_only_fields = ["slug"]
</code>```

views.py

```<code>class PostViewSet(ModelViewSet):
    queryset = Post.objects.select_related("author", "category").all()
    serializer_class = PostSerializer
    lookup_field = "slug"
</code>```

Body:
In my app, I want to hide absolute_url in the detail view and content in the list view. I always use different serializers and conditionals in view to achieve this goal. I wanted to know if it is a bad practice to use to_representation here.

serializers.py

class PostSerializer(serializers.ModelSerializer):
    absolute_url = serializers.SerializerMethodField()

    author = serializers.SlugRelatedField(slug_field="full_name", read_only=True)

    category = serializers.SlugRelatedField(
        queryset=Category.objects.all(),
        slug_field="id",
    )

    def get_absolute_url(self, obj):
        request = self.context.get("request")
        return request.build_absolute_uri(obj.slug)

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        request = self.context.get("request")

        if request.parser_context.get("kwargs").get("slug"):

            rep.pop("absolute_url", None)
        else:
            rep.pop("content", None)

        rep["category"] = CategorySerializer(instance.category).data["name"]

        return rep

    def create(self, validated_data):
        validated_data["author"] = User.objects.get(
            id=self.context.get("request").user.id
        )
        return super().create(validated_data)

    class Meta:
        model = Post
        fields = [
            "id",
            "author",
            "category",
            "title",
            "slug",
            "content",
            "status",
            "image",
            "absolute_url",
            "created_at",
            "updated_at",
            "published_at",
        ]
        read_only_fields = ["slug"]

views.py

class PostViewSet(ModelViewSet):
    queryset = Post.objects.select_related("author", "category").all()
    serializer_class = PostSerializer
    lookup_field = "slug"


问:
how to add bookmark and hyperlink to a table cell in python
I am trying to add bookmark to a cell in an existing table and want to create the hyperlink in a separate page.

I have seen a tutorial on how to create a bookmark and hyperlink but only to a run here:
how to create bookmarks in a word document, then create internal hyperlinks to the bookmark w/ python

Below is my code, when run it successfully created the file. But when I open the file cannot be opened as it gives out an error.

Not sure though if my code is correct. I grabbed them from all over the internet trying which one would work. Appreciate if anyone can point to the right direction. Just started learning python and programming in general

```<code>from docx import Document
from docx.oxml.ns import qn
from docx.oxml.shared import OxmlElement

document = Document("sample rows.docx")
table = document.tables[0]
rows = table.rows
xml_cell = rows[1].cells[0]._tc

start = OxmlElement('w:bookmarkStart')
start.set(qn('w:id'), 'row1')
start.set(qn('w:name'), 'row1')
start.set(qn('w:colFirst'), '0')
start.set(qn('w:colLast'), '0')
xml_cell.append(start)

end = OxmlElement('w:bookmarkEnd')
end.set(qn('w:id'), 'row1')
end.set(qn('w:name'), 'row1')
xml_cell.append(end)

# Adding new page and table
document.add_page_break()
new_table = document.add_table(1, 1)
cell = new_table.add_row().cells[0]
cell.text = "This is row 1 link"
c_tc = cell._tc

hyperlink = OxmlElement('w:hyperlink')
hyperlink.set(qn('w:anchor'), 'row1')

c_tc.append(hyperlink)

document.save("sample rows1.docx")
</code>```

Update: I reverted to using run in my bookmark by extracting it form inside the cell as I was not able to find solution to adding bookmark to a cell. I will still put out the question above in the hopes that somebody will answer. The below code works for me (not related to the above code).

```<code> def add_bookmark(self, run, title_id):
    run_tag = run._r
    # create start bookmark
    start = OxmlElement('w:bookmarkStart')
    start.set(qn('w:id'), f'{title_id}')
    start.set(qn('w:name'), f'{title_id}')
    run_tag.append(start)

    text = OxmlElement('w:r')
    text.text = ''
    run_tag.append(text)
    # create end bookmark
    end = OxmlElement('w:bookmarkEnd')
    end.set(qn('w:id'), f'{title_id}')

    run_tag.append(end)

def add_hyperlink(self, title_id, paragraph):
    hyperlink = OxmlElement('w:hyperlink')
    hyperlink.set(qn('w:anchor'), f'{title_id}')

    new_run = OxmlElement('w:r')
    rPr = OxmlElement('w:rPr')
    new_run.append(rPr)
    new_run.text = f"<Title>"
    hyperlink.append(new_run)
    r = paragraph.add_run()
    r._r.append(hyperlink)
    r.font.name = "Calibri"
    r.font.italic = True
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    r.font.underline = True
</code>```

Body:
I am trying to add bookmark to a cell in an existing table and want to create the hyperlink in a separate page.

I have seen a tutorial on how to create a bookmark and hyperlink but only to a run here:
how to create bookmarks in a word document, then create internal hyperlinks to the bookmark w/ python

Below is my code, when run it successfully created the file. But when I open the file cannot be opened as it gives out an error.

Not sure though if my code is correct. I grabbed them from all over the internet trying which one would work. Appreciate if anyone can point to the right direction. Just started learning python and programming in general

from docx import Document
from docx.oxml.ns import qn
from docx.oxml.shared import OxmlElement

document = Document("sample rows.docx")
table = document.tables[0]
rows = table.rows
xml_cell = rows[1].cells[0]._tc

start = OxmlElement('w:bookmarkStart')
start.set(qn('w:id'), 'row1')
start.set(qn('w:name'), 'row1')
start.set(qn('w:colFirst'), '0')
start.set(qn('w:colLast'), '0')
xml_cell.append(start)

end = OxmlElement('w:bookmarkEnd')
end.set(qn('w:id'), 'row1')
end.set(qn('w:name'), 'row1')
xml_cell.append(end)

# Adding new page and table
document.add_page_break()
new_table = document.add_table(1, 1)
cell = new_table.add_row().cells[0]
cell.text = "This is row 1 link"
c_tc = cell._tc

hyperlink = OxmlElement('w:hyperlink')
hyperlink.set(qn('w:anchor'), 'row1')

c_tc.append(hyperlink)

document.save("sample rows1.docx")

Update: I reverted to using run in my bookmark by extracting it form inside the cell as I was not able to find solution to adding bookmark to a cell. I will still put out the question above in the hopes that somebody will answer. The below code works for me (not related to the above code).

 def add_bookmark(self, run, title_id):
    run_tag = run._r
    # create start bookmark
    start = OxmlElement('w:bookmarkStart')
    start.set(qn('w:id'), f'{title_id}')
    start.set(qn('w:name'), f'{title_id}')
    run_tag.append(start)

    text = OxmlElement('w:r')
    text.text = ''
    run_tag.append(text)
    # create end bookmark
    end = OxmlElement('w:bookmarkEnd')
    end.set(qn('w:id'), f'{title_id}')

    run_tag.append(end)

def add_hyperlink(self, title_id, paragraph):
    hyperlink = OxmlElement('w:hyperlink')
    hyperlink.set(qn('w:anchor'), f'{title_id}')

    new_run = OxmlElement('w:r')
    rPr = OxmlElement('w:rPr')
    new_run.append(rPr)
    new_run.text = f"<Title>"
    hyperlink.append(new_run)
    r = paragraph.add_run()
    r._r.append(hyperlink)
    r.font.name = "Calibri"
    r.font.italic = True
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    r.font.underline = True


问:
Lex rule to recognize tab and allow white blanks?
I am trying to write a lex code to recognize if the string contains a tab and I also want to allow any blank spaces between words.

In my lex file, I write
[  \t] {yylval.str=strdup(yytext); return TAB;}
to recognize tabs. It does recognize tab, but if the given input string contains a white space yacc returns an error. For example my rule gives no error for "x=5" but it does for "x= 5" or "x = 5".
I'd like to write a lex rule that will allow me to recognize 4 consecutive blanks(a tab) and also will allow for one white space.
Thank you.


问:
Receiving Multiplied Rundown events instead of once for the same ETW session
I have a simple usage of ETW.

I've subscribed to receive events from USB4 provider.

I have 2 sessions:

A real time session which I use to print to the console log

Second for log the events to a log file for a further investigation.

```<code>  var s = new TraceEventSession("mySession", TraceEventSessionOptions.NoPerProcessorBuffering);
  var s2 = new TraceEventSession($"mySession-log", @"C:\mySession.etl", TraceEventSessionOptions.NoPerProcessorBuffering);

  var PROVIDER_GUID = new Guid("AE795D36-2B11-5EFB-C7E0-5D552BC55D6C");

  var dynamicTraceEventParser = s.Source.Dynamic;
  dynamicTraceEventParser.All += delegate (TraceEvent data)
  {
      Console.WriteLine($"Received DRD event: {data.EventName}");
  };

  s.EnableProvider(PROVIDER_GUID);
  s2.EnableProvider(PROVIDER_GUID);

  s.Source.Process();
</code>```

Excepted Result:

Receive the event RundownStart/Start only once in the log.

Actual result:

Receive the event RundownStart/Start twice in the log.

I've realized that creating only one session, I receive the event only once but I'm not sure how creating two different un depend sessions can cause this.

Are the sessions depend of each other?

Thank you :)

Body:
I have a simple usage of ETW.

I've subscribed to receive events from USB4 provider.

I have 2 sessions:

A real time session which I use to print to the console log

Second for log the events to a log file for a further investigation.

  var s = new TraceEventSession("mySession", TraceEventSessionOptions.NoPerProcessorBuffering);
  var s2 = new TraceEventSession($"mySession-log", @"C:\mySession.etl", TraceEventSessionOptions.NoPerProcessorBuffering);

  var PROVIDER_GUID = new Guid("AE795D36-2B11-5EFB-C7E0-5D552BC55D6C");

  var dynamicTraceEventParser = s.Source.Dynamic;
  dynamicTraceEventParser.All += delegate (TraceEvent data)
  {
      Console.WriteLine($"Received DRD event: {data.EventName}");
  };

  s.EnableProvider(PROVIDER_GUID);
  s2.EnableProvider(PROVIDER_GUID);

  s.Source.Process();

Excepted Result:

Receive the event RundownStart/Start only once in the log.

Actual result:

Receive the event RundownStart/Start twice in the log.

I've realized that creating only one session, I receive the event only once but I'm not sure how creating two different un depend sessions can cause this.

Are the sessions depend of each other?

Thank you :)