问:
CKEditor can't save/publish images using CKFinder
o/

I'm having a problem saving or both saving and then publishing images in the CKEditor (CKEditor 4).
Everytime I upload a picture from my PC or select a picture from the server storage (using CKFinder), everything works fine. It fills valid path to the image URL and then after that I try to save/publish and it does something like "rollback" to the last state it was before the changes I made (basically removing the picture or some text for example that I added somewhere AFTER the image was added). So basically, everything I add after the image, it dissapears. I can't understand why it doesn't work since every other CKEditor/CKFinder functionality works and displays correctly. I can even use Iframe to display image as alternative image holding element if I need to but it wouldn't be that user friendly for customer. Also, I have noticed that after I open CKEditor and select already uploaded picture from the server (using CKFinder), I think that is the point where it stops working correctly.

If I add pictures normaly using the non-working feature that im trying to mention, it appears in HTML Source but dissapears when saved/published. Even after you open editor again, the image isn't there.

If added through HTML Source (like using the  element with same path as CKFinder provided or non-existent URL), then it works when you save/publish it. It atleast saves the image.

Setting properties (size, border, linking..etc.) of the picture works correctly using the editor. Even if I manualy type the URL into the input box it works. It stops working when I open CKFinder.

ckeditor_image_properties

Web-App is running under ASP, just in case.

I was searching for articles with this exact problem but I couldn't find any. I found a few similar problems like this but not exactly the same and it didn't even help me. I found 1 article on the official page with indetical problem but it wasn't answered there and probably won't be since its 10+ years old question :D. So, I'm asking you guys and I will be glad for anyone trying to help me. For further information don't hesitate to ask me.

Things I tried/expected:

// 1 //
Checking CKEditor and CKFinder configs for anomalies.. Since I was looking for misspelling or some other type of thing. I threw this idea aside because the configs were empty - I don't have knowledge if they are supposed to be empty like this or if its OK. All I know is that my team uses CKEditor and CKFinder that way and it always worked.
ckeditor_empty_config_file
ckfinder_empty_config_file

// 2 //
Reimplemented both CKEditor/CKFinder - I thought it may be because of old version or something..

// 3 //
I tried changing various picture formats, such as: .png, .jpg, .jpeg, .gif - I thought it has some form of restriction for file formats

// 4 //
I also tried copy pasting already added picture via HTML Source which worked after save/publish but once again not after I set src attribude of the image using CKFinder.

// 5 //
Checking for images folder security policy - if it can be accessed on the internet (can be).

// 6 //
Checked for reversed slash in path of the image

// 7 //
Tried remove and reupload in case they were corrupted

Merry Christmas,
Mark.


来源: stackexchange

问:
Wrong values when trying to project a 3d point onto 2d screen
I am trying to implement a simple 3D render pipeline in C#.

For that I made implementations of useful classes, these inclide Vector3, GameObject, Matrix, Camera

Vector3 is just a simple class that holds 3 values (X, Y, Z) and has some helpful methods (ApplyRotation (applies rotation on all axis), Normalize (Normalizes the vector), Dot (returns the Dot Product of two vectors), Cross (returns cross product of two vectors))

The Matrix class is a class that represents any Matrix of a desired size and it has some helpful methods and a multiplication operator. Methods contained in Matrix include CreateLookAt, CreatePerspectiveFieldOfView

The code for those two methods in the matrix class is:

```<code>public static Matrix CreatePerspectiveFieldOfView(double fieldOfView, double aspectRatio, double nearPlaneDistance, double farPlaneDistance)
{
    if (fieldOfView <= 0f || fieldOfView >= Math.PI)
    {
        throw new ArgumentOutOfRangeException("fieldOfView");
    }

    if (nearPlaneDistance <= 0f)
    {
        throw new ArgumentOutOfRangeException("nearPlaneDistance");
    }

    if (farPlaneDistance <= 0f)
    {
        throw new ArgumentOutOfRangeException("farPlaneDistance");
    }

    if (nearPlaneDistance >= farPlaneDistance)
    {
        throw new ArgumentOutOfRangeException("nearPlaneDistance");
    }

    double num = 1f / Math.Tan(fieldOfView * 0.5f);
    Matrix result = new Matrix(4, 4);
    result.Elements = new double[16] {
num / aspectRatio, 0f, 0f, 0f,
0f, num, 0f, 0f,
0f, 0f, farPlaneDistance / (nearPlaneDistance - farPlaneDistance), -1f,
0f, 0f, nearPlaneDistance * farPlaneDistance / (nearPlaneDistance - farPlaneDistance), 0f

    return result;
}

public static Matrix CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector)
{
    Vector3 vector = Vector3.Normalize(cameraPosition - cameraTarget);
    Vector3 vector2 = Vector3.Normalize(Vector3.Cross(cameraUpVector, vector));
    Vector3 vector3 = Vector3.Cross(vector, vector2);
    Matrix result = new Matrix(4, 4);
    result.Elements = new double[16] {
        vector2.X, vector3.X, vector.X, 0f,
        vector2.Y, vector3.Y, vector.Y, 0f,
        vector2.Z, vector3.Z, vector.Z, 0f,
        0f - Vector3.Dot(vector2, cameraPosition),
        0f - Vector3.Dot(vector3, cameraPosition),
        0f - Vector3.Dot(vector, cameraPosition),
        1f
    };

    return result;
}
</code>```

Matrix.Elements is just a flat representation of the elements in the matrix.

Note: In my coordinate system X is forward, Y is right and Z is up

The code I use to project the vertices:

```<code>double fovRad = FOV * Math.PI / 180;

Matrix viewMatrix = Matrix.CreateLookAt(Position, Direction, DirectionUp); // the view matrix
Matrix projectionMatrix = Matrix.CreatePerspectiveFieldOfView(fovRad, AspectRatio, NearClip, FarClip); // the perspective projection matrix
Console.WriteLine(viewMatrix);
Console.WriteLine(projectionMatrix);
Color[] image = new Color[ScreenWidth * ScreenHeight];

foreach (var gameObject in _world)
{
    foreach (var meshVertex in gameObject.Mesh.Points)
    {
        Vector3 point3D = Vector3.ApplyRotation(meshVertex, gameObject.Rotation) + gameObject.Position;
        Console.WriteLine(point3D);
        point3D = point3D - Position;

        // convert the 3D point from world coordinates to view coordinates
        Matrix homogeneVector = new Matrix(1, 4);
        homogeneVector.Elements = new double[4]
        {
            point3D.X,
            point3D.Y,
            point3D.Z,
            0
        };
        Matrix pointView = viewMatrix * homogeneVector;

        // convert the view coordinates to clip coordinates
        Vector3 pointClip = projectionMatrix * pointView;

        // convert the clip coordinates to screen coordinates
        Vector3 pointScreen = new Vector3(
            (pointClip.X + 1) / 2,
            (pointClip.Y + 1) / 2 * ScreenWidth,
            (pointClip.Z + 1) / 2 * ScreenHeight
        );

        if (pointScreen.Y > 0 && pointScreen.Z > 0 && pointScreen.Y < ScreenWidth && pointScreen.Z < ScreenHeight)
        {
            image[(int)(pointScreen.Y * ScreenWidth + pointScreen.X)] = Color.Black;
        }
    }
}

</code>```

image is a flat representation of the rendered image.

_world is a list of gameObjects and item.Mesh.Points is a list of Vector3's

In my test case FOV is set to 90, ScreenWidth is set to 48 and ScreenHeight is set to 27. The AspectRatio is calculated as ScreenWidth / ScreenHeight (I don't know if this is the right way to do it). The screen dimensions are so small because I am testing this in the console.

Position is simply (X:0 Y:0 Z:0), Direction is Vector3.Forward (X:1 Y:0 Z:0) and DirectionUp is Vector3.Up (X:0 Y:0 Z:1)

My problem is that the resulting 2d coordinates do not make any sense and I am stuck.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to implement a simple 3D render pipeline in C#.

For that I made implementations of useful classes, these inclide Vector3, GameObject, Matrix, Camera

Vector3 is just a simple class that holds 3 values (X, Y, Z) and has some helpful methods (ApplyRotation (applies rotation on all axis), Normalize (Normalizes the vector), Dot (returns the Dot Product of two vectors), Cross (returns cross product of two vectors))

The Matrix class is a class that represents any Matrix of a desired size and it has some helpful methods and a multiplication operator. Methods contained in Matrix include CreateLookAt, CreatePerspectiveFieldOfView

The code for those two methods in the matrix class is:

public static Matrix CreatePerspectiveFieldOfView(double fieldOfView, double aspectRatio, double nearPlaneDistance, double farPlaneDistance)
{
    if (fieldOfView <= 0f || fieldOfView >= Math.PI)
    {
        throw new ArgumentOutOfRangeException("fieldOfView");
    }

    if (nearPlaneDistance <= 0f)
    {
        throw new ArgumentOutOfRangeException("nearPlaneDistance");
    }

    if (farPlaneDistance <= 0f)
    {
        throw new ArgumentOutOfRangeException("farPlaneDistance");
    }

    if (nearPlaneDistance >= farPlaneDistance)
    {
        throw new ArgumentOutOfRangeException("nearPlaneDistance");
    }

    double num = 1f / Math.Tan(fieldOfView * 0.5f);
    Matrix result = new Matrix(4, 4);
    result.Elements = new double[16] {
num / aspectRatio, 0f, 0f, 0f,
0f, num, 0f, 0f,
0f, 0f, farPlaneDistance / (nearPlaneDistance - farPlaneDistance), -1f,
0f, 0f, nearPlaneDistance * farPlaneDistance / (nearPlaneDistance - farPlaneDistance), 0f

    return result;
}

public static Matrix CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector)
{
    Vector3 vector = Vector3.Normalize(cameraPosition - cameraTarget);
    Vector3 vector2 = Vector3.Normalize(Vector3.Cross(cameraUpVector, vector));
    Vector3 vector3 = Vector3.Cross(vector, vector2);
    Matrix result = new Matrix(4, 4);
    result.Elements = new double[16] {
        vector2.X, vector3.X, vector.X, 0f,
        vector2.Y, vector3.Y, vector.Y, 0f,
        vector2.Z, vector3.Z, vector.Z, 0f,
        0f - Vector3.Dot(vector2, cameraPosition),
        0f - Vector3.Dot(vector3, cameraPosition),
        0f - Vector3.Dot(vector, cameraPosition),
        1f
    };

    return result;
}

Matrix.Elements is just a flat representation of the elements in the matrix.

Note: In my coordinate system X is forward, Y is right and Z is up

The code I use to project the vertices:

double fovRad = FOV * Math.PI / 180;

Matrix viewMatrix = Matrix.CreateLookAt(Position, Direction, DirectionUp); // the view matrix
Matrix projectionMatrix = Matrix.CreatePerspectiveFieldOfView(fovRad, AspectRatio, NearClip, FarClip); // the perspective projection matrix
Console.WriteLine(viewMatrix);
Console.WriteLine(projectionMatrix);
Color[] image = new Color[ScreenWidth * ScreenHeight];

foreach (var gameObject in _world)
{
    foreach (var meshVertex in gameObject.Mesh.Points)
    {
        Vector3 point3D = Vector3.ApplyRotation(meshVertex, gameObject.Rotation) + gameObject.Position;
        Console.WriteLine(point3D);
        point3D = point3D - Position;

        // convert the 3D point from world coordinates to view coordinates
        Matrix homogeneVector = new Matrix(1, 4);
        homogeneVector.Elements = new double[4]
        {
            point3D.X,
            point3D.Y,
            point3D.Z,
            0
        };
        Matrix pointView = viewMatrix * homogeneVector;

        // convert the view coordinates to clip coordinates
        Vector3 pointClip = projectionMatrix * pointView;

        // convert the clip coordinates to screen coordinates
        Vector3 pointScreen = new Vector3(
            (pointClip.X + 1) / 2,
            (pointClip.Y + 1) / 2 * ScreenWidth,
            (pointClip.Z + 1) / 2 * ScreenHeight
        );

        if (pointScreen.Y > 0 && pointScreen.Z > 0 && pointScreen.Y < ScreenWidth && pointScreen.Z < ScreenHeight)
        {
            image[(int)(pointScreen.Y * ScreenWidth + pointScreen.X)] = Color.Black;
        }
    }
}

image is a flat representation of the rendered image.

_world is a list of gameObjects and item.Mesh.Points is a list of Vector3's

In my test case FOV is set to 90, ScreenWidth is set to 48 and ScreenHeight is set to 27. The AspectRatio is calculated as ScreenWidth / ScreenHeight (I don't know if this is the right way to do it). The screen dimensions are so small because I am testing this in the console.

Position is simply (X:0 Y:0 Z:0), Direction is Vector3.Forward (X:1 Y:0 Z:0) and DirectionUp is Vector3.Up (X:0 Y:0 Z:1)

My problem is that the resulting 2d coordinates do not make any sense and I am stuck.


问:
CORS config at webpackDevServer.config.js doesn't work
i create a create-react-app project at localhost:3000 and install axios
after i ejected webpack config,i have set proxy in webpackDevServer.config.js like this

```<code>proxy: {
      "/api": {
        target: "http://127.0.0.1:7000",
        changeOrigin: true,
      },
    },
</code>```

the create-react-app project still send the request to localhost:3000,the proxy not working...
here's f12 error picture

and i also tried to restart the project many times...
also tried to set proxy at package.json,still not work

Body:
i create a create-react-app project at localhost:3000 and install axios
after i ejected webpack config,i have set proxy in webpackDevServer.config.js like this

proxy: {
      "/api": {
        target: "http://127.0.0.1:7000",
        changeOrigin: true,
      },
    },

the create-react-app project still send the request to localhost:3000,the proxy not working...
here's f12 error picture

and i also tried to restart the project many times...
also tried to set proxy at package.json,still not work


问:
Mono.Android.dll not support in .Net Maui, Any alternative for Android.Telephony?
I'm trying to create sms app in .net maui using Android.Telephony. I was successfully done it during debug. In release mode, although it return errors
enter image description here, it let me finished the app install to my device and it works fine too. but when I try to publish (create archive or an apk). its always failed to published. I believe its the Android.Telephony cause the failures. Any Suggestion or any alternative to Android.Telephony in .net maui? Thank you</p>


问:
Error when use camera in flutter(on android)
when I use camera library , when i use availableCameras() , I get error on Android but in IOS work correctly.

```<code>import 'package:camera/camera.dart';

cameras = await availableCameras();
cameraController = CameraController(cameras[selectedCamera], ResolutionPreset.max);
cameraController!.initialize().then((_) {
  if (!mounted) {
    return;
  }
  setState(() {});
}).catchError((Object e) {
  if (e is CameraException) {
    switch (e.code) {
      case 'CameraAccessDenied':
        print('User denied camera access.');
        break;
      default:
        print('Handle other errors.');
        break;
    }
  }
});
</code>```

error:

```<code>E/flutter ( 1927): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception:    Null check operator used on a null value E/flutter ( 1927): #0      AndroidCamera.availableCameras.<anonymous closure> (package:camera_android/src/android_camera.dart:85:60) E/flutter ( 1927): #1      MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31) E/flutter ( 1927): #2      ListIterator.moveNext (dart:_internal/iterable.dart:342:26) E/flutter ( 1927): #3      new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:189:27) E/flutter ( 1927): #4      new _GrowableList.of (dart:core-patch/growable_array.dart:150:28) E/flutter ( 1927): #5      new List.of (dart:core-patch/array_patch.dart:51:28) E/flutter ( 1927): #6      ListIterable.toList (dart:_internal/iterable.dart:213:44) E/flutter ( 1927): #7      AndroidCamera.availableCameras (package:camera_android/src/android_camera.dart:88:10) E/flutter ( 1927): <asynchronous suspension> E/flutter ( 1927): #8      _CameraPageState.initCamera (package:ocr_card/features/ocr/presentation/page/camera_page.dart:242:15) E/flutter ( 1927): <asynchronous suspension>
</code>```

Body:
when I use camera library , when i use availableCameras() , I get error on Android but in IOS work correctly.

import 'package:camera/camera.dart';

cameras = await availableCameras();
cameraController = CameraController(cameras[selectedCamera], ResolutionPreset.max);
cameraController!.initialize().then((_) {
  if (!mounted) {
    return;
  }
  setState(() {});
}).catchError((Object e) {
  if (e is CameraException) {
    switch (e.code) {
      case 'CameraAccessDenied':
        print('User denied camera access.');
        break;
      default:
        print('Handle other errors.');
        break;
    }
  }
});

error:

E/flutter ( 1927): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception:    Null check operator used on a null value E/flutter ( 1927): #0      AndroidCamera.availableCameras.<anonymous closure> (package:camera_android/src/android_camera.dart:85:60) E/flutter ( 1927): #1      MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31) E/flutter ( 1927): #2      ListIterator.moveNext (dart:_internal/iterable.dart:342:26) E/flutter ( 1927): #3      new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:189:27) E/flutter ( 1927): #4      new _GrowableList.of (dart:core-patch/growable_array.dart:150:28) E/flutter ( 1927): #5      new List.of (dart:core-patch/array_patch.dart:51:28) E/flutter ( 1927): #6      ListIterable.toList (dart:_internal/iterable.dart:213:44) E/flutter ( 1927): #7      AndroidCamera.availableCameras (package:camera_android/src/android_camera.dart:88:10) E/flutter ( 1927): <asynchronous suspension> E/flutter ( 1927): #8      _CameraPageState.initCamera (package:ocr_card/features/ocr/presentation/page/camera_page.dart:242:15) E/flutter ( 1927): <asynchronous suspension>


问:
WSM-01775 The policy "oracle/wss_username_token_service_policy" cannot be attached to ResourcePattern "/WLS/oim_domain/UNKNOWN"
I am unable to make request from OIM to SOA composite due to some policy mapping issue in Oracle Fusion Middleware.

```<code>at org.identityconnectors.framework.impl.api.BufferedResultsProxy$BufferedResultsHandler.run(BufferedResultsProxy.java:162)
Caused by: oracle.fabric.common.PolicyEnforcementException: WSM-07620 : Agent cannot enforce policies due to either failure in retrieving polices or error in validations, detail= "WSM-01775 The policy "oracle/wss_username_token_service_policy" cannot be attached to ResourcePattern "/WLS/oim_domain/UNKNOWN|#iam-ejb.jar|WS-Client({http://org.identityconnectors.genericws}wsconnector_client_ep#WebservicesConnectorService_pt,wls)" SubjectType "WLS_REFERENCE" of attachTo "binding.client" since it may only be used with "a service endpoint".
</code>```

Need to remove this policy attachment from this UNKNOWN application. How to do this. Snap is from oracle EM console.

Body:
I am unable to make request from OIM to SOA composite due to some policy mapping issue in Oracle Fusion Middleware.

at org.identityconnectors.framework.impl.api.BufferedResultsProxy$BufferedResultsHandler.run(BufferedResultsProxy.java:162)
Caused by: oracle.fabric.common.PolicyEnforcementException: WSM-07620 : Agent cannot enforce policies due to either failure in retrieving polices or error in validations, detail= "WSM-01775 The policy "oracle/wss_username_token_service_policy" cannot be attached to ResourcePattern "/WLS/oim_domain/UNKNOWN|#iam-ejb.jar|WS-Client({http://org.identityconnectors.genericws}wsconnector_client_ep#WebservicesConnectorService_pt,wls)" SubjectType "WLS_REFERENCE" of attachTo "binding.client" since it may only be used with "a service endpoint".

Need to remove this policy attachment from this UNKNOWN application. How to do this. Snap is from oracle EM console.


问:
Cursor pagination with random start position
I am trying to create a cursor paginator that can start in a random place of a result set, so the initial request can potentially have both previous and next cursors, unlike a normal request that will only have a next on the initial request. Please note that I am writing this in Laravel, but any frameworks solution might work, so please share any insights.

Imagine I have the following data:

```<code>[
    {
        id: 1,
        created_at: "2020-01-01 00:00:00"
    },
    {
        id: 2,
        created_at: "2020-02-01 00:00:00"
    },
    {
        id: 3
        created_at: "2020-03-01 00:00:00"
    },
]
</code>```

I would like to be able to request a cursor paginated response like so: .../api/data?from=2020-02-01&limit=1, which would match id: 2, and because this is in the middle of the complete data, it would make sense to get a previous cursor here, so I can get to id: 1 and id: 3 with next.

The problem I am facing is that in the initial requests query I'm specifying a specific date to get to the point in the data I wish to start from, but that query will then be passed into the next requests and be locked to the first timestamp. Example of initial query: Model::where('created_at' '2020-02-01 00:00:00')->orderBy('created_at'); The next request would then generate something like: Model::where('created_at' '2020-02-01 00:00:00')->orderBy('created_at')->where('created_at', '>', '2020-02-01 00:00:00'); which ofc will fail due to the first where clause.

I am not sure if this is even possible to achieve with Laravels default cursor implementation. I hope the problem is clear from my description, if not please let me know so I can try to elaborate.

Body:
I am trying to create a cursor paginator that can start in a random place of a result set, so the initial request can potentially have both previous and next cursors, unlike a normal request that will only have a next on the initial request. Please note that I am writing this in Laravel, but any frameworks solution might work, so please share any insights.

Imagine I have the following data:

[
    {
        id: 1,
        created_at: "2020-01-01 00:00:00"
    },
    {
        id: 2,
        created_at: "2020-02-01 00:00:00"
    },
    {
        id: 3
        created_at: "2020-03-01 00:00:00"
    },
]

I would like to be able to request a cursor paginated response like so: .../api/data?from=2020-02-01&limit=1, which would match id: 2, and because this is in the middle of the complete data, it would make sense to get a previous cursor here, so I can get to id: 1 and id: 3 with next.

The problem I am facing is that in the initial requests query I'm specifying a specific date to get to the point in the data I wish to start from, but that query will then be passed into the next requests and be locked to the first timestamp. Example of initial query: Model::where('created_at' '2020-02-01 00:00:00')->orderBy('created_at'); The next request would then generate something like: Model::where('created_at' '2020-02-01 00:00:00')->orderBy('created_at')->where('created_at', '>', '2020-02-01 00:00:00'); which ofc will fail due to the first where clause.

I am not sure if this is even possible to achieve with Laravels default cursor implementation. I hope the problem is clear from my description, if not please let me know so I can try to elaborate.


问:
Datadog Display External Data Source in Dashboard
I want to display a simple data table that I have stored in an AWS S3 bucket in .CSV format in a Datadog dashboard that I have created. Is that possible? If so, how do I get Datadog to reach that data and then, visualise it on my dashboard using its widgets, such as a Table or a Query Value.</p>


问:
I'm getting the following error: Server Error in '/' Application
My site is on a shared hosting and often I get the below error:

I found 2 solutions : link , but I don't know what is the best approach:

generate machine key?

OR

add <pages enableeventvalidation="false" viewstateencryptionmode="Never"></pages>

The Error:

Server Error in '/' Application. Validation of viewstate MAC failed.
If this application is hosted by a Web Farm or cluster, ensure that
 configuration specifies the same validationKey and
validation algorithm. AutoGenerate cannot be used in a cluster.

http://go.microsoft.com/fwlink/?LinkID=314055 Description: An
unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.

Exception Details: System.Web.HttpException: Validation of viewstate
MAC failed. If this application is hosted by a Web Farm or cluster,
ensure that  configuration specifies the same
validationKey and validation algorithm. AutoGenerate cannot be used in
a cluster.

http://go.microsoft.com/fwlink/?LinkID=314055

Source Error:

[No relevant source lines]

Source File:
d:\vhosts\sawexim.ro\tmp\root\9574527f\621fe154\App_Web_c1scnmd5.2.cs
Line: 0


问:
How to set absolute path in file templates?
I want to create a file in a concrete package, no matter where the user clicks in the file tree.

E.g. I want to always create a file inside relations package. Here I clicked on the entity package, but I expect to get the resulting file in relations package nevertheless.

Choosing package for new file

Here is a similar question for Android Studio. I guess, my question will cover a broader audience.

If I mention the full path to desired package (src/main/kotlin/relations), then in the example I will get a file that has the following path from the root: src/main/kotlin/entity/src/main/kotlin/relations. I tried writing path prefixes (like ../../src/main/kotlin/relations), but it does nothing, also the amount of these prefixes may vary depending on where I clicked in the file tree.

Is there any way that a file template creator can distinguish between absolute and relative paths?


问:
Display image in MVC
My images always show as errors

My view:

```<code>  <img src="@Url.Action("Images", "BookStore", new {id = item.Photo})"/>
</code>```

My Controller:

```<code>  public FileContentResult Images(string photo)
        {
            var image = _bookStoreService.GetImage(photo);
            //byte[] imgarray = System.IO.File.ReadAllBytes(photo);

            return new FileContentResult(image, "image/png");
        }
</code>```

photo is a path to image on disk

Im trying to display photo on my site using MVC c# with framework

Title: Display image in MVC

Body:
My images always show as errors

My view:

My Controller:

  public FileContentResult Images(string photo)
        {
            var image = _bookStoreService.GetImage(photo);
            //byte[] imgarray = System.IO.File.ReadAllBytes(photo);

            return new FileContentResult(image, "image/png");
        }

photo is a path to image on disk

Im trying to display photo on my site using MVC c# with framework


问:
Unable to load DLL 'Microsoft.Data.SqlClient.SNI.dll' or one of its dependencies: Access is denied. (0x80070005 (E_ACCESSDENIED))
I am trying to impersonate a user for this AspNertCore web API, to have one user for the database. This is done in .Net 6

On "open" it gives me this error:

```<code>Unable to load DLL 'Microsoft.Data.SqlClient.SNI.dll' or one of its
dependencies: Access is denied. (0x80070005 (E_ACCESSDENIED))
</code>```

I have a feeling, that this is related to the impersonated user not being to access the file rather than a connection issue.
Creating the SqlConnection before impersonating does not change anything.

Impersonation works, as I throw error messages there rather than saving to log file as the impersonated user cannot save to the disk.

The whole thing works when I run it without impersonation

Is there a way around this?

The code is:

```<code>IntPtr token = IntPtr.Zero;
try
{
    int TResult = LogonUser("user", "domain", "topSecret",
        LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, ref token);
    if (TResult > 0)
    {
        if (!ImpersonateLoggedOnUser(token))
            throw new Exception($"Failed to impersonate 2");
    }
    else
        throw new Exception($"Failed to impersonate 1");

    string connectionString = "Server=data;Database=db;";
    connectionString += "User Id=someone;Password=topSecret;";
    connectionString += "TrustServerCertificate=true;";
    connectionString += "Integrated Security=true;";
    //connectionString += "Integrated security=sspi";
    connection = new SqlConnection(connectionString);
    connection.Open();

    return connection.State == ConnectionState.Open;
}
catch (Exception ex)
{
    RevertToSelf();
    Log.Error($"OpenConnection: {ex.Message}");
    return false;
}
finally
{
    RevertToSelf();
    if (token != IntPtr.Zero)
    {
        CloseHandle(token);
    }
}
</code>```

Body:
I am trying to impersonate a user for this AspNertCore web API, to have one user for the database. This is done in .Net 6

On "open" it gives me this error:

Unable to load DLL 'Microsoft.Data.SqlClient.SNI.dll' or one of its
dependencies: Access is denied. (0x80070005 (E_ACCESSDENIED))

I have a feeling, that this is related to the impersonated user not being to access the file rather than a connection issue.
Creating the SqlConnection before impersonating does not change anything.

Impersonation works, as I throw error messages there rather than saving to log file as the impersonated user cannot save to the disk.

The whole thing works when I run it without impersonation

Is there a way around this?

The code is:

IntPtr token = IntPtr.Zero;
try
{
    int TResult = LogonUser("user", "domain", "topSecret",
        LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, ref token);
    if (TResult > 0)
    {
        if (!ImpersonateLoggedOnUser(token))
            throw new Exception($"Failed to impersonate 2");
    }
    else
        throw new Exception($"Failed to impersonate 1");

    string connectionString = "Server=data;Database=db;";
    connectionString += "User Id=someone;Password=topSecret;";
    connectionString += "TrustServerCertificate=true;";
    connectionString += "Integrated Security=true;";
    //connectionString += "Integrated security=sspi";
    connection = new SqlConnection(connectionString);
    connection.Open();

    return connection.State == ConnectionState.Open;
}
catch (Exception ex)
{
    RevertToSelf();
    Log.Error($"OpenConnection: {ex.Message}");
    return false;
}
finally
{
    RevertToSelf();
    if (token != IntPtr.Zero)
    {
        CloseHandle(token);
    }
}


问:
How to prepare JSON format export from Pandas dataframe for Apexcharts?
As an input I have pandas dataframe with few numeric columns, which I would like to use as a source in Apexcharts which reads data from JSON. Can you please help me with a right format of JSON and how to read it from javascript to display selected series in Apexcharts?

Test Data from python pandas:

```<code>planStartAmount = 1000
plan1Perc = 0.015
plan2Perc = 0.02

date_pattern = pd.date_range(start='2022-12-01', end='2022-12-20')
date_pattern = pd.DataFrame({"Date": date_pattern})
date_pattern['Weekday'] = date_pattern['Date'].dt.dayofweek + 1

date_pattern = date_pattern.reset_index(drop=True)
date_pattern['PlanDayNumber'] = date_pattern.index + 1

for index, row in date_pattern.iterrows():
    if index == 0:
        #print('index je nula')
        #date_pattern['BalanceStartOfDay'][index] = plan1StartAmount
        date_pattern.loc[index,'Plan1BalanceStartOfDay'] = planStartAmount
        date_pattern.loc[index,'Plan2BalanceStartOfDay'] = planStartAmount
    else:
        #date_pattern['BalanceStartOfDay'][index] = date_pattern['BalanceEndOfDay'][index-1]
        date_pattern.loc[index,'Plan1BalanceStartOfDay'] = date_pattern.loc[index-1,'Plan1BalanceEndOfDay']
        date_pattern.loc[index,'Plan2BalanceStartOfDay'] = date_pattern.loc[index-1,'Plan2BalanceEndOfDay']

    date_pattern.loc[index,'Plan1BalanceDayTarget'] = round(date_pattern.loc[index,'Plan1BalanceStartOfDay'] * plan1Perc)
    date_pattern.loc[index,'Plan2BalanceDayTarget'] = round(date_pattern.loc[index,'Plan2BalanceStartOfDay'] * plan2Perc)

    date_pattern.loc[index,'Plan1BalanceEndOfDay'] = date_pattern.loc[index,'Plan1BalanceStartOfDay'] + date_pattern.loc[index,'Plan1BalanceDayTarget']
    date_pattern.loc[index,'Plan2BalanceEndOfDay'] = date_pattern.loc[index,'Plan2BalanceStartOfDay'] + date_pattern.loc[index,'Plan2BalanceDayTarget']

date_pattern = pd.DataFrame( date_pattern,
                             columns=['Date', 'PlanDayNumber', 'Plan1BalanceEndOfDay', 'Plan2BalanceEndOfDay']
                                 )

date_pattern.to_json('plans.json', orient = 'table', compression = 'infer', index = 'true')
date_pattern
</code>```

In html, in  section I would like to create an Apexchart (or other charts) which uses columns Plan1BalanceEndOfDay and Plan2BalanceEndOfDay as a data series, and Date as a categories?

How to correctly format exported JSON file?

Code which must be modified in javascript:

```<code><script>
    var options = {
      chart: {
          height: 300,
          type: 'line',
      },
      dataLabels: {
          enabled: false
      },
      series: [],
      title: {
          text: 'Ajax Example',
      },
      noData: {
        text: 'Loading...'
      },
      stroke: {
        dashArray: 2
      },
      xaxis: {
          type: 'category',
          tickPlacement: 'on',
          labels: {
            rotate: -45,
            rotateAlways: true
          }
      }
    }

    var chart = new ApexCharts(document.querySelector("#apexcharts-line-chart"), options );
    chart.render();

    //  in order to create dynamic charts using JSON data, all you need to do is render an empty chart initially and then call the updateSeries method.
    // var url = 'data/yearly.json';
    var url = 'data/plans.json';

    $.getJSON(url, function(response) {
        chart.updateSeries([{
          name: 'Sales',
          data: response
        }])
      });

  </script>
</code>```

resp. how to modify below code to read my JSON?

```<code> <script>
        document.addEventListener("DOMContentLoaded", function() {
            // Line chart
            var options = {
                chart: {
                    height: 350,
                    type: "line",
                    zoom: {
                        enabled: false
                    },
                },
                dataLabels: {
                    enabled: false
                },
                stroke: {
                    width: [5, 7, 5],
                    curve: "straight",
                    dashArray: [0, 8, 5]
                },
                series: [{
                        name: "Series 1",
                        data: [45, 52, 38, 24, 33, 26, 21, 20, 6, 8, 15, 10]
                    },
                    {
                        name: "Series 2",
                        data: [35, 41, 62, 42, 13, 18, 29, 37, 36, 51, 32, 53]
                    },
                    {
                        name: "Series 3",
                        data: [87, 57, 74, 99, 75, 38, 62, 47, 82, 56, 63, 91]
                    }
                ],
                markers: {
                    size: 0,
                    style: "hollow", // full, hollow, inverted
                },
                xaxis: {
                    categories: ["01 Jan", "02 Jan", "03 Jan", "04 Jan", "05 Jan", "06 Jan", "07 Jan", "08 Jan", "09 Jan", "10 Jan", "11 Jan", "12 Jan"],
                },
                tooltip: {
                    y: [{
                        title: {
                            formatter: function(val) {
                                return val + " (mins)"
                            }
                        }
                    }, {
                        title: {
                            formatter: function(val) {
                                return val + " per session"
                            }
                        }
                    }, {
                        title: {
                            formatter: function(val) {
                                return val;
                            }
                        }
                    }]
                },
                grid: {
                    borderColor: "#f1f1f1",
                }
            }
            var chart = new ApexCharts(
                document.querySelector("#apexcharts-line"),
                options
            );
            chart.render();
        });
    </script>
</code>```

Body:
As an input I have pandas dataframe with few numeric columns, which I would like to use as a source in Apexcharts which reads data from JSON. Can you please help me with a right format of JSON and how to read it from javascript to display selected series in Apexcharts?

Test Data from python pandas:

planStartAmount = 1000
plan1Perc = 0.015
plan2Perc = 0.02

date_pattern = pd.date_range(start='2022-12-01', end='2022-12-20')
date_pattern = pd.DataFrame({"Date": date_pattern})
date_pattern['Weekday'] = date_pattern['Date'].dt.dayofweek + 1

date_pattern = date_pattern.reset_index(drop=True)
date_pattern['PlanDayNumber'] = date_pattern.index + 1

for index, row in date_pattern.iterrows():
    if index == 0:
        #print('index je nula')
        #date_pattern['BalanceStartOfDay'][index] = plan1StartAmount
        date_pattern.loc[index,'Plan1BalanceStartOfDay'] = planStartAmount
        date_pattern.loc[index,'Plan2BalanceStartOfDay'] = planStartAmount
    else:
        #date_pattern['BalanceStartOfDay'][index] = date_pattern['BalanceEndOfDay'][index-1]
        date_pattern.loc[index,'Plan1BalanceStartOfDay'] = date_pattern.loc[index-1,'Plan1BalanceEndOfDay']
        date_pattern.loc[index,'Plan2BalanceStartOfDay'] = date_pattern.loc[index-1,'Plan2BalanceEndOfDay']

    date_pattern.loc[index,'Plan1BalanceDayTarget'] = round(date_pattern.loc[index,'Plan1BalanceStartOfDay'] * plan1Perc)
    date_pattern.loc[index,'Plan2BalanceDayTarget'] = round(date_pattern.loc[index,'Plan2BalanceStartOfDay'] * plan2Perc)

    date_pattern.loc[index,'Plan1BalanceEndOfDay'] = date_pattern.loc[index,'Plan1BalanceStartOfDay'] + date_pattern.loc[index,'Plan1BalanceDayTarget']
    date_pattern.loc[index,'Plan2BalanceEndOfDay'] = date_pattern.loc[index,'Plan2BalanceStartOfDay'] + date_pattern.loc[index,'Plan2BalanceDayTarget']

date_pattern = pd.DataFrame( date_pattern,
                             columns=['Date', 'PlanDayNumber', 'Plan1BalanceEndOfDay', 'Plan2BalanceEndOfDay']
                                 )

date_pattern.to_json('plans.json', orient = 'table', compression = 'infer', index = 'true')
date_pattern

In html, in  section I would like to create an Apexchart (or other charts) which uses columns Plan1BalanceEndOfDay and Plan2BalanceEndOfDay as a data series, and Date as a categories?

How to correctly format exported JSON file?

Code which must be modified in javascript:

resp. how to modify below code to read my JSON?


问:
Two apps on Scalingo share redis connections issues (read error on connection)

Problem 1: Read error on connection

Regularily, I get reports on Sentry, for two Scalingo (Laravel) projects :

RedisException /app/Console/Commands/Laravel/WorkCommand.php in App\Console\Commands\Laravel\WorkCommand::handle

read error on connection to xxx-285.redis.dbs.scalingo.com:31659

I don't understand why, and when I relaunch the job, it just works. It happens 1 over 5 times. A few jobs are done every day for Project A, and the Project B have several thousands of jobs processed every hour (ie. 70k for the last hour).

I'm using Laravel 6, and a Scalingo container having a Redis addon. 256M on Project A and 4GB on Project B. Horizon is installed and every containers have only 1 instance (no replication).

Here is the Redis configuration (database.php) for both projects :

$redisDSN = env('REDIS_URL', 'tcp://127.0.0.1:6379/0');
$redisUrl = parse_url($redisDSN);

return [
    // ...
    'redis' => [
        'client' => 'phpredis',

        'default' => [
            'scheme'   => env('REDIS_SCHEME',   data_get($redisUrl, 'scheme')),
            'host'     => env('REDIS_HOST',     data_get($redisUrl, 'host')),
            'password' => env('REDIS_PASSWORD', data_get($redisUrl, 'pass')),
            'port'     => env('REDIS_PORT',     data_get($redisUrl, 'port')),
            'database' => env('REDIS_DATABASE', substr(data_get($redisUrl, 'path', '/0'), 1)) + $databaseOffset,
            'read_write_timeout' => -1, // please take note of -1 here
        ];
    ],
];
```
<p>and <code>queue.php</code></p>
<pre class="lang-php prettyprint-override"><code>        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
            'queue' => 'default',
            'retry_after' => 1800, // Run for max 30 minutes
        ],
</code>```

I tried adding this in database configuration, but doesn't seem to help, as i'm still facing the timeout issue:

'read_write_timeout' => -1,
```
<p>I contacted Scalingo several times so I can change the timeout variable in <code>redis.conf</code> but they told me I should not do that because they have safe values.
The Redis server is not under heavy load for both apps (see screenshots below)</p>
<h2>Project A</h2>
<p><img src="https://i.stack.imgur.com/CQueh.png" alt="Horizon dashboard A" />
<img src="https://i.stack.imgur.com/s4uXa.png" alt="256M Redis metrics" /></p>
<h2>Project B</h2>
<p><img src="https://i.stack.imgur.com/NaaWP.png" alt="Horizon dashboard B" />
<img src="https://i.stack.imgur.com/yGV5D.png" alt="4GB Redis metrics" /></p>
<p>But in the logs, I saw plenty of lines like this :</p>
```[redis-1] 1:M 15 Oct 2022 03:51:55.086 # Connection with replica client id #67041456 lost.
[redis-1] 1:M 16 Oct 2022 03:34:13.807 # Connection with replica client id #67721283 lost.
[redis-1] 1:M 17 Oct 2022 02:56:21.675 # Connection with replica client id #68226606 lost.
[redis-1] 1:M 18 Oct 2022 03:32:38.670 # Connection with replica client id #69431433 lost.
```
<p>And when the server starts it displays those warnings :</p>
```[redis-1] 1:M 05 Aug 2022 13:25:30.685 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
[redis-1] 1:M 05 Aug 2022 13:25:30.685 # Server initialized
[redis-1] 1:M 05 Aug 2022 13:25:30.685 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
```

Is there anything to worry about ? Do you have an idea why I have connection errors on for both projects, as they do not contact the same redis server ?

Problem 2: network unavailability

I don't know if the problem is related, but I have another issue in the Project B. This time, it's a big project with several thousands of jobs per hour. Here is the kind of issue I get :

RedisException /app/Http/Middleware/CheckForMaintenanceMode.php in App\Http\Middleware\CheckForMaintenanceMode::handle

php_network_getaddresses: getaddrinfo failed: No address associated with hostname

Symfony\Component\HttpClient\Exception\TransportException /app/Jobs/Report/AggregateReports.php in App\Jobs\Report\AggregateReports::generateZip

Timeout was reached for "https://xxx.ingest.sentry.io/api/xxx/store/".

Here are the running scalingo containers:

name
qty/size
command

horizon
(1:XL)
php artisan horizon

frames
(1:L)
php artisan horizon --environment=frames

web
(1:L)

Another developer made a self-scale CRON job, that is vertically scaling the frames queue. Is that okay to have vertical scaling here on php artisan horizon command ?

Body:
Problem 1: Read error on connection

Regularily, I get reports on Sentry, for two Scalingo (Laravel) projects :

RedisException /app/Console/Commands/Laravel/WorkCommand.php in App\Console\Commands\Laravel\WorkCommand::handle

read error on connection to xxx-285.redis.dbs.scalingo.com:31659

I don't understand why, and when I relaunch the job, it just works. It happens 1 over 5 times. A few jobs are done every day for Project A, and the Project B have several thousands of jobs processed every hour (ie. 70k for the last hour).

I'm using Laravel 6, and a Scalingo container having a Redis addon. 256M on Project A and 4GB on Project B. Horizon is installed and every containers have only 1 instance (no replication).

Here is the Redis configuration (database.php) for both projects :

$redisDSN = env('REDIS_URL', 'tcp://127.0.0.1:6379/0');
$redisUrl = parse_url($redisDSN);

return [
    // ...
    'redis' => [
        'client' => 'phpredis',

        'default' => [
            'scheme'   => env('REDIS_SCHEME',   data_get($redisUrl, 'scheme')),
            'host'     => env('REDIS_HOST',     data_get($redisUrl, 'host')),
            'password' => env('REDIS_PASSWORD', data_get($redisUrl, 'pass')),
            'port'     => env('REDIS_PORT',     data_get($redisUrl, 'port')),
            'database' => env('REDIS_DATABASE', substr(data_get($redisUrl, 'path', '/0'), 1)) + $databaseOffset,
            'read_write_timeout' => -1, // please take note of -1 here
        ];
    ],
];

and queue.php

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
            'queue' => 'default',
            'retry_after' => 1800, // Run for max 30 minutes
        ],

I tried adding this in database configuration, but doesn't seem to help, as i'm still facing the timeout issue:

'read_write_timeout' => -1,

I contacted Scalingo several times so I can change the timeout variable in redis.conf but they told me I should not do that because they have safe values.
The Redis server is not under heavy load for both apps (see screenshots below)

Project A

Project B

But in the logs, I saw plenty of lines like this :

[redis-1] 1:M 15 Oct 2022 03:51:55.086 # Connection with replica client id #67041456 lost.
[redis-1] 1:M 16 Oct 2022 03:34:13.807 # Connection with replica client id #67721283 lost.
[redis-1] 1:M 17 Oct 2022 02:56:21.675 # Connection with replica client id #68226606 lost.
[redis-1] 1:M 18 Oct 2022 03:32:38.670 # Connection with replica client id #69431433 lost.

And when the server starts it displays those warnings :

[redis-1] 1:M 05 Aug 2022 13:25:30.685 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
[redis-1] 1:M 05 Aug 2022 13:25:30.685 # Server initialized
[redis-1] 1:M 05 Aug 2022 13:25:30.685 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.

Is there anything to worry about ? Do you have an idea why I have connection errors on for both projects, as they do not contact the same redis server ?

Problem 2: network unavailability

I don't know if the problem is related, but I have another issue in the Project B. This time, it's a big project with several thousands of jobs per hour. Here is the kind of issue I get :

RedisException /app/Http/Middleware/CheckForMaintenanceMode.php in App\Http\Middleware\CheckForMaintenanceMode::handle

php_network_getaddresses: getaddrinfo failed: No address associated with hostname

Symfony\Component\HttpClient\Exception\TransportException /app/Jobs/Report/AggregateReports.php in App\Jobs\Report\AggregateReports::generateZip

Timeout was reached for "https://xxx.ingest.sentry.io/api/xxx/store/".

Here are the running scalingo containers:

name
qty/size
command

horizon
(1:XL)
php artisan horizon

frames
(1:L)
php artisan horizon --environment=frames

web
(1:L)

Another developer made a self-scale CRON job, that is vertically scaling the frames queue. Is that okay to have vertical scaling here on php artisan horizon command ?


问:
Retrieve and reuse object handle from C function in C#
I have a dynamic library (server_connect.so) that Im trying to interact with using C#.

server_connect.so exposes a few functions to interact with a "server". The user has to initiate/create a connection using fnConnect function which returns a server handle. This can then be used to call other functions e.g. send a command
to the server fnSendCommand.
All latter functions require a server handle object returned by fnConnect

How can I retrieve the server handle and pass it to other methods that call these subsequent functions i.e. fnSendCommand?

So far I have defined a method that calls fnConnect function, this seems to execute without any errors but I don't know how to store a reference to that object and then pass it to the next function

```<code>        [DllImport("server_connect.so",
            EntryPoint = "fnConnect",
            CallingConvention = CallingConvention.Cdecl,
            CharSet = CharSet.Auto)]
        static extern IntPtr ConnectFunction();

        [DllImport("server_connect.so",
            EntryPoint = "fnSendCommand",
            CallingConvention = CallingConvention.Cdecl,
            CharSet = CharSet.Auto)]
        static extern void SendCommand(object serverHandle, string command);

        public object Connect()
        {
            var serverRef = ConnectFunction();
            return serverRef;
        }

        public CommandSend(object serverHandle, string command)
        {
            SendCommand(serverHandle, command);
        }
</code>```

Body:
I have a dynamic library (server_connect.so) that Im trying to interact with using C#.

server_connect.so exposes a few functions to interact with a "server". The user has to initiate/create a connection using fnConnect function which returns a server handle. This can then be used to call other functions e.g. send a command
to the server fnSendCommand.
All latter functions require a server handle object returned by fnConnect

How can I retrieve the server handle and pass it to other methods that call these subsequent functions i.e. fnSendCommand?

So far I have defined a method that calls fnConnect function, this seems to execute without any errors but I don't know how to store a reference to that object and then pass it to the next function

        [DllImport("server_connect.so",
            EntryPoint = "fnConnect",
            CallingConvention = CallingConvention.Cdecl,
            CharSet = CharSet.Auto)]
        static extern IntPtr ConnectFunction();

        [DllImport("server_connect.so",
            EntryPoint = "fnSendCommand",
            CallingConvention = CallingConvention.Cdecl,
            CharSet = CharSet.Auto)]
        static extern void SendCommand(object serverHandle, string command);

        public object Connect()
        {
            var serverRef = ConnectFunction();
            return serverRef;
        }

        public CommandSend(object serverHandle, string command)
        {
            SendCommand(serverHandle, command);
        }


问:
How to Delete Auto suggestion values from input box using javaScript from chrome. there is any way to delete auto suggestions from UI in reactJs
is there any way to delete auto suggestions from input box using **javaScript **or reactJs.
I want to delete this auto suggestion from UI. add delete button side to auto suggestions when user click on  this delete button user able to remove from this suggestions from UI.

Here is some description about steps.
when user enter some value in input box and save it,
Next time user get the auto suggestions value as a suggestions when user click in input box.
I want to delete this auto suggestion or remembered items from UI when hitting delete button.
-- If anyone having any suggestion Please let me know.

I want to delete this auto suggestion or remembered items from UI when hitting delete button.


问:
how to remove a row from a dataset in R?
I am new to programming in general.
Using the dataset 'BigMac2003' and doing the summary(), I find a negative observation in TaxRate which I interpret as an outliar, and which I want to remove.

I would like to ask how you would do this, either using a loop or with a command that allows me to locate the observation and remove it.

thank you for your help

I tried removing the entire line, doing mydata=mydata[29,] but to no avail


问:
RaspberryPi+Pulse Water Meter: Code isn't adding up pulses
I'm currently working on a RaspberryPi project where I'm trying to hook up a pulse water meter to the Pi via an AD converter. The ADC came with some code that lets me check the different ports' voltages. Whenever I blow into the meter the wheels start turning and when they hit a full number, the displayed voltage goes from ~1.2v to ~3.2v. However, if I stop blowing while the meter sits on a full number, the voltage stays at 3.2v. All I'm trying to do is set up a variable "waterTotal" that increases whenever the analog meter 'pulses' like this.

Problem is, I've only ever coded in C# using Unity, so Python's kinda scary...
I guess in C# the code would look something like this:

```<code>    float voltage;
    bool totalHasIncreased = false;
    int waterTotal = 0;

    if (totalHasIncreased == false && voltage > 3.0)
    {
    waterTotal++
    totalHasIncreased = true;
    }
    else if (voltage < 1.5)
    {
    totalHasIncreased = false;
    }

    print(waterTotal)

</code>```

I've tried to translate this to Python but the console doesn't display any change to waterTotal, and my knowledge is too shallow to figure out what exactly's going awry. Keep in mind, the issue could be super basic, like maybe I'm not working with the correct library or something. Hope someone can help!

This is the code I'm currently working with. I've 'fixed' all the error messages that Thonny's thrown my way so far. The first half of this is the code that came with the ADC, the rest is my attempt:

```<code># SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import time
import board
import busio
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn

# Create the I2C bus
i2c = busio.I2C(board.SCL, board.SDA)

# Create the ADC object using the I2C bus
ads = ADS.ADS1115(i2c)

# Create single-ended input on channel 0
chan = AnalogIn(ads, ADS.P0)
chan_2 = AnalogIn(ads, ADS.P1)

# Create differential input between channel 0 and 1
# chan = AnalogIn(ads, ADS.P0, ADS.P1)

wTwasRaised = False
waterTotal = 0

def increaseWaterMeter(wTwR, wT):
    if wTwR == False:
        if chan.voltage > 3.0:
            wT += 1
            wTwR = True
    if chan.voltage < 1.5:
        wTwR = False

print("{:>5}\t{:>5}".format("raw", "v"))

while True:
    increaseWaterMeter(wTwasRaised, waterTotal)
    print("CHAN 0: "+"{:>5}\t{:>5.3f}".format(chan.value, chan.voltage))
    print("CHAN 1: "+"{:>5}\t{:>5.3f}".format(chan_2.value, chan_2.voltage))
    #print(waterTotal + " liters counted")
    print(" A0:%dliters "%waterTotal)
    time.sleep(1)
</code>```

Body:
I'm currently working on a RaspberryPi project where I'm trying to hook up a pulse water meter to the Pi via an AD converter. The ADC came with some code that lets me check the different ports' voltages. Whenever I blow into the meter the wheels start turning and when they hit a full number, the displayed voltage goes from ~1.2v to ~3.2v. However, if I stop blowing while the meter sits on a full number, the voltage stays at 3.2v. All I'm trying to do is set up a variable "waterTotal" that increases whenever the analog meter 'pulses' like this.

Problem is, I've only ever coded in C# using Unity, so Python's kinda scary...
I guess in C# the code would look something like this:

    float voltage;
    bool totalHasIncreased = false;
    int waterTotal = 0;

    if (totalHasIncreased == false && voltage > 3.0)
    {
    waterTotal++
    totalHasIncreased = true;
    }
    else if (voltage < 1.5)
    {
    totalHasIncreased = false;
    }

    print(waterTotal)

I've tried to translate this to Python but the console doesn't display any change to waterTotal, and my knowledge is too shallow to figure out what exactly's going awry. Keep in mind, the issue could be super basic, like maybe I'm not working with the correct library or something. Hope someone can help!

This is the code I'm currently working with. I've 'fixed' all the error messages that Thonny's thrown my way so far. The first half of this is the code that came with the ADC, the rest is my attempt:

# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import time
import board
import busio
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn

# Create the I2C bus
i2c = busio.I2C(board.SCL, board.SDA)

# Create the ADC object using the I2C bus
ads = ADS.ADS1115(i2c)

# Create single-ended input on channel 0
chan = AnalogIn(ads, ADS.P0)
chan_2 = AnalogIn(ads, ADS.P1)

# Create differential input between channel 0 and 1
# chan = AnalogIn(ads, ADS.P0, ADS.P1)

wTwasRaised = False
waterTotal = 0

def increaseWaterMeter(wTwR, wT):
    if wTwR == False:
        if chan.voltage > 3.0:
            wT += 1
            wTwR = True
    if chan.voltage < 1.5:
        wTwR = False

print("{:>5}\t{:>5}".format("raw", "v"))

while True:
    increaseWaterMeter(wTwasRaised, waterTotal)
    print("CHAN 0: "+"{:>5}\t{:>5.3f}".format(chan.value, chan.voltage))
    print("CHAN 1: "+"{:>5}\t{:>5.3f}".format(chan_2.value, chan_2.voltage))
    #print(waterTotal + " liters counted")
    print(" A0:%dliters "%waterTotal)
    time.sleep(1)


问:
Use Powershell to get data from Defender Advanced Hunting Queries
I have an advanced query on Defender to extract the number of vulnerabilities by it's severity type, which is this one:

```<code>DeviceTvmSoftwareVulnerabilities
| summarize count() by  VulnerabilitySeverityLevel
| order by VulnerabilitySeverityLevel
</code>```

Basically this produces a very simple table with this data:

Critical - 1000
High - 1000
Medium - 1000
Low - 1000

Is there any way to get this query from Powershell, so then I can do some extra tasks after?

Thanks

Body:
I have an advanced query on Defender to extract the number of vulnerabilities by it's severity type, which is this one:

DeviceTvmSoftwareVulnerabilities
| summarize count() by  VulnerabilitySeverityLevel
| order by VulnerabilitySeverityLevel

Basically this produces a very simple table with this data:

Critical - 1000
High - 1000
Medium - 1000
Low - 1000

Is there any way to get this query from Powershell, so then I can do some extra tasks after?

Thanks


问:
nginx doesn't acess folders inside static folder (django app)
I searched and didn't find this exact problem.

I deployed an application in django on GCP, using gunicorn + nginx

It's working normally, except for the static files

I ran django's collectstatic and got the files folder and statics like this:

```<code>lnmat@sistema-ag:~/app_repo$ ls
apps gunicorn-error-log requirements.txt static venv
base_static manage.py sistema_vendas_ag templates
lnmat@sistema-ag:~/app_repo$ cd static
lnmat@sistema-ag:~/app_repo/static$ ls
admin global
lnmat@sistema-ag:~/app_repo/static$ ls admin
css fonts img js
lnmat@sistema-ag:~/app_repo/static$ ls global
css js vendor
</code>```

In the nginx error log:

```<code>2022/12/13 20:36:00 [error] 8136#8136: *1 open() "/home/lnmat/app_repo/static/js/sb-admin-2.min.js" failed (2: No such file or directory), client: x.x.x.x, server: -, request: "GET /static/js/sb-admin-2.min.js HTTP/1.1", host: "x.x.x.x", referrer: "http://x.x.x.x/login/?next=/"
2022/12/13 20:36:09 [error] 8136#8136: *7 open() "/home/lnmat/app_repo/static/css/sb-admin-2.min.css" failed (2: No such file or directory), client: x.x.x.x, server: -, request: "GET /static/css/sb-admin-2.min.css HTTP/1.1", host: "x.x.x.x", referrer: "http://x.x.x.x/"
2022/12/13 20:36:09 [error] 8136#8136: *12 open() "/home/lnmat/app_repo/static/vendor/jquery/jquery.min.js" failed (2: No such file or directory), client: x.x.x.x, server: -, request: "GET /static/vendor/jquery/jquery.min.js HTTP/1.1", host: "x.x.x.x", referrer: "http://x.x.x.x/"
</code>```

Apparently nginx is trying to access the static files directly in the main folder without accessing the subfolders global/ and admin/ which is where the files are.

My nginx server block:

```<code>server {
    listen 80;
    server_name x.x.x.x;

    location = /favicon.ico { access_log off; log_not_found off; }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }

    location /static/ {
        autoindex on;
        alias /home/lnmat/app_repo/static/;
    }

}
</code>```

My settings.py:

```<code>STATIC_URL = '/static/'

STATICFILES_DIRS = [
    BASE_DIR / 'base_static',
]

STATIC_ROOT = BASE_DIR / 'static/'
</code>```

I don't know what it could be, any suggestions?

[EDIT]

My static tags in template:

```<code>{% load static %}
...
<link href="{% static 'css/sb-admin-2.min.css' %}" rel="stylesheet">
<link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css">
...
</code>```

My base_static folder:
image

Body:
I searched and didn't find this exact problem.

I deployed an application in django on GCP, using gunicorn + nginx

It's working normally, except for the static files

I ran django's collectstatic and got the files folder and statics like this:

lnmat@sistema-ag:~/app_repo$ ls
apps gunicorn-error-log requirements.txt static venv
base_static manage.py sistema_vendas_ag templates
lnmat@sistema-ag:~/app_repo$ cd static
lnmat@sistema-ag:~/app_repo/static$ ls
admin global
lnmat@sistema-ag:~/app_repo/static$ ls admin
css fonts img js
lnmat@sistema-ag:~/app_repo/static$ ls global
css js vendor

In the nginx error log:

2022/12/13 20:36:00 [error] 8136#8136: *1 open() "/home/lnmat/app_repo/static/js/sb-admin-2.min.js" failed (2: No such file or directory), client: x.x.x.x, server: -, request: "GET /static/js/sb-admin-2.min.js HTTP/1.1", host: "x.x.x.x", referrer: "http://x.x.x.x/login/?next=/"
2022/12/13 20:36:09 [error] 8136#8136: *7 open() "/home/lnmat/app_repo/static/css/sb-admin-2.min.css" failed (2: No such file or directory), client: x.x.x.x, server: -, request: "GET /static/css/sb-admin-2.min.css HTTP/1.1", host: "x.x.x.x", referrer: "http://x.x.x.x/"
2022/12/13 20:36:09 [error] 8136#8136: *12 open() "/home/lnmat/app_repo/static/vendor/jquery/jquery.min.js" failed (2: No such file or directory), client: x.x.x.x, server: -, request: "GET /static/vendor/jquery/jquery.min.js HTTP/1.1", host: "x.x.x.x", referrer: "http://x.x.x.x/"

Apparently nginx is trying to access the static files directly in the main folder without accessing the subfolders global/ and admin/ which is where the files are.

My nginx server block:

server {
    listen 80;
    server_name x.x.x.x;

    location = /favicon.ico { access_log off; log_not_found off; }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }

    location /static/ {
        autoindex on;
        alias /home/lnmat/app_repo/static/;
    }

}

My settings.py:

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    BASE_DIR / 'base_static',
]

STATIC_ROOT = BASE_DIR / 'static/'

I don't know what it could be, any suggestions?

[EDIT]

My static tags in template:

{% load static %}
...
<link href="{% static 'css/sb-admin-2.min.css' %}" rel="stylesheet">
<link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css">
...

My base_static folder:
image


问:
php socket server on multiple ec2 instances
I have a PHP socket running on port 15151 hosted on EC2 Ubuntu.
I have a php project that push a message to this socket, and this message is received by clients connected to the socket are using a VB6 application.

When more than 1024 clients connect to the socket, the socket is crashing and a php error is returned

stream_select(): You MUST recompile PHP with a larger value of FD_SETSIZE.
It is set to 1024, but you have descriptors numbered at least as high as 1123.
--enable-fd-setsize=2048 is recommended

What I tried to do is to create a new ec2 instance, same code, socket server, same port and i have added a load balancer.

The problem is now that if a client (foo) vb6 is connected to instance 1, how the php project that send the message to this client will know that foo is connected to 1 and not to instance 2

How should I manage this


问:
Android Instrumentation Orchestrator's `clearPackageData` does not clear data
I have defined these into my build.gradle, to enable Orchestrator in my Android Instrumented tests:

```<code>defaultConfig {
 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
 testInstrumentationRunnerArguments clearPackageData: 'true'
}

testOptions {
  animationsDisabled = true
  execution 'ANDROIDX_TEST_ORCHESTRATOR'
}

dependencies {
 androidTestImplementation 'androidx.test:runner:1.5.1'
 androidTestUtil 'androidx.test:orchestrator:1.4.2'
}
</code>```

Sadly, when I start tests, data is not cleared and it persists between test runs.

I tried both, start test from Android Studio and by gradle cli ./gradlew connectedStageDebugAndroidTest

Any idea what I am doing wrong?

Body:
I have defined these into my build.gradle, to enable Orchestrator in my Android Instrumented tests:

defaultConfig {
 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
 testInstrumentationRunnerArguments clearPackageData: 'true'
}

testOptions {
  animationsDisabled = true
  execution 'ANDROIDX_TEST_ORCHESTRATOR'
}

dependencies {
 androidTestImplementation 'androidx.test:runner:1.5.1'
 androidTestUtil 'androidx.test:orchestrator:1.4.2'
}

Sadly, when I start tests, data is not cleared and it persists between test runs.

I tried both, start test from Android Studio and by gradle cli ./gradlew connectedStageDebugAndroidTest

Any idea what I am doing wrong?


问:
How do I ignore empty JSON arrays when deserializing POCO classes?
I am using the NuGet package Hl7.Fhir.STU3 to save me from having to create all the POCO classes.

The Json returned from the NHS FHIR Server is (I've removed a huge chunk to make it easier to read):

```<code>{
"id": "000049660991",
"meta": {
    "versionId": "3",
    "profile": [
        "https://fhir.nhs.uk/STU3/StructureDefinition/eRS-ReferralRequest-1"
    ]
},
"resourceType": "ReferralRequest",
"supportingInfo": [],
"intent": "plan"
</code>```

}

The problem comes when I try to deserialize it as the "supportingInfo" element contains an empty array so I receive the following error (ignore the position):

```<code>Hl7.Fhir.Serialization.DeserializationFailedException: 'One or more errors occurred. (An array needs to have at least one element. At line 1, position 2445.)'
</code>```

Is there a way to ignore empty arrays?

Body:
I am using the NuGet package Hl7.Fhir.STU3 to save me from having to create all the POCO classes.

The Json returned from the NHS FHIR Server is (I've removed a huge chunk to make it easier to read):

{
"id": "000049660991",
"meta": {
    "versionId": "3",
    "profile": [
        "https://fhir.nhs.uk/STU3/StructureDefinition/eRS-ReferralRequest-1"
    ]
},
"resourceType": "ReferralRequest",
"supportingInfo": [],
"intent": "plan"

}

The problem comes when I try to deserialize it as the "supportingInfo" element contains an empty array so I receive the following error (ignore the position):

Hl7.Fhir.Serialization.DeserializationFailedException: 'One or more errors occurred. (An array needs to have at least one element. At line 1, position 2445.)'

Is there a way to ignore empty arrays?


问:
How to pass external data to stat_compare_means in ggplot2
I created a barplot based on ggplot2 using an original long format that has been transferred with mean and standard error, which means I was not using raw data to generate a barplot with an errorbar but using processed mean and error data to generate a barplot. Therefore, I wonder how to add statistical comparison under such a situation using the original data because it is difficult to do statistics with only mean and error values.

This is my code, and you could imagine that df was the original long format data, and the data were grouped to calculate the mean and standard error, leading to the data summaryFGA.

The barplot with errorbar was generated using summaryFGA like below using the following code:
errorbar without statistical comparsion

```<code>summaryFGA <- df %>% group_by(DMP,tumor) %>% dplyr::summarize(mean = mean(FGA, na.rm = TRUE), se = std(FGA, na.rm = TRUE)) %>% as.data.frame
p1 <- ggplot(summaryFGA, aes(x = DMP, y = mean,fill = DMP)) +
  geom_bar(stat = 'identity') +
  geom_errorbar(aes(ymax = mean+se, ymin = mean-se),position = position_dodge(0.9), width = 0.15) +
  scale_fill_manual(values = jco[1:2]) +   scale_color_manual(values = jco[1:2]) +
  ylab("Fraction of Genome Altered") + xlab("") +
  facet_wrap(.~tumor, nrow = 1,scales = "fixed") +
  # stat_compare_means(data = df,
  #                    aes(x = DMP, y = FGA, fill=DMP),
  #                    comparisons = my_comparisons,
  #                    method = "wilcox.test",  inherit.aes = F) +
  theme(axis.text.x = element_text(hjust = 1, vjust = 0.5,size = 10, angle = 90,color = "black"),
        axis.text.y = element_text(size = 10,color = "black"),
        axis.ticks = element_line(size=0.2, color="black"),
        axis.ticks.length = unit(0.2, "cm"),
        panel.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        legend.position = "bottom",
        strip.text = element_text(colour = 'white', size = 10),
        axis.line = element_line(colour = "black"))
p1
g <- ggplot_gtable(ggplot_build(p1))
stripr <- which(grepl('strip-t', g$layout$name))
k <- 1
for (i in stripr) {
  j <- which(grepl('rect', g$grobs[[i]]$grobs[[1]]$childrenOrder))
  g$grobs[[i]]$grobs[[1]]$children[[j]]$gp$fill <- tumorColor[k]
  k <- k+1
}
</code>```

What I want is the following:
errorbar with statistical comparison

to add statistical comparison using the code I annotated, but it doesn't work. Obviously, it should be based on the original df data instead of summaryFGA.

If anyone wants an example, please refer to this thread and add a statistical comparison using "original data" in the example.
Many thanks in advance.

Body:
I created a barplot based on ggplot2 using an original long format that has been transferred with mean and standard error, which means I was not using raw data to generate a barplot with an errorbar but using processed mean and error data to generate a barplot. Therefore, I wonder how to add statistical comparison under such a situation using the original data because it is difficult to do statistics with only mean and error values.

This is my code, and you could imagine that df was the original long format data, and the data were grouped to calculate the mean and standard error, leading to the data summaryFGA.

The barplot with errorbar was generated using summaryFGA like below using the following code:
errorbar without statistical comparsion

summaryFGA <- df %>% group_by(DMP,tumor) %>% dplyr::summarize(mean = mean(FGA, na.rm = TRUE), se = std(FGA, na.rm = TRUE)) %>% as.data.frame
p1 <- ggplot(summaryFGA, aes(x = DMP, y = mean,fill = DMP)) +
  geom_bar(stat = 'identity') +
  geom_errorbar(aes(ymax = mean+se, ymin = mean-se),position = position_dodge(0.9), width = 0.15) +
  scale_fill_manual(values = jco[1:2]) +   scale_color_manual(values = jco[1:2]) +
  ylab("Fraction of Genome Altered") + xlab("") +
  facet_wrap(.~tumor, nrow = 1,scales = "fixed") +
  # stat_compare_means(data = df,
  #                    aes(x = DMP, y = FGA, fill=DMP),
  #                    comparisons = my_comparisons,
  #                    method = "wilcox.test",  inherit.aes = F) +
  theme(axis.text.x = element_text(hjust = 1, vjust = 0.5,size = 10, angle = 90,color = "black"),
        axis.text.y = element_text(size = 10,color = "black"),
        axis.ticks = element_line(size=0.2, color="black"),
        axis.ticks.length = unit(0.2, "cm"),
        panel.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        legend.position = "bottom",
        strip.text = element_text(colour = 'white', size = 10),
        axis.line = element_line(colour = "black"))
p1
g <- ggplot_gtable(ggplot_build(p1))
stripr <- which(grepl('strip-t', g$layout$name))
k <- 1
for (i in stripr) {
  j <- which(grepl('rect', g$grobs[[i]]$grobs[[1]]$childrenOrder))
  g$grobs[[i]]$grobs[[1]]$children[[j]]$gp$fill <- tumorColor[k]
  k <- k+1
}

What I want is the following:
errorbar with statistical comparison

to add statistical comparison using the code I annotated, but it doesn't work. Obviously, it should be based on the original df data instead of summaryFGA.

If anyone wants an example, please refer to this thread and add a statistical comparison using "original data" in the example.
Many thanks in advance.


问:
JsPlumb, How to save connector labels?

Could someone help me out with what I am missing?

The scenario is: there are several nodes. Among them, one node can connect with 3 other nodes and those connections should be labeled.

The codes are connecting multiple nodes with labels, but on save it doesn't save the labels. On page load, it shows the connections but not the labels.

Here are my codes.

```<code>let connector = [
  "EditableBezier",
  {
    cornerRadius: 0,
    curviness: 30,
  },
];
let paintStyle = {
  strokeWidth: 2,
  stroke: "rgb(217,217,217)",
  outlineWidth: 3,
  outlineStroke: "transparent",
};
let paintStyle = {
  strokeWidth: 2,
  stroke: "rgb(217,217,217)",
  outlineWidth: 3,
  outlineStroke: "transparent",
};
let hoverStyle = {
  strokeWidth: 2,
  stroke: "rgb(67,67,67)",
};
let abLabelCounter = 1;

function abSplitConnections(params) {
  var source = params.connection.source;
  var target = params.connection.target;
  if (source.id === target.id) return false;
  var conn = jsPlumb.getInstance();
  let c = conn.connect({
    source: source,
    target: target,
    editable: true,
    anchor: "AutoDefault",
    endpoint: "Blank",
    connector: connector,
    paintStyle: paintStyle,
    hoverPaintStyle: hoverStyle,
    overlays: [
      [
        "Arrow",
        {
          location: 1,
          width: 10,
          length: 10,
        },
      ],
      [
        "Label",
        {
          location: 0.5,
          label: () => {
            if (abLabelCounter === 1) {
              abLabelCounter++;
              return "A";
            }
            if (abLabelCounter === 2) {
              abLabelCounter++;
              return "B";
            }
            if (abLabelCounter === 3) {
              abLabelCounter = 1;
              return "C";
            }
          },
          id: "partition",
        },
      ],
    ],
  });
}
</code>```

Title: JsPlumb, How to save connector labels?

Body:
Could someone help me out with what I am missing?

The scenario is: there are several nodes. Among them, one node can connect with 3 other nodes and those connections should be labeled.

The codes are connecting multiple nodes with labels, but on save it doesn't save the labels. On page load, it shows the connections but not the labels.

Here are my codes.

let connector = [
  "EditableBezier",
  {
    cornerRadius: 0,
    curviness: 30,
  },
];
let paintStyle = {
  strokeWidth: 2,
  stroke: "rgb(217,217,217)",
  outlineWidth: 3,
  outlineStroke: "transparent",
};
let paintStyle = {
  strokeWidth: 2,
  stroke: "rgb(217,217,217)",
  outlineWidth: 3,
  outlineStroke: "transparent",
};
let hoverStyle = {
  strokeWidth: 2,
  stroke: "rgb(67,67,67)",
};
let abLabelCounter = 1;

function abSplitConnections(params) {
  var source = params.connection.source;
  var target = params.connection.target;
  if (source.id === target.id) return false;
  var conn = jsPlumb.getInstance();
  let c = conn.connect({
    source: source,
    target: target,
    editable: true,
    anchor: "AutoDefault",
    endpoint: "Blank",
    connector: connector,
    paintStyle: paintStyle,
    hoverPaintStyle: hoverStyle,
    overlays: [
      [
        "Arrow",
        {
          location: 1,
          width: 10,
          length: 10,
        },
      ],
      [
        "Label",
        {
          location: 0.5,
          label: () => {
            if (abLabelCounter === 1) {
              abLabelCounter++;
              return "A";
            }
            if (abLabelCounter === 2) {
              abLabelCounter++;
              return "B";
            }
            if (abLabelCounter === 3) {
              abLabelCounter = 1;
              return "C";
            }
          },
          id: "partition",
        },
      ],
    ],
  });
}


问:
Adding two columns to a dataframe
I am trying to add to columns of a dataframe read from a .csv:

```<code>dfMammals = pd.read_csv('MamFuncDatCSV.csv')
dfMammals['FANM'] = df['Diet-Fruit'] + df['Diet-Nect']
</code>```

But when I look at the results they dont make sense as they are not the sum of the values

```<code>'Diet-Fruit'= 0,0,0,0,0,20,20,20,20,20 dtype: int64
'Diet-Nect'=0,0,0,0,0,0,0,0,40,0 dtype: int64
'FANM'=0,20,0,80,80,60,30,10,10,0
</code>```

Could anyone tell me what may be going on?

Title: Adding two columns to a dataframe

Body:
I am trying to add to columns of a dataframe read from a .csv:

dfMammals = pd.read_csv('MamFuncDatCSV.csv')
dfMammals['FANM'] = df['Diet-Fruit'] + df['Diet-Nect']

But when I look at the results they dont make sense as they are not the sum of the values

'Diet-Fruit'= 0,0,0,0,0,20,20,20,20,20 dtype: int64
'Diet-Nect'=0,0,0,0,0,0,0,0,40,0 dtype: int64
'FANM'=0,20,0,80,80,60,30,10,10,0

Could anyone tell me what may be going on?


问:
Is it possible to parse rich snippets on Google Search API? JSON
I'm trying to scrape a country from linkedin profile that's displayed on google results.

When I try to get info that's on this search results snippet through the following code:
All I get is the 'description' of this search result and not the grey part;
var country=JSON.parse(response).items[0].snippet


问:
Gmail custom email signature created with HTML tables
I've created an email signature which is built using tables as per advised, and looks great when opened in a browser.

However when I paste the code into the email signature section, it stays as just that, code.

I can create a signature in Word, and when pasted in to Gmail, this works, but this does not give me the control over the styling that I am after.

What am I missing here as I believe I should be able to do this?

Thanks


问:
Run php with cron in a container
I'm trying to run a php file with cron inside a container.

I already tested with an "echo" directly in cron and it worked.

If I try to run the php file in the console, it also works.

I just can't seem to run a php file, I request your help.

I have tested several solutions I found on the internet without success.

Thanks

crontab

```<code>* * * * * /usr/local/bin/php /var/www/html/index.php
#Empty Line
</code>```

Dockerfile

```<code>FROM php:8.2-apache

COPY index.php  /var/www/html/

ADD crontab /etc/cron.d/hello-cron
RUN chmod 0644 /etc/cron.d/hello-cron

RUN touch /var/log/cron.log

RUN apt update
RUN apt install cron -y

CMD cron && tail -f /var/log/cron.log
</code>```

index.php

```<code><?php
$crontext = "Cron Run at ".date("r")." by ".$_SERVER['USER']."\n" ;
$folder = substr($_SERVER['SCRIPT_FILENAME'],0,strrpos($_SERVER['SCRIPT_FILENAME'],"/")+1);
$filename = $folder."cron_test.txt" ;
$fp = fopen($filename,"a") or die("Open error!");
fwrite($fp, $crontext) or die("Write error!");
fclose($fp);
echo "Wrote to ".$filename."\n\n" ;
?>
</code>```

Title: Run php with cron in a container

Body:
I'm trying to run a php file with cron inside a container.

I already tested with an "echo" directly in cron and it worked.

If I try to run the php file in the console, it also works.

I just can't seem to run a php file, I request your help.

I have tested several solutions I found on the internet without success.

Thanks

crontab

* * * * * /usr/local/bin/php /var/www/html/index.php
#Empty Line

Dockerfile

FROM php:8.2-apache

COPY index.php  /var/www/html/

ADD crontab /etc/cron.d/hello-cron
RUN chmod 0644 /etc/cron.d/hello-cron

RUN touch /var/log/cron.log

RUN apt update
RUN apt install cron -y

CMD cron && tail -f /var/log/cron.log

index.php

<?php
$crontext = "Cron Run at ".date("r")." by ".$_SERVER['USER']."\n" ;
$folder = substr($_SERVER['SCRIPT_FILENAME'],0,strrpos($_SERVER['SCRIPT_FILENAME'],"/")+1);
$filename = $folder."cron_test.txt" ;
$fp = fopen($filename,"a") or die("Open error!");
fwrite($fp, $crontext) or die("Write error!");
fclose($fp);
echo "Wrote to ".$filename."\n\n" ;
?>


问:
Getting error at the time of build creation with emoji_picker_flutter
i am creating build using flutter 2.10.3 and emoji_picker_flutter: 1.2.1. But it is giving this issue

```<code>/C:/Users/M.LAPTOP/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/emoji_picker_flutter-1.3.0/lib/src/emoji_picker.dart:164:44: Error: Method 'addPostFrameCallback' cannot be called on 'WidgetsBinding?' because it is potentially null.
 - 'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('/C:/Users/M.LAPTOP/fvm/versions/2.10.3/packages/flutter/lib/src/widgets/binding.dart').
Try calling using ?. instead.
        (value) => WidgetsBinding.instance.addPostFrameCallback((_) {
</code>```

FAILURE: Build failed with an exception.

Where:
Script 'C:\Users\M.LAPTOP\fvm\versions\2.10.3\packages\flutter_tools\gradle\flutter.gradle' line: 1102

What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\Users\M.LAPTOP\fvm\versions\2.10.3\bin\flutter.bat'' finished with non-zero exit value 1

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

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

BUILD FAILED in 3m 33s
Exception: Gradle task assembleDebug failed with exit code 1

Any solutions how to solve it?

I tried updating the packages but it didn't help.

Body:
i am creating build using flutter 2.10.3 and emoji_picker_flutter: 1.2.1. But it is giving this issue

/C:/Users/M.LAPTOP/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/emoji_picker_flutter-1.3.0/lib/src/emoji_picker.dart:164:44: Error: Method 'addPostFrameCallback' cannot be called on 'WidgetsBinding?' because it is potentially null.
 - 'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('/C:/Users/M.LAPTOP/fvm/versions/2.10.3/packages/flutter/lib/src/widgets/binding.dart').
Try calling using ?. instead.
        (value) => WidgetsBinding.instance.addPostFrameCallback((_) {

FAILURE: Build failed with an exception.

Where:
Script 'C:\Users\M.LAPTOP\fvm\versions\2.10.3\packages\flutter_tools\gradle\flutter.gradle' line: 1102

What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\Users\M.LAPTOP\fvm\versions\2.10.3\bin\flutter.bat'' finished with non-zero exit value 1

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

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

BUILD FAILED in 3m 33s
Exception: Gradle task assembleDebug failed with exit code 1

Any solutions how to solve it?

I tried updating the packages but it didn't help.


问:
Check whether an app or thread is already running when restarting qpython script
For me the the behaviour of Android regarding the lifetime of an application is something mysterious. Specifically:

I start qPython and run a script. This script launches a thread that runs in the background.
If I exit the qPython interpreter by clicking the "back" arrow several times, the qPython window disappears. However, this does not seem to mean that qPython is stopped, as when I display the active windows by clicking the "square" key, the qPython window is still there, and if I select it it shows qPython in the last state I saw it before hitting "back".

Apparently, when the active windows are shown, if I drag the qPython thumbnail out of the screen, the thread running in the background is killed.

Question 1: should I infer that dragging the thumbnail of qPython off screen kills an app, including its background threads?

It happens to me to restart qPython and launch the script while a previous instance is already running. I then get errors because of conflicting access to the same resources.

Question 2: is there a way to know that a previous instance is running, so that my code can show an explicit message and prevent a resource conflict?


Title: Transforming data (to a format appropriate for Event History analysis, survival analysis, or panel regressions)

Body:
I am struggling with converting existing data to a format appropriate for Event History Analysis (EHA), or in other words, Survival Analysis.
The data is on a daily basis.

Company_name
Date
Policy_Type

A
2021-01-03
vaccination

A
2021-01-04
quarantine

A
2021-01-05
tracing

A
2021-01-08
sickleave

A
2021-01-10
voucher

A
2021-01-11
testingkit

B
2021-01-02
quarantine

B
2021-01-03
vaccination

B
2021-01-05
voucher

C
2021-01-05
tracing

C
2021-01-08
sickleave

D
2021-01-04
voucher

D
2021-01-07
vaccination

D
2021-01-10
tracing

D
2021-01-11
quarantine

D
2021-01-12
surveys

D
2021-01-15
sickleave

D
2021-01-15
testingkit

D
2021-01-15
travellimit

E
2021-01-05
quarantine

E
2021-01-11
vaccination

E
2021-01-14
tracing

E
2021-01-15
testingkit

...

I would like to transform the data above to a format appropriate for the event history analysis OR panel regressions like below:

Company_name
Date
vaccination
quarantine
tracing
sickleave
voucher
testingkit
surveys
travellimit

A
2021-01-01
0
0
0
0
0
0
0
0

A
2021-01-02
0
0
0
0
0
0
0
0

A
2021-01-03
1
0
0
0
0
0
0
0

A
2021-01-04
1
1
0
0
0
0
0
0

A
2021-01-05
1
1
1
0
0
0
0
0

A
2021-01-06
1
1
1
0
0
0
0
0

A
2021-01-07
1
1
1
0
0
0
0
0

A
2021-01-08
1
1
1
1
0
0
0
0

A
2021-01-09
1
1
1
1
0
0
0
0

A
2021-01-10
1
1
1
1
1
0
0
0

A
2021-01-11
1
1
1
1
1
1
0
0

A
2021-01-12
1
1
1
1
1
1
0
0

A
2021-01-13
1
1
1
1
1
1
0
0

A
2021-01-14
1
1
1
1
1
1
0
0

A
2021-01-15
1
1
1
1
1
1
0
0

B
2021-01-01
0
0
0
0
0
0
0
0

B
2021-01-02
0
1
0
0
0
0
0
0

B
2021-01-03
1
1
0
0
0
0
0
0

B
2021-01-04
1
1
0
0
0
0
0
0

B
2021-01-05
1
1
0
0
1
0
0
0

B
2021-01-06
1
1
0
0
1
0
0
0

B
2021-01-07
1
1
0
0
1
0
0
0

B
2021-01-08
1
1
0
0
1
0
0
0

B
2021-01-09
1
1
0
0
1
0
0
0

B
2021-01-10
1
1
0
0
1
0
0
0

B
2021-01-11
1
1
0
0
1
0
0
0

B
2021-01-12
1
1
0
0
1
0
0
0

B
2021-01-13
1
1
0
0
1
0
0
0

B
2021-01-14
1
1
0
0
1
0
0
0

B
2021-01-15
1
1
0
0
1
0
0
0

C
2021-01-01
0
0
0
0
0
0
0
0

C
2021-01-02
0
0
0
0
0
0
0
0

C
2021-01-03
0
0
0
0
0
0
0
0

C
2021-01-04
0
0
0
0
0
0
0
0

C
2021-01-05
0
0
1
0
0
0
0
0

C
2021-01-06
0
0
1
0
0
0
0
0

C
2021-01-07
0
0
1
0
0
0
0
0

C
2021-01-08
0
0
1
1
0
0
0
0

C
2021-01-09
0
0
1
1
0
0
0
0

C
2021-01-10
0
0
1
1
0
0
0
0

C
2021-01-11
0
0
1
1
0
0
0
0

C
2021-01-12
0
0
1
1
0
0
0
0

C
2021-01-13
0
0
1
1
0
0
0
0

C
2021-01-14
0
0
1
1
0
0
0
0

C
2021-01-15
0
0
1
1
0
0
0
0

D
2021-01-01
0
0
0
0
0
0
0
0

D
2021-01-02
0
0
0
0
0
0
0
0

D
2021-01-03
0
0
0
0
0
0
0
0

D
2021-01-04
0
0
0
0
1
0
0
0

D
2021-01-05
0
0
0
0
1
0
0
0

D
2021-01-06
0
0
0
0
1
0
0
0

D
2021-01-07
1
0
0
0
1
0
0
0

D
2021-01-08
1
0
0
0
1
0
0
0

D
2021-01-09
1
0
0
0
1
0
0
0

D
2021-01-10
1
0
1
0
1
0
0
0

D
2021-01-11
1
1
1
0
1
0
0
0

D
2021-01-12
1
1
1
0
1
0
1
0

D
2021-01-13
1
1
1
0
1
0
1
0

D
2021-01-14
1
1
1
0
1
0
1
0

D
2021-01-15
1
1
1
1
1
1
1
1

E
2021-01-01
0
0
0
0
0
0
0
0

E
2021-01-02
0
0
0
0
0
0
0
0

E
2021-01-03
0
0
0
0
0
0
0
0

E
2021-01-04
0
0
0
0
0
0
0
0

E
2021-01-05
0
1
0
0
0
0
0
0

E
2021-01-06
0
1
0
0
0
0
0
0

E
2021-01-07
0
1
0
0
0
0
0
0

E
2021-01-08
0
1
0
0
0
0
0
0

E
2021-01-09
0
1
0
0
0
0
0
0

E
2021-01-10
0
1
0
0
0
0
0
0

E
2021-01-11
1
1
0
0
0
0
0
0

E
2021-01-12
1
1
0
0
0
0
0
0

E
2021-01-13
1
1
0
0
0
0
0
0

E
2021-01-14
1
1
1
0
0
0
0
0

E
2021-01-15
1
1
1
0
0
1
0
0

Is there any program that I can use to transform the first format into the second format?
I can use Stata and R. The original data is in the csv format. I can also consider python as well.

Thank you so much for considering my question!


问:
C# get request Unable to read data from the transport connection from Confluent Schema Registry
I have a docker container running a confluent schema registry image. This is the configuration:

  kafka-schema-registry:
    image: confluentinc/cp-schema-registry
    container_name: kafka-schema-registry
    hostname: schemaregistry
    ports:
      - '5001:8081'
    restart: always
    depends_on:
      - kafka
    environment:
      - SCHEMA_REGISTRY_HOST_NAME=schemaregistry
      - SCHEMA_REGISTRY_LISTENERS=http://0.0.0.0:8081
      - SCHEMA_REGISTRY_DEBUG=true
      # Kafka configuration
      - SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS=kafka:9093
```
<p>The container works as expected, everything running fine from the docker side.</p>
<p>However, when I try to make an HTTP request from C#, I get the following error:</p>
```Unhandled exception. System.AggregateException: One or more errors occurred. (An error occurred while sending the request.)
 ---> System.Net.Http.HttpRequestException: An error occurred while sending the request.
 ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
 ---> System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by the remote host.
   --- End of inner exception stack trace ---
```
<p>The thing that's bothering me is that curl requests are working, for example:</p>
```curl -X GET http://localhost:5001/subjects
```
<p>The equivalent c# code fails:</p>
<pre class="lang-cs prettyprint-override"><code>var client = new HttpClient();
var response = await c.GetAsync("http://localhost:5001/subjects");
</code>```

It also fails on PowerShell Invoke-WebRequest http://localhost:5001/ which makes sense since it uses c# under the hood.

Why is curl working and httpclinet from c# doesn't?

On this topic, I found lots of responses about SSL and configuring the SecurityProtocol. Tried that, lots of variations, currently having it set as: ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;.

Also used a client request handler to make sure that there is no SSL issues:

var handler = new HttpClientHandler
{
  ClientCertificateOptions = ClientCertificateOption.Manual,
  ServerCertificateCustomValidationCallback =
  (httpRequestMessage, cert, cetChain, policyErrors) =>
  {
    return true;
  }
};
```

Body:
I have a docker container running a confluent schema registry image. This is the configuration:

  kafka-schema-registry:
    image: confluentinc/cp-schema-registry
    container_name: kafka-schema-registry
    hostname: schemaregistry
    ports:
      - '5001:8081'
    restart: always
    depends_on:
      - kafka
    environment:
      - SCHEMA_REGISTRY_HOST_NAME=schemaregistry
      - SCHEMA_REGISTRY_LISTENERS=http://0.0.0.0:8081
      - SCHEMA_REGISTRY_DEBUG=true
      # Kafka configuration
      - SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS=kafka:9093

The container works as expected, everything running fine from the docker side.

However, when I try to make an HTTP request from C#, I get the following error:

Unhandled exception. System.AggregateException: One or more errors occurred. (An error occurred while sending the request.)
 ---> System.Net.Http.HttpRequestException: An error occurred while sending the request.
 ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
 ---> System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by the remote host.
   --- End of inner exception stack trace ---

The thing that's bothering me is that curl requests are working, for example:

curl -X GET http://localhost:5001/subjects

The equivalent c# code fails:

var client = new HttpClient();
var response = await c.GetAsync("http://localhost:5001/subjects");

It also fails on PowerShell Invoke-WebRequest http://localhost:5001/ which makes sense since it uses c# under the hood.

Why is curl working and httpclinet from c# doesn't?

On this topic, I found lots of responses about SSL and configuring the SecurityProtocol. Tried that, lots of variations, currently having it set as: ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;.

Also used a client request handler to make sure that there is no SSL issues:

var handler = new HttpClientHandler
{
  ClientCertificateOptions = ClientCertificateOption.Manual,
  ServerCertificateCustomValidationCallback =
  (httpRequestMessage, cert, cetChain, policyErrors) =>
  {
    return true;
  }
};


问:
How I can set dynamic mongoose schema property when e.g expired_at property is less than Date.now?
I have created_at date, duration by minutes set by admin and expires_at properties, I have written a logic to calculate the expires_at property and its working fine, also I need to set expired as a boolean to set to true if now date is greater than  expires_at I have written a function and its working but I don't know if mongoose can trigger it or when?

so the question is how can I update expired property to true when current time is passed the expires_at time ?

```<code>const PollSchema = new mongoose.Schema({
  question: {
    type: String,
    required: true,
  },
  options: {
    type: Array,
    required: true,
  },
  expires_at: {
    type: Date,
  },
  expired: {
    type: Boolean,
    default: false // how I can update this value to true when now > expires_at;
  },
  duration: {
    type: Number,
    required: true,
  },
});

PollSchema.pre('save', function (next) {
  const poll = this;
  poll.expired = expired(poll);
  next();
});
PollSchema.pre('save', function (next) {
  const poll = this;
  var now = new Date();
  poll.expires_at = now.setMinutes(now.getMinutes() + poll.duration);
  next();
});

// I am triggering this function on save, but I think it should be triggered when now > poll.expires_at;

PollSchema.pre('save', function (next) {
  const poll = this;
  const now = new Date();
  poll.expired = now > poll.expires_at;
  next();
});
</code>```

Body:
I have created_at date, duration by minutes set by admin and expires_at properties, I have written a logic to calculate the expires_at property and its working fine, also I need to set expired as a boolean to set to true if now date is greater than  expires_at I have written a function and its working but I don't know if mongoose can trigger it or when?

so the question is how can I update expired property to true when current time is passed the expires_at time ?

const PollSchema = new mongoose.Schema({
  question: {
    type: String,
    required: true,
  },
  options: {
    type: Array,
    required: true,
  },
  expires_at: {
    type: Date,
  },
  expired: {
    type: Boolean,
    default: false // how I can update this value to true when now > expires_at;
  },
  duration: {
    type: Number,
    required: true,
  },
});

PollSchema.pre('save', function (next) {
  const poll = this;
  poll.expired = expired(poll);
  next();
});
PollSchema.pre('save', function (next) {
  const poll = this;
  var now = new Date();
  poll.expires_at = now.setMinutes(now.getMinutes() + poll.duration);
  next();
});

// I am triggering this function on save, but I think it should be triggered when now > poll.expires_at;

PollSchema.pre('save', function (next) {
  const poll = this;
  const now = new Date();
  poll.expired = now > poll.expires_at;
  next();
});


问:
How to get SoapUi assertion result back in jenkins script
In my Jenkins file, i am executing maven command and it is executing very well.

```<code>mvn com.smartbear.soapui:soapui-maven-plugin:5.5.0:test -f src/main/resources/testcases/pom.xml
</code>```

I can see reports generated and in Jenkins log i can see status of test execution.

```<code>SoapUI 5.3.0 TestCaseRunner Summary
Time Taken: 3922ms
Total TestSuites: 1
Total TestCases: 1 (0 failed)
Total TestSteps: 1
Total Request Assertions: 3
Total Failed Assertions: 0
Total Exported Results: 1
</code>```

what i want is to get the status of test execution, like success or failure, how can i get test execution result back in Jenkins file so i can add stage as success of failure.

Body:
In my Jenkins file, i am executing maven command and it is executing very well.

mvn com.smartbear.soapui:soapui-maven-plugin:5.5.0:test -f src/main/resources/testcases/pom.xml

I can see reports generated and in Jenkins log i can see status of test execution.

SoapUI 5.3.0 TestCaseRunner Summary
Time Taken: 3922ms
Total TestSuites: 1
Total TestCases: 1 (0 failed)
Total TestSteps: 1
Total Request Assertions: 3
Total Failed Assertions: 0
Total Exported Results: 1

what i want is to get the status of test execution, like success or failure, how can i get test execution result back in Jenkins file so i can add stage as success of failure.


问:
How to convert multiple records into single row using T-SQL PIVOT?
I have a table that stores data for each type of record. I want to convert multiple rows into a single row using PIVOT function.

Input table:

Expected output:

I was able to PIVOT the table using CHAR_TYPE field but not getting the respective date for E_DATE and CO_DATE fields.

My code:

```<code>SELECT * FROM
(
  SELECT ACCT, CHAR_TYPE, EFF_DATE, ADHOC_CHAR_VAL
  FROM ACCT
)
PIVOT
(
  MIN(ADHOC_CHAR_VAL) FOR CHAR_TYPE IN ('C' AS C, 'M' AS M, 'E' AS E, 'CO' AS CO)
)
WHERE (C IS NOT NULL OR M IS NOT NULL OR E IS NOT NULL OR CO IS NOT NULL)
</code>```

This is giving me output as:

Please assist with the query to get data in expected output format.

Body:
I have a table that stores data for each type of record. I want to convert multiple rows into a single row using PIVOT function.

Input table:

Expected output:

I was able to PIVOT the table using CHAR_TYPE field but not getting the respective date for E_DATE and CO_DATE fields.

My code:

SELECT * FROM
(
  SELECT ACCT, CHAR_TYPE, EFF_DATE, ADHOC_CHAR_VAL
  FROM ACCT
)
PIVOT
(
  MIN(ADHOC_CHAR_VAL) FOR CHAR_TYPE IN ('C' AS C, 'M' AS M, 'E' AS E, 'CO' AS CO)
)
WHERE (C IS NOT NULL OR M IS NOT NULL OR E IS NOT NULL OR CO IS NOT NULL)

This is giving me output as:

Please assist with the query to get data in expected output format.