问:
How to use optimistic lock version for cascade entity in micronaut
I already updated micronaut version to latest and micronaut-data is 3.9.1. I don't know whether it is a bug of micronaut-data.
There is a version field for opt lock in entity1 and entity2:

```<code>`data class Entity1(
@Relation(Relation.Kind.MANY_TO_ONE, cascade = [Cascade.ALL])
val verification: Entity2,
@field:Version val version: Long? = 0L
)`

`data class Entity2(
@DateCreated(truncatedTo = ChronoUnit.MILLIS) val createdAt: Instant? = null,
@DateUpdated(truncatedTo = ChronoUnit.MILLIS) val updatedAt: Instant? = null,
@field:Version val version: Long? = 0L
)`
</code>```

when I use repository.update(entity1), I found the generated sql without version like below:
10:10:34.134 [Test worker] DEBUG io.micronaut.data.query - Executing SQL query: UPDATE "entity2" SET "deleted_at"=?,"updated_at"=? WHERE ("id" = ?)

And the updated sql for entity1 is correct like below:
10:10:34.139 [Test worker] DEBUG io.micronaut.data.query - Executing SQL query: UPDATE "entity1" SET "entity1_id"=?,"version"=? WHERE ("id" = ? AND "version" = ?)

I want to use the optimistic lock of entity2 when I update entity1.

How to do? Does anyone have the same case?
Thanks.

Body:
I already updated micronaut version to latest and micronaut-data is 3.9.1. I don't know whether it is a bug of micronaut-data.
There is a version field for opt lock in entity1 and entity2:

`data class Entity1(
@Relation(Relation.Kind.MANY_TO_ONE, cascade = [Cascade.ALL])
val verification: Entity2,
@field:Version val version: Long? = 0L
)`

`data class Entity2(
@DateCreated(truncatedTo = ChronoUnit.MILLIS) val createdAt: Instant? = null,
@DateUpdated(truncatedTo = ChronoUnit.MILLIS) val updatedAt: Instant? = null,
@field:Version val version: Long? = 0L
)`

when I use repository.update(entity1), I found the generated sql without version like below:
10:10:34.134 [Test worker] DEBUG io.micronaut.data.query - Executing SQL query: UPDATE "entity2" SET "deleted_at"=?,"updated_at"=? WHERE ("id" = ?)

And the updated sql for entity1 is correct like below:
10:10:34.139 [Test worker] DEBUG io.micronaut.data.query - Executing SQL query: UPDATE "entity1" SET "entity1_id"=?,"version"=? WHERE ("id" = ? AND "version" = ?)

I want to use the optimistic lock of entity2 when I update entity1.

How to do? Does anyone have the same case?
Thanks.


来源: stackexchange

问:
Hygraph: TypeError: Expected `limit` to be a finite number
I'm running into issue with my Hygraph CMS that saying that not allow me to make request anymore.

So I have contact the support team over at Hygraph CMS to see if they would helped me figure this problem but having a hard time understand:

Setup my Throttling to allows you to fetch 1 concurrent request maximum, with a minimum delay of 0.5 seconds.

I have read this blog: https://hygraph.com/docs/api-reference/basics/rate-limits

An follow the step on how to setup my code correct to fetch the request so I can get an delay of 0.5 sec but had to bring up becuase an error message that getting TypeError: Expected limit to be a finite number.

GraphQL data can be fetched using the code below. It is from Hygraph CMS that we want this information, but prior to that, I was fetching the url with the url that Hygraph provided, but now all the requests I had made on the account will not allow me to make any more requests for me to save money on my first project being built using Hygraph. My first time using Hygraph, they told me to setup a throttle. I wasn't sure where to begin, but I got to setup and understood a little bit, but I ran into an error message that stopped me from working on my project.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
import { createHttpLink } from "apollo-link-http";
import pThrottle from "p-throttle";
import App from './app.js';

// Throttle fetches to a maximum of 1 concurrent request and
// a minimum delay of 500 milliseconds between requests.

const throttledFetch = pThrottle((...args) => {
  console.log(throttledFetch);
  return fetch(...args);
}, 1, 5000);

const link = createHttpLink({
  uri: '/graphql',
  fetch: throttledFetch,
});

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
});

ReactDOM.render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  </React.StrictMode>,
  document.getElementById('root')
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm running into issue with my Hygraph CMS that saying that not allow me to make request anymore.

So I have contact the support team over at Hygraph CMS to see if they would helped me figure this problem but having a hard time understand:

Setup my Throttling to allows you to fetch 1 concurrent request maximum, with a minimum delay of 0.5 seconds.

I have read this blog: https://hygraph.com/docs/api-reference/basics/rate-limits

An follow the step on how to setup my code correct to fetch the request so I can get an delay of 0.5 sec but had to bring up becuase an error message that getting TypeError: Expected limit to be a finite number.

GraphQL data can be fetched using the code below. It is from Hygraph CMS that we want this information, but prior to that, I was fetching the url with the url that Hygraph provided, but now all the requests I had made on the account will not allow me to make any more requests for me to save money on my first project being built using Hygraph. My first time using Hygraph, they told me to setup a throttle. I wasn't sure where to begin, but I got to setup and understood a little bit, but I ran into an error message that stopped me from working on my project.

import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
import { createHttpLink } from "apollo-link-http";
import pThrottle from "p-throttle";
import App from './app.js';

// Throttle fetches to a maximum of 1 concurrent request and
// a minimum delay of 500 milliseconds between requests.

const throttledFetch = pThrottle((...args) => {
  console.log(throttledFetch);
  return fetch(...args);
}, 1, 5000);

const link = createHttpLink({
  uri: '/graphql',
  fetch: throttledFetch,
});

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
});

ReactDOM.render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  </React.StrictMode>,
  document.getElementById('root')
);


问:
Tell if a webblog is hosted under medium.com
I am writing a small webcrawler to crawl web docs. I have a list of hosts, is there an easy way to tell if a host is hosted under medium.com? such as https://betterprogramming.pub/?


问:
How to display the Hierarchy Group Thingsboard list?
I'm using Thingsboards when the parent user is clicked I want to display all the child's hierarchies in the table, but now when I click on the parent only one data is displayed. Like this:

How can all child Device data be loaded in the Entity Table Thingsboard?


问:
Applovin ad from representable much larger than the frame containing it
The ad that I am trying the load in SwiftUI is scaled much larger than it should be. It should be 320 x 50 but appears to be much more than this. AppLovin doesn't support SwiftUI yet (and they should), so I had to make a representable to make it work for SwiftUI. I have tried many other people's approaches at this, but still get the same result.

Here is the code for the represent able (All I add in the main SwiftUI view is just the reference to to the ad representable)

```<code>import Foundation
import SwiftUI
import AppLovinSDK

struct AppLovinBannerAd : UIViewControllerRepresentable {
typealias UIViewControllerType = AppLovinAdViewController

func makeUIViewController(context: Context) -> AppLovinAdViewController {
    return AppLovinAdViewController()
}

func updateUIViewController(_ uiViewController: AppLovinAdViewController, context: Context) {
    uiViewController.createBannerAd()
}
}

class AppLovinAdViewController: UIViewController, MAAdViewAdDelegate
{
func didDisplay(_ ad: MAAd) {}

func didHide(_ ad: MAAd) {}

var adView: MAAdView!

public func createBannerAd()
{
    //Don't  worry about my ad id, it is a test id, but without your own SDK key, you won't be able to load it as a test
    adView = MAAdView(adUnitIdentifier: "3178a4370cc1ab34")
    adView.delegate = self

    adView.frame = CGRect(x: 0, y: 0, width: 320, height: 50)

    // Set background or background color for banners to be fully functional
    adView.backgroundColor = UIColor.white

    view.addSubview(adView)

    // Load the first ad
    adView.loadAd()
}
// MARK: MAAdDelegate Protocol

func didLoad(_ ad: MAAd) { print("Ad is loaded, needs to appear now") }

func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) { print("Ad failed to load") }

func didClick(_ ad: MAAd) {}

func didFail(toDisplay ad: MAAd, withError error: MAError) {}

// MARK: MAAdViewAdDelegate Protocol

func didExpand(_ ad: MAAd) {}

func didCollapse(_ ad: MAAd) {}
}
</code>```

And this is my output (Sorry the image is large, the banner is what says "Congrats!"):

I have tried changing the frame size: Didn't work

I have tried changing the X and Y position: Slightly worked by showing more of the ad in the specified position, but was still a large size

I have tried using other methods to making the representable: Gets this same result

Am I doing something wrong? Or is this how the SDK send me the ad?

Body:
The ad that I am trying the load in SwiftUI is scaled much larger than it should be. It should be 320 x 50 but appears to be much more than this. AppLovin doesn't support SwiftUI yet (and they should), so I had to make a representable to make it work for SwiftUI. I have tried many other people's approaches at this, but still get the same result.

Here is the code for the represent able (All I add in the main SwiftUI view is just the reference to to the ad representable)

import Foundation
import SwiftUI
import AppLovinSDK

struct AppLovinBannerAd : UIViewControllerRepresentable {
typealias UIViewControllerType = AppLovinAdViewController

func makeUIViewController(context: Context) -> AppLovinAdViewController {
    return AppLovinAdViewController()
}

func updateUIViewController(_ uiViewController: AppLovinAdViewController, context: Context) {
    uiViewController.createBannerAd()
}
}

class AppLovinAdViewController: UIViewController, MAAdViewAdDelegate
{
func didDisplay(_ ad: MAAd) {}

func didHide(_ ad: MAAd) {}

var adView: MAAdView!

public func createBannerAd()
{
    //Don't  worry about my ad id, it is a test id, but without your own SDK key, you won't be able to load it as a test
    adView = MAAdView(adUnitIdentifier: "3178a4370cc1ab34")
    adView.delegate = self

    adView.frame = CGRect(x: 0, y: 0, width: 320, height: 50)

    // Set background or background color for banners to be fully functional
    adView.backgroundColor = UIColor.white

    view.addSubview(adView)

    // Load the first ad
    adView.loadAd()
}
// MARK: MAAdDelegate Protocol

func didLoad(_ ad: MAAd) { print("Ad is loaded, needs to appear now") }

func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) { print("Ad failed to load") }

func didClick(_ ad: MAAd) {}

func didFail(toDisplay ad: MAAd, withError error: MAError) {}

// MARK: MAAdViewAdDelegate Protocol

func didExpand(_ ad: MAAd) {}

func didCollapse(_ ad: MAAd) {}
}

And this is my output (Sorry the image is large, the banner is what says "Congrats!"):

I have tried changing the frame size: Didn't work

I have tried changing the X and Y position: Slightly worked by showing more of the ad in the specified position, but was still a large size

I have tried using other methods to making the representable: Gets this same result

Am I doing something wrong? Or is this how the SDK send me the ad?


问:
How to implement a solution to change the orientation to landscape and vice versa
I'm from RN background and pretty new to Objective-C/Swift. Though it is RN project, but there are lot of implementation written by previous engineers in Objective-C/Swift. This particular implementation was written in Objective-C which is to lock the screen in both portrait and landscape. But the problem here the landscape mode doesn't work for iOS 16.

Upon reading through the docs I discover that iOS 16 uses requestGeometryUpdateWithPreferences which our code need to be updated based on that. I've been looking around for the solution in Objective-C and I found this partial solution and the solution in Swift.

I thought of using the partial solution above with the my little update to define the deviceOrientation. But I know it won't work and is incorrect with the code below. What can I try next?

```<code>  UIInterfaceOrientation deviceOrientation = [UIApplication sharedApplication].statusBarOrientation;

    UIWindowScene  *windowScene  = ( UIWindowScene  *)[[[ UIApplication sharedApplication] connectedScenes]      allObjects].firstObject;

         UIWindowSceneGeometryPreferencesIOS  *perference  = [[ UIWindowSceneGeometryPreferencesIOS alloc]  init];
        perference.interfaceOrientations  =  1  < deviceOrientation;

        [windowScene requestGeometryUpdateWithPreferences:perference errorHandler: ^( NSError  * _Nonnull error) {
             NSLog(@ "error--%@", error);
        }];
</code>```

Body:
I'm from RN background and pretty new to Objective-C/Swift. Though it is RN project, but there are lot of implementation written by previous engineers in Objective-C/Swift. This particular implementation was written in Objective-C which is to lock the screen in both portrait and landscape. But the problem here the landscape mode doesn't work for iOS 16.

Upon reading through the docs I discover that iOS 16 uses requestGeometryUpdateWithPreferences which our code need to be updated based on that. I've been looking around for the solution in Objective-C and I found this partial solution and the solution in Swift.

I thought of using the partial solution above with the my little update to define the deviceOrientation. But I know it won't work and is incorrect with the code below. What can I try next?

  UIInterfaceOrientation deviceOrientation = [UIApplication sharedApplication].statusBarOrientation;

    UIWindowScene  *windowScene  = ( UIWindowScene  *)[[[ UIApplication sharedApplication] connectedScenes]      allObjects].firstObject;

         UIWindowSceneGeometryPreferencesIOS  *perference  = [[ UIWindowSceneGeometryPreferencesIOS alloc]  init];
        perference.interfaceOrientations  =  1  < deviceOrientation;

        [windowScene requestGeometryUpdateWithPreferences:perference errorHandler: ^( NSError  * _Nonnull error) {
             NSLog(@ "error--%@", error);
        }];


问:
How to tokenize text for NLP model on AWS Lambda when using tflite and keras package is too big to add to a layer?
I am trying to deploy a tensorflow NLP model to AWS Lambda. I have converted my model to tensorflow lite and added the tflite and numpy packages to layers in the Lambda function. The problem I'm having is that I first need to tokenize the text before running it through my model. In training the model I did this using tensorflow.keras.preprocessing.text and tensorflow.keras.preprocessing.sequence. These functions are not available in tflite and so I am looking for help with how to convert my text to vectors using my tokenizer. The tokenizer is currently pickled. At the moment I don't have access to AWS ECR.

I have found some posts which convert the tokenizer word index to a Python dict object and store this as a json which I could upload to AWS Lambda, but I'm struggling to figure out how to use this dict to tokenize my text.

Any help would be GREATLY appreciated!

Code snippet below:

```<code>with open('tokenizer.pickle', 'rb') as handle:
    tokenizer = pickle.load(handle)

interpreter = tf.lite.Interpreter(model_content=intent_model_lite)
interpreter.allocate_tensors()

input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[0]["index"]

intent_test = np.array(comment).flatten()
          intent_test_tokenize = tokenizer.texts_to_sequences(intent_test)
          intent_padded = np.pad(intent_test_tokenize, (105 - len(model_test_token)%105,0),   'constant')
          interpreter.set_tensor(input_index, sample_pad2)
          interpreter.invoke()
          x = np.round(interpreter.get_tensor(output_index))[0]
          predictions = float(x[0])
</code>```

Body:
I am trying to deploy a tensorflow NLP model to AWS Lambda. I have converted my model to tensorflow lite and added the tflite and numpy packages to layers in the Lambda function. The problem I'm having is that I first need to tokenize the text before running it through my model. In training the model I did this using tensorflow.keras.preprocessing.text and tensorflow.keras.preprocessing.sequence. These functions are not available in tflite and so I am looking for help with how to convert my text to vectors using my tokenizer. The tokenizer is currently pickled. At the moment I don't have access to AWS ECR.

I have found some posts which convert the tokenizer word index to a Python dict object and store this as a json which I could upload to AWS Lambda, but I'm struggling to figure out how to use this dict to tokenize my text.

Any help would be GREATLY appreciated!

Code snippet below:

with open('tokenizer.pickle', 'rb') as handle:
    tokenizer = pickle.load(handle)

interpreter = tf.lite.Interpreter(model_content=intent_model_lite)
interpreter.allocate_tensors()

input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[0]["index"]

intent_test = np.array(comment).flatten()
          intent_test_tokenize = tokenizer.texts_to_sequences(intent_test)
          intent_padded = np.pad(intent_test_tokenize, (105 - len(model_test_token)%105,0),   'constant')
          interpreter.set_tensor(input_index, sample_pad2)
          interpreter.invoke()
          x = np.round(interpreter.get_tensor(output_index))[0]
          predictions = float(x[0])


问:
The timestamp(unix) i am creating locally in flutter is 8 minutes later
Hello every one i have an issue that the timestamp (unix) i am creating locally in editor is 8 minutes later and when i am creating online it is fine mean uptodate. so what to do now?

Tell me what is the issue?


问:
NSIS Permission not working as expected for "Users"
I have searched almost many posts and articles. But not helping me with this.

I'm trying to add permission to the $APPDATA\MY_APP\conf directory. I have observed the command is not working properly with multiple machines.

Any suggestions, as to why this below command is behaving differently on 2 different laptops? Both laptops are having Windows 10 Enterprise and Windows 10 Home edition. What mistake am I'm doing?

```<code>SetShellVarContext all
;Before Permission
nsExec::ExecToLog '"icacls" "$appDataDir\conf"'
Pop $0
AccessControl::GrantOnFile  "$appDataDir\conf" "(BU)" "FullAccess"
;After Permission
nsExec::ExecToLog '"icacls" "$appDataDir\conf"'
Pop $0
</code>```

Laptop 1: Working on this laptop. The "Users" option is visible on the folder level.

Laptop 2: It's not working on the laptop, I can see on folder permission also "Users" is not visible.

Thanks in advance.

Edit:-
If I add this below permission manually its works fine. How to add only this below permission on NSIS?

Body:
I have searched almost many posts and articles. But not helping me with this.

I'm trying to add permission to the $APPDATA\MY_APP\conf directory. I have observed the command is not working properly with multiple machines.

Any suggestions, as to why this below command is behaving differently on 2 different laptops? Both laptops are having Windows 10 Enterprise and Windows 10 Home edition. What mistake am I'm doing?

SetShellVarContext all
;Before Permission
nsExec::ExecToLog '"icacls" "$appDataDir\conf"'
Pop $0
AccessControl::GrantOnFile  "$appDataDir\conf" "(BU)" "FullAccess"
;After Permission
nsExec::ExecToLog '"icacls" "$appDataDir\conf"'
Pop $0

Laptop 1: Working on this laptop. The "Users" option is visible on the folder level.

Laptop 2: It's not working on the laptop, I can see on folder permission also "Users" is not visible.

Thanks in advance.

Edit:-
If I add this below permission manually its works fine. How to add only this below permission on NSIS?


问:
Write a function unpack() which takes a 32-bit integer as input and decodes it to find age, occupation and year of birth
Bitfields: Write a function pack(), that encodes the following data into a 32-bit integer: age (0-100), occupation (engineer, doctor, student, other), year of birth (1900 - 2016). Write a function unpack() which takes a 32-bit integer as input and decodes it to find age, occupation and year of birth. Do this using both bitwise operators and bitfields. Try the combination of packing using bit-fields and unpacking using bitwise operators and vice versa.

Output: Inverted number is: 207


问:
VBA Incrementing Numbers with Different Words and Dates
I'm new to programming and vba. I want to generate an incrementing numbers base on the year and account code. for example "TES1-2023-OE-01-001", and when I want to add another item with the same year and account code it will increment but when it is different year or account code, it will generate a new number starting 001. So far a, b, c, d variables are working fine but the last number stays 0. Here's my code below. Thank you in advance.

```<code>Sub FindPropertyNum()

Dim ws As Worksheet

Set ws = ThisWorkbook.Sheets("UserForm1")
    If Range("D4").Value = Empty Then 'D4 is where they can select the account code
        Exit Sub
    End If
'Check Account Code
    CheckAccCode 'Variable c - OE,ICT,CE,FFE,ME,TSE,DRRE,OSM,OPPE,SE,PE

a = "TES1"
b = Right(Range("D6").Value, 4) 'YEAR
d = Left(Range("D6").Value, 2) 'MONTH

myProp = UCase(a & "-" & b & "-" & c & "-" & d & "-")

lr = Cells(Rows.Count, "C").End(xlUp).Row
    For x = 15 To lr
        If ws.Cells(x, 7) = myProp Then 'Column 7 is where the incrementing numbers are stored
        lastnum = (ws.Cells(x, 7)

    Stop
        lastnum = Format(lastnum + 1, "000#")

         End If
    Next x
Range("E2").Value = myProp & lastnum
End Sub
</code>```

Body:
I'm new to programming and vba. I want to generate an incrementing numbers base on the year and account code. for example "TES1-2023-OE-01-001", and when I want to add another item with the same year and account code it will increment but when it is different year or account code, it will generate a new number starting 001. So far a, b, c, d variables are working fine but the last number stays 0. Here's my code below. Thank you in advance.

Sub FindPropertyNum()

Dim ws As Worksheet

Set ws = ThisWorkbook.Sheets("UserForm1")
    If Range("D4").Value = Empty Then 'D4 is where they can select the account code
        Exit Sub
    End If
'Check Account Code
    CheckAccCode 'Variable c - OE,ICT,CE,FFE,ME,TSE,DRRE,OSM,OPPE,SE,PE

a = "TES1"
b = Right(Range("D6").Value, 4) 'YEAR
d = Left(Range("D6").Value, 2) 'MONTH

myProp = UCase(a & "-" & b & "-" & c & "-" & d & "-")

lr = Cells(Rows.Count, "C").End(xlUp).Row
    For x = 15 To lr
        If ws.Cells(x, 7) = myProp Then 'Column 7 is where the incrementing numbers are stored
        lastnum = (ws.Cells(x, 7)

    Stop
        lastnum = Format(lastnum + 1, "000#")

         End If
    Next x
Range("E2").Value = myProp & lastnum
End Sub


问:
How to upload file using file_get_contents() to Telegram API in PHP?
I need to upload file with POST method from my server to telegram bot api using file_get_contents()

Documentation to upload file to Telegram:
https://core.telegram.org/bots/api#senddocument

For some reasons i don't want to use cURL, Guzzle for POST files

```<code>function testresponse2($method, $datas = [])
{
    $url = 'https://api.telegram.org/bot' . API_KEY . '/' . $method;
    $post = http_build_query($datas);

    if (str_contains($post, '%5Bpostname%5D')) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POSTFIELDS => $datas,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT => 60
        ]);
        $result = json_decode(curl_exec($ch));
        return $result;
    } else {
        $options = array(
            'http' => [
                'method' => 'POST',
                'timeout' => 60,
                'ignore_errors' => true,
                'content' => $post
            ]
        );
        $stream = @stream_context_create($options);
        $result = json_decode(file_get_contents($url, false, $stream));
        return $result;
    }
}

testresponse2('SendDocument', [
    'chat_id' => $messageChatId,
    'document' => curl_file_create('data/bot.json')
]);
</code>```

I wrote the code above that switches to cURL when POST data has file on it
and it works fine

But i need to POST file only with file_get_contents()

Body:
I need to upload file with POST method from my server to telegram bot api using file_get_contents()

Documentation to upload file to Telegram:
https://core.telegram.org/bots/api#senddocument

For some reasons i don't want to use cURL, Guzzle for POST files

function testresponse2($method, $datas = [])
{
    $url = 'https://api.telegram.org/bot' . API_KEY . '/' . $method;
    $post = http_build_query($datas);

    if (str_contains($post, '%5Bpostname%5D')) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POSTFIELDS => $datas,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT => 60
        ]);
        $result = json_decode(curl_exec($ch));
        return $result;
    } else {
        $options = array(
            'http' => [
                'method' => 'POST',
                'timeout' => 60,
                'ignore_errors' => true,
                'content' => $post
            ]
        );
        $stream = @stream_context_create($options);
        $result = json_decode(file_get_contents($url, false, $stream));
        return $result;
    }
}

testresponse2('SendDocument', [
    'chat_id' => $messageChatId,
    'document' => curl_file_create('data/bot.json')
]);

I wrote the code above that switches to cURL when POST data has file on it
and it works fine

But i need to POST file only with file_get_contents()


问:
How to connect CKAN Database (PostgreSQL) to Navicat (or any DBMS)
Hy everyone, i tried to connect CKAN database with Navicat but no table show up

how can i open CKAN database via Database Management System?

i tried to open CKAN Database via DBMS (Navicat in my case)


问:
Global constant that involves reading from a file
I am trying, to do the following in Haskell:

Read the contents of a single, statically-named file

Separate the contents into a list where every newline is a list item, while
having that list be globally accessible.

Here is my best attempt:

```<code>listFromFile :: FilePath -> IO [String]
listFromFile filePath = do
  contents <- readFile filePath
  return (lines contents)

listConstant :: [String]
listConstant = do
  list <- listFromFile "file/path.txt"
  return list
</code>```

The line list <- listFromFile "file/path.txt" gives the error

```<code>Couldn't match type `IO' with `[]'
  Expected: [[String]]
    Actual: IO [String]
</code>```

while the line return list gives the error

```<code>Couldn't match type `[Char]' with `Char'
  Expected: String
    Actual: [String]
</code>```

I really do not understand why. I'm trying to separate my "performance" (IO) code from my "functional" code but the types still aren't matching up.

Body:
I am trying, to do the following in Haskell:

Read the contents of a single, statically-named file

Separate the contents into a list where every newline is a list item, while
having that list be globally accessible.

Here is my best attempt:

listFromFile :: FilePath -> IO [String]
listFromFile filePath = do
  contents <- readFile filePath
  return (lines contents)

listConstant :: [String]
listConstant = do
  list <- listFromFile "file/path.txt"
  return list

The line list <- listFromFile "file/path.txt" gives the error

Couldn't match type `IO' with `[]'
  Expected: [[String]]
    Actual: IO [String]

while the line return list gives the error

Couldn't match type `[Char]' with `Char'
  Expected: String
    Actual: [String]

I really do not understand why. I'm trying to separate my "performance" (IO) code from my "functional" code but the types still aren't matching up.


问:
Php laravel test not loading relationships
I've got the following method in my controller:

```<code>public function assignCustomer(string $orderID) : JsonResponse
    {
        $customersID = \request()->get('customers_id');

        try {
            $order = AddCustomerToOrderAction::execute($orderID, $customersID);
            Log::info("Order $orderID successfully updated with customer $customersID");
            return (new OrdersResource($order->loadMissing('orderItems', 'orderItems.product', 'customer')))
                ->response()
                ->setStatusCode(ResponseAlias::HTTP_OK);
        } catch (ModelNotFoundException) {
            return response()->json(['message' => "Record Not Found. Check that either Customer's ID or Order ID are valid"], ResponseAlias::HTTP_UNPROCESSABLE_ENTITY);

        } catch (Exception $e) {
            Log::error("failed to add customer $customersID to Order $orderID : $e");
            return response()->json(['message' => "An error has happened. Please try again or contact IT service for help"], ResponseAlias::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
</code>```

where AddCustomerToOrderActions is:

```<code>class AddCustomerToOrderAction
{
    public static function execute($orderID, $customersID)
    {
        $order = null;

        // validate customer
        $customer = ViewCustomer::findOrFail($customersID);

        if ($customer) {
            $order = Order::find($orderID);
            $order->customers_id = $customer->id;
            $order->save();
        }

        return $order;
    }
}
</code>```

If I perform a call to POST http://127.0.0.1:8000/api/orders/982007c0-78e8-4f2a-bfcc-8297c3731dbb/customers with a body such as:

```<code>{
    "customers_id": "982007a0-420b-41c0-b3e3-c07ad1901b7f"
}
</code>```

I'm getting back:

```<code>{
    "data": {
        "id": "982007c0-78e8-4f2a-bfcc-8297c3731dbb",
        "type": "orders",
        "attributes": {
            "status": "paid",
            "payment_type": "cash",
            "payment_transaction_no": "",
            "customer": {
                "id": "982007a0-420b-41c0-b3e3-c07ad1901b7f",
                "type": "customers",
                "attributes": {
                    "customer_type": "individuals",
                    "identification": "9832342123",
                    "identification_type": "cc",
                    "name": "SEBASTIAN  BONILLA ",
                    "primary_phone_number": "6464698219",
                    "created_at": "2023-01-02T04:22:23.000000Z"
                }
            },
            "items": [
                {
                    "id": 1,
                    "order_id": "982007c0-78e8-4f2a-bfcc-8297c3731dbb",
                    "product": {
                        "id": "98200742-2994-429b-8915-5591716ea249",
                        "type": "products",
                        "attributes": {
                            "barcode": "3234423423909",
                            "name": "Test 1",
                            "slug": "test-1",
                            "sku": null,
                            "description": null,
                            "type": "goods",
                            "wholesale_price": null,
                            "retail_price": 20000,
                            "base_picture": null,
                            "current_stock_level": 0,
                            "active": 1
                        }
                    },
                    "qty": 2,
                    "price": 20000,
                    "total": 40000,
                    "created_at": "2023-01-02T04:22:44.000000Z",
                    "updated_at": "2023-01-02T04:22:44.000000Z"
                },
                {
                    "id": 2,
                    "order_id": "982007c0-78e8-4f2a-bfcc-8297c3731dbb",
                    "product": {
                        "id": "98200770-9d13-4e9b-ab36-56a66f632324",
                        "type": "products",
                        "attributes": {
                            "barcode": "3234423423121",
                            "name": "Test 2",
                            "slug": "test-2",
                            "sku": null,
                            "description": null,
                            "type": "goods",
                            "wholesale_price": null,
                            "retail_price": 15500,
                            "base_picture": null,
                            "current_stock_level": 0,
                            "active": 1
                        }
                    },
                    "qty": 1,
                    "price": 15500,
                    "total": 15500,
                    "created_at": "2023-01-02T04:22:54.000000Z",
                    "updated_at": "2023-01-02T04:22:54.000000Z"
                }
            ],
            "subtotal": 55500,
            "taxes": 0,
            "total": 55500,
            "created_at": "2023-01-02T04:22:44.000000Z",
            "updated_at": "2023-01-02T04:23:09.000000Z"
        }
    }
}
</code>```

Notice how customer is a nested object that contains the customer's info.

Now, i've got the following test:

```<code>it('should return customer\'s information nested in the response when a customer is assigned to an order', function () {

    // create a customer
    $individual = Individual::factory()->create();

    // create an order with a customer
    $order = createOrderWithProducts(3);

    $customerData = ['customers_id' => $individual->id];

    $url = ORDERS_URI . "/{$order->id}/customers";

    $response = $this->postJson($url, $customerData);

    dd($response->json());
})->only();
</code>```

When I run it I'm getting:

```<code>"data" => array:3 [
    "id" => "712a4b1c-3fd2-393c-9f4d-bf0fa52149c8"
    "type" => "orders"
    "attributes" => array:10 [
      "status" => "new"
      "payment_type" => ""
      "payment_transaction_no" => ""
      "customer" => null
      "items" => array:3 [
...
</code>```

(omitted the rest of the response for simplicity). Notice how customers is empty.

I've added multiple debug statements and everything seems ok, until I added the following one:

```<code>$order = AddCustomerToOrderAction::execute($orderID, $customersID);
            Log::info("Order $orderID successfully updated with customer $customersID");
            $tmp = new OrdersResource($order->loadMissing('orderItems', 'orderItems.product', 'customer'));
            dd($tmp);
</code>```

When I run a call from the rest client and from the test itself the results are consistent except for this piece:

Call from rest client:

```<code>#relations: array:2 [▼
      "orderItems" => Illuminate\Database\Eloquent\Collection {#1353 ▶}
      "customer" => Domain\Customer\Models\ViewCustomer {#1373 ▶}
    ]
</code>```

Call from test:

```<code>#relations: array:1 [
              "product" => Domain\Product\Models\Product^
]
</code>```

Notice how the loaded relationships are empty.

I checked multiple times and yes, the customer is being created in the test. Also, if I print the order before passing it to the resource, it does contain the customers_id, it is when passed to the resource that it is not loading the relationship.

What am i missing?

thanks

Body:
I've got the following method in my controller:

public function assignCustomer(string $orderID) : JsonResponse
    {
        $customersID = \request()->get('customers_id');

        try {
            $order = AddCustomerToOrderAction::execute($orderID, $customersID);
            Log::info("Order $orderID successfully updated with customer $customersID");
            return (new OrdersResource($order->loadMissing('orderItems', 'orderItems.product', 'customer')))
                ->response()
                ->setStatusCode(ResponseAlias::HTTP_OK);
        } catch (ModelNotFoundException) {
            return response()->json(['message' => "Record Not Found. Check that either Customer's ID or Order ID are valid"], ResponseAlias::HTTP_UNPROCESSABLE_ENTITY);

        } catch (Exception $e) {
            Log::error("failed to add customer $customersID to Order $orderID : $e");
            return response()->json(['message' => "An error has happened. Please try again or contact IT service for help"], ResponseAlias::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

where AddCustomerToOrderActions is:

class AddCustomerToOrderAction
{
    public static function execute($orderID, $customersID)
    {
        $order = null;

        // validate customer
        $customer = ViewCustomer::findOrFail($customersID);

        if ($customer) {
            $order = Order::find($orderID);
            $order->customers_id = $customer->id;
            $order->save();
        }

        return $order;
    }
}

If I perform a call to POST http://127.0.0.1:8000/api/orders/982007c0-78e8-4f2a-bfcc-8297c3731dbb/customers with a body such as:

{
    "customers_id": "982007a0-420b-41c0-b3e3-c07ad1901b7f"
}

I'm getting back:

{
    "data": {
        "id": "982007c0-78e8-4f2a-bfcc-8297c3731dbb",
        "type": "orders",
        "attributes": {
            "status": "paid",
            "payment_type": "cash",
            "payment_transaction_no": "",
            "customer": {
                "id": "982007a0-420b-41c0-b3e3-c07ad1901b7f",
                "type": "customers",
                "attributes": {
                    "customer_type": "individuals",
                    "identification": "9832342123",
                    "identification_type": "cc",
                    "name": "SEBASTIAN  BONILLA ",
                    "primary_phone_number": "6464698219",
                    "created_at": "2023-01-02T04:22:23.000000Z"
                }
            },
            "items": [
                {
                    "id": 1,
                    "order_id": "982007c0-78e8-4f2a-bfcc-8297c3731dbb",
                    "product": {
                        "id": "98200742-2994-429b-8915-5591716ea249",
                        "type": "products",
                        "attributes": {
                            "barcode": "3234423423909",
                            "name": "Test 1",
                            "slug": "test-1",
                            "sku": null,
                            "description": null,
                            "type": "goods",
                            "wholesale_price": null,
                            "retail_price": 20000,
                            "base_picture": null,
                            "current_stock_level": 0,
                            "active": 1
                        }
                    },
                    "qty": 2,
                    "price": 20000,
                    "total": 40000,
                    "created_at": "2023-01-02T04:22:44.000000Z",
                    "updated_at": "2023-01-02T04:22:44.000000Z"
                },
                {
                    "id": 2,
                    "order_id": "982007c0-78e8-4f2a-bfcc-8297c3731dbb",
                    "product": {
                        "id": "98200770-9d13-4e9b-ab36-56a66f632324",
                        "type": "products",
                        "attributes": {
                            "barcode": "3234423423121",
                            "name": "Test 2",
                            "slug": "test-2",
                            "sku": null,
                            "description": null,
                            "type": "goods",
                            "wholesale_price": null,
                            "retail_price": 15500,
                            "base_picture": null,
                            "current_stock_level": 0,
                            "active": 1
                        }
                    },
                    "qty": 1,
                    "price": 15500,
                    "total": 15500,
                    "created_at": "2023-01-02T04:22:54.000000Z",
                    "updated_at": "2023-01-02T04:22:54.000000Z"
                }
            ],
            "subtotal": 55500,
            "taxes": 0,
            "total": 55500,
            "created_at": "2023-01-02T04:22:44.000000Z",
            "updated_at": "2023-01-02T04:23:09.000000Z"
        }
    }
}

Notice how customer is a nested object that contains the customer's info.

Now, i've got the following test:

it('should return customer\'s information nested in the response when a customer is assigned to an order', function () {

    // create a customer
    $individual = Individual::factory()->create();

    // create an order with a customer
    $order = createOrderWithProducts(3);

    $customerData = ['customers_id' => $individual->id];

    $url = ORDERS_URI . "/{$order->id}/customers";

    $response = $this->postJson($url, $customerData);

    dd($response->json());
})->only();

When I run it I'm getting:

"data" => array:3 [
    "id" => "712a4b1c-3fd2-393c-9f4d-bf0fa52149c8"
    "type" => "orders"
    "attributes" => array:10 [
      "status" => "new"
      "payment_type" => ""
      "payment_transaction_no" => ""
      "customer" => null
      "items" => array:3 [
...

(omitted the rest of the response for simplicity). Notice how customers is empty.

I've added multiple debug statements and everything seems ok, until I added the following one:

$order = AddCustomerToOrderAction::execute($orderID, $customersID);
            Log::info("Order $orderID successfully updated with customer $customersID");
            $tmp = new OrdersResource($order->loadMissing('orderItems', 'orderItems.product', 'customer'));
            dd($tmp);

When I run a call from the rest client and from the test itself the results are consistent except for this piece:

Call from rest client:

#relations: array:2 [▼
      "orderItems" => Illuminate\Database\Eloquent\Collection {#1353 ▶}
      "customer" => Domain\Customer\Models\ViewCustomer {#1373 ▶}
    ]

Call from test:

#relations: array:1 [
              "product" => Domain\Product\Models\Product^
]

Notice how the loaded relationships are empty.

I checked multiple times and yes, the customer is being created in the test. Also, if I print the order before passing it to the resource, it does contain the customers_id, it is when passed to the resource that it is not loading the relationship.

What am i missing?

thanks


问:
Is there a tool to stitch together splices of a larger image with variable pixel perfect overlaps?
I have a folder of images that are overlapping splices of a larger image, i.e. the images may be variable in size and also have columns and/or rows of pixel perfect overlaps that also vary in width and height.

I would like to automate the stitching together of the images into a larger montage / mosaic.

I don’t need to do any transformations to fix distortions or do any blending as the edge columns or rows will be matching pixel perfect.

I’ve done research into this but all the results are for panorama like images that require transformations and blending.


问:
how to set env path in zshrc file in suca as this situation?
A few days ago I installed oh-my-zsh. and I tried to manage some program and it occures "command not found:program". So, I tried to set the program's env path in ~/.zshrc file. but It seemed different with when I didn't get oh-my-zsh. I mean at that time my zshrc file has just some lines about PATH~~~. but now, It has like below and I don't get how to set env path in this file and tried to write path here but don't work. Please help me.
my zshrc version is "zsh 5.8.1 (x86_64-apple-darwin22.0)"</p>
```<code># If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH

# Path to your oh-my-zsh installation.
export ZSH="$HOME/.oh-my-zsh"

# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
ZSH_THEME="agnoster"

# Set list of themes to pick from when loading at random
# Setting this variable when ZSH_THEME=random will cause zsh to load
# a theme from this variable instead of looking in $ZSH/themes/
# If set to an empty array, this variable will have no effect.
# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )

# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"

# Uncomment the following line to use hyphen-insensitive completion.
# Case-sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"

# Uncomment one of the following lines to change the auto-update behavior
# zstyle ':omz:update' mode disabled  # disable automatic updates
# zstyle ':omz:update' mode auto      # update automatically without asking
# zstyle ':omz:update' mode reminder  # just remind me to update when it's time

# Uncomment the following line to change how often to auto-update (in days).
# zstyle ':omz:update' frequency 13

# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS="true"

# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"

# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"

# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"

# Uncomment the following line to display red dots whilst waiting for completion.
# You can also set it to another string to have that shown instead of the default red dots.
# e.g. COMPLETION_WAITING_DOTS="%F{yellow}waiting...%f"
# Caution: this setting can cause issues with multiline prompts in zsh < 5.7.1 (see #5765)
# COMPLETION_WAITING_DOTS="true"

# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"

# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# You can set one of the optional three formats:
# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# or set a custom format using the strftime function format specifications,
# see 'man strftime' for details.
# HIST_STAMPS="mm/dd/yyyy"

# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder

# Which plugins would you like to load?
# Standard plugins can be found in $ZSH/plugins/
# Custom plugins may be added to $ZSH_CUSTOM/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git)

source $ZSH/oh-my-zsh.sh

# User configuration

# export MANPATH="/usr/local/man:$MANPATH"
# export flutter="/Users/shinheejin/Downloads/flutter/bin"

# You may need to manually set your language environment
# export LANG=en_US.UTF-8

# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
#   export EDITOR='vim'
# else
#   export EDITOR='mvim'
# fi

# Compilation flags
# export ARCHFLAGS="-arch x86_64"

# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"

prompt_context() {

}

plugins=(
        git
        vscode
        pm2
        yarn
        brew
        docker
        dotenv
        node
        npm
        nvm
        ubuntu
)
</code>```

Body:
A few days ago I installed oh-my-zsh. and I tried to manage some program and it occures "command not found:program". So, I tried to set the program's env path in ~/.zshrc file. but It seemed different with when I didn't get oh-my-zsh. I mean at that time my zshrc file has just some lines about PATH~~~. but now, It has like below and I don't get how to set env path in this file and tried to write path here but don't work. Please help me.
my zshrc version is "zsh 5.8.1 (x86_64-apple-darwin22.0)"

# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH

# Path to your oh-my-zsh installation.
export ZSH="$HOME/.oh-my-zsh"

# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
ZSH_THEME="agnoster"

# Set list of themes to pick from when loading at random
# Setting this variable when ZSH_THEME=random will cause zsh to load
# a theme from this variable instead of looking in $ZSH/themes/
# If set to an empty array, this variable will have no effect.
# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )

# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"

# Uncomment the following line to use hyphen-insensitive completion.
# Case-sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"

# Uncomment one of the following lines to change the auto-update behavior
# zstyle ':omz:update' mode disabled  # disable automatic updates
# zstyle ':omz:update' mode auto      # update automatically without asking
# zstyle ':omz:update' mode reminder  # just remind me to update when it's time

# Uncomment the following line to change how often to auto-update (in days).
# zstyle ':omz:update' frequency 13

# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS="true"

# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"

# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"

# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"

# Uncomment the following line to display red dots whilst waiting for completion.
# You can also set it to another string to have that shown instead of the default red dots.
# e.g. COMPLETION_WAITING_DOTS="%F{yellow}waiting...%f"
# Caution: this setting can cause issues with multiline prompts in zsh < 5.7.1 (see #5765)
# COMPLETION_WAITING_DOTS="true"

# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"

# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# You can set one of the optional three formats:
# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# or set a custom format using the strftime function format specifications,
# see 'man strftime' for details.
# HIST_STAMPS="mm/dd/yyyy"

# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder

# Which plugins would you like to load?
# Standard plugins can be found in $ZSH/plugins/
# Custom plugins may be added to $ZSH_CUSTOM/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git)

source $ZSH/oh-my-zsh.sh

# User configuration

# export MANPATH="/usr/local/man:$MANPATH"
# export flutter="/Users/shinheejin/Downloads/flutter/bin"

# You may need to manually set your language environment
# export LANG=en_US.UTF-8

# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
#   export EDITOR='vim'
# else
#   export EDITOR='mvim'
# fi

# Compilation flags
# export ARCHFLAGS="-arch x86_64"

# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"

prompt_context() {

}

plugins=(
        git
        vscode
        pm2
        yarn
        brew
        docker
        dotenv
        node
        npm
        nvm
        ubuntu
)


问:
Why my temporary file output reversed row?
Anyone can help me ?
i want to calculate the sum of squares of given integers, excluding any negatives.

The first line of the input will be an integer N (1 <= N <= 100), indicating the number of test cases to follow.

```<code>
from functools import reduce
from tempfile import NamedTemporaryFile

N = int(input())

def main(N):
with NamedTemporaryFile(mode="r+", encoding="utf-8") as temp:

        try :
            if 1 <= N <=100 :

                out=(reduce(lambda x, y: x + (y * y if 0 < y <=100 else 0), map(int, input().split()), 0))
                temp.write(str(out))
                return main(N-1)

        finally :
            ##Why my output reversed row ??
            temp.seek(0)
            print(temp.read())
            return

if __name__ == "__main__":
main(N)

</code>```

Sample input :
2
3
6

Expected Output :
9
36

but the output is:
36
9

Body:
Anyone can help me ?
i want to calculate the sum of squares of given integers, excluding any negatives.

The first line of the input will be an integer N (1 <= N <= 100), indicating the number of test cases to follow.

from functools import reduce
from tempfile import NamedTemporaryFile

N = int(input())

def main(N):
with NamedTemporaryFile(mode="r+", encoding="utf-8") as temp:

        try :
            if 1 <= N <=100 :

                out=(reduce(lambda x, y: x + (y * y if 0 < y <=100 else 0), map(int, input().split()), 0))
                temp.write(str(out))
                return main(N-1)

        finally :
            ##Why my output reversed row ??
            temp.seek(0)
            print(temp.read())
            return

if __name__ == "__main__":
main(N)

Sample input :
2
3
6

Expected Output :
9
36

but the output is:
36
9


问:
Can you overcome WatchOS 75MB app size limitation using WatchConnectivity?
I'm looking to build an Apple Watch app which would utilize SceneKit and render a 3D model with many different animations. I imagine the resources would easily take up over the 75MB bundle limit.

I have two questions:

Is it possible to overcome this using WatchConnectivity to fetch the required assets as needed?

Is it possible to perform the data transfer from the iPhone to the Watch while the iPhone is locked?

I have only done some preliminary research through Apple's documentation as I'm exploring whether what I am thinking of doing is possible.


问:
How do I set a variable to a variable name
I am making a library in Python, and I have a function that is supposed to create a new line of text in a GUI every time you use it. This is using Tkinter as the graphical library it's built on top of.

I first tried

```<code>def newtext(n,t):
    str(n) = Label(text=t)
</code>```

with

```<code>from aiui import *
newtext("test","test")
</code>```

In the other file,
This didn't work, which was expected because you can't put a variable in a string for it to work, but I wanted to try anyway. Then I tried just putting it as n without the str modifier, but obviously that didn't work. Now I'm stuck and don't know what to try. Is there a function or way you can even do this?

Body:
I am making a library in Python, and I have a function that is supposed to create a new line of text in a GUI every time you use it. This is using Tkinter as the graphical library it's built on top of.

I first tried

def newtext(n,t):
    str(n) = Label(text=t)

with

from aiui import *
newtext("test","test")

In the other file,
This didn't work, which was expected because you can't put a variable in a string for it to work, but I wanted to try anyway. Then I tried just putting it as n without the str modifier, but obviously that didn't work. Now I'm stuck and don't know what to try. Is there a function or way you can even do this?


问:
How do I get a COM object in Runsimpersonated?
How do I get a COM object in Runsimpersonated in NET 6.0?

```<code>WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, () =>
{
    Type? peepTypeFromId = Type.GetTypeFromProgID("Wppeep.Document", true);
});
</code>```

Returns an error:

(0x800401F3 (CO_E_CLASSSTRING)).

There is definitely data in the registry.

I tried doing test projects on .NET 5, .NET 6, .NET 7 on different machines. I also substituted the keys. But if you make Windowsidentity.ruNimpersonated (Windowsidentity.acCesstoken, () => then everything doesn't work both with WPPEEP.Document and with excel. It seems to me that the RunImpersonated method restricts the rights to work with the registry. Users with different rights also do not affect anything. Register entry Peep.zip.

Body:
How do I get a COM object in Runsimpersonated in NET 6.0?

WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, () =>
{
    Type? peepTypeFromId = Type.GetTypeFromProgID("Wppeep.Document", true);
});

Returns an error:

(0x800401F3 (CO_E_CLASSSTRING)).

There is definitely data in the registry.

I tried doing test projects on .NET 5, .NET 6, .NET 7 on different machines. I also substituted the keys. But if you make Windowsidentity.ruNimpersonated (Windowsidentity.acCesstoken, () => then everything doesn't work both with WPPEEP.Document and with excel. It seems to me that the RunImpersonated method restricts the rights to work with the registry. Users with different rights also do not affect anything. Register entry Peep.zip.


问:
Evaluate JSON object with expression with variable name, Josson Evaluate
We need to evaluate JSON object expressions in java.

We have the following source JSON object

```<code>{
  "a": 100,
  "b": 200,
  "c": 300,
  "d": "calc(a+c)",
  "f": {
    "g": 100,
    "h": 200,
    "i": "calc(g+h)",
    "k": {
      "m": 50,
      "n": 70,
      "p": "calc(m+n)"
    }
  }
}
</code>```

we need to output this format

```<code>{
  "a": 100,
  "b": 200,
  "c": 300,
  "d": 400,
  "f": {
    "g": 100,
    "h": 200,
    "i": 300,
    "k": {
      "m": 50,
      "n": 70,
      "p": 120
    }
  }
}
</code>```

we know the json structure. But can you suggest more generic way where the json structure is not known and json can be iterated and eval can be done wherever some formuala like calc, concat is used. Also maintain the depth of json.

Body:
We need to evaluate JSON object expressions in java.

We have the following source JSON object

{
  "a": 100,
  "b": 200,
  "c": 300,
  "d": "calc(a+c)",
  "f": {
    "g": 100,
    "h": 200,
    "i": "calc(g+h)",
    "k": {
      "m": 50,
      "n": 70,
      "p": "calc(m+n)"
    }
  }
}

we need to output this format

{
  "a": 100,
  "b": 200,
  "c": 300,
  "d": 400,
  "f": {
    "g": 100,
    "h": 200,
    "i": 300,
    "k": {
      "m": 50,
      "n": 70,
      "p": 120
    }
  }
}

we know the json structure. But can you suggest more generic way where the json structure is not known and json can be iterated and eval can be done wherever some formuala like calc, concat is used. Also maintain the depth of json.


问:
Not sure what to do with attempting to unpack a non-sequence
I am running through my text book after a season of to try and understand a few things. I am trying to get a server and client network going. The client is giving me issues.

server:

```<code>import string
import zmq

host = '127.0.0.1'
port = 6789
ctx = zmq.Context()
pub = ctx.socket(zmq.PUB)
pub.bind('tcp://%s:%s' % (host, port))

with open('mammoth.txt', 'rt') as poem:
    words = poem.read()
for word in words.split():
    word = word.strip(string.punctuation)
    data = word.encode('utf-8')
    if word.startswith(('a','e','o','u','A','e','i','o','u')):
        pub.send_multipart([b'vowels', data])
if len(word) == 5:
    pub.send_multipart([b'five', data])
</code>```

client:

```<code>import string
import zmq

host = '127.0.0.1'
port = 6789

ctx = zmq.Context()
sub = ctx.socket(zmq.SUB)
sub.connect('tcp://%s:%s' % (host, port))
sub.setsockopt(zmq.SUBSCRIBE, b'vowels')
sub.setsockopt(zmq.SUBSCRIBE, b'five')
while True:
    topic, word = sub.recv_multipart()
    print(topic, word)
</code>```

specifically I don't understand why this is an issue.

```<code>topic, word = sub.recv_multipart()
</code>```

Its been a bit, so researching the answers related to this are not making sense to me. Help is appreciated.

Body:
I am running through my text book after a season of to try and understand a few things. I am trying to get a server and client network going. The client is giving me issues.

server:

import string
import zmq

host = '127.0.0.1'
port = 6789
ctx = zmq.Context()
pub = ctx.socket(zmq.PUB)
pub.bind('tcp://%s:%s' % (host, port))

with open('mammoth.txt', 'rt') as poem:
    words = poem.read()
for word in words.split():
    word = word.strip(string.punctuation)
    data = word.encode('utf-8')
    if word.startswith(('a','e','o','u','A','e','i','o','u')):
        pub.send_multipart([b'vowels', data])
if len(word) == 5:
    pub.send_multipart([b'five', data])

client:

import string
import zmq

host = '127.0.0.1'
port = 6789

ctx = zmq.Context()
sub = ctx.socket(zmq.SUB)
sub.connect('tcp://%s:%s' % (host, port))
sub.setsockopt(zmq.SUBSCRIBE, b'vowels')
sub.setsockopt(zmq.SUBSCRIBE, b'five')
while True:
    topic, word = sub.recv_multipart()
    print(topic, word)

specifically I don't understand why this is an issue.

topic, word = sub.recv_multipart()

Its been a bit, so researching the answers related to this are not making sense to me. Help is appreciated.


问:
How to calculate 'predict_proba' manually (Catboost)?
I train the model using Catboost and get the output probabilities (between 0 and 1) as per the below (where X_train are the input predictors):

```<code>output = model.predict_proba(X_train)[:,1]
</code>```

However, I am looking to manually re-compute the output predicted probabilities for each datapoint(i.e., each row sample in my Test set) after training a classification model without having to use the 'predict_proba' function.

I have the feature values of each variable/feature - it is a mix of both categorical and numerical variables. I am looking to get pointed in the right direction for some insights on how I can do this calculation myself.

Body:
I train the model using Catboost and get the output probabilities (between 0 and 1) as per the below (where X_train are the input predictors):

output = model.predict_proba(X_train)[:,1]

However, I am looking to manually re-compute the output predicted probabilities for each datapoint(i.e., each row sample in my Test set) after training a classification model without having to use the 'predict_proba' function.

I have the feature values of each variable/feature - it is a mix of both categorical and numerical variables. I am looking to get pointed in the right direction for some insights on how I can do this calculation myself.


问:
Hhow to highlight today's day with a custom image/icon in a UICalendarView?
Does anybody know how to highlight today's day with a custom image/icon in a UICalendarView?

something like the image below with the star

I have only found ways to add icons UNDER the day but I cannot find a way to overlap it like a zstack with the day

```<code>class Coordinator: NSObject, UICalendarViewDelegate, UICalendarSelectionSingleDateDelegate {
        var parent: CalendarView
        @ObservedObject var eventStore: EventStore
        @Environment(\.managedObjectContext) var viewContext
        var journalItemsC: FetchedResults<JournalItem>

        init(parent: CalendarView, eventStore: ObservedObject<EventStore>, journalItemsC: FetchedResults<JournalItem>) {
            self.parent = parent
            self._eventStore = eventStore
            self.journalItemsC = journalItemsC
        }

        @MainActor

        func calendarView(_ calendarView: UICalendarView,
                          decorationFor dateComponents: DateComponents) -> UICalendarView.Decoration? {

            let foundEvents = journalItemsC
                .filter {$0.date?.startOfDay == dateComponents.date?.startOfDay}
            if foundEvents.isEmpty { return nil }

            let today = Calendar.current.startOfDay(for: Date())

            // At least one event was found, so create a decoration object to display a dot for the date
            //return UICalendarView.Decoration(__color: .red, size: .large)
            return .customView {
                let imageView = UILabel()
                imageView.text = "☺"
//                            UIImageView(image: UIImage(systemName: "star.fill"))
//                            imageView.tintColor = .yellow
                return imageView
            }

        }
</code>```

Body:
Does anybody know how to highlight today's day with a custom image/icon in a UICalendarView?

something like the image below with the star

I have only found ways to add icons UNDER the day but I cannot find a way to overlap it like a zstack with the day

class Coordinator: NSObject, UICalendarViewDelegate, UICalendarSelectionSingleDateDelegate {
        var parent: CalendarView
        @ObservedObject var eventStore: EventStore
        @Environment(\.managedObjectContext) var viewContext
        var journalItemsC: FetchedResults<JournalItem>

        init(parent: CalendarView, eventStore: ObservedObject<EventStore>, journalItemsC: FetchedResults<JournalItem>) {
            self.parent = parent
            self._eventStore = eventStore
            self.journalItemsC = journalItemsC
        }

        @MainActor

        func calendarView(_ calendarView: UICalendarView,
                          decorationFor dateComponents: DateComponents) -> UICalendarView.Decoration? {

            let foundEvents = journalItemsC
                .filter {$0.date?.startOfDay == dateComponents.date?.startOfDay}
            if foundEvents.isEmpty { return nil }

            let today = Calendar.current.startOfDay(for: Date())

            // At least one event was found, so create a decoration object to display a dot for the date
            //return UICalendarView.Decoration(__color: .red, size: .large)
            return .customView {
                let imageView = UILabel()
                imageView.text = "☺"
//                            UIImageView(image: UIImage(systemName: "star.fill"))
//                            imageView.tintColor = .yellow
                return imageView
            }

        }


问:
How to update the Private Ranges of the Azure Firewall Policy through Landing Zone Deployment
Unable to capture the private ranges I manually add in the Azure portal under the Azure Firewall Policy when I deploy landing zone.

Landing Zone deployment is successful.

But, the private ranges I add in the Azure portal cannot be captured when I redeploy the Landing Zone.

Every time I redeploy the Landing Zone through the pipeline, it only overwrites the Landing Zone deployment.

That is why it does not get the updated private ranges I add manually in the portal.

Any suggestions on how to not overwrite the list of private ranges in the azure firewall policy when I redeploy the landing zone?


问:
`document.getElementById('id').innerHTML=document.getElementById('id').innerHTML` changes the website
Here is what the website looks like at first:

I run

document.getElementById('top-level-buttons').innerHTML = document.getElementById('top-level-buttons').innerHTML
```

Here is what the website looks like now:

Why is this happening?

It is worth noting that this is an issue present in Chrome DevTools. Here are some observations that I have made:

The button tags contain inside them svg tags. These svg tags are getting removed, which is why the content inside the buttons disappear.

Clicking on "Copy Element" in the Chrome Inspect tab removes these svg tags, so I have to copy the svg tags separately

Running the command noted above in the "Console" tab also removes the svg tags from the website

Any idea why this is happening? This issue could be specific to Chrome DevTools, or it could be not; I have no way of testing this. The website is YouTube Music and the div in question is top-level-buttons, which displays the Shuffle, Play, Add To Library, and Radio buttons on pages like playlists, albums, and artists.

Body:
Here is what the website looks like at first:

I run

document.getElementById('top-level-buttons').innerHTML = document.getElementById('top-level-buttons').innerHTML

Here is what the website looks like now:

Why is this happening?

It is worth noting that this is an issue present in Chrome DevTools. Here are some observations that I have made:

The button tags contain inside them svg tags. These svg tags are getting removed, which is why the content inside the buttons disappear.

Clicking on "Copy Element" in the Chrome Inspect tab removes these svg tags, so I have to copy the svg tags separately

Running the command noted above in the "Console" tab also removes the svg tags from the website

Any idea why this is happening? This issue could be specific to Chrome DevTools, or it could be not; I have no way of testing this. The website is YouTube Music and the div in question is top-level-buttons, which displays the Shuffle, Play, Add To Library, and Radio buttons on pages like playlists, albums, and artists.


问:
Uncaught SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Please any solution for this error. It is for a Chrome extension
this is the code manifest.json

```<code>{
"manifest_version": 3,
"name": "Volume",
"description": "this show the v",
"version": "1.0",
"host_permissions": \[
"https://www.googleapis.com/*"
\],
"content_scripts": \[
{
"matches": \["https://www.youtube.com/*"\],
"js": \["popup.js"\]
}
\],
"action": {
"default_popup": "popup.html"
}
}

</code>```

and this the html code

```<code>
<!DOCTYPE html>
<html>
<head>
  <title>Vol</title>
</head>
<body>
  <h1>Vol</h1>
  <p>wordss:</p>
  <input type="text" id="query" />
  <button id="checkPage">Buscar</button>
  <script src="popup.js"></script>
</body>
</html>
</code>```

i don't know why this error appear

Body:
Please any solution for this error. It is for a Chrome extension
this is the code manifest.json

{
"manifest_version": 3,
"name": "Volume",
"description": "this show the v",
"version": "1.0",
"host_permissions": \[
"https://www.googleapis.com/*"
\],
"content_scripts": \[
{
"matches": \["https://www.youtube.com/*"\],
"js": \["popup.js"\]
}
\],
"action": {
"default_popup": "popup.html"
}
}

and this the html code

<!DOCTYPE html>

  <title>Vol</title>

Vol

wordss:

  <input type="text" id="query" />
  <button id="checkPage">Buscar</button>

i don't know why this error appear


问:
the seed entity for entity type dictionary<string,object> cannot be added because no value was provided for the required property
I need help with a way how to fix this error :

the seed entity for entity type ArtistEvent (Dictionary<string,object>) cannot be added because no value was provided for the required property AristsArtistId

I want to create a many-to-many relationship between Events and Artists.

Here is code for Event.cs

```<code>public class Event
    {
        public Event()
        {
            Artists = new HashSet<Artist>();
        }
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int EventId { get; set; }
        [Required]
        [Column("EventName")]
        [StringLength(30)]
        public string? Name { get; set; }
        [Required]
        [Column("EventDescription")]
        [StringLength(150)]
        public string Description { get; set; }
        [Required]
        [Column("EventType")]
        [StringLength(30)]
        public string TypeOfEvent { get; set; }
        [Required]
        public DateTime DateOfEvent { get; set; }
        [Required]
        public decimal TicketPrice { get; set; }
        virtual public ISet<Artist> Artists { get; set; }

    }
</code>```

Here is code for Artist.cs

```<code> public class Artist
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ArtistId { get; set; }
        [Required]
        [Column("Name")]
        [StringLength(30)]
        public string? Name { get; set; }
        [Required]
        [Column("Surname")]
        [StringLength(30)]
        public string Surname { get; set; }
        [Required]
        [Column("Nickname")]
        [StringLength(30)]
        public string Nickname { get; set; }
        virtual public ISet<Event> Events { get; set; }

    }
</code>```

And code for my Database context

```<code> public class AppDbContext : DbContext
    {
        public DbSet<Event> Events { get; set; }
        public DbSet<Artist> Artists { get; set; }
        public DbSet<Ticket> Tickets { get; set; }
        public AppDbContext(DbContextOptions options) : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Event>().HasData(
                new Event() { EventId = 1, Name = "aaa", Description = "aaa!", TypeOfEvent = "aaa", DateOfEvent = new DateTime (2023,2,1,18,30,0), TicketPrice = 40},
                new Event() { EventId = 2, Name = "bbb", Description = "bbb ", TypeOfEvent = "bbb", DateOfEvent = new DateTime(2023, 4, 12, 12, 0, 0), TicketPrice = 30 },
                new Event() { EventId = 3, Name = "Opera", Description = "ccc", TypeOfEvent = "ccc", DateOfEvent = new DateTime(2023, 5, 14, 15, 0, 0), TicketPrice = 50 }
                );

            modelBuilder.Entity<Artist>().HasData(
                new Artist() { ArtistId = 1, Name = "aaa", Surname = "aaa", Nickname = "aaa" },
                new Artist() { ArtistId = 2, Name = "bbb", Surname = "bbb", Nickname = "bbb" },
                new Artist() { ArtistId = 3 , Name = "ccc", Surname = "ccc", Nickname = "ccc" }
                );

            modelBuilder.Entity<Artist>()
                .HasMany<Event>(a => a.Events)
                .WithMany(b => b.Artists)
                .UsingEntity(join => join.HasData(
                    new { EventsId = 1, ArtistsId= 2 },
                    new { EventsId = 3, ArtistsId = 1 },
                    new { EventsId = 2, ArtistsId = 3 }
                    ));

        }
    }
</code>```

I've tried changing the following code:

```<code>modelBuilder.Entity<Artist>()
                .HasMany<Event>(a => a.Events)
                .WithMany(b => b.Artists)
                .UsingEntity(join => join.HasData(
                    new { EventsId = 1, ArtistsId= 2 },
                    new { EventsId = 3, ArtistsId = 1 },
                    new { EventsId = 2, ArtistsId = 3 }
                    ));
</code>```

to

```<code>modelBuilder.Entity<Artist>()
                .HasMany<Event>(a => a.Events)
                .WithMany(b => b.Artists)
                .UsingEntity(join => join.HasData(
                    new { EventsId = 1, AristsArtistId = 2 },
                    new { EventsId = 3, AristsArtistId = 1 },
                    new { EventsId = 2, AristsArtistId = 3 }

                    ));
</code>```

And it still doesn't work so I dont have any idea how to fix this.

Body:
I need help with a way how to fix this error :

the seed entity for entity type ArtistEvent (Dictionary<string,object>) cannot be added because no value was provided for the required property AristsArtistId

I want to create a many-to-many relationship between Events and Artists.

Here is code for Event.cs

public class Event
    {
        public Event()
        {
            Artists = new HashSet<Artist>();
        }
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int EventId { get; set; }
        [Required]
        [Column("EventName")]
        [StringLength(30)]
        public string? Name { get; set; }
        [Required]
        [Column("EventDescription")]
        [StringLength(150)]
        public string Description { get; set; }
        [Required]
        [Column("EventType")]
        [StringLength(30)]
        public string TypeOfEvent { get; set; }
        [Required]
        public DateTime DateOfEvent { get; set; }
        [Required]
        public decimal TicketPrice { get; set; }
        virtual public ISet<Artist> Artists { get; set; }

    }

Here is code for Artist.cs

 public class Artist
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ArtistId { get; set; }
        [Required]
        [Column("Name")]
        [StringLength(30)]
        public string? Name { get; set; }
        [Required]
        [Column("Surname")]
        [StringLength(30)]
        public string Surname { get; set; }
        [Required]
        [Column("Nickname")]
        [StringLength(30)]
        public string Nickname { get; set; }
        virtual public ISet<Event> Events { get; set; }

    }

And code for my Database context

 public class AppDbContext : DbContext
    {
        public DbSet<Event> Events { get; set; }
        public DbSet<Artist> Artists { get; set; }
        public DbSet<Ticket> Tickets { get; set; }
        public AppDbContext(DbContextOptions options) : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Event>().HasData(
                new Event() { EventId = 1, Name = "aaa", Description = "aaa!", TypeOfEvent = "aaa", DateOfEvent = new DateTime (2023,2,1,18,30,0), TicketPrice = 40},
                new Event() { EventId = 2, Name = "bbb", Description = "bbb ", TypeOfEvent = "bbb", DateOfEvent = new DateTime(2023, 4, 12, 12, 0, 0), TicketPrice = 30 },
                new Event() { EventId = 3, Name = "Opera", Description = "ccc", TypeOfEvent = "ccc", DateOfEvent = new DateTime(2023, 5, 14, 15, 0, 0), TicketPrice = 50 }
                );

            modelBuilder.Entity<Artist>().HasData(
                new Artist() { ArtistId = 1, Name = "aaa", Surname = "aaa", Nickname = "aaa" },
                new Artist() { ArtistId = 2, Name = "bbb", Surname = "bbb", Nickname = "bbb" },
                new Artist() { ArtistId = 3 , Name = "ccc", Surname = "ccc", Nickname = "ccc" }
                );

            modelBuilder.Entity<Artist>()
                .HasMany<Event>(a => a.Events)
                .WithMany(b => b.Artists)
                .UsingEntity(join => join.HasData(
                    new { EventsId = 1, ArtistsId= 2 },
                    new { EventsId = 3, ArtistsId = 1 },
                    new { EventsId = 2, ArtistsId = 3 }
                    ));

        }
    }

I've tried changing the following code:

modelBuilder.Entity<Artist>()
                .HasMany<Event>(a => a.Events)
                .WithMany(b => b.Artists)
                .UsingEntity(join => join.HasData(
                    new { EventsId = 1, ArtistsId= 2 },
                    new { EventsId = 3, ArtistsId = 1 },
                    new { EventsId = 2, ArtistsId = 3 }
                    ));

to

modelBuilder.Entity<Artist>()
                .HasMany<Event>(a => a.Events)
                .WithMany(b => b.Artists)
                .UsingEntity(join => join.HasData(
                    new { EventsId = 1, AristsArtistId = 2 },
                    new { EventsId = 3, AristsArtistId = 1 },
                    new { EventsId = 2, AristsArtistId = 3 }

                    ));

And it still doesn't work so I dont have any idea how to fix this.


问:
is it possible to regex out repeating substrings in a concatenated string?
String=AUGACGCAUAACCGACGAUGCAGCGGGCAACUAA

I tried

```<code>re.findall(r'AUG\w*UAA',string)
</code>```

this gives me

```<code>"AUGACGCAUAACCGACGAUGCAGCGGGCAACUAA"
</code>```

i want answer to be

```<code>"AUGACGCAUAA"

"AUGCAGCGGGCAACUAA"
</code>```

Body:
String=AUGACGCAUAACCGACGAUGCAGCGGGCAACUAA

I tried

re.findall(r'AUG\w*UAA',string)

this gives me

"AUGACGCAUAACCGACGAUGCAGCGGGCAACUAA"

i want answer to be

"AUGACGCAUAA"

"AUGCAGCGGGCAACUAA"


问:
Validating a List from JSON data using Flask WTF forms?
I have an endpoint that receives JSON data. I would like to validate the JSON data to ensure the data is correct.

Since I am using Flask-WTF, I would like to reuse it for validation. I know some threads here suggest using WTForms-JSON, but I would like to stick with just Flask-WTF since it is one less third party dependency to worry about and maintain.

My JSON scheme:

```<code>{
    id: 3,
    name: HelloWorld,
    list_dict: [{"id": 23}, {"id":94}],
    list_custom: ["123", "456", "blah"]
}
</code>```

list_dict can have 0 or more dict items, but they must be in a dict.

list_custom can have 0 or more strings.

Flask WTF form:

```<code>class SaveForm(Flaskform):
    id = IntegerField("id", validators=[DataRequired()])
    name = StringField("name", validators=[DataRequired(), Length(max=10))

    # The confusing part...
    list_dict = ???
    list_custom = ???
</code>```

My endpoint:

```<code>@app.route("/save", methods=["POST"])
def save():
    data = MultiDict(mapping=request.get_json())
    form = SaveForm(data)
    if form.validate():
        # Data is correct, do something
</code>```

I use a MultiDict() to pass the data to the Form, but I'm having trouble trying to get it to convert to a list like I have in my JSON scheme. What would be the correct wtf field to use here, and how would the validation work?

Body:
I have an endpoint that receives JSON data. I would like to validate the JSON data to ensure the data is correct.

Since I am using Flask-WTF, I would like to reuse it for validation. I know some threads here suggest using WTForms-JSON, but I would like to stick with just Flask-WTF since it is one less third party dependency to worry about and maintain.

My JSON scheme:

{
    id: 3,
    name: HelloWorld,
    list_dict: [{"id": 23}, {"id":94}],
    list_custom: ["123", "456", "blah"]
}

list_dict can have 0 or more dict items, but they must be in a dict.

list_custom can have 0 or more strings.

Flask WTF form:

class SaveForm(Flaskform):
    id = IntegerField("id", validators=[DataRequired()])
    name = StringField("name", validators=[DataRequired(), Length(max=10))

    # The confusing part...
    list_dict = ???
    list_custom = ???

My endpoint:

@app.route("/save", methods=["POST"])
def save():
    data = MultiDict(mapping=request.get_json())
    form = SaveForm(data)
    if form.validate():
        # Data is correct, do something

I use a MultiDict() to pass the data to the Form, but I'm having trouble trying to get it to convert to a list like I have in my JSON scheme. What would be the correct wtf field to use here, and how would the validation work?


问:
player not rotating as per code after root motion
I have coded a simple program that rotates the player in the direction of movement,
the code :

```<code>Vector3 movement = new Vector3(verticalInput, 0,-horizontalInput).normalized;

    if (movement == Vector3.zero)
    {
        rotationMove  = transform.rotation;
    }

    else{
    Quaternion rotationMove = Quaternion.LookRotation(movement);
    rotationMove= Quaternion.RotateTowards( transform.rotation,rotationMove,360* Time.fixedDeltaTime);
    Debug.Log(rotationMove);

    rb.MoveRotation(rotationMove);

     }
</code>```

this code is working as expected when I use it without root motion
and even I have tried to bake the rotation, and position of the performing animation:
the image

please help me how can I rotate the player with root motion enabled

Body:
I have coded a simple program that rotates the player in the direction of movement,
the code :

Vector3 movement = new Vector3(verticalInput, 0,-horizontalInput).normalized;

    if (movement == Vector3.zero)
    {
        rotationMove  = transform.rotation;
    }

    else{
    Quaternion rotationMove = Quaternion.LookRotation(movement);
    rotationMove= Quaternion.RotateTowards( transform.rotation,rotationMove,360* Time.fixedDeltaTime);
    Debug.Log(rotationMove);

    rb.MoveRotation(rotationMove);

     }

this code is working as expected when I use it without root motion
and even I have tried to bake the rotation, and position of the performing animation:
the image

please help me how can I rotate the player with root motion enabled


问:
Unable to create venv in directory venv
I open the webui-user.bat file from the stable-diffusion-webui, artificial intelligence that creates art, but cmd opens and says:

```<code>Creating venv in directory venv using python "C:\Python27\python.exe"
Unable to create venv in directory venv

exit code: 1

stderr:
C:\Python27\python.exe: No module named venv

Launch unsuccesful. Exiting.
Press a key to continue...
</code>```

I have the version 2.7.15 of Python, I don't know if the stable diffusion supports that version really. The thing is that after reading on another site that I could try typing commands such as py -m pip install --user virtualenv, I type it, but I always get a syntaxerror:

```<code>py -m pip install --user virtualenv
File "<stdin>", line 1
py -m pip install --user virtualenv

SyntaxError: invalid syntax
</code>```

How can I solve this issue? Anyone who can help me, please?

Title: Unable to create venv in directory venv

Body:
I open the webui-user.bat file from the stable-diffusion-webui, artificial intelligence that creates art, but cmd opens and says:

Creating venv in directory venv using python "C:\Python27\python.exe"
Unable to create venv in directory venv

exit code: 1

stderr:
C:\Python27\python.exe: No module named venv

Launch unsuccesful. Exiting.
Press a key to continue...

I have the version 2.7.15 of Python, I don't know if the stable diffusion supports that version really. The thing is that after reading on another site that I could try typing commands such as py -m pip install --user virtualenv, I type it, but I always get a syntaxerror:

py -m pip install --user virtualenv
File "<stdin>", line 1
py -m pip install --user virtualenv

SyntaxError: invalid syntax

How can I solve this issue? Anyone who can help me, please?


问:
Kafka Error 'com/fasterxml/jackson/core/JsonFactory' (current frame, stack[0]) is not assignable to 'com/fasterxml/jackson/core/TokenStreamFactory
I need help with Kafka, use Ant project with Eclipse IDE, got error :

```<code>Caused by: org.apache.kafka.common.KafkaException: Could not instantiate class io.confluent.kafka.serializers.json.KafkaJsonSchemaSerializer
        at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:396)
        at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:401)
        at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:436)
        at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:421)
        at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:394)
        ... 34 more
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:392)
        ... 38 more
Caused by: java.lang.VerifyError: Bad return type
Exception Details:
  Location:
    com/fasterxml/jackson/databind/cfg/MapperBuilder.streamFactory()Lcom/fasterxml/jackson/core/TokenStreamFactory; @7: areturn
  Reason:
    Type 'com/fasterxml/jackson/core/JsonFactory' (current frame, stack[0]) is not assignable to 'com/fasterxml/jackson/core/TokenStreamFactory' (from method signature)
  Current Frame:
    bci: @7
    flags: { }
    locals: { 'com/fasterxml/jackson/databind/cfg/MapperBuilder' }
    stack: { 'com/fasterxml/jackson/core/JsonFactory' }
  Bytecode:
    0x0000000: 2ab4 0002 b600 08b0

        at com.fasterxml.jackson.databind.json.JsonMapper.builder(JsonMapper.java:114)
        at io.confluent.kafka.schemaregistry.json.jackson.Jackson.newObjectMapper(Jackson.java:64)
        at io.confluent.kafka.schemaregistry.json.jackson.Jackson.newObjectMapper(Jackson.java:55)
        at io.confluent.kafka.serializers.json.AbstractKafkaJsonSchemaSerializer.<init>(AbstractKafkaJsonSchemaSerializer.java:47)
        at io.confluent.kafka.serializers.json.KafkaJsonSchemaSerializer.<init>(KafkaJsonSchemaSerializer.java:41)
        ... 43 more
java.lang.Exception: org.apache.kafka.common.KafkaException: Failed to construct kafka producer
</code>```

if jackson* libs removed it throws some like NoClassDefFoundError...  java.lang.NoClassDefFoundError: com/fasterxml/jackson/annotation/JsonMerge so i import missing jackson* . if i import the error as shown happen :

```<code>Location:
    com/fasterxml/jackson/databind/cfg/MapperBuilder.streamFactory()Lcom/fasterxml/jackson/core/TokenStreamFactory; @7: areturn
  Reason:
    Type 'com/fasterxml/jackson/core/JsonFactory' (current frame, stack[0]) is not assignable to 'com/fasterxml/jackson/core/TokenStreamFactory' (from method signature)
</code>```

another information i deploy in 2 place with same docker and same setting, 1 in my local mac, 2 in AWS server with Ubuntu

in my local all work, nothing error happen, but in AWS Server that error happen

------EDITED------

I have tried my project with Ivy dependencies management, imported 2 Kafka dependencies

```<code><?xml version="1.0" encoding="ISO-8859-1"?>

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
<info
organisation=""
module="project"
status="integration">
</info>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients -->
<dependency org="org.apache.kafka" name="kafka-clients" rev="3.3.1"/>

<!-- https://mvnrepository.com/artifact/io.confluent/kafka-json-schema-serializer -->
<dependency org="io.confluent" name="kafka-json-schema-serializer" rev="7.3.1"/>
</dependencies>
</ivy-module>
</code>```

import:

```<code>import io.confluent.kafka.serializers.json.KafkaJsonSchemaSerializer;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

Properties props = new Properties();
props.put("bootstrap.servers", url);
props.put("linger.ms", 1);
props.put("max.block.ms", 10000);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaJsonSchemaSerializer.class.getName());
props.put("schema.registry.url", schemaurl);
Producer<String, Payment> producer = new KafkaProducer<String, Payment>(props);
ProducerRecord<String, Payment> record = new ProducerRecord<String, Payment>(topic, uuid, message);

Future<RecordMetadata> resp = producer.send(record);

System.out.print(resp.get());

producer.close();
</code>```

new error appear but the error lib i can import with no error :

```<code>java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.JavaType.getBindings()Lcom/fasterxml/jackson/databind/type/TypeBindings;
</code>```

this lib automatically downloaded from ivy :

and i don't know what lib conflict

Body:
I need help with Kafka, use Ant project with Eclipse IDE, got error :

Caused by: org.apache.kafka.common.KafkaException: Could not instantiate class io.confluent.kafka.serializers.json.KafkaJsonSchemaSerializer
        at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:396)
        at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:401)
        at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:436)
        at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:421)
        at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:394)
        ... 34 more
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:392)
        ... 38 more
Caused by: java.lang.VerifyError: Bad return type
Exception Details:
  Location:
    com/fasterxml/jackson/databind/cfg/MapperBuilder.streamFactory()Lcom/fasterxml/jackson/core/TokenStreamFactory; @7: areturn
  Reason:
    Type 'com/fasterxml/jackson/core/JsonFactory' (current frame, stack[0]) is not assignable to 'com/fasterxml/jackson/core/TokenStreamFactory' (from method signature)
  Current Frame:
    bci: @7
    flags: { }
    locals: { 'com/fasterxml/jackson/databind/cfg/MapperBuilder' }
    stack: { 'com/fasterxml/jackson/core/JsonFactory' }
  Bytecode:
    0x0000000: 2ab4 0002 b600 08b0

        at com.fasterxml.jackson.databind.json.JsonMapper.builder(JsonMapper.java:114)
        at io.confluent.kafka.schemaregistry.json.jackson.Jackson.newObjectMapper(Jackson.java:64)
        at io.confluent.kafka.schemaregistry.json.jackson.Jackson.newObjectMapper(Jackson.java:55)
        at io.confluent.kafka.serializers.json.AbstractKafkaJsonSchemaSerializer.<init>(AbstractKafkaJsonSchemaSerializer.java:47)
        at io.confluent.kafka.serializers.json.KafkaJsonSchemaSerializer.<init>(KafkaJsonSchemaSerializer.java:41)
        ... 43 more
java.lang.Exception: org.apache.kafka.common.KafkaException: Failed to construct kafka producer

if jackson* libs removed it throws some like NoClassDefFoundError...  java.lang.NoClassDefFoundError: com/fasterxml/jackson/annotation/JsonMerge so i import missing jackson* . if i import the error as shown happen :

Location:
    com/fasterxml/jackson/databind/cfg/MapperBuilder.streamFactory()Lcom/fasterxml/jackson/core/TokenStreamFactory; @7: areturn
  Reason:
    Type 'com/fasterxml/jackson/core/JsonFactory' (current frame, stack[0]) is not assignable to 'com/fasterxml/jackson/core/TokenStreamFactory' (from method signature)

another information i deploy in 2 place with same docker and same setting, 1 in my local mac, 2 in AWS server with Ubuntu

in my local all work, nothing error happen, but in AWS Server that error happen

------EDITED------

I have tried my project with Ivy dependencies management, imported 2 Kafka dependencies

<?xml version="1.0" encoding="ISO-8859-1"?>

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
<info
organisation=""
module="project"
status="integration">
</info>
<dependencies>

<dependency org="org.apache.kafka" name="kafka-clients" rev="3.3.1"/>

<dependency org="io.confluent" name="kafka-json-schema-serializer" rev="7.3.1"/>
</dependencies>
</ivy-module>

import:

import io.confluent.kafka.serializers.json.KafkaJsonSchemaSerializer;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

Properties props = new Properties();
props.put("bootstrap.servers", url);
props.put("linger.ms", 1);
props.put("max.block.ms", 10000);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaJsonSchemaSerializer.class.getName());
props.put("schema.registry.url", schemaurl);
Producer<String, Payment> producer = new KafkaProducer<String, Payment>(props);
ProducerRecord<String, Payment> record = new ProducerRecord<String, Payment>(topic, uuid, message);

Future<RecordMetadata> resp = producer.send(record);

System.out.print(resp.get());

producer.close();

new error appear but the error lib i can import with no error :

java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.JavaType.getBindings()Lcom/fasterxml/jackson/databind/type/TypeBindings;

this lib automatically downloaded from ivy :

and i don't know what lib conflict


问:
how to input unicode character via summernote into database
i try to input unicode character like " សួស្តី " into database via summernote but in database it display ??? instead of the unicode caracter, in database colliation i use latin_general_bin2 since the before i use summernote it could display unicode correctly, sorry may i know the correct way to do this.

above image  is data inputed in database

and this is the data that i submit before it in database

and this is collation that i used