instruction
stringlengths
0
30k
I modify the [config.yaml][1] form the tutorials in the [hydra][2] repository as follows: defaults: - db: mysql - ui: full - schema: school test_key: ${db.user} However, the `test_key` is still `${db.user}` in the output without being replaced by the actual value `omry`. I type the command `python my_app.py` in the [folder][3]. [1]: https://github.com/facebookresearch/hydra/blob/main/examples/tutorials/basic/your_first_hydra_app/6_composition/conf/config.yaml [2]: https://github.com/facebookresearch/hydra/tree/main [3]: https://github.com/facebookresearch/hydra/tree/main/examples/tutorials/basic/your_first_hydra_app/6_composition
Why does the value interpolation not work when using python hydra library?
|python|yaml|fb-hydra|hydra-core|
You can achieve what you want in one statement by grouping on whether the `car` value is `Skoda` or not: ```python m = df["car"] == "Skoda" list_others, list_skoda = df['model'].groupby(m).agg(list).to_list() print(list_skoda, list_others, sep='\n') ``` Output: ``` ['Citigo', 'Fabia', 'Rapid'] ['Fiesta', 'Focus', 'Mondeo', 'Octavia', 'B-Max'] ```
I am try to testing out version check and other things with Rust `std::process::command`. Other command are working fine but when I try to call `npm -v`, I got program not found error. **My Error:** ![My Error](https://i.stack.imgur.com/i3hpi.png) **My Code:** ![My Code](https://i.stack.imgur.com/JvCvH.png) **NPM Test:** ![NPM Test](https://i.stack.imgur.com/OmRRo.png) I want to `npm -v` command runnable with rust
the simplest and fastest algorithm is by XORing with the (1 << 23) and then subtracting (1 << 23) from the result: ``` const int Val = 1 << 23; int transform(int value) { return (value ^ Val) - Val; } ```
You need to [create scope][1] before calling the Scoped service. ``` public static void DoSomething(WebApplication app) { using IServiceScope? scope = app.Services.CreateScope(); IConfigurateServices configService = scope.ServiceProvider.GetRequiredService<IConfigurateServices>(); } ``` [1]: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.serviceproviderserviceextensions.createscope?view=dotnet-plat-ext-6.0
This issue just appeared from nowhere. It was working just fine the day before. When I try to refer to any, literally ANY, data or var of whatever, the same problem appears, even when referring to a pre-declared var that was working fine. Whether it's a new or old used var the same issue persists. I've used both VS Code and VS community with no update or solution. Idk whether the Intellesence is working too. Any thoughts ???[![enter image description here][1]][1] Note that in this example, this float is used below and works, but now when I try to use it again it just refuses to. [1]: https://i.stack.imgur.com/NyMZN.png
Unity - Visual Studio Community IDE1007 : The name '...' does not exist in the current context
|c#|visual-studio|unity-game-engine|game-development|
I am using itext5 to create pdf files with painted non-removable watermarks as follows: public class TestWatermark { public static String resourcesPath = "C:\\Users\\java\\Desktop\\TestWaterMark\\"; public static String FILE_NAME = resourcesPath + "test.pdf"; public static void main(String[] args) throws IOException { System.out.println("########## STARTED ADDING WATERMARK ###########"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { byte[] byteArray = Files.readAllBytes(Paths.get(FILE_NAME)); String watermarkText = "confidential"; String fontPath = resourcesPath + "myCustomFont.ttf"; Font arabicFont = FontFactory.getFont(fontPath, BaseFont.IDENTITY_H, 16); BaseFont baseFont = arabicFont.getBaseFont(); PdfReader reader = new PdfReader(byteArray); PdfStamper stamper = new PdfStamper(reader, baos); int numberOfPages = reader.getNumberOfPages(); float height = baseFont.getAscentPoint(watermarkText, 24) + baseFont.getDescentPoint(watermarkText, 24); for (int i = 1; i <= numberOfPages; i++) { Rectangle pageSize = reader.getPageSizeWithRotation(i); PdfContentByte overContent = stamper.getOverContent(i); PdfPatternPainter bodyPainter = stamper.getOverContent(i).createPattern(pageSize.getWidth(), pageSize.getHeight()); BaseColor baseColor = new BaseColor(10, 10, 10); bodyPainter.setColorStroke(baseColor); bodyPainter.setColorFill(baseColor); bodyPainter.setLineWidth(0.85f); bodyPainter.setLineDash(0.2f, 0.2f, 0.2f); PdfGState state = new PdfGState(); state.setFillOpacity(0.01f); overContent.saveState(); overContent.setGState(state); for (float x = 70f; x < pageSize.getWidth(); x += height + 100) { for (float y = 90; y < pageSize.getHeight(); y += height + 100) { bodyPainter.beginText(); bodyPainter.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_FILL); bodyPainter.setFontAndSize(baseFont, 13); bodyPainter.showTextAlignedKerned(Element.ALIGN_MIDDLE, watermarkText, x, y, 45f); bodyPainter.endText(); overContent.setColorFill(new PatternColor(bodyPainter)); overContent.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight()); overContent.fill(); } } overContent.restoreState(); } stamper.close(); reader.close(); byteArray = baos.toByteArray(); File outputFile = new File(resourcesPath + "output.pdf"); if (outputFile.exists()) { outputFile.delete(); } Files.write(outputFile.toPath(), byteArray); System.out.println("########## FINISHED ADDING WATERMARK ###########"); } catch (Exception e) { e.printStackTrace(); } } } the above code makes the watermark non-selectable and non-removable in the Adobe Pro editing function but the issue is when opening this pdf file from VMware Workspace ONE Boxer email, the watermark is not displayed! Any advice how to fix this issue ?
I am building Docker images of a web app locally on my Mac and then running them via Docker Compose on a remote server that's running Ubuntu AMD64. I get an error that the platform isn't compatible, and I'm curious what's the best practice in real production environments to tackle this issue. Do I support 2 image types? Do I specify something in the Dockerfile that allows the image to run on all platforms? Appreciate any answer, especially ones that are following industry best practices. Thanks. I was trying to run an image that was built locally on my Mac (ARM64) on a remote Ubuntu server which is AMD64. I was able to bypass this by re-building the image on the remote server, but not sure if this is a best practice.
Best practice to deal with Docker images ARM/AMD compatibility issues
|docker|docker-compose|
null
{"Voters":[{"Id":205233,"DisplayName":"Filburt"},{"Id":354577,"DisplayName":"Chris"},{"Id":12632699,"DisplayName":"SwissCodeMen"}],"SiteSpecificCloseReasonIds":[18]}
{"Voters":[{"Id":20513099,"DisplayName":"I_O "}],"DeleteType":1}
I am trying to open up a blob storage stored document on browser , bue grtting below error [enter image description here](https://i.stack.imgur.com/fMkgf.png) The blob storage code that i use is below: import DocViewer, { DocViewerRenderers } from '@cyntler/react-doc-viewer'; const byte = base64ToArrayBuffer(arr); const type = getMIMEType('docx'); const blob = new Blob([byte], { type }); const aElement = document.createElement('a'); aElement.setAttribute('download', 'Shreya'); const href = URL.createObjectURL(blob); This creats a blob storage link const docs = [ { uri: href, fileType: type } ]; <DocViewer documents={docs} pluginRenderers={DocViewerRenderers} /> I tried using this url with iframes but getting the same error
React document not viewing using ReactDocViewer using blob storage link
|javascript|reactjs|frontend|web-development-server|react-doc-viewer|
`read` by default trims leading and trailing whitespace and consumes backslashes. You can disable those by setting `IFS` to empty string and invoking `read` with the `-r` flag respectively. ``` $ echo ' \" ' | { read i; echo ${#i}; } 1 $ echo ' \" ' | { IFS= read -r i; echo ${#i}; } 4 ``` Note that `wc -c` would print `5` but that's not an error, `wc` counts the terminating newline too while `read` trims it regardless of the value of `IFS`.
This issue seems to be a common issue with Django and how it handles multi-threaded operations and their timings. Specifically in this instance the issue is arising when a new thread is started for the CERTIFICATE_ISSUED event, before the SUCCESS event has fully updated the database. There are some solutions that Django offers, and the one I found best is to use post_save and receiver to automatically issue certificates in the instance that the event being processed is the SUCCESS event. The imports needed would be: from django.db.models.signals import post_save from django.dispatch import receiver The method to implement would look something like: @receiver(post_save, sender=RegistrationEvent) def issue_certificate_if_success(sender, instance, created, **kwargs): if created and instance.event_type == RegistrationEvent.EventType.SUCCESS: instance.course_registration.threaded_issue_certificate() There are other ways to do it if you don't want to adopt this approach. I've seen solutions using the transaction module as well.
null
null
null
null
null
The first constructor of a `Chroma` object is `collection_name`. You should pass the `persist_directory` variable to the `persist_directory` constructor argument. So It will look like this: ``` docsearch = Chroma(persist_directory=persist_directory, embedding_function=embeddings) ```
The command sometimes succesfully launches the batch file however, sometimes it doesn't work and it immediately closes. When I launch the batch file directly from either cmd or by double clicking the file, it always works flawlessly. I was wondering what I could do to fix this issue. #a couple of the commands I have tried start-process -wait -filepath "C:\Windows\System32\cmd.exe" -argumentlist "/c 'C:\path\stream3.bat' .\refresh.bat" start-process -wait -filepath "C:\Windows\System32\cmd.exe" -argumentlist "/c 'C:\path\stream3.bat'" #The contents of the batch file ffmpeg -loglevel error -i "rtmp://mystream" -vf "scale=426:240,boxblur=luma_radius=1:chroma_radius=1" -vcodec libx264 -an -r 25 -b:v 550000 -crf 31 -sc_threshold 0 -f hls -hls_time 5 -segment_time 5 -hls_list_size 5 "C:\nginx\srv\hls\stream3\output.m3u8"
I'm currently trying to learn how to make Minecraft mods in Intellij and I'm fresh off a set of tutorials on youtube but when I try to run Minecraft with the content I've added there just isn't anything there. The only evidence my mod has even loaded is the name of it in the Mods section. It is as if I just ran regular Minecraft. I can't help but notice that my Java classes are orange when my Java classes in the tutorial files are white. I copied over the Java classes from the tutorial mod I needed to my first mod. [enter image description here](https://i.stack.imgur.com/ureAs.png) I've looked through the internet but can't find anything that works. Any help would be greatly appreciated.
You need to add to `package.json`: ```json "nx": {}, ``` Then, change ```json "prettier": { "inputs": ["**/*.{ts,js,cjs,json,yaml}"], "outputs": [] } ``` to ```json "prettier": { "inputs": ["{workspaceRoot}/**/*.{ts,js,cjs,json,yaml}"], "outputs": [] }, ```
I'm trying to install tink library to use it on my python scripts on my Windows system. Python version I'm using: 3.12.10 I have encountered some errors before but I have been solving them: - I needed protoc; I installed it and added it to PATH - I needed bazel; I installed it and added it to PATH - I needed bash; I installed Cywing and added basth to PATH After that, I keep getting the following error that I don't quite understand when I use "pip install tink": ``` INFO: Repository local_config_python instantiated at: C:/temp/pip-install-tolrs06x/tink_587703b11fa04dc4b3364796d840ea99/WORKSPACE:11:18: in <toplevel> C:/temp/pip-install-tolrs06x/tink_587703b11fa04dc4b3364796d840ea99/tink_py_deps_init.bzl:24:21: in tink_py_deps_init Repository rule python_configure defined at: C:/users/0014401/_bazel_0014401/dd6c7pmm/external/pybind11_bazel/python_configure.bzl:414:35: in <toplevel> ERROR: An error occurred during the fetch of repository 'local_config_python': Traceback (most recent call last): File "C:/users/0014401/_bazel_0014401/dd6c7pmm/external/pybind11_bazel/python_configure.bzl", line 411, column 36, in _python_autoconf_impl _create_local_python_repository(repository_ctx) File "C:/users/0014401/_bazel_0014401/dd6c7pmm/external/pybind11_bazel/python_configure.bzl", line 360, column 22, in _create_local_python_repository _check_python_lib(repository_ctx, python_lib) File "C:/users/0014401/_bazel_0014401/dd6c7pmm/external/pybind11_bazel/python_configure.bzl", line 243, column 14, in _check_python_lib _fail("Invalid python library path: %s" % python_lib) File "C:/users/0014401/_bazel_0014401/dd6c7pmm/external/pybind11_bazel/python_configure.bzl", line 29, column 9, in _fail fail("%sPython Configuration Error:%s %s\n" % (red, no_color, msg)) Error in fail: Python Configuration Error: Invalid python library path: C:\Users\0014401\AppData\Local\Programs\Python\Python312 ERROR: C:/temp/pip-install-tolrs06x/tink_587703b11fa04dc4b3364796d840ea99/WORKSPACE:11:18: fetching python_configure rule //external:local_config_python: Traceback (most recent call last): File "C:/users/0014401/_bazel_0014401/dd6c7pmm/external/pybind11_bazel/python_configure.bzl", line 411, column 36, in _python_autoconf_impl _create_local_python_repository(repository_ctx) File "C:/users/0014401/_bazel_0014401/dd6c7pmm/external/pybind11_bazel/python_configure.bzl", line 360, column 22, in _create_local_python_repository _check_python_lib(repository_ctx, python_lib) File "C:/users/0014401/_bazel_0014401/dd6c7pmm/external/pybind11_bazel/python_configure.bzl", line 243, column 14, in _check_python_lib _fail("Invalid python library path: %s" % python_lib) File "C:/users/0014401/_bazel_0014401/dd6c7pmm/external/pybind11_bazel/python_configure.bzl", line 29, column 9, in _fail fail("%sPython Configuration Error:%s %s\n" % (red, no_color, msg)) Error in fail: Python Configuration Error: Invalid python library path: C:\Users\0014401\AppData\Local\Programs\Python\Python312 ERROR: no such package '@@local_config_python//': Python Configuration Error: Invalid python library path: C:\Users\0014401\AppData\Local\Programs\Python\Python312 ERROR: C:/temp/pip-install-tolrs06x/tink_587703b11fa04dc4b3364796d840ea99/tink/cc/pybind/BUILD.bazel:264:17: //tink/cc/pybind:tink_bindings.so depends on @@local_config_python//:python_headers in repository @@local_config_python which failed to fetch. no such package '@@local_config_python//': Python Configuration Error: Invalid python library path: C:\Users\0014401\AppData\Local\Programs\Python\Python312 ERROR: Analysis of target '//tink/cc/pybind:tink_bindings' failed; build aborted: Analysis failed Analyzing: target //tink/cc/pybind:tink_bindings (91 packages loaded, 907 targets configured) [1 / 1] checking cached actions INFO: Elapsed time: 88.382s, Critical Path: 0.13s INFO: 1 process: 1 internal. ERROR: Build did NOT complete successfully FAILED: error: command 'C:\\Users\\0014401\\Downloads\\Bazel\\bazel.exe' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for tink Failed to build tink ERROR: Could not build wheels for tink, which is required to install pyproject.toml-based projects WARNING: Failed to remove contents in a temporary directory 'C:\Temp\pip-install-tolrs06x\tink_587703b11fa04dc4b3364796d840ea99'. You can safely remove it manually. WARNING: Failed to remove contents in a temporary directory 'C:\Temp\pip-install-tolrs06x'. You can safely remove it manually. ``` I believe it has something to do with python path, but I'm not sure. I have checked and my python is correctly set on PATH. I also set variables "BAZEL_PYTHON" and "PYTHON_BIN_PATH". I don't know whath else to try. I hope you can help. Thanks and regards.
Install tink library for Python on Windows
|python|bazel|tink|
null
I am trying to save a URL to a file then retrieving it: This is working: ```# Get version information #$content = Invoke-RestMethod -Uri "https://docs.microsoft.com/en-us/officeupdates/update-history-office365-proplus-by-date" -Method Get $content = Invoke-RestMethod -Uri "https://learn.microsoft.com/en-us/officeupdates/update-history-microsoft365-apps-by-date#version-history" -Method Get # Cast current version to a version $build = [Version]"16.0.16731.20600" # Get the version using regex $content -match "<a href=`"(?<Channel>.+?)`".+?>Version (?<Version>\d{4}) \(Build $($build.Build)\.$($build.Revision)\)" # Output the data $output = [PSCustomObject]@{ Build = $build Version = $Matches['Version'] Channel = ($Matches['Channel'] -split "#")[0] } Write-Output $output ``` The end result is: Build Version Channel ----- ------- ------- 16.0.16731.20600 2308 semi-annual-enterprise-channel Then saving the URL to a file. In my brower the file is looking good. ``` $content | out-file \\server\version.html Testing the file in my browser and it is looking good. # Get version information $content=get-content \\server\version.html # Cast current version to a version $build = [Version]"16.0.16731.20600" # Get the version using regex $content -match "<a href=`"(?<Channel>.+?)`".+?>Version (?<Version>\d{4}) \(Build $($build.Build)\.$($build.Revision)\)" # Output the data $output = [PSCustomObject]@{ Build = $build Version = $Matches['Version'] Channel = ($Matches['Channel'] -split "#")[0] } Write-Output $output ``` The the end result is Write-Output $output <td style="text-align: left;"><a href="semi-annual-enterprise-channel#version-2308-march-12" data-linktype="relative-path">Version 2308 (Build 16731.20600)</a><br/><a href="semi-annual-enterprise-channel#version-2302--march-12" data-linktype="rel ative-path">Version 2302 (Build 16130.20928)</a></td> Indexation impossible dans un tableau Null. Au caractère Ligne:12 : 1 + $output = [PSCustomObject]@{ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation : (:) [], RuntimeException + FullyQualifiedErrorId : NullArray Any idea what is the difference between querying the web page and the file? Thanks,
Save URL to file and interrogate it then end result is different between querying the URL or the file
|powershell|
I have a MariaDB database with a few roles. For simplicity let's assume I have a `admins` role. It was created by the `root` user with the commands below: ``` CREATE ROLE admins; GRANT ALL PRIVILEGES ON *.* TO admins WITH GRANT OPTION; ``` I also have another role `default` which does not have any privileges. I granted the `admins` role to a user `myuser` (again with `root`): ``` CREATE USER myuser IDENTIFIED BY 'mysuperstrongpassword'; GRANT admins TO myuser; ``` With that in mind I logged into a session using the `myuser` account, activated the `admins` role and created a new user `newuser`. However when I try to grant the `default` role to `newuser` with ``` GRANT default TO newuser; ``` I get hit with a `Access denied to user 'myuser'@'%'`. As of my understanding of the `GRANT OPTION` privilege, the grantee should have the permission to grant any privileges. Is there a different privilege required to allow setting roles? I have found some information regarding the `ADMIN OPTION` privilege, however have not been able to grant it to a user or role with ``` GRANT ALL PRIVILEGES ON *.* TO [role|user] WITH ADMIN OPTION; ``` I haven't been able to verify if the `ADMIN OPTION` even exists for my version. Current MariaDB version is 10.11.7
null
I'm iterating on a `json.loads` object that have all the info i need (original_title) When i iterate on it i got incomplete result. Where is my mistake ? How can I improve this code to have complete result? My code: ``` TMDB_TOKEN = "PUT YOURS HERE IF YOU WANNA TEST" headers = { "accept": "application/json", "Authorization": TMDB_TOKEN } id = 17520 url = "https://api.themoviedb.org/3/person/{person_id}/movie_credits".format(person_id=id) response = requests.get(url, headers=headers,) parsed = json.loads(response.text) print(json.dumps(parsed, indent=1)) all_filmo = { "doc":[] , 'cinema': [] , "tv" : [] } for i in parsed['cast']: print(i['original_title']) ``` you can see that there is A LOT of missing. the `json.dumps`. i kept only the original title ``` "original_title": "Cin\u00e9ma par... C\u00e9dric Klapisch", "original_title": "Quand Jean devint Renoir", "original_title": "Toujours pas ... A bout de souffle", "original_title": "Babyphone", "original_title": "Un air de famille", "original_title": "In Transit", "original_title": "Belmondo l'influenceur", "original_title": "Les Poup\u00e9es russes", "original_title": "Peut-\u00eatre", "original_title": "Casse-T\u00eate Chinois", "original_title": "Ballerina", "original_title": "Belmondo, il \u00e9tait une fois le beau monde", "original_title": "L'Auberge espagnole", "original_title": "Ce qui nous lie", "original_title": "Le P\u00e9ril jeune", "original_title": "Le ramoneur des lilas", "original_title": "Babysitter", "original_title": "L'Auberge espagnole", "original_title": "Les Poup\u00e9es russes", "original_title": "Paris", "original_title": "Peut-\u00eatre", "original_title": "Ni pour, ni contre (bien au contraire)", "original_title": "Chacun cherche son chat", "original_title": "Le P\u00e9ril jeune", "original_title": "Un air de famille", "original_title": "Lumi\u00e8re et Compagnie", "original_title": "Riens du tout", "original_title": "Ma part du g\u00e2teau", "original_title": "Casse-T\u00eate Chinois", "original_title": "Ce qui me meut", "original_title": "In Transit", "original_title": "Ce qui nous lie", "original_title": "Le ramoneur des lilas", "original_title": "Deux moi", "original_title": "Aur\u00e9lie Dupont, l'espace d'un instant", "original_title": "En corps", "original_title": "Le Poisson rouge", "original_title": "La F\u00eate du Cin\u00e9ma", "original_title": "La Venue de l\u2019Avenir", "original_title": "Casse-T\u00eate Chinois", "original_title": "Paris", "original_title": "Ce qui nous lie", "original_title": "Les Confins du monde", "original_title": "Princesses", "original_title": "Deux moi", "original_title": "L'Auberge espagnole", "original_title": "Les Poup\u00e9es russes", "original_title": "Paris", "original_title": "Chacun cherche son chat", "original_title": "Peut-\u00eatre", "original_title": "Le P\u00e9ril jeune", "original_title": "Casse-T\u00eate Chinois", "original_title": "Ce qui me meut", "original_title": "Ni pour, ni contre (bien au contraire)", "original_title": "Ma part du g\u00e2teau", "original_title": "Un air de famille", ``` And my iteration result: ``` Cinéma par... Cédric Klapisch Quand Jean devint Renoir Toujours pas ... A bout de souffle Babyphone Un air de famille In Transit Belmondo l'influenceur Les Poupées russes Peut-être Casse-Tête Chinois Ballerina Belmondo, il était une fois le beau monde L'Auberge espagnole Ce qui nous lie Le Péril jeune Le ramoneur des lilas ```
Why doesn't iterating on this api output give me different data than the one in the json.dumps(json.loads)?
My ModalBottomSheet works perfectly the first time I open it, but after hiding it, it becomes unresponsive and blocks all other UI interactions. ``` Button( onClick = { showBottomSheet = true } ) { Text(text = "Done") } if (showBottomSheet) StyleBottomSheet() ``` ``` @OptIn(ExperimentalMaterial3Api::class) @Composable fun StyleBottomSheet() { val scope = rememberCoroutineScope() val sheetState = rememberModalBottomSheetState() var showBottomSheet by remember { mutableStateOf(false) } ModalBottomSheet( onDismissRequest = { showBottomSheet = false }, sheetState = sheetState ) { // Sheet content Button(onClick = { scope.launch { sheetState.hide() }.invokeOnCompletion { if (!sheetState.isVisible) { showBottomSheet = false } } }) { Text("Hide bottom sheet") } } } ```
|android|android-jetpack-compose|android-jetpack-compose-material3|
I am aiming to estimate the breakpoint of a linear model of how animals are performing (proportion of trials correct, $propcorrect) on a causal reasoning test as they age ($agedays). The goal is to find when does the learning stop increasing and start to plateu? However, it seems not to be registering when I try to set the initial PSI estimate to run the segmented model. I used the following code to run the lm: ```r causal.lm <- lm(propcorrect ~ agedays, data = causal_red_data) summary(causal.lm) ``` I then used the following code to run the breakpoint analysis: ```r causal.seg <- segmented.lm(causal.lm, seg.Z = ~agedays, psi=97)) summary(causal.seg) ``` The breakpoint looks to me as if it is around 97 days, so I set psi=97. However, it is finding a breakfpoint much earlier instead (probably due to lots of uncertainty around the early days so the line dips a big before it starts steadily increasing), and the output looks like this: ``` #> causal.seg$psi #> Initial Est. St.Err #> psi1.agedays NA 62 1.103706 ``` Why does it say Initial PSI is NA, when I had set it to 97? In the example codes I looked at to learn how to do this, it always showed whatever the user had set psi equal to under "Initial". No matter what I set it to (closer to 62, farther), the Initial comes back as NA. Does this mean it is not reading/taking into to account the PSI estimate I am trying to set? Something wrong with my code?
null
If anyone came here looking for how to add multiple environment variables dynamically by using a variable here's a solution I found running `az containerapp` command in bash: ```bash #!/bin/bash # I usually run some commands to parse a json into a key=value space separated string env_vars='"key1=val1" "key2=val2" "key3=val3"' create_revision_cmd="az containerapp update \ -n $CONTAINERAPP \ -g $RESOURCE_GROUP \ --image "$IMAGE" \ --replace-env-vars $env_vars" # or --set-env-vars cmd_output=$(eval $create_revision_cmd) ```
Minecraft Mod not adding content
|intellij-idea|minecraft|
null
u need to add -I"C:\Program Files\mosquitto\devel" parameters to your compile command.
You can replace your current condition with ``` if (input$p_values & table_2 |> filter(new_est == max(new_est)) |> ungroup() |> select(Sig) |> (\(.) all(!is.na(.)))() ) ``` It additionally checks that for the relevant variable (your table is already filtered at this point), `Sig` is not `NA` at the maximum of `new_est`. Also notice that this relies on the fact that your table is already grouped, which I assumed since this is the case in your given example. If it is not, you can delete the `ungroup()`.
As others pointed out make sure where to store your files. After that You should add `download` attribute to your anchor tag. [link](https://www.w3schools.com/TAGS/att_a_download.asp) > The download attribute specifies that the target (the file specified in the href attribute) will be downloaded when a user clicks on the hyperlink. > >The optional value of the download attribute will be the new name of the file after it is downloaded. ### static files: ```html <a href="{% static 'files/{{ filename }}' %}" download="{{ filename }}">Download: {{ filename }} </a> ``` ### media files: ```html <a href="{{ dynamic_filename_url }}" download="{{ filename }}">Download: {{ filename }} </a> ```
|c++|c|linux|system-calls|seccomp|
Being new to the IT field, I want to create an entertainment and moderation bot but I encounter several problems: >Process exited with code 1 Uncaught ReferenceError ReferenceError: client is not defined Here are my lines of code: const { Client } = require("discord.js"); const bot = new Client({ intents: ["Guilds"] }); console.log("Connexion au bot..."); bot.login("MY TOKEN") .then(() => console.log("Connecté au bot !")) .catch((error) => console.log("Impossible de se connecter au bot - " + error)); bot.on("ready", async () => { await bot.application.commands.set([ { name: "ping", description: "Pong!" } ]); console.log("Le bot est prêt !"); }); bot.on("interactionCreate", (interaction) => { if (!interaction.isCommand()) return; if (interaction.commandName === "ping") interaction.reply("Pong!"); if (interaction.commandName === "maj") interaction.reply("Pour connaître les derniers mises à jours du bot, merci de vous référencer à Xinfeng"); }); client.on("messageCreate", message => { if(message.author.bot) return; //+help if (message.content === prefix + "help"){ const embed = new Discord.EmbedBuilder() .setColor("#ffcc00") .setTitle("**__Les commandes du bot__**") .setURL("https://discord.js.org/") .setDescription("Vous trouverez toutes les commandes dont vous pouvez faire usage") .addFields( { name: '**__+commandes:__**', value: 'Affiche la liste des commandes' }, { name: '**__+description:__**', value: 'Affiche la description du bot' }, { name: '**__+info:__**', value: 'Affiche les informations du bot' }, { name: '**__Support Developpement:__**', value: 'https://discord.gg/H9mSXeAm8C' } ); message.channel.send({ embeds: [embed]}); } //+description if (message.content === prefix + "description"){ const embed = new Discord.EmbedBuilder() .setColor("#ffcc00") .setTitle("**__Description du bot__**") .setURL("https://discord.js.org/") .setDescription("Je suis Athéna, une déesse grec de l'artisanat et de la stratégie guerrière. Je m'occupe de la modération, jeux et de trackage d’information "); message.channel.send({ embeds: [embed]}); } console.log(message); if(message.content === "Salut"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "salut"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Coucou"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "coucou"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Hey"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Heyyy"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Hello"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Hello tlm"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "hello"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "hello tlm"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Hoyaa"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Hey tlm"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "slt tlm"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Slt tlm"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "hey"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Bonjour"){ message.reply("Bonjour jeune aventurier"); } else if(message.content === "help"){ message.channel.send("**__les commandes du bot ATHENA sont__**\n - +help: Il permettra de configurer et de mieux comprendre les commandes") } else if(message.content === "description"){ message.channel.send("**__Pour connaître la description du bot ATHENA sont__**\n - +description: Il permettra de connaître l'histoire et la naîssance du bot") } else if(message.content === "mention"){ message.reply("Mention d'un utilisateur : <@" + message.author.id + "> \n Mention d'un salon : <#" + message.channel.id + ">"); } }); I would like to know if we can resolve this problem and also if I did the lines of code correctly, thank you.
1. `char c[2]` is needed hold a string with one character with the terminating `'\0'`. 1. Always use a maximum field width when reading a string with `scanf()` to avoid buffer overflow. 1. The format string `%s` requires a matching `char *` which you write as just `c`. 1. On success `scanf()` return the number of items successfully matched. If you don't check for that you may be operating on uninitialized variables. 1. (Not fixed) If you only enter two numbers, `scanf()` will be waiting for the operator. If you don't want this behavior use `fgets()` or `getline()` then use `sscanf()` or lower level functions like `strtol()` to parse the line of input. ``` #include <stdio.h> int main(void) { int a; int b; char c[2]; if(scanf("%i%i%1s", &a, &b, c) != 3) { printf("scanf failed\n"); return 1; }; printf("%i %i %s", a, b, c); } ``` Example run: ``` $ ./a.out 1 x scanf failed $ ./a.out 1 2 + 1 2 + ```
I'm currently trying to learn how to make Minecraft mods in Intellij and I'm fresh off a set of tutorials on youtube but when I try to run Minecraft with the content I've added there just isn't anything there. The only evidence my mod has even loaded is the name of it in the Mods section. It is as if I just ran regular Minecraft. I can't help but notice that my Java classes are orange when my Java classes in the tutorial files are white. I copied over the Java classes from the tutorial mod I needed to my first mod. [Directories](https://i.stack.imgur.com/ureAs.png) I've looked through the internet but can't find anything that works. Any help would be greatly appreciated.
``` import { View, Text } from 'react-native' import React, { useEffect, useState } from 'react' import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import LogInviaPhone from '../Screens/LogInviaPhone'; import LogInviaEmail from '../Screens/LogInviaEmail'; import OTPScreen from '../Screens/OTPScreen'; import OTPScreenEmail from '../Screens/OTPScreenEmail'; import HomeScreen from '../Screens/HomeScreen'; import * as RNLocalize from 'react-native-localize'; import ISO3166 from 'iso-3166-1-alpha-2'; const Stack=createNativeStackNavigator(); export default function Navigation() { const [country,setCountry]=useState(null); useEffect(()=>{ const fetchCountry=async()=>{ try{ const locales = RNLocalize.getLocales(); const countryCode = locales[0]?.countryCode; const countryName = ISO3166.getCountry(countryCode); setCountry(countryName); }catch(error){ console.log('Error fetching country:', error); } } fetchCountry(); },[]); useEffect(() => { console.log("Country ",country); // Log the country name whenever it changes }, [country]); return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name='Phone Login' component={LogInviaPhone} options={{ headerShown:false }}/> <Stack.Screen name='Email Login' component={LogInviaEmail} options={{ headerShown:false }}/> <Stack.Screen name='OTP Phone' component={OTPScreen} options={{ headerShown:false }}/> <Stack.Screen name='OTP Email' component={OTPScreenEmail} options={{ headerShown:false }}/> <Stack.Screen name='Home' component={HomeScreen} options={{ headerShown:false }}/> </Stack.Navigator> </NavigationContainer> ) } ``` I am getting united states in result but I am in india so it is not giving appropriate result what should I do. Is there any other package for this purpose. I am making a react native app where when user open the app first he has to login and if he is from india then app will open login with phone number and if he is from outside of india then app will open login with email.
I want to get device country name so I am using react-native localize package but it is giving united states but I am in india
|react-native|react-native-localize|
null
**server.go** package main import ( "context" mathservices "service/mathservices" "github.com/smallnest/rpcx/server" ) func main() { s := server.NewServer() s.RegisterName("MathService", new(MathService.Mul), "") s.Serve("tcp", ":8972") } **math_service.go** package mathservices import ( "context" "fmt" ) type Args struct { A int B int } type Reply struct { C int } type MathService int func (t *MathService) Mul(ctx context.Context, args *Args, reply *Reply) error { reply.C = args.A * args.B return nil } given this go microservice made with rpcx framework i want it to communicate with nest js microservice, here is the code of the nest js microservice: **nestmicroservice/src/appmodule.ts** import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { ClientsModule, Transport } from '@nestjs/microservices'; @Module({ imports: [ ClientsModule.register([ { name: 'MathService', transport: Transport.TCP, options: { host: 'localhost', port: 8972, }, }, ]), ], controllers: [AppController], providers: [AppService], }) export class AppModule {} **nestmicroservice/src/appcontroller.ts** import { Controller, Inject } from '@nestjs/common'; import { ClientProxy, EventPattern, MessagePattern, } from '@nestjs/microservices'; import { Observable } from 'rxjs'; @Controller() export class AppController { constructor( @Inject('MathService') private client: ClientProxy, ) {} multiply(): Observable<any> { { console.log('first line run'); const pattern = { cmd: 'Mul' }; return this.client.send<any>(pattern, {a:10, b:5}); } } } first line run gets printed in the console but the code **return this.client.send<any>(pattern, {a:10, b:5});** produces error please guys help me!
Can't grant roles with GRANT OPTION privilege
|mariadb|
null
I'm trying to read numerous csv files and search for the word 'error'. Using csv.reader is causing an issue as I believe it is looking for a string. I'm not sure if changing to text would help? import glob import os # Imported os import csv import pathlib def find_cell(csv_file, check): with open(csv_file,'r') as file: reader = csv.reader(file) for row_idx, row in enumerate(reader): for col_idx, cell in enumerate(row): if cell == check: return row_idx, col_idx return None def errorCheck(Filename): is_match = False with open(Filename) as f: csv_file = csv.reader(f, delimiter='|') check = 'Error' cell_location = find_cell(csv_file, check) if cell_location: row_idx, col_idx = cell_location print("ERROR") print_and_log('ERROR IN FILE - '+ Filename + 'row '+ {row_idx} +'column ' + {col_idx}) is_match = True if is_match: return
TypeError: expected str, bytes or os.PathLike object, not reader
|python|
null
The input is line-buffered. When you enter characters and hit <kbd>ENTER</kbd> the buffer contains all the characters you have entered + `'\n'`(new line). The `getchar` function takes one character from this buffer and returns it. It does not discard the rest of this buffer. Other characters entered will be available for the next `getchar` call. Example: 1. you enter `123456789`<kbd><samp>ENTER</samp></kbd>. 2. the buffer contains `123456789\n` 3. first call to getchar will return `'1'` 4. second call to getchar will return `'2'` `...` 5. tenth call will return `'\n'` Your code: - Your first program reads one charter from this buffer, prints it and then terminates. - your second program is looping taking the characters from this buffer one by one including the new line `'\n'` character too.
this is the dialog component that im using ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:composite="http://java.sun.com/jsf/composite" xmlns:p="http://primefaces.org/ui"> <composite:interface> <composite:attribute name="headerDialog" /> <composite:attribute name="widgetVar" /> <composite:attribute name="renderTesto" type="boolean" default="false"/> <composite:attribute name="testo" /> <composite:attribute name="renderHeaderTextArea" type="boolean" default="false"/> <composite:attribute name="headerTextArea" /> <composite:attribute name="renderTextArea" type="boolean" default="false"/> <composite:attribute name="requiredTextArea" shortDescription="Booleano che mi indica se è richiesta la nota" type="boolean" /> <composite:attribute name="textArea" /> <composite:attribute name="actionlistener" method-signature="java.lang.String action()" /> <composite:attribute name="modificalistener" method-signature="java.lang.String action()" /> <composite:attribute name="valueBtnLeft" /> <composite:attribute name="renderedBtnLeft" default="true"/> <composite:attribute name="valueBtnRight" /> <composite:attribute name="renderedBtnRight" default="true"/> <composite:attribute name="renderedBtnModifica" default="false"/> <composite:attribute name="escapeTestoCharacters" default="true"/> <composite:attribute name="renderList" type="boolean" default="false"/> <composite:attribute name="listaElementi" type="java.util.List"/> </composite:interface> <composite:implementation> <p:dialog id="dialogComponent" header="#{cc.attrs.headerDialog}" widgetVar="#{cc.attrs.widgetVar}" modal="true" resizable="false" width="400" appendTo="@(body)" closable="false" > <h:form id="formDialogComponent"> <div class="cm-margin-10px"> <!-- Elenco puntato dinamico --> <p:outputPanel id="divRenderedList" rendered="#{cc.attrs.renderList}"> <p:panelGrid columns="1" styleClass="ui-grid-col-12 cm-padding-10px"> <ul> <ui:repeat value="#{cc.attrs.listaElementi}" var="elemento"> <li>#{elemento}</li> </ui:repeat> </ul> </p:panelGrid> </p:outputPanel> <!-- Testo con supporto al ritorno a capo --> <p:outputPanel id="divRenderedTesto" rendered="#{cc.attrs.renderTesto}" styleClass="ui-grid"> <p:outputPanel layout="block" styleClass="ui-grid-row cm-margin-top-10px"> <p:outputPanel id="divTesto" layout="block" styleClass="ui-grid-col-12 cm-padding-10px"> <p:outputLabel value="#{cc.attrs.testo}" styleClass="cm-font-bold cm-color-black" escape="false" /> </p:outputPanel> </p:outputPanel> </p:outputPanel> <!-- TextArea --> <p:outputPanel id="divTextArea" rendered="#{cc.attrs.renderTextArea}" styleClass="ui-grid" style="max-height: 600px; overflow-y: auto;"> <p:outputPanel layout="block" styleClass="ui-grid-row cm-margin-top-10px cm-background-color-light-grey"> <p:outputPanel layout="block" rendered="#{cc.attrs.renderHeaderTextArea}" styleClass="ui-grid-col-12 cm-padding-10px"> <h:outputText value="#{cc.attrs.headerTextArea}" styleClass="cm-font-bold" /> </p:outputPanel> </p:outputPanel> <p:outputPanel layout="block" styleClass="ui-grid-row"> <p:outputPanel id="panelNota" styleClass="ui-grid-col-12"> <p:message id="notaTextAreaError" for="idNotaTextArea" display="text" escape="false" styleClass="cm-alert-text-area"/> <p:inputTextarea id="idNotaTextArea" value="#{cc.attrs.textArea}" style="width:100%;" scrollHeight="100" maxlength="10000" counterTemplate="{0} caratteri rimanenti" counter="displayCaratteriRimanenti" required="true" requiredMessage="Inserire un valore &lt;script type='text/javascript'&gt;hide_ajax_status_modal_div('ajax_status_change_page');&lt;/script&gt;" validator="validator.isNotBlank" validatorMessage="Valore Errato &lt;script type='text/javascript'&gt;hide_ajax_status_modal_div('ajax_status_change_page');&lt;/script&gt;" /> </p:outputPanel> </p:outputPanel> <p:outputPanel styleClass="ui-grid-row cm-margin-top-5px"> <p:outputPanel styleClass="ui-grid-col-12"> <h:outputText id="displayCaratteriRimanenti" style="float:right;" /> </p:outputPanel> </p:outputPanel> </p:outputPanel> <!-- Pulsanti --> <p:outputPanel layout="block" styleClass="ui-grid-row"> <p:outputPanel styleClass="ui-grid-row cm-margin-top-10px"> <p:outputPanel styleClass="ui-grid-col-12"> <p:commandButton value="#{cc.attrs.valueBtnRight}" update="formDialogComponent" action="#{cc.attrs.actionlistener}" rendered="#{cc.attrs.renderedBtnRight}" onclick="display_ajax_status_modal_div('ajax_status_change_page')" styleClass="btn-color-blu cm-margin-bottom-10px cm-float-right" /> <p:commandButton value="#{cc.attrs.valueBtnLeft}" update="formDialogComponent" rendered="#{cc.attrs.renderedBtnLeft}" onclick="PF('#{cc.attrs.widgetVar}').hide()" styleClass="btn-color-blu cm-margin-bottom-10px" /> <p:commandButton value="#{cc.attrs.valueBtnLeft}" update="formDialogComponent" rendered="#{cc.attrs.renderedBtnModifica}" action="#{cc.attrs.modificalistener}" styleClass="btn-color-blu cm-margin-bottom-10px" /> </p:outputPanel> </p:outputPanel> </p:outputPanel> </div> </h:form> </p:dialog> </composite:implementation> </html> ``` When i click a button the application do some controls and populate a list of warnings in case of warning. It is a list of Strings. If this list is not empty i show it in the dialog like this (getListaWarning()): ``` <gft:dialog_component_elenco id="alertInoltroPraticaRD" widgetVar="alertInoltroPraticaRD" headerDialog="#{commonBundle.attenzione}" renderList="#{approvazioneCategoriaRDBean.isWarningValorizzato()}" listaElementi="#{approvazioneCategoriaRDBean.getListaWarning()}" renderTesto="true" testo="Alla conferma la pratica verrà inoltrata al Responsabile Rating Desk per verifica e approvazione. Si desidera proseguire?" valueBtnLeft="#{commonBundle.btn_indietro}" valueBtnRight="#{commonBundle.btn_prosegui}" actionlistener="#{approvazioneCategoriaRDBean.salvataggiCheckOk()}" /> ``` My problem is that when i click for the first time on the button the list doesn't appear. I used some debug and it is correctly populated. If i click for the second time it works as it should What can i do ? thank you I tried to populate a list in the initialization and the problem is still there
My dialog component on PrimeFaces can't render a list on first click
|javascript|java|spring|primefaces|xhtml|
null
My input is this dataframe (but it could be a simple list) : ``` import pandas as pd df = pd.DataFrame({'description': ['ij edf m-nop ij abc', 'abc ij mnop yz', 'yz yz mnop aa abc', 'i j y y abc xxx mnop y z', 'yz mnop ij kl abc uvwxyz', 'aaabc ijij uuu yz mnop']}) ``` I also have a list of keywords (between 3 and 7 items) that I need to valid. We should only validate an exact combination of the whole keywords and ignore characters in between. The problem is that those keywords don't respect the order I put them in my list (here `keywords`). I searched in google and here too but couldn't find any post that talks about a similar topic. So I made the code below which is making a permuation of the keywords and put them in a regex string. ``` import re import itertools keywords = ['abc', 'ij', 'mnop', 'yz'] regex = '' for perm in list(itertools.permutations(keywords)): perm = [fr'\b{key}\b' for key in perm] regex += f'(?:{".*".join(perm)})|' regex = regex.rstrip('|') ``` Here is a snippet of my regex : ``` # (?:\babc\b.*\bij\b.*\bmnop\b.*\byz\b)|(?:\babc\b.*\bij\b.*\byz\b.*\bmnop\b)|(?:\ # babc\b.*\bmnop\b.*\bij\b.*\byz\b)|(?:\babc\b.*\bmnop\b.*\byz\b.*\bij\b)|(?:\babc # \b.*\byz\b.*\bij\b.*\bmnop\b)|(?:\babc\b.*\byz\b.*\bmnop\b.*\bij\b)|(?:\bij\b.*\ # babc\b.*\bmnop\b.*\byz\b)|(?:\bij\b.*\babc\b.*\byz\b.*\bmnop\b)|(?:\bij\b.*\bmno # p\b.*\babc\b.*\byz\b)|(?:\bij\b.*\bmnop\b.*\byz\b.*\babc\b)|(?:\bij\b.*\byz\b.*\ # babc\b.*\bmnop\b)|(?:\bij\b.*\byz\b.*\bmnop\b.*\babc\b)|(?:\bmnop\b.*\babc\b.*\b # ij\b.*\byz\b)|(?:\bmnop\b.*\babc\b.*\byz\b.*\bij\b)|(?:\bmnop\b.*\bij\b.*\babc\b # .*\byz\b)|(?:\bmnop\b.*\bij\b.*\byz\b.*\babc\b)|(?:\bmnop\b.*\byz\b.*\babc\b.*\b # ij\b)|(?:\bmnop\b.*\byz\b.*\bij\b.*\babc\b)|(?:\byz\b.*\babc\b.*\bij\b.*\bmnop\b # )|(?:\byz\b.*\babc\b.*\bmnop\b.*\bij\b)|(?:\byz\b.*\bij\b.*\babc\b.*\bmnop\b)|(? # :\byz\b.*\bij\b.*\bmnop\b.*\babc\b)|(?:\byz\b.*\bmnop\b.*\babc\b.*\bij\b)|(?:\by # z\b.*\bmnop\b.*\bij\b.*\babc\b) ``` While it works on the example I gave, it takes 5-15 minutes on my real dataset (50k rows and very long descriptions with breaklines) and I'm not sure if my approach handles correctly all the rows. And there is also a problem, sometimes I had to validate a list of 6 keywords, which gives 720 permuation ! Can you guys help me solve this ? Is regex the right way to approach my problem ? My expected ouptut is this : ``` description valid 0 ij edf m-nop ij abc 1 abc ij mnop yz True 2 yz yz mnop aa abc 3 i j y y abc xxx mnop y z 4 yz mnop ij kl abc uvwxyz True 5 aaabc ijij uuu yz mnop ```
e.g connecting go microservice made with rpcx with nestJs(popular node framework)
|go|nestjs|microservices|rpc|
In C#, you can't put statments (that are not variable decelerations) in the class scope, so you can only access class members inside methods.
{"Voters":[{"Id":272109,"DisplayName":"David Makogon"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":12632699,"DisplayName":"SwissCodeMen"}],"SiteSpecificCloseReasonIds":[11]}
I am building Docker images of a web app locally on my Mac and then running them via Docker Compose on a remote server that's running Ubuntu AMD64. I get an error that the platform isn't compatible, and I'm curious what's the best practice in real production environments to tackle this issue. Do I support 2 image types? Do I specify something in the Dockerfile that allows the image to run on all platforms? I was able to bypass this by re-building the image on the remote server, but not sure if this is a best practice.
The **problem** is that currently the overloaded `operator+=(const float&)` that you've provided takes the right hand operand which is a `float` instead of `Vector2`. Now, the expression `scaledDir * mass` is of type `Vector2` which means that you're trying to use `operator+=` with right hand operand of type `Vector2`. But since you haven't provided any such `opertor+=` that takes right hand operand of type `Vector2`, you get the mentioned error. --- To solve this, just provide an overload that takes an operand of type `Vector2`. One way of doing this is as shown below: ``` //----------------------------vvvvvvv---------->changed float to Vector2 Vector2& operator+=(const Vector2& vec) { X += vec.X; Y += vec.Y; return *this; } ``` [Working demo](https://godbolt.org/z/fvMozzenz)
I wanted to create a Grafana dashboard and an alarm on top of that for calculating Average Active concurrent connections per GPU/Node with a specific threshold value for the alarm. There is a Load Balancer in place which distributes the traffic on the nodes(which are dynamic) because of autoscaling. I was looking for the method/metrics to get the average connection count per GPU/Nodes. I created a Grafana Dashboard with "Sum" as statistics and "ActiveConnectionCount" as metric and got the sum of Active connections count for a particular Load balancer. But as i need to setup a threshold value for the alarm and the calculation/formulae to calculate the threshold value includes the value "no of nodes" which is dynamic in this scenario hence looking for a technique on how to perform these calculations with such dynamic values of Node. Another option i am trying was to calculate the average concurrent connections per GPU/Node where the threshold calculation for the alarm will not require this dynamic nature/value of Nodes. So just wanted to know if this can be achieved and how.
null
Instead of a for loop you could achieve your desired result using `dplyr::across` like so: ``` r library(dplyr, warn = FALSE) df <- data.frame( year = c(1977:1981), set852 = c(1, 1, 0, 0, 0), set857 = c(0, 0, 1, 1, 0), set874 = c(0, 0, 0, 1, 1) ) myfun <- function(.x, year) { case_when( .x == 1 & year == 1977 ~ "start", .x == 1 & lag(.x) == 0 ~ "start", .x == 1 & lead(.x) == 0 ~ "end", .default = "no change" ) } set_cols <- grep("\\d+$", names(df), value = TRUE) df |> mutate( across(all_of(set_cols), ~ myfun(.x, year), .names = "{gsub('^.*?(\\\\d+)$', 'c\\\\1', .col)}" ) ) |> select(-all_of(set_cols)) #> year c852 c857 c874 #> 1 1977 start no change no change #> 2 1978 end no change no change #> 3 1979 no change start no change #> 4 1980 no change end start #> 5 1981 no change no change no change ```
ModuleNotFoundError Traceback (most recent call last) Cell In[2], line 16 14 import pandas as pd 15 from datetime import datetime ---> 16 from coastsat import SDS_download, SDS_preprocess, SDS_shoreline, SDS_tools, SDS_transects ModuleNotFoundError: No module named 'coastsat' I have not try anything
The issue is that `npm` isn't just `npm`, there's actually multiple (scripts): - `npm` - `npm.cmd` - `npm.ps1` When you execute `npm` in your terminal, then your terminal is smart and automatically picks the one it recognizes. In the same way that if you (on Windows) execute `foo` it will automatically run `foo.exe`. However, `Command::new()` does not take this into account. So when it tries to locate `npm` it ends up with `npm` (sh script) and not `npm.cmd`. You can resolve your issue by changing `"npm"` to `"npm.cmd"`. To have it be a bit more flexible for other operating systems, then you can use a function like this: ```rust pub fn npm() -> Command { #[cfg(windows)] const NPM: &str = "npm.cmd"; #[cfg(not(windows))] const NPM: &str = "npm"; Command::new(NPM) } ``` Then you simply replace your `Command::new("npm")` with `npm()`. **Example:** ```rust use std::process::Command; pub fn npm() -> Command { #[cfg(windows)] const NPM: &str = "npm.cmd"; #[cfg(not(windows))] const NPM: &str = "npm"; Command::new(NPM) } fn main() -> std::io::Result<()> { npm().arg("-v").spawn()?.wait()?; Ok(()) } ```
I'm exporting multiple sheets to PDF with the following code: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> ThisWorkbook.Sheets(Array("3rd party", "Dashboard", "BS_3rd")).Select ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, fileName:=PDF_FileName, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True <!-- end snippet --> The code works fine with any sheet except "Dashboard". That sheet in any combination (even on its own) causes a Run-time error '1004': Application-defined or object-defined error on the second line. Selection is fine, export to PDF runs into this bug. Please advise.
Excel VBA error 1004 on PDF export - not a path issue
|excel|vba|google-sheets|pdf|runtime-error|
- Mitmproxy: 10.2.4 - Python: 3.10.12 ```python from mitmproxy import http, flow def request(flow: flow): headers = [ (b'set-cookie', b'name1=value1'), (b'set-cookie', b'name2=value2'), (b'content-type', b'text/html'), ] flow.response = http.Response.make(200, b'<html>my content</html>', headers) You can also call encode() method, like so `'set-cookie'.encode('utf-8')`, instead of `b'set-cookie'`. This is useful when iterating over a list/dict for building up your headers list of tuples.
By uninstalling and then reinstalling media pipe worked in my case. I have created a virtual environment for installing media pipe and by activating, it worked.
How to make a regex orderless when validating a list of texts?
|python|pandas|
For my custom compiled native x64 JIT-code, I have certain instrinsic functions. A lot of them are just called from my code, thus I will generate with my own compiler. Some of them however are directly called from c++-code, and thus I want to have them be compiled inside a static-lib, so that they can at least be linked statically, if not inlined. I need to use inline-assembly for those functions, as they perform actions that cannot be expressed in regular C++, like setting a non-volatile register from a function-input. However, the function itself must behave like a regular x64-function - it needs a prolog/epilogue, and it must have the necessary unwind-information to support stack-traces and exception-handling. Thus I cannot use MSVC (which is my native compiler), so I decided to make a static lib with clang-cl in Visual Studio instead. The best I got so far is the following: void interruptEntry(void* pState, const char* pAddress) { __asm { // load state into RBX mov rbx,rcx // load callstack-top into RDI mov rax,[rbx] mov rdi,[rax] // call address call rdx }; } This will generate the proper prolog, epilogue and all required unwind-information. However, it critically lacks the 32 bytes of shadow-space that are necessary by x64 (which pAddress needs to be called by): Acclimate Engine.dll!interruptEntry(void *, const char *): push rdi push rbx mov rbx,rcx mov rax,qword ptr [rbx] mov rdi,qword ptr [rax] call rdx pop rbx pop rdi ret Keep in mind, while this code is generated via clang-cl, the DLL is linked with MSVC. The static-lib is compiled with O2 (set from the VisualStudio-project page). Things I've tried: - Modifying RSP manually, with sub RSP,32. This results in a frame-pointer register being established, as the compiler will count this as a dynamic stack allocation. This adds too much overhead to make it worth using a statically compiled function in the first place - Similarily, I could reference "pState" directly in asm (mov rbx,pState), this will cause the shadow-space to be added - but also, pState will then be copied onto the stack, and loaded into rbx from that stack location, instead of the register. This once again defeats the purpose of what I am doing here. - Calling "pAddress" as a function-pointer directly, after the asm-block. This will still not result in any difference in code-gen - Using normal asm(), or extended asm, in combination with "__attribute__((naked))". That will not generate the prolog/epilogue, which I can write myself - but then the unwind-information is missing. clang-cl seems to not understand any of the unwind-data directives, like .allocstack or .pushreg, resulting in a "error : unknown directive" - regardless of in which type of asm-block it's being used. Is there any reason why the shadow-space is missing, and any way to get it there without adding any uncessary overhead like a frame-pointer (while still having unwind-information)? I'm also open for other suggestions - for example, if there is some intrinsic that let's me set those registers (while still compiling down to the one move), I would not need to use assembly (manipulating specific registers with global effect is the main reason I cannot write plain C++).
null
|php|magento|filter|collections|
null
Like any kind of `Stream` (e.g. `Promise`s), when you see nesting in `Observable`s you might want to take a step back to see if it's really warranted. Let's examine your solution bit by bit. Our starting point is: this.router.paramMap.pipe(takeUntil(this.ngUnsubscribe)) Then you subscribe, but within that subscribe you do observable operations on the given data, this strongly suggests you should be `pipe`ing an operation instead, and then subscribe on the final result. In this case you want to `map` your `params` to some `Observable`. You also might benefit from the "interrupt early" behavior that [`switchMap`](https://rxjs.dev/api/index/function/switchMap) offers. Otherwise there's also [`mergeMap`](https://rxjs.dev/api/index/function/mergeMap) as a potential option if you don't want to "interrupt early" (it used to be more appropriately named [`flatMap`](https://rxjs.dev/api/index/const/flatMap)). We'll add a [`filter`](https://rxjs.dev/api/index/function/filter) and [`map`](https://rxjs.dev/api/index/function/map) for good measure, to ensure we have the `team` param, and to pluck it out (since we don't need the rest). this.router.paramMap.pipe( takeUntil(this.ngUnsubscribe), filter(params => params.has("team")) map(params => params.get("team")) switchMap(team => { this.teamToFilterOn = team as string; // We'll dissect the rest }) ) // [...] Then comes the part with what you want to do with that team. You have multiple "tasks" that rely on the same input, and you want them both at the same time, so reaching for [`forkJoin`](https://rxjs.dev/api/index/function/forkJoin) is a good call. But there's also [`combineLatest`](https://rxjs.dev/api/index/function/combineLatest) that does something similar, but combine the results "step by step" instead. You use the word "latest" for both your tasks, so we'll indeed reach for `combineLatest` instead: const releaseDef$ = // [...] const pipelineDef$ = // [...] return combineLatest([releaseDef$, pipelineDef$]); Now let's dissect these two operations. From what I gather, you're only interested in releases that have a `lastRelease`. You also don't want to "switch" when a new one comes in, you want them all, let's encode that: const releaseDef$ = this.apiService.getReleaseDefinitions(this.teamToFilterOn as string).pipe( filter(releaseDef => releaseDef.lastRelease), mergeMap(lastReleaseDef => this.apiService.getRelease(releaseDefinition.lastRelease.id)), filter(info => !!info) mergeMap(info => this.apiService.getTestRunsByRelease(info.releaseId).pipe(map(testruns => ({ testruns, info }))), ) You'll notice I also pipe into the result of `getTestRunsByRelease`. That is because unlike `Promise`s, we don't have an alternative syntax like `async/await` that help with keeping previous state in an easy way. Instead we have to rely on the monoid operation `map` from within our monad operation `flatMap` and drag the previous results along. For `Promise`s, both `map` and `flatMap` are `.then`. For `Observable`s they are respectively `map` and `mergeMap`. We apply a very similar transformation to your pipelines: const pipelineDef$ = this.apiService.getPipelineDefinitions(this.teamToFilterOn as string) .pipe( mergeMap(pipelineDef => this.apiService.getLatestPipelineRun(pipelineDef.id)), filter(info => !!info), mergeMap(info => this.apiService.getTestRunsByPipeline(info.pipelineRunId).pipe(map(testruns => ({ testruns, info }))), ); Here if you need to operate independently on the results of `releaseDef$` and `pipelineDef$` you can use [`tap`](https://rxjs.dev/api/index/function/tap). Note that these could easily be extracted into two methods. As the end operation is the same for both, and their results have the same shape, you can use [`merge`](https://rxjs.dev/api/index/function/merge) instead of `combineLatest` to merge the two observables into one that emits all values of both as they come in (instead of combining the latest value of each in an array): return merge(releaseDef$, pipelineDef$); To wrap this up, let's put it all together: ngOnInit(): void { this.router.paramMap.pipe( takeUntil(this.ngUnsubscribe), filter(params => params.has("team")) map(params => params.get("team")) switchMap(team => { this.teamToFilterOn = team as string; const releaseDef$ = this.apiService.getReleaseDefinitions(this.teamToFilterOn as string).pipe( filter(releaseDef => releaseDef.lastRelease), mergeMap(lastReleaseDef => this.apiService.getRelease(releaseDefinition.lastRelease.id)), filter(info => !!info) mergeMap(info => this.apiService.getTestRunsByRelease(info.releaseId).pipe(map(testruns => ({ testruns, infos })))), ); const pipelineDef$ = this.apiService.getPipelineDefinitions(this.teamToFilterOn as string) .pipe( mergeMap(pipelineDef => this.apiService.getLatestPipelineRun(pipelineDef.id)), filter(info => !!info), mergeMap(info => this.apiService.getTestRunsByPipeline(info.pipelineRunId).pipe(map(testruns => ({ testruns, info }))), ) return merge(releaseDef$, pipelineDef$); }) ).subscribe(({ testruns, infos }) => { this.isLoading = false; this.results = [...this.results, { info: info, testruns: testruns, totals: this.calculateEnvironmentTotals(testruns.testRunResults)}]; this.dataSource.data = this.results; }); } You'll notice I only used on `takeUntil(this.ngUnsubscribe)` as the "main" observable chain will stop with that, which means operation will stop as well. If you're unsure or encounter issues, you can still sprinkle them as the very first argument of each `.pipe`.
[enter image description here][1] [1]: https://i.stack.imgur.com/P7Fm3.png How I can produce the labels show in the attached image, X are the labels desire to remove. I want to show "Elevation, NDVI and Rivers " on the x axis but only "Elevation is appearing, while I want to show single label for "Ibex, Snow Leopard and Cooccurance" on right hand side.
Facet wrap labels