问:
print preview page UI is different from actual UI
scenario: I am trying to print a page and save it as PDF in Angular 9. I have attached window.print() to the print button. when the user clicks the print button it will invoke the function and pops up the print preview window. everything works correctly thus far.

issue: In print preview, few things are getting rendered improperly which makes UI a little clumsy. simply put, the printed web page looks different from the actual page. similar to this issue. I don't know why it is happening. the issue is the same in other browsers as well.

I have tried setting the width:100% and height:100% in @media print{} and a few other StackOverflow solutions but none worked. Please tell me how to rectify the issue. thanks.


来源: stackexchange

问:
Is there anyway to collect JVM metrics using datadog statsd client inside java code?
I am trying to collect JVM metrics inside the dataflow job

using java.lang.Runtime package I am able to get

available processors

total memory

max memory

active thread count

but I also need to capture GC metrics like total GC count, GC NPause and stack allocation

I tried using a internal package sun.management.ManagementFactoryHelper to get GC metrics but it is not a recommended way in newer java version. I also need to capture stack allocation metrics as well

ContentLicense: CC BY-SA 4.0


问:
Autocomplete not providing unit numbers using HERE API
I have recently started using here API to autocomplete addresses. Yet I can't seem to figure out why the unit numbers aren't coming through? For example if I am using a random address such as 123/1 Georgina Street, Newtown, NSW 2042 Australia it will only suggest 1 Georgina Street (without 123 in front). How can I go about fixing this? Thanks.

Example API call:
https://autocomplete.search.hereapi.com/v1/autocomplete?q=123/1+Georgina+Street+Newtown+NSW+2042&apiKey={MY_API_KEY}


问:
How to get PR dependencies from Gitea API
I want to get list of blocking dependencies from a PR request through Gitea API.

I searched through the internet and API documentation, but I didn't find any solution.

For adding a blocking dependency to a PR Gitea uses an api call to /{owner}/{repo}/pulls/{index}/dependency/add

For deleting /{owner}/{repo}/pulls/{index}/dependency/delete

These routes are not documented in Gitea API documentation.


问:
CMake override executable command on pressing play button in the IDE
I use Emscripten c++ compiler which makes html/js files on add_executable targets

CLion automatically detects targets and its executables

w4-temp executable here points on the js file and tries to launch it (and fails)

(CLion allows manually choose executable command but I have about 100 targets and want to automate it. Also this shoud work in Visual Studio, not on CLion only)

My question is - how to override target executable execute command inside cmake to call custom command (e.g. python http server inside the build directory)?

I'm thinking that solution exists and should look a bit like target_set_executable_override(targetName "python -m http 8080 -d build") but couldn't find anything in the docs


问:
How do we get immutable version of HashSet, List, and other stuffs
For example,

I have hashSet like this

```<code>Protected ReadOnly Property idsOfExistingOrder As HashSet(Of String)
</code>```

It's ReadOnly

However, the ReadOnliness of that variable simple means that outsider cannot change the HashSet. It can still say add element to idsOfExistingOrder

So I should do something like this

```<code>Function getidsOfExistingOrder() As something

End Function
</code>```

What is that something?

I look that HashSet support some interface

```<code> ICollection<T>, IEnumerable<T>, IEnumerable, ISerializable, IDeserializationCallback, ISet<T>, IReadOnlyCollection<T>
</code>```

None of which is appropriate

IReadOnlyCollection<T> seems good but only support count. I want to test if the HashSet also contains some string.

So how should I do this?

Body:
For example,

I have hashSet like this

Protected ReadOnly Property idsOfExistingOrder As HashSet(Of String)

It's ReadOnly

However, the ReadOnliness of that variable simple means that outsider cannot change the HashSet. It can still say add element to idsOfExistingOrder

So I should do something like this

Function getidsOfExistingOrder() As something

End Function

What is that something?

I look that HashSet support some interface

 ICollection<T>, IEnumerable<T>, IEnumerable, ISerializable, IDeserializationCallback, ISet<T>, IReadOnlyCollection<T>

None of which is appropriate

IReadOnlyCollection<T> seems good but only support count. I want to test if the HashSet also contains some string.

So how should I do this?


问:
Laravel 9: Is it fine to use default soft delete procedure as a form of archiving a record/model?
I have a few table whose records should not be deleted but needs some archiving in the long run. I've searched for a few options and some of them requires me to install some new packages or may be add a new field in the database table.

But the problem is that my project is nearly done, and installing new package or adding a new fields forces me to update all eloquent queries related to the affected models and that would take too much time. So I thought, "Why don't I use the default soft delete procedure?"

and hence, my main question "Is it fine to use default soft delete procedure as a form of archiving a record/model?"

I want to know if maybe doing this might violates any of the Laravel Conventions. I want to keep my project up to standards you see.


问:
Monkey patch side effect
I would like to monkey patch a function retrieve_files which retrieves files from different directories,there are two calls to this function and for each call I need a different value, I am aware it is possible with mock using side effects but how can I acheive the same with Monkeypatch in Python</p>

Title: Monkey patch side effect


问:
How can I anchor an AR Object to a wall in my home with ARKit?
I want to create an app that shows signs and objects on walls of my home as directions or explanations of wall decor.

Is there a way to have these things consistently mapped to the right spots on the right walls? How do I go about mapping my home? I've not done any work with ARKit before so I have limited knowledge of what is possible and what isn't with the current SDK features.

Please guide me to resources which can help me learn and make a cool project


问:
SPA Authentication using Laravel 9 Sanctum, Vue 3 and Vite
I am new to Vue and I am following this tutorial about SPA Authentication using Laravel 9 Sanctum, Vue 3 and Vite but when I try "npm run build" I get this error:

```<code>Could not resolve entry module "resource/scss/app.scss".
error during build:
RollupError: Could not resolve entry module "resource/scss/app.scss".
    at error (file:///C:/Users/ASUS/lara9sanctum-vue3-vite/node_modules/rollup/dist/es/shared/rollup.js:2001:30)
    at ModuleLoader.loadEntryModule (file:///C:/Users/ASUS/lara9sanctum-vue3-vite/node_modules/rollup/dist/es/shared/rollup.js:22875:20)
    at async Promise.all (index 0)

</code>```

What can be the reason for this error?

I don't know where to look to fix this error

Body:
I am new to Vue and I am following this tutorial about SPA Authentication using Laravel 9 Sanctum, Vue 3 and Vite but when I try "npm run build" I get this error:

Could not resolve entry module "resource/scss/app.scss".
error during build:
RollupError: Could not resolve entry module "resource/scss/app.scss".
    at error (file:///C:/Users/ASUS/lara9sanctum-vue3-vite/node_modules/rollup/dist/es/shared/rollup.js:2001:30)
    at ModuleLoader.loadEntryModule (file:///C:/Users/ASUS/lara9sanctum-vue3-vite/node_modules/rollup/dist/es/shared/rollup.js:22875:20)
    at async Promise.all (index 0)

What can be the reason for this error?

I don't know where to look to fix this error


问:
Is it possible to add dynamic event listeners to elements in the parsed React virtual DOM tree before returning it in function Component?
Since there are not many resources online for manipulating React Dom with SVG, I plan to build the scheduling orders chart using React with svg graphs.
I'm planning to use the js libraries available already & in my project I'll get the js innerHTML string from the graph created by these functions, i have idea to parse them into React DOM & i want to add dynamic event listeners to the elements of the parsed react virtaul dom tree before returning in the function component.enter image description here

Can anyone help me in this, Thanks in Advance.

Tried to create my own SVG in react with JSON data & tried to align the schedule to timeline.
Needed to Separate DAL & BAL


问:
Stability of logstash-logback-encoder if ELK server is down?
If the ELK server is down for a long time (an hour or more) could that cause stability issues for the server sending logs?

We are using Encoder version 7.2, Java 17, AWS Linux 2, sending somewhere around 650 requests/second distributed across 3 servers (so each one sending about 230/sec thru logstash-logback-encoder). Logback config:

```<code><appender name="stash" class="net.logstash.logback.appender.LogstashUdpSocketAppender">
    <host>elk.mycorp</host>
    <port>{{ logstash_udp_port }}</port>
    <layout class="net.logstash.logback.layout.LogstashLayout"/>
</appender>
</code>```

Our ELK server was down for over an hour, and during that time we had problems with the servers (the ones on the same subnet as ELK showed massively increased response times, and 700,000 open file handles; curiously, servers on a different subnet had no problems).

The Encoder should drop messages if the ring buffer becomes full. But I wonder what's going on when the remote server is offline.  Is it possible that the ELK server going offline caused our servers to fail because ELK could not be reached? If so, any suggestions on how to make our setup more robust?

Body:
If the ELK server is down for a long time (an hour or more) could that cause stability issues for the server sending logs?

We are using Encoder version 7.2, Java 17, AWS Linux 2, sending somewhere around 650 requests/second distributed across 3 servers (so each one sending about 230/sec thru logstash-logback-encoder). Logback config:

<appender name="stash" class="net.logstash.logback.appender.LogstashUdpSocketAppender">
    <host>elk.mycorp</host>
    <port>{{ logstash_udp_port }}</port>
    <layout class="net.logstash.logback.layout.LogstashLayout"/>
</appender>

Our ELK server was down for over an hour, and during that time we had problems with the servers (the ones on the same subnet as ELK showed massively increased response times, and 700,000 open file handles; curiously, servers on a different subnet had no problems).

The Encoder should drop messages if the ring buffer becomes full. But I wonder what's going on when the remote server is offline.  Is it possible that the ELK server going offline caused our servers to fail because ELK could not be reached? If so, any suggestions on how to make our setup more robust?


问:
Using Microsoft Graph to send a message to Teams and update the Taskbar Icon
I'm using the older method of httpclient in C# to send a message to MS Teams using the provided connectors and this is working fine, however the Teams Taskbar icon does not get updated with the little read flag to indicate the presence of a new chat message.

Before I go down the path of testing the MS Graph API does anyone know if the Graph methods will update the taskbar icon? Or is there another way around this or something I can do to get that icon updated?

Thanks


问:
Pandas Merge all xls files in folder (NOT CONCAT)
I'm trying to merge all files within folder using pandas (merge function, on="columnB", how='outer')

What currently working, is manually reading the excel then merge

import pandas as pd

#just to pick up columns to read
tr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

#manually enter selected files
df1=pd.read_excel(r'C:\\Users\\english\Downloads\\filename (0).xls',skiprows=1,usecols=tr)
df2=pd.read_excel(r"C:\Users\english\Downloads\filename (1).xls",skiprows=1,usecols=tr)
df3=pd.read_excel(r"C:\Users\english\Downloads\filename (2).xls",skiprows=1,usecols=tr)
df4=pd.read_excel(r"C:\Users\english\Downloads\filename (3).xls",skiprows=1,usecols=tr)

#Merge all in
df = df1.merge(df2, on="columnB",how='outer').merge(df3, on="columnB",how='outer').merge(df4, on="columnB",how='outer')
df
```
<p>Now to loop through all files in folder, I need to read, then merge
my attempt as following: (hold your laugh :D )</p>
<pre class="lang-py prettyprint-override"><code>#import modules
import pandas as pd
import glob

path="C:\\Users\\english\Downloads\\"

# reading all the excel files
filenames = glob.glob(path + "\*.xls")
print('File names:', filenames)

# initializing empty data frame
finalexcelsheet = pd.DataFrame()

# to iterate excel file one by one
for file in filenames:
    tr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    df = pd.merge(pd.read_excel(file,skiprows=1,usecols=tr, sheet_name=None,engine='openpyxl'))
    # merging excel files one by one
    finalexcelsheet = finalexcelsheet.merge(df, on="columnB",how='outer', ignore_index=True)

finalexcelsheet
</code>```

For a moment i thought, WOW! I really got it from first try without googling, however python bites with this error

```<code>BadZipFile                                Traceback (most recent call last)
Cell In [15], line 18
     14 for file in filenames:
     15     # combining multiple excel worksheets
     16     # into single data frames
     17     tr=[1,2,4,6,8,10,12,14,16,18,20]
---> 18     df = pd.merge(pd.read_excel(file,skiprows=1,usecols=tr, sheet_name=None,engine='openpyxl'))
     19     # merging excel files one by one
     20     finalexcelsheet = finalexcelsheet.merge(df, on="columnB",how='outer', ignore_index=True)

File c:\Users\english\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\util\_decorators.py:311, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
    305 if len(args) > num_allow_args:
    306     warnings.warn(
    307         msg.format(arguments=arguments),
...
-> 1334     raise BadZipFile("File is not a zip file")
   1335 if self.debug > 1:
   1336     print(endrec)

BadZipFile: File is not a zip file
</code>```

My thoughts, Read all files, then through a loop, read then merge into 1st df or in empty df, however all attempt through back the same error!
Any help is highly appreciated (Not restricted to pandas)

Body:
I'm trying to merge all files within folder using pandas (merge function, on="columnB", how='outer')

What currently working, is manually reading the excel then merge

import pandas as pd

#just to pick up columns to read
tr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

#manually enter selected files
df1=pd.read_excel(r'C:\\Users\\english\Downloads\\filename (0).xls',skiprows=1,usecols=tr)
df2=pd.read_excel(r"C:\Users\english\Downloads\filename (1).xls",skiprows=1,usecols=tr)
df3=pd.read_excel(r"C:\Users\english\Downloads\filename (2).xls",skiprows=1,usecols=tr)
df4=pd.read_excel(r"C:\Users\english\Downloads\filename (3).xls",skiprows=1,usecols=tr)

#Merge all in
df = df1.merge(df2, on="columnB",how='outer').merge(df3, on="columnB",how='outer').merge(df4, on="columnB",how='outer')
df

Now to loop through all files in folder, I need to read, then merge
my attempt as following: (hold your laugh :D )

#import modules
import pandas as pd
import glob

path="C:\\Users\\english\Downloads\\"

# reading all the excel files
filenames = glob.glob(path + "\*.xls")
print('File names:', filenames)

# initializing empty data frame
finalexcelsheet = pd.DataFrame()

# to iterate excel file one by one
for file in filenames:
    tr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    df = pd.merge(pd.read_excel(file,skiprows=1,usecols=tr, sheet_name=None,engine='openpyxl'))
    # merging excel files one by one
    finalexcelsheet = finalexcelsheet.merge(df, on="columnB",how='outer', ignore_index=True)

finalexcelsheet

For a moment i thought, WOW! I really got it from first try without googling, however python bites with this error

BadZipFile                                Traceback (most recent call last)
Cell In [15], line 18
     14 for file in filenames:
     15     # combining multiple excel worksheets
     16     # into single data frames
     17     tr=[1,2,4,6,8,10,12,14,16,18,20]
---> 18     df = pd.merge(pd.read_excel(file,skiprows=1,usecols=tr, sheet_name=None,engine='openpyxl'))
     19     # merging excel files one by one
     20     finalexcelsheet = finalexcelsheet.merge(df, on="columnB",how='outer', ignore_index=True)

File c:\Users\english\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\util\_decorators.py:311, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
    305 if len(args) > num_allow_args:
    306     warnings.warn(
    307         msg.format(arguments=arguments),
...
-> 1334     raise BadZipFile("File is not a zip file")
   1335 if self.debug > 1:
   1336     print(endrec)

BadZipFile: File is not a zip file

My thoughts, Read all files, then through a loop, read then merge into 1st df or in empty df, however all attempt through back the same error!
Any help is highly appreciated (Not restricted to pandas)


Title: How to covert data to pandas dataframe


问:
How to generate a single HTML report for a test suites that includes multiple test case files in selenium using python unittest framework?
I have a test suite file in which the test cases are being called. So when I run the test suite(For e.g which has 2 test case files), 2 HTML reports are being generated i.e. each of every test case file.

How can I generate a single HTML report even if I have multiple test case files?

Below is the snippet of my test suite file:

```<code>import unittest
import HtmlTestRunner

from Project_Files.DynamicID import DynamicIDTest
from Project_Files.ShadowDOM import ShadowDOMTest

tc1 = unittest.TestLoader().loadTestsFromTestCase(DynamicIDTest)
tc2 = unittest.TestLoader().loadTestsFromTestCase(ShadowDOMTest)

all_tests = unittest.TestSuite([tc1, tc2])

# unittest.TextTestRunner().run(all_tests)

if __name__ == "__main__":
    unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output= "..\\Reports"))
</code>```

Body:
I have a test suite file in which the test cases are being called. So when I run the test suite(For e.g which has 2 test case files), 2 HTML reports are being generated i.e. each of every test case file.

How can I generate a single HTML report even if I have multiple test case files?

Below is the snippet of my test suite file:

import unittest
import HtmlTestRunner

from Project_Files.DynamicID import DynamicIDTest
from Project_Files.ShadowDOM import ShadowDOMTest

tc1 = unittest.TestLoader().loadTestsFromTestCase(DynamicIDTest)
tc2 = unittest.TestLoader().loadTestsFromTestCase(ShadowDOMTest)

all_tests = unittest.TestSuite([tc1, tc2])

# unittest.TextTestRunner().run(all_tests)

if __name__ == "__main__":
    unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output= "..\\Reports"))


问:
handle escape characters in the json.loads in python?
I have a record -

input_json = {"id": 109504954315901999, "created_at": "2022-12-13T06:29:58+00:00", "in_reply_to_id": null, "in_reply_to_account_id": null, "sensitive": false, "spoiler_text": "", "visibility": "public", "language": "de", "uri": "https://troet.cafe/users/TGamay/statuses/109504954282374823", "url": "https://troet.cafe/@TGamay/109504954282374823", "replies_count": 0, "reblogs_count": 0, "favourites_count": 0, "edited_at": null, "content": "
13. Dez: \"Eh? Wer bist denn Du? Willste etwa Koks haben? Das kannste vergessen. So wie Du aussiehst, hast Du auch gar keins nötig. Dein Bart ist ja noch ganz weiß. Hast Dir wohl grad die Markierungslinie der Autobahn reingezogen, was? Hehehe.\"
Dem Weihnachtsmann gefiel der Humor.
", "reblog": null, "account": {"id": 108218397610933167, "username": "TGamay", "acct": "TGamay@troet.cafe", "display_name": "TGamay", "locked": false, "bot": false, "discoverable": true, "group": false, "created_at": "2022-04-25T00:00:00+00:00", "note": "
Eine Perlenkette von Lichtern erschien mir. Seitdem bin ich bei Mastodon. Summa Rudis
", "url": "https://troet.cafe/@TGamay", "avatar": "https://files.mastodon.social/cache/accounts/avatars/108/218/397/610/933/167/original/2019387a4907e0ce.jpg", "avatar_static": "https://files.mastodon.social/cache/accounts/avatars/108/218/397/610/933/167/original/2019387a4907e0ce.jpg", "header": "https://files.mastodon.social/cache/accounts/headers/108/218/397/610/933/167/original/6ebd292535d3f7b1.jpg", "header_static": "https://files.mastodon.social/cache/accounts/headers/108/218/397/610/933/167/original/6ebd292535d3f7b1.jpg", "followers_count": 159, "following_count": 381, "statuses_count": 603, "last_status_at": "2022-12-13T00:00:00", "emojis": [], "fields": []}, "media_attachments": [], "mentions": [], "tags": [], "emojis": [], "card": null, "poll": null}

Getting error -

json.decoder.JSONDecodeError: Invalid \escape: line 1 column 28 (char 27)

Used below approach-

```<code>data = json.loads("""{}""".format(input_json))
</code>```

Please help.

Body:
I have a record -

input_json = {"id": 109504954315901999, "created_at": "2022-12-13T06:29:58+00:00", "in_reply_to_id": null, "in_reply_to_account_id": null, "sensitive": false, "spoiler_text": "", "visibility": "public", "language": "de", "uri": "https://troet.cafe/users/TGamay/statuses/109504954282374823", "url": "https://troet.cafe/@TGamay/109504954282374823", "replies_count": 0, "reblogs_count": 0, "favourites_count": 0, "edited_at": null, "content": "
13. Dez: \"Eh? Wer bist denn Du? Willste etwa Koks haben? Das kannste vergessen. So wie Du aussiehst, hast Du auch gar keins nötig. Dein Bart ist ja noch ganz weiß. Hast Dir wohl grad die Markierungslinie der Autobahn reingezogen, was? Hehehe.\"
Dem Weihnachtsmann gefiel der Humor.
", "reblog": null, "account": {"id": 108218397610933167, "username": "TGamay", "acct": "TGamay@troet.cafe", "display_name": "TGamay", "locked": false, "bot": false, "discoverable": true, "group": false, "created_at": "2022-04-25T00:00:00+00:00", "note": "
Eine Perlenkette von Lichtern erschien mir. Seitdem bin ich bei Mastodon. Summa Rudis
", "url": "https://troet.cafe/@TGamay", "avatar": "https://files.mastodon.social/cache/accounts/avatars/108/218/397/610/933/167/original/2019387a4907e0ce.jpg", "avatar_static": "https://files.mastodon.social/cache/accounts/avatars/108/218/397/610/933/167/original/2019387a4907e0ce.jpg", "header": "https://files.mastodon.social/cache/accounts/headers/108/218/397/610/933/167/original/6ebd292535d3f7b1.jpg", "header_static": "https://files.mastodon.social/cache/accounts/headers/108/218/397/610/933/167/original/6ebd292535d3f7b1.jpg", "followers_count": 159, "following_count": 381, "statuses_count": 603, "last_status_at": "2022-12-13T00:00:00", "emojis": [], "fields": []}, "media_attachments": [], "mentions": [], "tags": [], "emojis": [], "card": null, "poll": null}

Getting error -

json.decoder.JSONDecodeError: Invalid \escape: line 1 column 28 (char 27)

Used below approach-

data = json.loads("""{}""".format(input_json))

Please help.


问:
MongoDB - How to migrate LUUID to UUID?
How can I change all existing documents LUUID properties to UUID?

My collection looks like:

```<code>{
    "_id" : LUUID("70094955-9989-49bf-8261-6d32f46a2040"),
    "metadata" : {
        "userUuid" : LUUID("827ac2d6-2c49-40c4-9437-e7c2e41f983e"),
    },
}
</code>```

I want to convert all documents with _id and metadata.userUuid LUUID to UUID. So, after migration documents need to look like:

```<code>{
    "_id" : UUID("70094955-9989-49bf-8261-6d32f46a2040"),
    "metadata" : {
        "userUuid" : UUID("827ac2d6-2c49-40c4-9437-e7c2e41f983e"),
    },
}
</code>```

Some documents have already been changed manually. Mongo query cannot "brake" already migrated documents.

How to do this? MongoDB v4.4

Title: MongoDB - How to migrate LUUID to UUID?

Body:
How can I change all existing documents LUUID properties to UUID?

My collection looks like:

{
    "_id" : LUUID("70094955-9989-49bf-8261-6d32f46a2040"),
    "metadata" : {
        "userUuid" : LUUID("827ac2d6-2c49-40c4-9437-e7c2e41f983e"),
    },
}

I want to convert all documents with _id and metadata.userUuid LUUID to UUID. So, after migration documents need to look like:

{
    "_id" : UUID("70094955-9989-49bf-8261-6d32f46a2040"),
    "metadata" : {
        "userUuid" : UUID("827ac2d6-2c49-40c4-9437-e7c2e41f983e"),
    },
}

Some documents have already been changed manually. Mongo query cannot "brake" already migrated documents.

How to do this? MongoDB v4.4


问:
How to Convert system.img to ext4 in ubantu
How to Convert system.img to ext4 in linex command, basically I was trying to unmount android sdk system img to get ext4</p>


问:
How do you make a clickable timeline template in powerpoint?
I am looking to make a template wherein a particular slide has a linear timeline of years displayed with a bubble-like icon above each year. Whenever a bubble is clicked, the info corresponding to that particular year is displayed.

I don't want to make a presentation displaying the information chronologically (2000->2001->2002 etc). Any year's info should be revealed in-place and exclusively seen when it's clicked on

Is it possible to do so in PowerPoint? If so, please guide me to a resource or template for the same!


问:
mobile PIN based authentication for mobile app in flutter with authnitication
I need to build a mobile app where i need to first register a user by phone number followed by setting up a 4 digit PIN. Next time when user logs in user can directly input the set 4 digit PIN and logs in on the app. How can i implement it with spring security? My thought is, when user registers with his/her phone no + PIN then do i need to keep this combination in Spring token store or an IDP like keycloack so that when user opens the app again then i can do a check in db if the device is registered in the db (with IMEA no) with mpin set up then show the PIN screen to input? In this case, will PIN be a part of IDP then which field in IDP should hold PIN? like password or something..? can you pls give me some direction around this.</p>


问:
Hasura WebSocket connection to 'wss://XXX.XXX.XXX.XXX/v1/graphql' failed: WebSocket is closed before the connection is established
This error message will appear when the system is connecting, but sometimes it is good and sometimes it is abnormal.
I use Angular & apollo-angular to connect.

```<code>  const ws = new WebSocketLink({
    uri:'wss://XXX.XXX.XXX.XXX/v1/graphql',
    options:{
      reconnect:true,
      lazy: true,
      connectionParams: {
        headers: {
          "x-hasura-admin-secret": "XXXXXX"
        }
      }
    },

  });
</code>```

I try to use "lazy: true", but it failure.

Body:
This error message will appear when the system is connecting, but sometimes it is good and sometimes it is abnormal.
I use Angular & apollo-angular to connect.

  const ws = new WebSocketLink({
    uri:'wss://XXX.XXX.XXX.XXX/v1/graphql',
    options:{
      reconnect:true,
      lazy: true,
      connectionParams: {
        headers: {
          "x-hasura-admin-secret": "XXXXXX"
        }
      }
    },

  });

I try to use "lazy: true", but it failure.


问:
How to calculate between two timings SQL
Table 1:

ID
Name
Class
Date
Intime
Outtime
Hours

1001
Paul
1st
09-12-2022
8:30 AM
4:30 PM
8

Could someone help me how can I calculate Intime, Outtime between hours. Thank you...


问:
Why is Collection<String> converted to record[] postgresql spring jpa
Created such a function in postgresql

```<code>CREATE FUNCTION server_delete(
    remove_station_id bigint,
    server_names varchar(60)[]
)
    RETURNS TABLE
            (
                station_id integer,
                server_name varchar,
                code        integer
            )
    LANGUAGE plpgsql
AS
$$
DECLARE
    server_id               integer;
    server_name             varchar;
    server_count            integer;
    server_station_id_count integer;
    station_server_count    integer;
    result                  integer;
BEGIN
    CREATE TEMPORARY TABLE temp_server_delete_table
    (
        station_id  integer,
        server_name varchar,
        code        integer
    ) ON COMMIT DROP;

    FOREACH server_name IN ARRAY server_names
        LOOP
            SELECT COUNT(*)
            INTO server_count
            FROM c_server
            WHERE name = server_name;

            SELECT COUNT(*)
            INTO server_station_id_count
            FROM c_server cse
                     LEFT JOIN l_station_server lss ON cse.c_server = lss.c_server
            WHERE lss.c_station = remove_station_id
              AND cse.name = server_name;

            SELECT COUNT(*)
            INTO station_server_count
            FROM c_server cse
                     LEFT JOIN l_station_server lss ON cse.c_server = lss.c_server
            WHERE lss.c_station = remove_station_id;

            SELECT cse.c_server
            INTO server_id
            FROM c_server cse
                     LEFT JOIN l_station_server lss ON cse.c_server = lss.c_server
            WHERE lss.c_station = remove_station_id
              AND cse.name = server_name;

            IF server_count != server_station_id_count THEN
                result := 4007;
            ELSIF server_id IS NULL THEN
                result := 4010;
            ELSE
                IF station_server_count >= 1 THEN
                    BEGIN
                         DELETE
                         FROM public.c_server
                         WHERE c_server = server_id;
                        result := 2000;
                    END;
                ELSE
                    result := 500;
                END IF;
            END IF;

            INSERT INTO temp_server_delete_table (station_id, server_name, code)
            VALUES (remove_station_id, server_name, result);
        END LOOP;

    SELECT COUNT(*)
    INTO station_server_count
    FROM l_station_server
    WHERE c_station = remove_station_id;
    IF station_server_count = 0 THEN
        BEGIN
             DELETE
             FROM public.c_station
             WHERE c_station = remove_station_id;
            result := 2001;
            INSERT INTO temp_server_delete_table (station_id, code) VALUES (remove_station_id, result);
        END;
    END IF;

    RETURN QUERY
        SELECT * FROM temp_server_delete_table;
END;
$$;
</code>```

I'm trying to call it through Spring JPA

    @Query(value = "SELECT * FROM server_delete(:id, ARRAY [:names])", nativeQuery = true)
    List<ServerDeleteProjection> deleteByStationIdAndServerNameIn(@Param("id") Long id, @Param("names") Collection<String> names);
```
<p>but throwing Error</p>
<p><strong>[SqlExceptionHelper.java:142] ERROR: function server_delete(bigint, record[]) does not exist
No function matches the given name and argument types. You might need to add explicit type casts.</strong></p>
<ol>
<li>Why Collection casted to record[]?</li>
<li>How can I call a postgesql function via JPA (hibernate)?</li>
</ol>
<p><strong>UPD:</strong>
When I use CAST to get the parameter it looks like <strong>['test_1_c_server,test_2_c_server']</strong></p>
<pre class="lang-java prettyprint-override"><code>    @Query(value = "SELECT * FROM server_delete(:id, CAST(ARRAY [:names] as varchar[]))", nativeQuery = true)
    List<ServerDeleteProjection> deleteByStationIdAndServerNameIn(@Param("id") Long id, @Param("names") Collection<String> names);
</code>```

Body:
Created such a function in postgresql

CREATE FUNCTION server_delete(
    remove_station_id bigint,
    server_names varchar(60)[]
)
    RETURNS TABLE
            (
                station_id integer,
                server_name varchar,
                code        integer
            )
    LANGUAGE plpgsql
AS
$$
DECLARE
    server_id               integer;
    server_name             varchar;
    server_count            integer;
    server_station_id_count integer;
    station_server_count    integer;
    result                  integer;
BEGIN
    CREATE TEMPORARY TABLE temp_server_delete_table
    (
        station_id  integer,
        server_name varchar,
        code        integer
    ) ON COMMIT DROP;

    FOREACH server_name IN ARRAY server_names
        LOOP
            SELECT COUNT(*)
            INTO server_count
            FROM c_server
            WHERE name = server_name;

            SELECT COUNT(*)
            INTO server_station_id_count
            FROM c_server cse
                     LEFT JOIN l_station_server lss ON cse.c_server = lss.c_server
            WHERE lss.c_station = remove_station_id
              AND cse.name = server_name;

            SELECT COUNT(*)
            INTO station_server_count
            FROM c_server cse
                     LEFT JOIN l_station_server lss ON cse.c_server = lss.c_server
            WHERE lss.c_station = remove_station_id;

            SELECT cse.c_server
            INTO server_id
            FROM c_server cse
                     LEFT JOIN l_station_server lss ON cse.c_server = lss.c_server
            WHERE lss.c_station = remove_station_id
              AND cse.name = server_name;

            IF server_count != server_station_id_count THEN
                result := 4007;
            ELSIF server_id IS NULL THEN
                result := 4010;
            ELSE
                IF station_server_count >= 1 THEN
                    BEGIN
                         DELETE
                         FROM public.c_server
                         WHERE c_server = server_id;
                        result := 2000;
                    END;
                ELSE
                    result := 500;
                END IF;
            END IF;

            INSERT INTO temp_server_delete_table (station_id, server_name, code)
            VALUES (remove_station_id, server_name, result);
        END LOOP;

    SELECT COUNT(*)
    INTO station_server_count
    FROM l_station_server
    WHERE c_station = remove_station_id;
    IF station_server_count = 0 THEN
        BEGIN
             DELETE
             FROM public.c_station
             WHERE c_station = remove_station_id;
            result := 2001;
            INSERT INTO temp_server_delete_table (station_id, code) VALUES (remove_station_id, result);
        END;
    END IF;

    RETURN QUERY
        SELECT * FROM temp_server_delete_table;
END;
$$;

I'm trying to call it through Spring JPA

    @Query(value = "SELECT * FROM server_delete(:id, ARRAY [:names])", nativeQuery = true)
    List<ServerDeleteProjection> deleteByStationIdAndServerNameIn(@Param("id") Long id, @Param("names") Collection<String> names);

but throwing Error

[SqlExceptionHelper.java:142] ERROR: function server_delete(bigint, record[]) does not exist
No function matches the given name and argument types. You might need to add explicit type casts.

Why Collection casted to record[]?

How can I call a postgesql function via JPA (hibernate)?

UPD:
When I use CAST to get the parameter it looks like ['test_1_c_server,test_2_c_server']

    @Query(value = "SELECT * FROM server_delete(:id, CAST(ARRAY [:names] as varchar[]))", nativeQuery = true)
    List<ServerDeleteProjection> deleteByStationIdAndServerNameIn(@Param("id") Long id, @Param("names") Collection<String> names);


问:
how to use axios request to exchange google authorization code for access and refresh tokens
I am working on a expo react native app, I tried to implement the google login function.
I am following this expo-auth-session docs https://docs.expo.dev/guides/authentication/#google,

I've successfully gotten the authorization code using the code below:

```<code>const [request, response, promptAsync] = Google.useAuthRequest({
    expoClientId: google_client_id,
    scopes: [
      "https://www.googleapis.com/auth/drive",
    ],
    responseType: "code",
    shouldAutoExchangeCode: false,
    redirectUri: REDIRECT_URI,
    extraParams: {
      access_type: "offline"
    },
  })

  useEffect(() => {
        if (response?.type === 'success'){
            console.log(response.params.code)
        }
    },
    [response]);
</code>```

response.params.code

is the authorization code that returns to me.

I am now trying to use this authorization code to send a post request to the google token endpoint to exchange for a token. I am following this document here: https://developers.google.com/identity/protocols/oauth2/native-app

I tried the following 2 methods, but both of them gives me an axios error code of 400. I am not sure what's wrong with my code. Can someone please help me with it please, thanks!

```<code>axios.request({
                method: 'POST',
                url: 'https://oauth2.googleapis.com/token',
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                    //Authorization: `Basic ${new Buffer.from(`${google_client_id}:${google_client_secret}`).toString('base64')}`,
                },
                data: {
                    grant_type: 'authorization_code',
                    code: response.params.code,
                    redirect_uri: REDIRECT_URI,
                    client_id: google_client_id,
                    client_secret: google_client_secret
                }
            }).then((res) => {
                console.log(res.data)
            }).catch(err => {console.log(err)})
</code>```

and

```<code>axios.request({
                method: 'POST',
                url: 'https://oauth2.googleapis.com/token',
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                    Authorization: `Basic ${new Buffer.from(`${google_client_id}:${google_client_secret}`).toString('base64')}`,
                },
                data: {
                    grant_type: 'authorization_code',
                    code: response.params.code,
                    redirect_uri: REDIRECT_URI,

                }
            }).then((res) => {
                console.log(res.data)
            }).catch(err => {console.log(err)})
</code>```

Body:
I am working on a expo react native app, I tried to implement the google login function.
I am following this expo-auth-session docs https://docs.expo.dev/guides/authentication/#google,

I've successfully gotten the authorization code using the code below:

const [request, response, promptAsync] = Google.useAuthRequest({
    expoClientId: google_client_id,
    scopes: [
      "https://www.googleapis.com/auth/drive",
    ],
    responseType: "code",
    shouldAutoExchangeCode: false,
    redirectUri: REDIRECT_URI,
    extraParams: {
      access_type: "offline"
    },
  })

  useEffect(() => {
        if (response?.type === 'success'){
            console.log(response.params.code)
        }
    },
    [response]);

response.params.code

is the authorization code that returns to me.

I am now trying to use this authorization code to send a post request to the google token endpoint to exchange for a token. I am following this document here: https://developers.google.com/identity/protocols/oauth2/native-app

I tried the following 2 methods, but both of them gives me an axios error code of 400. I am not sure what's wrong with my code. Can someone please help me with it please, thanks!

axios.request({
                method: 'POST',
                url: 'https://oauth2.googleapis.com/token',
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                    //Authorization: `Basic ${new Buffer.from(`${google_client_id}:${google_client_secret}`).toString('base64')}`,
                },
                data: {
                    grant_type: 'authorization_code',
                    code: response.params.code,
                    redirect_uri: REDIRECT_URI,
                    client_id: google_client_id,
                    client_secret: google_client_secret
                }
            }).then((res) => {
                console.log(res.data)
            }).catch(err => {console.log(err)})

and

axios.request({
                method: 'POST',
                url: 'https://oauth2.googleapis.com/token',
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                    Authorization: `Basic ${new Buffer.from(`${google_client_id}:${google_client_secret}`).toString('base64')}`,
                },
                data: {
                    grant_type: 'authorization_code',
                    code: response.params.code,
                    redirect_uri: REDIRECT_URI,

                }
            }).then((res) => {
                console.log(res.data)
            }).catch(err => {console.log(err)})


问:
What is this typescript type `[_user: 'some one']`? How can I retrieve the key '_user' in this?
When I get a log by using ethers.js, after I parsed the log, I got a variable args, if I console.log(args) it, it prints like below:

```<code>[
  '1111',
  '2222',
  _name: '1111',
  _user: '2222'
]
</code>```

When I try to encode it to json:

```<code>JSON.stringify(args);
</code>```

It becomes:

```<code>['1111','2222']
</code>```

So what is type this parsed args?  Is there a way to retrieve the key we see above, like the '_name'?

Thanks!

Body:
When I get a log by using ethers.js, after I parsed the log, I got a variable args, if I console.log(args) it, it prints like below:

[
  '1111',
  '2222',
  _name: '1111',
  _user: '2222'
]

When I try to encode it to json:

JSON.stringify(args);

It becomes:

['1111','2222']

So what is type this parsed args?  Is there a way to retrieve the key we see above, like the '_name'?

Thanks!


问:
Waiting in the main method. Await vs Wait
Judging by the debugger and the "threads" window, both constructs below lead to the same consequences. If we use a non-blocking wait on a worker thread, then it can take up other operations. But what if we use non-blocking wait in the main method, as far as I know the main thread can only execute the main method and cannot switch to other operations outside of this method.

Question: What is the benefit of using a non-blocking wait instead of a blocking wait in the main method?

```<code>//await Task.Delay(int.MaxValue); //Main Thread System.Threading.Monitor.Wait
Task.Delay(int.MaxValue).Wait(); //Main Thread System.Threading.Monitor.Wait
</code>```

Body:
Judging by the debugger and the "threads" window, both constructs below lead to the same consequences. If we use a non-blocking wait on a worker thread, then it can take up other operations. But what if we use non-blocking wait in the main method, as far as I know the main thread can only execute the main method and cannot switch to other operations outside of this method.

Question: What is the benefit of using a non-blocking wait instead of a blocking wait in the main method?

//await Task.Delay(int.MaxValue); //Main Thread System.Threading.Monitor.Wait
Task.Delay(int.MaxValue).Wait(); //Main Thread System.Threading.Monitor.Wait


问:
How can I apply different colours to a GLTF model component?
I was able to display a model on a web page using three JS and add GUI folders to that model. Now I am trying to change the colour of the model components, but I am not able to do that. I have the JSON data, which i have consoled in a log now you view on my website here www.exthack.com

enter image description here

And this was consoled in log through t variable below is code please refer that

```<code>loader.load(
   'models/b.glb',
   function (gltf) {
       turboshaftModel  = gltf.scene;
           console.log(turboshaftModel);
           scene.add(gltf.scene)
           var t = gltf.scenes[0].children;
           console.log(t)
</code>```

So how can I access this object and change its colour?

Thank You

How can we add a different color to different parts of a object i ma getting all the object parts name . How to select single object and it's color

Body:
I was able to display a model on a web page using three JS and add GUI folders to that model. Now I am trying to change the colour of the model components, but I am not able to do that. I have the JSON data, which i have consoled in a log now you view on my website here www.exthack.com

enter image description here

And this was consoled in log through t variable below is code please refer that

loader.load(
   'models/b.glb',
   function (gltf) {
       turboshaftModel  = gltf.scene;
           console.log(turboshaftModel);
           scene.add(gltf.scene)
           var t = gltf.scenes[0].children;
           console.log(t)

So how can I access this object and change its colour?

Thank You

How can we add a different color to different parts of a object i ma getting all the object parts name . How to select single object and it's color


问:
Instance doesn't update the reservation date from Django form
```<code>from django import forms
from . import models
from reservations.models import Reservation
from datetime import datetime, date, timedelta
from django.core.exceptions import ValidationError

class ReservationForm(forms.ModelForm):

    class Meta:
        model = models.Reservation
        fields = '__all__'

        exclude = {'no_of_days', 'room_price'}

    def clean(self):
        data = self.cleaned_data
        booked_for_date = data['check_in']
        booked_till_date = data['check_out']
        roomNumber = data['roomNumber']
        customer_name = data['customer_name']
        bookingList = Reservation.objects.filter(roomNumber=roomNumber)
        for booking in bookingList:
            if booking.check_in >= booked_till_date or booking.check_out <= booked_for_date:
                pass
            else:
                raise ValidationError("Change Date")
        if booked_till_date < booked_for_date:
            raise forms.ValidationError(
                "End date should be greater than start date.")
            return data

</code>```
```<code>from django.db import models
from django.conf import settings
from rooms.models import Room
from django.urls import reverse
from django.utils import timezone
from django.core.exceptions import ValidationError
from datetime import datetime, date, timedelta

# Create your models here.

class Reservation(models.Model):
    PAY_TYPES = (
        ('P', 'Paying'),
        ('PD', 'Paying Debtor'),
        ('NP', 'Non Paying'),
    )

    discount_types = (
        (None, 'No Discount'),
        ('10', '10%'),
        ('20', '20%'),
        ('30', '30%'),
        ('Oth', 'Other'),
    )

    discount = models.CharField(
        max_length=20, choices=discount_types, null=True, blank=True)
    Pay_Type = models.CharField(
        max_length=20, choices=PAY_TYPES, null=True, blank=True)
    room_price = models.IntegerField(null=True, blank=True)
    check_in = models.DateField(auto_now=False, auto_now_add=False)
    check_out = models.DateField(auto_now=False, auto_now_add=False)
    book_date = models.DateField(default=timezone.now)
    customer_name = models.CharField(max_length=225)
    customer_address = models.CharField(max_length=225)
    customer_number = models.IntegerField(null=True)
    no_of_days = models.IntegerField(null=True, blank=True)

    roomNumber = models.ForeignKey(
        Room, related_name="reservations", on_delete=models.CASCADE)

    def __str__(self):
        return self.customer_name

    def value(self):
        if self.discount == '10':
            price = self.roomNumber.roomtype.price
            self.room_price = (price - (price*0.1))
            return self.room_price
        if self.discount == '20':
            price = self.roomNumber.roomtype.price
            self.room_price = (price - (price*0.2))
            return self.room_price
        if self.discount == '30':
            price = self.roomNumber.roomtype.price
            self.room_price = (price - (price*0.3))
            return self.room_price
        if self.discount == None:
            self.room_price = self.roomNumber.roomtype.price
            return self.room_price

    def save(self, *args, **kwargs):
        self.no_of_days = (self.check_out - self.check_in).days
        self.room_price = self.value()
        # print(self.value())
        # self.clean()
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('reservations:all')

</code>```
```<code>class UpdateReservation(LoginRequiredMixin, generic.UpdateView):
    login_url = '/login/'
    redirect_field_name = 'reservations/reservation_detail.html'

    form_class = ReservationForm

    model = Reservation
</code>```

When I attempt to update a reservation,I always get the validation error "Change Date" from the form.The only way I'm able to update successfully is when I change the date to another available date.But if I want to update just the names or other fields besides the date,I always get the validation error " Change Date".Please help

Body:
from django import forms
from . import models
from reservations.models import Reservation
from datetime import datetime, date, timedelta
from django.core.exceptions import ValidationError

class ReservationForm(forms.ModelForm):

    class Meta:
        model = models.Reservation
        fields = '__all__'

        exclude = {'no_of_days', 'room_price'}

    def clean(self):
        data = self.cleaned_data
        booked_for_date = data['check_in']
        booked_till_date = data['check_out']
        roomNumber = data['roomNumber']
        customer_name = data['customer_name']
        bookingList = Reservation.objects.filter(roomNumber=roomNumber)
        for booking in bookingList:
            if booking.check_in >= booked_till_date or booking.check_out <= booked_for_date:
                pass
            else:
                raise ValidationError("Change Date")
        if booked_till_date < booked_for_date:
            raise forms.ValidationError(
                "End date should be greater than start date.")
            return data

from django.db import models
from django.conf import settings
from rooms.models import Room
from django.urls import reverse
from django.utils import timezone
from django.core.exceptions import ValidationError
from datetime import datetime, date, timedelta

# Create your models here.

class Reservation(models.Model):
    PAY_TYPES = (
        ('P', 'Paying'),
        ('PD', 'Paying Debtor'),
        ('NP', 'Non Paying'),
    )

    discount_types = (
        (None, 'No Discount'),
        ('10', '10%'),
        ('20', '20%'),
        ('30', '30%'),
        ('Oth', 'Other'),
    )

    discount = models.CharField(
        max_length=20, choices=discount_types, null=True, blank=True)
    Pay_Type = models.CharField(
        max_length=20, choices=PAY_TYPES, null=True, blank=True)
    room_price = models.IntegerField(null=True, blank=True)
    check_in = models.DateField(auto_now=False, auto_now_add=False)
    check_out = models.DateField(auto_now=False, auto_now_add=False)
    book_date = models.DateField(default=timezone.now)
    customer_name = models.CharField(max_length=225)
    customer_address = models.CharField(max_length=225)
    customer_number = models.IntegerField(null=True)
    no_of_days = models.IntegerField(null=True, blank=True)

    roomNumber = models.ForeignKey(
        Room, related_name="reservations", on_delete=models.CASCADE)

    def __str__(self):
        return self.customer_name

    def value(self):
        if self.discount == '10':
            price = self.roomNumber.roomtype.price
            self.room_price = (price - (price*0.1))
            return self.room_price
        if self.discount == '20':
            price = self.roomNumber.roomtype.price
            self.room_price = (price - (price*0.2))
            return self.room_price
        if self.discount == '30':
            price = self.roomNumber.roomtype.price
            self.room_price = (price - (price*0.3))
            return self.room_price
        if self.discount == None:
            self.room_price = self.roomNumber.roomtype.price
            return self.room_price

    def save(self, *args, **kwargs):
        self.no_of_days = (self.check_out - self.check_in).days
        self.room_price = self.value()
        # print(self.value())
        # self.clean()
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('reservations:all')

class UpdateReservation(LoginRequiredMixin, generic.UpdateView):
    login_url = '/login/'
    redirect_field_name = 'reservations/reservation_detail.html'

    form_class = ReservationForm

    model = Reservation

When I attempt to update a reservation,I always get the validation error "Change Date" from the form.The only way I'm able to update successfully is when I change the date to another available date.But if I want to update just the names or other fields besides the date,I always get the validation error " Change Date".Please help


问:
How to Find Total number of legends in amcharts?
actually i want to set min height of chart excluding legends, my problem is when i choose small screen then legends are coming in one line and it will take lots of height and chart height is very small. so i am trying to do is that chart minimum height is remaining and if legends are more then it will take space accordingly. i know about legends scrollable give max height and setting scrollbar, but i want legends showing without scrollbar and chart min height is also showing, it is not an issue if graph is going big

actually i want to set min height of chart excluding legends, my problem is when i choose small screen then legends are coming in one line and it will take lots of height and chart height is very small. so i am trying to do is that chart minimum height is remaining and if legends are more then it will take space accordingly. i know about legends scrollable give max height and setting scrollbar, but i want legends showing without scrollbar and chart min height is also showing, it is not an issue if graph is going big


问:
TCP - Recv-Q not receiving bytes properly
Tcp, recv-Q is non-zero value - those connections are in CLOSE_WAIT state

In my application lot of connections are in CLOSE_WAIT state, but i dont know what is the reason for that, but the same program is working properly different machine.

In this case when i execute the netstat command lots of connections are in CLOSE_WAIT state, and recv Q buffer is 1, i don't know what is the reason for this issue

Someone please help me to resolve this.

OS (issue occurs in)
CentOS Linux release 7.9.2009 (Core)


问:
EBP, ESP and EIP physically located on the stack?
I am currently learning buffer overflow attacks, in order to pass the OSCP exam.
My current understanding of the stack is that ESP and EIP are not located on the stack itself. I always thought that the current value of EIP, is just held in the CPU register "EIP".

The course continuously uses terminology such as the EIP is being over written, so the EIP value must be physically there.

I understand why EBP is recorded within the stack.

My current theory is that EIP and ESP are added to the stack when a function calls another function?

Below is diagram from the course.


问:
How can I encode a string in Typescript when implementing Figma plugin
I'm implementing a Figma plugin, and I need to encode a line of text in base 64.
I've found that I can implement that function with

I've tried

```<code>Buffer.from('STRING').toString('base64')
</code>```

but Buffer is not recognized in @figma/plugin-typings

This project is not a Node.js project but a Figma plugin, so I wonder if there's another way to implement this or a package that is available for Typescript.

Body:
I'm implementing a Figma plugin, and I need to encode a line of text in base 64.
I've found that I can implement that function with

I've tried

Buffer.from('STRING').toString('base64')

but Buffer is not recognized in @figma/plugin-typings

This project is not a Node.js project but a Figma plugin, so I wonder if there's another way to implement this or a package that is available for Typescript.


问:
how many variables a for loop can contain?
I finished a code challenge on HackerRank, and subsequently went to check some answers in order to see other's solutions and learn something new.
I bumped into a code base that contains the following code snippet.
thus arises the question, how many variables can a for loop contain, before the comparison check?</p>
```<code>for (let i = 0, j = n - 1; i < n; i++, j-- ) {
    leftToRightArr.push(arr[i][i]);
    rightToLeftArr.push(arr[i][j]);
};
</code>```

Body:
I finished a code challenge on HackerRank, and subsequently went to check some answers in order to see other's solutions and learn something new.
I bumped into a code base that contains the following code snippet.
thus arises the question, how many variables can a for loop contain, before the comparison check?

for (let i = 0, j = n - 1; i < n; i++, j-- ) {
    leftToRightArr.push(arr[i][i]);
    rightToLeftArr.push(arr[i][j]);
};


问:
Why most test frameworks for Node.js require binaries that parse the tests and inject globals? Wouldn't it be enough to require the test functions?
I've been trying Mocha, Jest and similar test frameworks.

These frameworks require you to run their binary (npx mocha or npx jest), they parse your test scripts (in fact Jest requires you to pass --experimental-vm-modules to Node.js, if your test script is an ES Module). and they inject some special functions (describe etc) as globals in the script.

Wouldn't it possible (and much, much simpler) to write tests in regular files supposed to get executed by Node?

Something like this, for instance:

my-project.test.js

```<code>// run this test file with: "node my-project.test.js"
import { describe, it, expect } from 'whatever-test-framework';

describe ( "my project", () => {
  test ( "my test", () => {
    test_something();
  } );
} );
</code>```

Is there any test framework that works like this? What would be its limitations, compared to what Mocha, Jest etc do?

Body:
I've been trying Mocha, Jest and similar test frameworks.

These frameworks require you to run their binary (npx mocha or npx jest), they parse your test scripts (in fact Jest requires you to pass --experimental-vm-modules to Node.js, if your test script is an ES Module). and they inject some special functions (describe etc) as globals in the script.

Wouldn't it possible (and much, much simpler) to write tests in regular files supposed to get executed by Node?

Something like this, for instance:

my-project.test.js

// run this test file with: "node my-project.test.js"
import { describe, it, expect } from 'whatever-test-framework';

describe ( "my project", () => {
  test ( "my test", () => {
    test_something();
  } );
} );

Is there any test framework that works like this? What would be its limitations, compared to what Mocha, Jest etc do?


问:
When set up pyrouge on Google Colab
I encountered a problem when I set up pyrouge on Google Colab.
I run

```<code> !which perl
!perl runROUGE-test.pl
</code>```

And it throw an error:

```<code>Cannot open exception db file for reading: mypath/ROUGE-1.5.5/RELEASE-1.5.5/data/WordNet-2.0.exc.db
</code>```

I have tried this way

```<code>os.chdir("data/WordNet-2.0-Exceptions/")
!sudo rm WordNet-2.0.exc.db # only if exist
!perl ./buildExeptionDB.pl . exc WordNet-2.0.exc.db

os.chdir("../")
!sudo rm WordNet-2.0.exc.db # only if exist
!sudo ln -s WordNet-2.0-Exceptions/WordNet-2.0.exc.db WordNet-2.0.exc.db
</code>```

But it does not work. I want to know how to solve it on Google Colab
And my Installation references is

Title: When set up pyrouge on Google Colab

Body:
I encountered a problem when I set up pyrouge on Google Colab.
I run

 !which perl
!perl runROUGE-test.pl

And it throw an error:

Cannot open exception db file for reading: mypath/ROUGE-1.5.5/RELEASE-1.5.5/data/WordNet-2.0.exc.db

I have tried this way

os.chdir("data/WordNet-2.0-Exceptions/")
!sudo rm WordNet-2.0.exc.db # only if exist
!perl ./buildExeptionDB.pl . exc WordNet-2.0.exc.db

os.chdir("../")
!sudo rm WordNet-2.0.exc.db # only if exist
!sudo ln -s WordNet-2.0-Exceptions/WordNet-2.0.exc.db WordNet-2.0.exc.db

But it does not work. I want to know how to solve it on Google Colab
And my Installation references is


问:
vuejs yup validations accessible
hello good day i have a little question

If I want to access the validation function written in the setup from a method outside the setup, how can I do it with the onSubmit Function?

```<code>  setup() {
const store = useStore();
const router = useRouter();

const loading = ref(false);

const validationSchema = Yup.object().shape({
  email: Yup.string().trim().email().required().label("Email"),
  password: Yup.string().trim().min(6).required().label("Parola"),
});

const { handleSubmit } = useForm({ validationSchema });
return {
  loading,
  validationSchema,
};
</code>```

where i want to reach

```<code>  methods: {
onSubmit() {
  alert();
},
</code>```

},

Title: vuejs yup validations accessible

Body:
hello good day i have a little question

If I want to access the validation function written in the setup from a method outside the setup, how can I do it with the onSubmit Function?

  setup() {
const store = useStore();
const router = useRouter();

const loading = ref(false);

const validationSchema = Yup.object().shape({
  email: Yup.string().trim().email().required().label("Email"),
  password: Yup.string().trim().min(6).required().label("Parola"),
});

const { handleSubmit } = useForm({ validationSchema });
return {
  loading,
  validationSchema,
};

where i want to reach

  methods: {
onSubmit() {
  alert();
},

},


问:
VBA Error: Application-defined or object-defined error
I am trying to add a loop if formula for a single cell range called "Analysis" in sheet1. Depends on how many facilities report user selects, the "Analysis" cell will show the name of the facility not credible if the amount is less than 400k or unit less than 50. Each facility table has exactly 28 rows, and the "Analysis" range is 3 rows above the first table. I want to show all the facilities that are not credible using a loop formula.

The code used:

```<code>termfaccnt = Me.lstTermFacilitiesSelected.ListCount
sheet1.Range("Analysis").FormulaR1C1 = Analysis(Me.lstTermFacilitiesSelected.ListCount)

Public Function Analysis(TermFacCnt As Integer)
    Dim i As Integer
    Dim FormulaStr As String

    FormulaStr = "=if R[30]C < 500000 or R[16]C[-2] < 500 then R[3]C[-2] & ""- Not Credible."" ELSE end"

    For i = 2 To TermFacCnt
        FormulaStr = FormulaStr & "if R[" & 28 * i + 2 & "]C < 400000 or R[" & 28 * i - 12 & "]C[-2] < 50 then R[" & 28 * i - 25 & "]C[-2] & ""- Not Credible."" ELSE end"
    Next i

    Analysis = FormulaStr
End Function

</code>```

If facility 1 and 3 are not credible, I would like to see if formula to yield "Facility 1 - not credible. Facility 3 - not credible." in Analysis range in sheet1. But I got an error of Application-defined or object-defined error pointing at the sheet1.Range("Analysis").FormulaR1C1 = Analysis(Me.lstTermFacilitiesSelected.ListCount).

Body:
I am trying to add a loop if formula for a single cell range called "Analysis" in sheet1. Depends on how many facilities report user selects, the "Analysis" cell will show the name of the facility not credible if the amount is less than 400k or unit less than 50. Each facility table has exactly 28 rows, and the "Analysis" range is 3 rows above the first table. I want to show all the facilities that are not credible using a loop formula.

The code used:

termfaccnt = Me.lstTermFacilitiesSelected.ListCount
sheet1.Range("Analysis").FormulaR1C1 = Analysis(Me.lstTermFacilitiesSelected.ListCount)

Public Function Analysis(TermFacCnt As Integer)
    Dim i As Integer
    Dim FormulaStr As String

    FormulaStr = "=if R[30]C < 500000 or R[16]C[-2] < 500 then R[3]C[-2] & ""- Not Credible."" ELSE end"

    For i = 2 To TermFacCnt
        FormulaStr = FormulaStr & "if R[" & 28 * i + 2 & "]C < 400000 or R[" & 28 * i - 12 & "]C[-2] < 50 then R[" & 28 * i - 25 & "]C[-2] & ""- Not Credible."" ELSE end"
    Next i

    Analysis = FormulaStr
End Function

If facility 1 and 3 are not credible, I would like to see if formula to yield "Facility 1 - not credible. Facility 3 - not credible." in Analysis range in sheet1. But I got an error of Application-defined or object-defined error pointing at the sheet1.Range("Analysis").FormulaR1C1 = Analysis(Me.lstTermFacilitiesSelected.ListCount).


问:
i have been trying to install new man on my mac but i'm not able to generate html reports in my mac i'm getting the below error
npm install -g newman
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.

i have been  trying to install new man on my mac but i'm not able to generate html reports in my mac i'm getting the above error


问:
Path Problem In Vs Code for Almost every thing including Files in CWD or imported library
Whenever I need to use a file in Vscode whether if it is imported or in the CWD Vscode can not find it unless I enter the file path fully, is there anything that help to use files in current working directory. or when I import something like QIcon I have the same problem.

from PyQt6.QtWidgets import QApplication, QWidget
from PyQt6.QtGui import QIcon
import sys

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('PyQT6  Window')
        self.setWindowIcon("qt.png")  # this is not working I need to set a path
```


问:
AWS EC2 Instance: ssh_dispatch_run_fatal
I just created an EC2 AWS server which I'm trying to SSH into through terminal. However whenever I try to connect I get the following error:

```<code>ssh_dispatch_run_fatal: Connection to 18.222.183.247 port 22: Broken pipe
</code>```

This is the command I entered to get the error.

```<code>ssh -i "Key.pem" ec2-user@ec2-18-222-183-247.us-east-2.compute.amazonaws.com

</code>```

To be clear, I DID select port 22 for this instance per the security rules.

Body:
I just created an EC2 AWS server which I'm trying to SSH into through terminal. However whenever I try to connect I get the following error:

ssh_dispatch_run_fatal: Connection to 18.222.183.247 port 22: Broken pipe

This is the command I entered to get the error.

ssh -i "Key.pem" ec2-user@ec2-18-222-183-247.us-east-2.compute.amazonaws.com

To be clear, I DID select port 22 for this instance per the security rules.


问:
Connect 3rd model to 1st model thought two interconnecting model
I have models below

```<code>class HospitalBlockingRemark < ApplicationRecord
  belongs_to :hospital
  belongs_to :worker
end
</code>```

This is to keep hospital blocking a worker in chat conversation

```<code>class HospitalBlockingRemark < ApplicationRecord
  belongs_to :hospital
  belongs_to :worker
end
</code>```

Every time hospital blocks a worker, they are required to give a remark in string. They can unblock and block again with different remark, therefore, a hospital with id 1 block a worker with id 3, can have remarks in multiple rows with id 1 and 2.
For example:

HospitalBlockingRemark

id
hospital_id
worker_id
remark

1
1
3
"remark reason 1"

2
1
3
"remark reason 2"

HospitalWorkerBlocking

id
hospital_id
worker_id

1
1
3

We wish to left join HospitalWorkerBlocking with HospitalBlockingRemark so that we can get an array of HospitalBlockingRemark instance on every HospitalWorkerBlocking instance

For example, hospital_worker_blockings[0].hospital_blocking_remarks will give us the list of remark instances, where hospital_worker_blockings[0] can have hospital_id of 1 and worker_id of 3, [1] can have hospital_id of 2 and worker_id of 4 (The whole table of HospitalWorkerBlocking records). How should we configure our model class or write a rails active record joins that able to support that?

Body:
I have models below

class HospitalBlockingRemark < ApplicationRecord
  belongs_to :hospital
  belongs_to :worker
end

This is to keep hospital blocking a worker in chat conversation

class HospitalBlockingRemark < ApplicationRecord
  belongs_to :hospital
  belongs_to :worker
end

Every time hospital blocks a worker, they are required to give a remark in string. They can unblock and block again with different remark, therefore, a hospital with id 1 block a worker with id 3, can have remarks in multiple rows with id 1 and 2.
For example:

HospitalBlockingRemark

id
hospital_id
worker_id
remark

1
1
3
"remark reason 1"

2
1
3
"remark reason 2"

HospitalWorkerBlocking

id
hospital_id
worker_id

1
1
3

We wish to left join HospitalWorkerBlocking with HospitalBlockingRemark so that we can get an array of HospitalBlockingRemark instance on every HospitalWorkerBlocking instance

For example, hospital_worker_blockings[0].hospital_blocking_remarks will give us the list of remark instances, where hospital_worker_blockings[0] can have hospital_id of 1 and worker_id of 3, [1] can have hospital_id of 2 and worker_id of 4 (The whole table of HospitalWorkerBlocking records). How should we configure our model class or write a rails active record joins that able to support that?


问:
R: Understanding the Difference Between Different Parallel Computing Options
I am working with the R programming language.

Currently, I am trying to learn more about Parallel Computing and how to optimize running functions on large datasets, but I find I keep getting confused with the different options that are available. As an example, here are some of the options I have come across:

DoParallel

foreach

future

doSNOW

makePSOCKcluster

clusterEvalQ

To give some context to my problem - here is the dataset I am working with (the real dataset has over 10 million rows):

```<code>id = sample.int(10000, 100000, replace = TRUE)
res = c(1,0)
results = sample(res, 100000, replace = TRUE)
date_exam_taken = sample(seq(as.Date('1999/01/01'), as.Date('2020/01/01'), by="day"), 100000, replace = TRUE)

my_data = data.frame(id, results, date_exam_taken)
my_data <- my_data[order(my_data$id, my_data$date_exam_taken),]

my_data$general_id = 1:nrow(my_data)
my_data$exam_number = ave(my_data$general_id, my_data$id, FUN = seq_along)
my_data$general_id = NULL

      id results date_exam_taken exam_number
42599  1       1      2000-11-11           1
56091  1       1      2001-01-04           2
26039  1       0      2001-06-24           3
84767  1       1      2001-10-19           4
20920  1       1      2004-10-12           5
20653  1       1      2006-04-04           6
</code>```

And here is the function I am currently running on this data (calculating conditional probabilities):

```<code>my_list = list()

for (i in 1:length(unique(my_data$id)))

{
    {tryCatch({

        start_i = my_data[my_data$id == i,]

        pairs_i =  data.frame(first = head(start_i$results, -1), second = tail(start_i$results, -1))
        frame_i =  as.data.frame(table(pairs_i))
        frame_i$id = i
        print(frame_i)
        my_list[[i]] = frame_i
    }, error = function(e){})
    }}

 final = do.call(rbind.data.frame, my_list)
</code>```

So far, I have learned how to run this same code using two different Parallel Computing based options in R:

Option 1: DoParallel and foreach

```<code># Load required libraries
library(foreach)
library(doParallel)

# Set up a parallel cluster with 4 cores
cl <- makeCluster(4)
registerDoParallel(cl)

# Define a function that takes a single value of "i" and computes the desired output
my_function <- function(i) {
    {tryCatch({
  start_i = my_data[my_data$id == i,]

  pairs_i =  data.frame(first = head(start_i$results, -1), second = tail(start_i$results, -1))
  frame_i =  as.data.frame(table(pairs_i))
  frame_i$id = i

  return(frame_i)
}, error = function(e){})
    }
}

# Use the foreach function to apply "my_function" in parallel to each value of "i"
my_list <- foreach(i = 1:length(unique(my_data$id)), .combine = rbind) %dopar% my_function(i)

# Stop the parallel cluster
stopCluster(cl)
</code>```

Option 2: clusterEvalQ

```<code># Define the cluster of workers
cluster = makeCluster(4)

# Export the my_data object to the cluster
clusterExport(cluster, "my_data")

# Use clusterEvalQ to evaluate the code on the cluster
clusterEvalQ(cluster, {
  my_list = list()

  for (i in 1:length(unique(my_data$id))) {
    {tryCatch({
      start_i = my_data[my_data$id == i,]

      pairs_i =  data.frame(first = head(start_i$results, -1), second = tail(start_i$results, -1))
      frame_i =  as.data.frame(table(pairs_i))
      frame_i$id = i
      print(frame_i)
      my_list[[i]] = frame_i
    }, error = function(e){})
    }}

  final = do.call(rbind.data.frame, my_list)
})
</code>```

Can someone please comment on the code I have written? Are these two methods essentially performing the same task at a similar level of efficiency? In general, are there any other methods I could employ to increase the efficiency of this code?

Thanks!

Body:
I am working with the R programming language.

Currently, I am trying to learn more about Parallel Computing and how to optimize running functions on large datasets, but I find I keep getting confused with the different options that are available. As an example, here are some of the options I have come across:

DoParallel

foreach

future

doSNOW

makePSOCKcluster

clusterEvalQ

To give some context to my problem - here is the dataset I am working with (the real dataset has over 10 million rows):

id = sample.int(10000, 100000, replace = TRUE)
res = c(1,0)
results = sample(res, 100000, replace = TRUE)
date_exam_taken = sample(seq(as.Date('1999/01/01'), as.Date('2020/01/01'), by="day"), 100000, replace = TRUE)

my_data = data.frame(id, results, date_exam_taken)
my_data <- my_data[order(my_data$id, my_data$date_exam_taken),]

my_data$general_id = 1:nrow(my_data)
my_data$exam_number = ave(my_data$general_id, my_data$id, FUN = seq_along)
my_data$general_id = NULL

      id results date_exam_taken exam_number
42599  1       1      2000-11-11           1
56091  1       1      2001-01-04           2
26039  1       0      2001-06-24           3
84767  1       1      2001-10-19           4
20920  1       1      2004-10-12           5
20653  1       1      2006-04-04           6

And here is the function I am currently running on this data (calculating conditional probabilities):

my_list = list()

for (i in 1:length(unique(my_data$id)))

{
    {tryCatch({

        start_i = my_data[my_data$id == i,]

        pairs_i =  data.frame(first = head(start_i$results, -1), second = tail(start_i$results, -1))
        frame_i =  as.data.frame(table(pairs_i))
        frame_i$id = i
        print(frame_i)
        my_list[[i]] = frame_i
    }, error = function(e){})
    }}

 final = do.call(rbind.data.frame, my_list)

So far, I have learned how to run this same code using two different Parallel Computing based options in R:

Option 1: DoParallel and foreach

# Load required libraries
library(foreach)
library(doParallel)

# Set up a parallel cluster with 4 cores
cl <- makeCluster(4)
registerDoParallel(cl)

# Define a function that takes a single value of "i" and computes the desired output
my_function <- function(i) {
    {tryCatch({
  start_i = my_data[my_data$id == i,]

  pairs_i =  data.frame(first = head(start_i$results, -1), second = tail(start_i$results, -1))
  frame_i =  as.data.frame(table(pairs_i))
  frame_i$id = i

  return(frame_i)
}, error = function(e){})
    }
}

# Use the foreach function to apply "my_function" in parallel to each value of "i"
my_list <- foreach(i = 1:length(unique(my_data$id)), .combine = rbind) %dopar% my_function(i)

# Stop the parallel cluster
stopCluster(cl)

Option 2: clusterEvalQ

# Define the cluster of workers
cluster = makeCluster(4)

# Export the my_data object to the cluster
clusterExport(cluster, "my_data")

# Use clusterEvalQ to evaluate the code on the cluster
clusterEvalQ(cluster, {
  my_list = list()

  for (i in 1:length(unique(my_data$id))) {
    {tryCatch({
      start_i = my_data[my_data$id == i,]

      pairs_i =  data.frame(first = head(start_i$results, -1), second = tail(start_i$results, -1))
      frame_i =  as.data.frame(table(pairs_i))
      frame_i$id = i
      print(frame_i)
      my_list[[i]] = frame_i
    }, error = function(e){})
    }}

  final = do.call(rbind.data.frame, my_list)
})

Can someone please comment on the code I have written? Are these two methods essentially performing the same task at a similar level of efficiency? In general, are there any other methods I could employ to increase the efficiency of this code?

Thanks!


问:
Can we share/export the report templates in GA4? Is there any way to do that?
I have created custom reports in GA4 & now I want to export/share the template of that report without data so that other people need not to create the reports again like adding dimensions & metrics. Is there any option to do that?</p>


问:
How to set System Feature programatically on Android
I am implementing an application that transmits private TV broadcasting by referring to AOSP.

By default in AOSP, it says
"Enable the feature PackageManager.FEATURE_LIVE_TV".

I assumed this would be set by editing the manifest

```<code><uses-feature
    android:name="android.software.live_tv"
    android:required="true" />
</code>```

But this doesn't work,

```<code>getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_LIVE_TV)
</code>```

this returns false
(I made sure that getContext is never null!)
First of all, since there is no part to set Feature Flag among Developer Options in my device, I try to solve it programmatically.

Please tell me how to set software feature

Body:
I am implementing an application that transmits private TV broadcasting by referring to AOSP.

By default in AOSP, it says
"Enable the feature PackageManager.FEATURE_LIVE_TV".

I assumed this would be set by editing the manifest

<uses-feature
    android:name="android.software.live_tv"
    android:required="true" />

But this doesn't work,

getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_LIVE_TV)

this returns false
(I made sure that getContext is never null!)
First of all, since there is no part to set Feature Flag among Developer Options in my device, I try to solve it programmatically.

Please tell me how to set software feature


问:
Get UserId variable in Jenkins pipeline
My jenkins pipeline code is as follows:

```<code>def cause = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')

pipeline {
    agent any
    stages {
        stage('Create timing') {
            steps {
                sh '''#!/bin/bash
                if [[ "$TIMING" == 15 ]]
                 then
                    execute a script
                    echo $TIMING
                    echo ${cause.userId}
                fi
         '''
            }
        }

post {
       success {
           slackSend color: "#2EB67D",channel: "#just-test", message: "SSM session generated Successfully: \n Details: \n -User: ${cause.userId} \n -URL: ${env.BUILD_URL} \n -Session_Timeout: ${TIMING} \n -INSTANCE: ${ChooseInstance}"
       }
       failure {
           slackSend color: "#E01E5A",channel: "#just-test", message: "SSM session generation Failed: \n Details: \n -User:${cause.userId} \n -URL: ${env.BUILD_URL} \n -Session_Timeout: ${TIMING} \n -INSTANCE: ${ChooseInstance}"
       }
    }
}
</code>```

The ${cause.userId} variable returns the user ID only in the post section. However in the 'create timing' stage, the echo ${cause.userId} command throws ${cause.userId}: bad substitution error. I have tried putting quotes around ${cause.userId}, still returns the same.
I also tried ${env.BUILD_USER_ID}, this also did not work.
Does anyone know how to get user variables in the jenkins pipeline using shell?

Expecting the UserId to be printed.

Title: Get UserId variable in Jenkins pipeline

Body:
My jenkins pipeline code is as follows:

def cause = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')

pipeline {
    agent any
    stages {
        stage('Create timing') {
            steps {
                sh '''#!/bin/bash
                if [[ "$TIMING" == 15 ]]
                 then
                    execute a script
                    echo $TIMING
                    echo ${cause.userId}
                fi
         '''
            }
        }

post {
       success {
           slackSend color: "#2EB67D",channel: "#just-test", message: "SSM session generated Successfully: \n Details: \n -User: ${cause.userId} \n -URL: ${env.BUILD_URL} \n -Session_Timeout: ${TIMING} \n -INSTANCE: ${ChooseInstance}"
       }
       failure {
           slackSend color: "#E01E5A",channel: "#just-test", message: "SSM session generation Failed: \n Details: \n -User:${cause.userId} \n -URL: ${env.BUILD_URL} \n -Session_Timeout: ${TIMING} \n -INSTANCE: ${ChooseInstance}"
       }
    }
}

The ${cause.userId} variable returns the user ID only in the post section. However in the 'create timing' stage, the echo ${cause.userId} command throws ${cause.userId}: bad substitution error. I have tried putting quotes around ${cause.userId}, still returns the same.
I also tried ${env.BUILD_USER_ID}, this also did not work.
Does anyone know how to get user variables in the jenkins pipeline using shell?

Expecting the UserId to be printed.


问:
same string but it return false while using equals method with two StringBuilder objects
```<code>Scanner s = new Scanner(System.in);
        char[] ch = s.next().toCharArray();
        Arrays.sort(ch);
        StringBuilder sb = new StringBuilder();
        sb.append(ch);
        int n = s.nextInt();
        while (n-- > 0) {
            char[] book = s.next().toCharArray();
            Arrays.sort(book);
            StringBuilder sb2 = new StringBuilder();
            sb2.append(book);
            System.out.println(sb.equals(sb2));

        }
it returns false.
input
act
1
cat
output
false
</code>```

i tried to check two string are same or not without working with array but input will be in array.

Body:
Scanner s = new Scanner(System.in);
        char[] ch = s.next().toCharArray();
        Arrays.sort(ch);
        StringBuilder sb = new StringBuilder();
        sb.append(ch);
        int n = s.nextInt();
        while (n-- > 0) {
            char[] book = s.next().toCharArray();
            Arrays.sort(book);
            StringBuilder sb2 = new StringBuilder();
            sb2.append(book);
            System.out.println(sb.equals(sb2));

        }
it returns false.
input
act
1
cat
output
false

i tried to check two string are same or not without working with array but input will be in array.


问:
Django: While keeping debug=True APIs are running faster
I have observed that our production environment is slow while keeping

debug=False

We need to wait 20s or 15 sec for one API response.

The same API's are performing in milliseconds, only we changed

```<code>debug=True
</code>```

Body:
I have observed that our production environment is slow while keeping

debug=False

We need to wait 20s or 15 sec for one API response.

The same API's are performing in milliseconds, only we changed

debug=True


问:
How to do version control of Nuget package in bamboo pipeline
How to do version control of Nuget package in bamboo pipeline? please help in this.

Not able to find the script or method.


问:
AG-Grid: How to save and reload the filter in AG-Grid?
Using AG-Grid, Users can use filters in the way they like. I need to allow the user to save the filter , so that it becomes the default filter for them.

```<code>const onGridReady = (params) => {

    var filterState = JSON.parse(localStorage.getItem("myfilterState"));

    if (filterState) {
      params.api.setFilterModel(filterState);
    }
};
</code>```
```<code> const DisplayedColumnsChanged = (params) => {
    var filterState = JSON.stringify(params.api.getFilterModel());
    localStorage.setItem("myfilterState", filterState);
  };
</code>```

Using this, I am not able to save and reload the filters.

Body:
Using AG-Grid, Users can use filters in the way they like. I need to allow the user to save the filter , so that it becomes the default filter for them.

const onGridReady = (params) => {

    var filterState = JSON.parse(localStorage.getItem("myfilterState"));

    if (filterState) {
      params.api.setFilterModel(filterState);
    }
};

 const DisplayedColumnsChanged = (params) => {
    var filterState = JSON.stringify(params.api.getFilterModel());
    localStorage.setItem("myfilterState", filterState);
  };

Using this, I am not able to save and reload the filters.


问:
Redis server 'make test' failure when running in Alpine Docker
I am installing a redis server within a docker container using the following steps

```<code>- wget https://download.redis.io/releases/redis-6.2.4.tar.gz
- tar xvf redis-6.2.4.tar.gz
- cd redis-6.2.4
- make
</code>```

When I run make test I get the following failure. Anyone has an idea what this means and how this may impact my installation?

```<code>> !!! WARNING The following tests failed:

*** [err]: BITFIELD overflow detection fuzzing in tests/unit/bitfield.tcl
OW not detected where needed: i64 -9223372036854775808+-9223372036854775808
Cleanup: may take some time... OK
make[1]: *** [Makefile:383: test] Error 1
make[1]: Leaving directory '/var/delphix/redis/redis-6.2.4/src'
make: *** [Makefile:6: test] Error 2
</code>```

Followed instructions on downloading and installing redis on Linux.
Expecting a successful output to make test

Body:
I am installing a redis server within a docker container using the following steps

- wget https://download.redis.io/releases/redis-6.2.4.tar.gz
- tar xvf redis-6.2.4.tar.gz
- cd redis-6.2.4
- make

When I run make test I get the following failure. Anyone has an idea what this means and how this may impact my installation?

> !!! WARNING The following tests failed:

*** [err]: BITFIELD overflow detection fuzzing in tests/unit/bitfield.tcl
OW not detected where needed: i64 -9223372036854775808+-9223372036854775808
Cleanup: may take some time... OK
make[1]: *** [Makefile:383: test] Error 1
make[1]: Leaving directory '/var/delphix/redis/redis-6.2.4/src'
make: *** [Makefile:6: test] Error 2

Followed instructions on downloading and installing redis on Linux.
Expecting a successful output to make test


问:
Stored Procedure with SQL Server and Laravel
so I have a stored procedure with parameter, the parameter is no_skbdn which i can get from the $skbdn

```<code>$skbdn = DB::select('SELECT no_skbdn FROM selectSKBDN');
$nama = DB::select('EXEC selectNameInSO :no_skbdn', $skbdn);
return view('layouts.form_so', ['skbdn' => $skbdn, 'nama' => $nama]);
</code>```

but when i ran this code, all i get is an error

Object of class stdClass could not be converted to string

Body:
so I have a stored procedure with parameter, the parameter is no_skbdn which i can get from the $skbdn

$skbdn = DB::select('SELECT no_skbdn FROM selectSKBDN');
$nama = DB::select('EXEC selectNameInSO :no_skbdn', $skbdn);
return view('layouts.form_so', ['skbdn' => $skbdn, 'nama' => $nama]);

but when i ran this code, all i get is an error

Object of class stdClass could not be converted to string


问:
Secure POST request against manipulation
I'm currently building a little mini game collection web app, with Fat Free Framework in the Backend (which shouldn't matter too much here).

Now in the games, you can also reach highscores - sending the highscores after finish currently looks something like that:

```<code>      $.ajax({
        "url": "/submitHighscore",
        "type": "post",
        "data": {
            "game": "Tetris",
            "score": player.score
        }
    });
</code>```

Then, at the /submitHighscore route, I'm receiving that request and enter the info to the database. Now right now, somebody could just intercept that request and change the game and score to enter the database with a different score and game, which is not too great.

My idea I already had was just storing those two things in the session variable, so just set a session with a name of gamePlaying to the current game (once they start it) and just set the session var for the points right before sending the highscore.. That way, I don't need to pass any parameters at all and it's all stored in the session.

I'm however not sure, if it's the best solution - would also include quite some code rewriting.

Do you have a better idea to prevent the manipulation of the POST request?

Body:
I'm currently building a little mini game collection web app, with Fat Free Framework in the Backend (which shouldn't matter too much here).

Now in the games, you can also reach highscores - sending the highscores after finish currently looks something like that:

      $.ajax({
        "url": "/submitHighscore",
        "type": "post",
        "data": {
            "game": "Tetris",
            "score": player.score
        }
    });

Then, at the /submitHighscore route, I'm receiving that request and enter the info to the database. Now right now, somebody could just intercept that request and change the game and score to enter the database with a different score and game, which is not too great.

My idea I already had was just storing those two things in the session variable, so just set a session with a name of gamePlaying to the current game (once they start it) and just set the session var for the points right before sending the highscore.. That way, I don't need to pass any parameters at all and it's all stored in the session.

I'm however not sure, if it's the best solution - would also include quite some code rewriting.

Do you have a better idea to prevent the manipulation of the POST request?


问:
Locust Parameterization
`

```<code>from locust import HttpUser,User,task,constant

class myfirsttest(HttpUser):
    host = "https://assessments-api-qa.kh3ira.com/api/assessment-attempt"
    weight = 2
    wait_time = constant(1)

    @task
    def get_users(self):
       self.client.post("/63980c3c1a3185d030a14a2f/start")
</code>```

`

How can I Parameterize the "63980c3c1a3185d030a14a2f" in the Post Request? Please share the Answer

Title: Locust Parameterization

Body:
`

from locust import HttpUser,User,task,constant

class myfirsttest(HttpUser):
    host = "https://assessments-api-qa.kh3ira.com/api/assessment-attempt"
    weight = 2
    wait_time = constant(1)

    @task
    def get_users(self):
       self.client.post("/63980c3c1a3185d030a14a2f/start")

`

How can I Parameterize the "63980c3c1a3185d030a14a2f" in the Post Request? Please share the Answer


问:
Gitlab-ci: Unable to read file deb: unsupported tar compression in deb: control.tar.zst
I am new to gitlab-ci and learning it. I am trying to push my deb package on remote server. I am able to do it when I am running individual commands mentioned in gitlab-ci.yml manually in ubunty/debian docker container. The deb package shows up in the remote server.

But when trying to do it on gitlab-ci then it show me the this error:

```<code>Loading packages...
[!] Unable to read file release-1.0.25.deb: unsupported tar compression in release-1.0.25.deb: control.tar.zst
ERROR: some files failed to be added
[!] Some files were skipped due to errors:
  release-1.0.25.deb
ECHO sudo aptly snapshot create release-1.0.25-unstable_2022.12.13-05.56.24 from repo unstable
Snapshot release-1.0.25-unstable_2022.12.13-05.56.24 successfully created.
You can run 'aptly publish snapshot release-1.0.25-unstable_2022.12.13-05.56.24' to publish snapshot as Debian repository.
ECHO sudo aptly publish -passphrase=abc switch xenial release-1.0.25-unstable_2022.12.13-05.56.24
Loading packages...
Generating metadata files and linking package files...
Finalizing metadata files...
Signing file 'Release' with gpg, please enter your passphrase when prompted:
gpg: cannot open tty `/dev/tty': No such device or address
ERROR: unable to publish: unable to detached sign file: exit status 2
Cleaning up project directory and file based variables
00:01
ERROR: Job failed: exit code 1
</code>```

Here is the part of gitlab-ci.yml which pushes the code to remote:

```<code>publish to remote:
  stage: publish-to-remote
  image: debian:latest
  before_script:
    - apt-get update
    - apt-get install sshpass -y
    - apt-get install aptly -y
    - apt-get install sudo -y
  script:
     - sshpass -p abc ssh -oStrictHostKeyChecking=no abc@something.com mkdir -p /home/
     - md5sum build/$DebFileName.deb
     - sshpass -p abc scp -oStrictHostKeyChecking=no build/$DebFileName.deb abc@something.com:/home/
     - chmod +x ./publishToRemote.sh
     - ./publishToRemote.sh
</code>```

I have this thing in my publishToRemote.sh

```<code>echo "making time"
file_name=release-1.0.25
current_time=$(date "+%Y.%m.%d-%H.%M.%S")

sshpass -p abc ssh -t -oStrictHostKeyChecking=no abc@something.com '
echo "doing cd"
cd /home/

echo "ECHO sudo aptly repo add unstable '$file_name'.deb"
sudo aptly repo add unstable '$file_name'.deb

echo "ECHO sudo aptly snapshot create '$file_name'-unstable_'$current_time' from repo unstable"
sudo aptly snapshot create '$file_name'-unstable_'$current_time' from repo unstable

echo "ECHO sudo aptly publish -passphrase=abc switch xenial '$file_name'-unstable_'$current_time'"
sudo aptly admin -passphrase=abc switch xenial '$file_name'-unstable_'$current_time'
</code>```

To resolve this, I downloaded the deb package made by gitlab-ci and tried to untar it manually on mac, it is getting untared properly. But when I am trying to do it on the remote server it shows the same thing. I also check the md5sum of the deb file before the scp and then on the server(manually) after the scp. And they both are same, so there is no issue in the integrity of the deb file.

Any pointers would be very helpful!!

Body:
I am new to gitlab-ci and learning it. I am trying to push my deb package on remote server. I am able to do it when I am running individual commands mentioned in gitlab-ci.yml manually in ubunty/debian docker container. The deb package shows up in the remote server.

But when trying to do it on gitlab-ci then it show me the this error:

Loading packages...
[!] Unable to read file release-1.0.25.deb: unsupported tar compression in release-1.0.25.deb: control.tar.zst
ERROR: some files failed to be added
[!] Some files were skipped due to errors:
  release-1.0.25.deb
ECHO sudo aptly snapshot create release-1.0.25-unstable_2022.12.13-05.56.24 from repo unstable
Snapshot release-1.0.25-unstable_2022.12.13-05.56.24 successfully created.
You can run 'aptly publish snapshot release-1.0.25-unstable_2022.12.13-05.56.24' to publish snapshot as Debian repository.
ECHO sudo aptly publish -passphrase=abc switch xenial release-1.0.25-unstable_2022.12.13-05.56.24
Loading packages...
Generating metadata files and linking package files...
Finalizing metadata files...
Signing file 'Release' with gpg, please enter your passphrase when prompted:
gpg: cannot open tty `/dev/tty': No such device or address
ERROR: unable to publish: unable to detached sign file: exit status 2
Cleaning up project directory and file based variables
00:01
ERROR: Job failed: exit code 1

Here is the part of gitlab-ci.yml which pushes the code to remote:

publish to remote:
  stage: publish-to-remote
  image: debian:latest
  before_script:
    - apt-get update
    - apt-get install sshpass -y
    - apt-get install aptly -y
    - apt-get install sudo -y
  script:
     - sshpass -p abc ssh -oStrictHostKeyChecking=no abc@something.com mkdir -p /home/
     - md5sum build/$DebFileName.deb
     - sshpass -p abc scp -oStrictHostKeyChecking=no build/$DebFileName.deb abc@something.com:/home/
     - chmod +x ./publishToRemote.sh
     - ./publishToRemote.sh

I have this thing in my publishToRemote.sh

echo "making time"
file_name=release-1.0.25
current_time=$(date "+%Y.%m.%d-%H.%M.%S")

sshpass -p abc ssh -t -oStrictHostKeyChecking=no abc@something.com '
echo "doing cd"
cd /home/

echo "ECHO sudo aptly repo add unstable '$file_name'.deb"
sudo aptly repo add unstable '$file_name'.deb

echo "ECHO sudo aptly snapshot create '$file_name'-unstable_'$current_time' from repo unstable"
sudo aptly snapshot create '$file_name'-unstable_'$current_time' from repo unstable

echo "ECHO sudo aptly publish -passphrase=abc switch xenial '$file_name'-unstable_'$current_time'"
sudo aptly admin -passphrase=abc switch xenial '$file_name'-unstable_'$current_time'

To resolve this, I downloaded the deb package made by gitlab-ci and tried to untar it manually on mac, it is getting untared properly. But when I am trying to do it on the remote server it shows the same thing. I also check the md5sum of the deb file before the scp and then on the server(manually) after the scp. And they both are same, so there is no issue in the integrity of the deb file.

Any pointers would be very helpful!!


问:
Jp Graph data point custom values
I need to display custom text on the base of some conditions applied on each marker on the scattered graph.

I am trying Balloon plots

I have been looking for

```<code>SetFormatCallback
</code>```

but it only formats the datapoint values shown on the marker.

Any help would be appreciated

Title: Jp Graph data point custom values

Body:
I need to display custom text on the base of some conditions applied on each marker on the scattered graph.

I am trying Balloon plots

I have been looking for

SetFormatCallback

but it only formats the datapoint values shown on the marker.

Any help would be appreciated