instruction
stringlengths
0
30k
so in an intro to AI course we where given a project to find the optimal route using search algorithms to a relevant hospital in a certain city, and we are asked to consider the map of the hospitals in this city, i have a problem of how to select the initial state it sure is the patient localization but how can i incorporate it into my search graph which is the map of hospitals dynamically (im thinking that localization is in long/lat format) i thought of a dynamic graph but i can't see how can i incorporate the patient localization dynamically
Hospital route finding ai project
|search|mapping|path-finding|a-star|
null
<!-- language-all: sh --> [zett42](https://stackoverflow.com/users/7571258/zett42) has provided the crucial pointer: From the [`ConvertFrom-StringData`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertfrom-stringdata) help topic (emphasis added), as of PowerShell 7.4.x: > `ConvertFrom-StringData` supports escape character sequences that are allowed by conventional machine translation tools. That is, the **cmdlet can interpret backslashes (`\`) *as escape characters* in the string data** [...] You **can also preserve a literal backslash in your results by escaping it with a preceding backslash, like this: `\\`**. Unescaped backslash characters, such as those that are commonly used in file paths, can render as illegal escape sequences in your results. Therefore, **assuming that all `\` characters in your input file are meant to be interpreted _literally_**: ``` (Get-Content -Raw C:\<ConfigFolder>\basic.conf).Replace('\', '\\') | ConvertFrom-StringData).FileLocation ``` Note the use of `-Raw` with [`Get-Content`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-content) to ensure that the file content is read _in full_, as a single, (typically) _multiline_ string, which in turn ensures that `ConvertFrom-StringData` outputs a _single_ `[hashtable]` instance. (If, by contrast, you really mean to output a separate hashtable _for each input line_, omit `-Raw`). --- Given that this escaping need may be inconvenient (and possibly somewhat unexpected, but that cannot be helped), **it would be helpful if `ConvertFrom-StringData` itself supported _verbatim_ (literal) parsing by way of an _opt-in_**: * [GitHub issue #20418](https://github.com/PowerShell/PowerShell/issues/20418) asks for just that, by way of a future `-Raw` switch. This enhancement has been green-lit, but is yet to be implemented.
To display the legend outside of the plot in matplotlib, you can use the bbox_to_anchor papameter along with the loc parameter of the legend function, here's how you can modify your code to achieve that:
Bom dia pessoal, feliz Páscoa!! Estou fazendo um curso de JavaScript com o Gustavo Guanabara e estou tento problemas no resultado da function em um exercício. Alguém por favor poderia me ajudar a achar o erro? obs: Minha primeira vez aqui na plataforma. ``` <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="assets/main.css"> </head> <body> <header> <h1>Verificador de idade</h1> </header> <section> <div> <p> Ano de Nascimento: <input type="number" name="txtano" id="txtano"> </p> <p> Sexo: <input type="radio" name="radsex" id="mas" checked> <label for="masc">Masculino</label> <input type="radio" name="radsex" id="fem"> <label for="fem">Feminino</label> </p> <p> <input type="button" value="Verificar" onclick="verificar()"> </p> </div> <div id="res"></div> </section> <footer> <p> &copy; Todos os direitos reservados 2024 </p> </footer> <script src="assets/script.js"></script> </body> </html> function verificar() { let data = new Date() let anoAtual = data.getFullYear() let fAno = document.getElementsByName('txtano') let res = window.document.querySelector('div#res') if (fAno == 0 || fAno > anoAtual) { window.alert ('Verifique os dados e tente novamente!') } else { let fSex = window.document.getElementsByName( 'radsex' ) let idade = anoAtual - Number(fAno) res.innerHTML = `Idade calculada: ${idade}` } } ``` [enter image description here][1] [1]: https://i.stack.imgur.com/0vTI4.png
The relevant part of [the documentation](https://doc.rust-lang.org/std/fs/fn.rename.html) is this: > On Unix, if […] `from` is not a directory, `to` must also be not a directory. In contrast, on Windows, `from` can be anything, but `to` must not be a directory. I.e. `to` *may not be* a directory, but you've passed the name of a directory to the second parameter. So you'll have to append the file name to the directory name yourself: ```rust let mut file_path = PathBuf::from("apps/a"); let mut destination_path = PathBuf::from("apps/test/"); destination_path = destination_path.join(file_path.file_name().unwrap()); let result = fs::rename(file_path, destination_path).unwrap(); ```
I stumbled on this class when browsing the internet this morning: [`CStrBufT`][1]. I understand that it is meant to be used instead of: ```cpp CString::GetBuffer CString::GetBufferSetLength CString::ReleaseBuffer ``` But the documentation lacks a usage example, and my searches on the internet don't seem to show this class being used, but the respective `CString` methods. What is the correct way to use this wrapper when you need a buffer? [1]: https://learn.microsoft.com/en-us/cpp/atl-mfc-shared/reference/cstrbuft-class?view=msvc-170
i have problem in Google Colab Deep Learning coding any one help me about this issue Chat GPT fail to solve my error
Extracting the value of CSS Property directly from Stylesheet doesn't seem to be the right thing to do. I say this because the value of a property might change when multiple CSS files work together to bring the final value of any class's property. Consider the case where StyleSheetA, and StyleSheetB both have `sample-class`, and one sets `font-size` to `2em` while the other sets it to `3em`. In this case which value do you want? Do you know which one will be applied on any element, what if one of them marks it as `!important`? If you just want to access the final CSS property for any element, consider using [getComputedStyle][1] instead. [1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
|python|pdf|
I have created a custom SAML application in the Google Admin panel for my workspace account to allow users to login via SSO to an application using their Google Workspace credentials. Currently only users of my organisation can login to this application. I want to make it so that users of an external organisation can also login to this application using their Google Workspace credentials using SSO. How do I do this? Tried: I have created a Google Group and all users who should have access to this application (both internal and external organisation users) and turned on access to this Google Group in the access settings of the custom SAML app. Expected: Both internal and external users should have access to the application. Result: Only internal users are able to login to the application using their credentials.
Allow external users to login using custom SAML app in Google Admin
|single-sign-on|saml|google-workspace|google-admin-sdk|
null
{"Voters":[{"Id":18157,"DisplayName":"Jim Garrison"},{"Id":4405757,"DisplayName":"Thiyagu"},{"Id":642706,"DisplayName":"Basil Bourque"}]}
``` const express = require('express'); const jwt = require('jsonwebtoken'); const passport = require('passport'); const localStrategy = require('passport-local').Strategy; const router = express.Router(); passport.use( new localStrategy(async (email , password , done)=>{ try{ const user = {email: "piyu" , password: "123"} return done(null , user) } catch(err){ return done(err) } }) ) ... router .route('/login') .get(async (req , res) => { return res.render("login") }) .post( async (req , res , next) => { passport.authenticate('local' , async (err , user , info )=>{ if(err){ return next(err.message); } if(!user){ return res.send("user not found") } if(user){ return res.send("user found successfully") } })(req , res , next) }) module.exports = router; ``` Here I have hardcoded some stuff because I was trying things out. Inside "passport.use" i have hardcoded user object, so that the callback function in "passport.authenticate" should always receive user object and print "user found successfully". But for some reason the opposite has been happening and "user not found" has been printing on the webpage. I tried `console.log(user)` inside the "passport.authenticate" and found that the callback function has not received user object or error . So i tried `console.log("123")` inside passport.use and found that when "local" function is called from "passport.authenticate" the "passport.use" is never being called or invoked for some reason. EDIT: okay I've found that the problem was in synatx as is replaced ``` passport.use(new localStrategy( async (email, password, done) => { try { const user = { email: "piyu", password: "123" }; return done(null, user); } catch (err) { return done(err); } })); ``` with ``` passport.use(new localStrategy({ usernameField: 'email', passwordField: 'password' }, async (email, password, done) => { try { const user = { email: "piyu", password: "123" }; return done(null, user); } catch (err) { return done(err); } })); ```
I have a problem with GitLab it won't run my UI tests from an Xcode project. I get an error: This job is stuck because of one of the following problems. There are no active runners online, no runners for the protected branch, or no runners that match all of the job's tags: saas-macos-medium-m1 My yml file is: ``` stages: - test ui_tests: stage: test tags: - saas-macos-medium-m1 script: - xcodebuild test -workspace DatePlanner.xcodeproj -scheme DatePlanner -destination 'platform=iOS Simulator,name=iPad (9th generation)' -configuration Debug artifacts: paths: - DerivedData/ only: - merge_requests ``` Becouse its xcode i am trying to run it on tags with the mac machines which are available from gitlab runners. [![enter image description here](https://i.stack.imgur.com/sVWaE.png)](https://i.stack.imgur.com/sVWaE.png) I expect that the xcui tests are runned.
There are no active runners online GitLab
|xcode|gitlab|gitlab-ci|gitlab-ci-runner|gitlab-ci.yml|
null
I have this format, the result should be of Item data type, **test 1:** `"<A \"Test\">"` **test 2:** `r#"<A "Test">"#` **Result:** `Item { item_type: TEXT, ascii_data: Some("Test") }` **test 3:** `<A>` **Result:** `Item { item_type: TEXT, ascii_data: None }` For test 1 and test 2, following code parse, but for type 3, it is failing, It also contains nested types. ``` <L <A "Test1"> <L <A> <A "Test2"> > <A "Test3"> > ``` **Result:** ``` Item { item_type: LIST, sub_items: [ Item { item_type: ASCII, ascii_data: "Test1", }, Item { item_type: LIST, sub_items: [ Item { item_type: ASCII, ascii_data: None, } Item { item_type: ASCII, ascii_data: "Test2", } ], }, Item { item_type: ASCII, ascii_data: "Test3", }, ], } ``` #### Rust [Playgroud link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=11f11eb1189784af753d102c07c732bb) ``` use nom::{ branch::alt, bytes::complete::{tag, take_until}, character::complete::multispace0, combinator::map, IResult, }; #[derive(Clone, Debug, PartialEq)] enum ItemType { LIST, TEXT, NONE, } #[derive(Clone, Debug, PartialEq)] struct Item { item_type: ItemType, sub_items: Option<Vec<Item>>, ascii_data: Option<String>, } impl Default for Item { fn default() -> Self { Item { item_type: ItemType::NONE, sub_items: None, ascii_data: None, } } } // Parse string data, it may empty then return none, fn parse_ascii_data(input: &str) -> IResult<&str, String> { let (input, _) = tag("\"")(input)?; let (input, ascii_data) = take_until("\"")(input)?; let (input, _) = tag("\"")(input)?; Ok((input, ascii_data.to_string())) } // Parse <A> or <A "string">, if no string then return empty string then return none fn parse_ascii_item(input: &str) -> IResult<&str, Item> { let (input, _) = tag("<A")(input)?; let (input, _) = multispace0(input)?; let (input, ascii_data) = alt((parse_ascii_data, map(tag("\"\""), |_| "".to_string())))(input)?; let (input, _) = tag(">")(input)?; Ok(( input, Item { item_type: ItemType::TEXT, ascii_data: Some(ascii_data), ..Default::default() }, )) } // Parse <L> or <L <A "string">>, if no string then return empty string then return none fn parse_list_item(input: &str) -> IResult<&str, Item> { let (input, _) = tag("<L")(input)?; let (input, _) = multispace0(input)?; let (input, sub_items) = alt((parse_ascii_item, map(tag("<>"), |_| Item::default())))(input)?; let (input, _) = tag(">")(input)?; Ok(( input, Item { item_type: ItemType::LIST, sub_items: Some(vec![sub_items]), ..Default::default() }, )) } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_ascii_item() { let input = "<A \"Test\">"; let expected_item = Item { item_type: ItemType::TEXT, ascii_data: Some("Test".to_string()), ..Default::default() }; assert_eq!(parse_ascii_item(input), Ok(("", expected_item))); let input = r#"<A "Test">"#; let expected_item = Item { item_type: ItemType::TEXT, ascii_data: Some("Test".to_string()), ..Default::default() }; assert_eq!(parse_ascii_item(input), Ok(("", expected_item))); assert_eq!( parse_ascii_item("<A>"), Ok(( "", Item { item_type: ItemType::TEXT, ascii_data: None, ..Default::default() } )) ); } #[test] fn test_parse_list_item() { let input = "<L <A \"Test\">>"; let expected_item = Item { item_type: ItemType::LIST, sub_items: Some(vec![Item { item_type: ItemType::TEXT, ascii_data: Some("Test".to_string()), ..Default::default() }]), ..Default::default() }; assert_eq!(parse_list_item(input), Ok(("", expected_item))); assert_eq!( parse_list_item("<L>"), Ok(( "", Item { item_type: ItemType::LIST, sub_items: Some(vec![Item::default()]), ..Default::default() } )) ); } #[test] fn test_parse_nested_list_item() { let input = "<L \n <A \"Test1\">\n <L\n <A \"Test2\">\n >\n>"; let expected_item = Item { item_type: ItemType::LIST, sub_items: Some(vec![Item { item_type: ItemType::TEXT, ascii_data: Some("Test".to_string()), ..Default::default() }]), ..Default::default() }; assert_eq!(parse_list_item(input), Ok(("", expected_item))); assert_eq!( parse_list_item("<L>"), Ok(( "", Item { item_type: ItemType::LIST, sub_items: Some(vec![Item::default()]), ..Default::default() } )) ); } } ```
Parse this custom data format for data type with nested list
|rust|nom|
Instead of using a `ZStack`, try showing the yellow circle as an overlay over the `Image`. This way, the size and position of the circle will always correspond to the size and position of the image. - If the `.scaleEffect` is applied after the green background and the overlay, these will be scaled too. - The blue background can be applied using another `.background` modifier to the `Image`. To fill all of the screen background, set a frame with `maxWidth: .infinity, maxHeight: .infinity`. - When you update the flag `isAnimating`, you can either do it `withAnimation`, or you can add an `.animation` modifier to the `Image`. ```swift NavigationStack { NavigationLink("Show image") { Image(poke.imageUrl) .resizable() .aspectRatio(contentMode: .fit) .padding() .clipShape(Circle()) .background(Circle().fill(Color.green)) .overlay { Circle() .stroke(Color.yellow, lineWidth: 3) // .scaleEffect(animationAmount) .opacity(Double(2 - animationAmount)) .animation(.easeInOut(duration: 2).repeatForever(autoreverses: false), value: animationAmount) } .scaleEffect(isAnimating ? 1.2 : 1.0) // 이미지 크기 조절 .rotationEffect(.degrees(isAnimating ? 10 : 0)) // 이미지 회전 .shadow(radius: 8) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.blue) .animation(.easeInOut(duration: 2).repeatForever(autoreverses: false), value: isAnimating) .onAppear { isAnimating = true animationAmount = 2 } .onDisappear { isAnimating = false animationAmount = 1 } } } ``` ![Animation](https://i.stack.imgur.com/sfOw2.gif)
I have a website for car and tow services for passenger cars and services which includes assistance and assistance for damaged cars in the North Only the pages I create will not be indexed for long. Please do a check. I used the yoast plugin and registered my sitemap in Google Search Console, but it didn't change much. Is there a better solution to get my pages indexed sooner?
”ft.VideoMedia( "https://user-images.githubusercontent.com/28951144/229373720-14d69157-1a56-4a78-a2f4-d7a134d7c3e9.mp4" ),” When I read reference I found that is "http resource" only. Can I use local resources for mp4 playback? ``` import random import flet as ft def main(page: ft.Page): page.theme_mode = ft.ThemeMode.LIGHT page.title = "TheEthicalVideo" page.window_always_on_top = True page.spacing = 20 page.horizontal_alignment = ft.CrossAxisAlignment.CENTER def handle_pause(e): video.pause() print("Video.pause()") def handle_play_or_pause(e): video.play_or_pause() print("Video.play_or_pause()") def handle_play(e): video.play() print("Video.play()") sample_media = [ ft.VideoMedia( "https://user-images.githubusercontent.com/28951144/229373709-603a7a89-2105-4e1b-a5a5-a6c3567c9a59.mp4", extras={ "artist": "Thousand Foot Krutch", "album": "The End Is Where We Begin", }, http_headers={ "Foo": "Bar", "Accept": "*/*", }, ), ] page.add( video := ft.Video( expand=True, playlist=sample_media[0:2], playlist_mode=ft.PlaylistMode.LOOP, fill_color=ft.colors.BLUE_400, aspect_ratio=16/9, volume=100, autoplay=False, filter_quality=ft.FilterQuality.HIGH, muted=False, on_loaded=lambda e: print("Video loaded successfully!"), on_enter_fullscreen=lambda e: print("Video entered fullscreen!"), on_exit_fullscreen=lambda e: print("Video exited fullscreen!"), ), ft.Row( wrap=True, alignment=ft.MainAxisAlignment.CENTER, controls=[ ft.ElevatedButton("Play", on_click=handle_play), ft.ElevatedButton("Pause", on_click=handle_pause), ft.ElevatedButton("Play Or Pause", on_click=handle_play_or_pause), ft.ElevatedButton("Stop", on_click=handle_stop), ft.ElevatedButton("Next", on_click=handle_next), ft.ElevatedButton("Previous", on_click=handle_previous), ft.ElevatedButton("Seek s=10", on_click=handle_seek), ft.ElevatedButton("Jump to first Media", on_click=handle_jump), ft.ElevatedButton("Add Random Media", on_click=handle_add_media), ft.ElevatedButton("Remove Random Media", on_click=handle_remove_media), ], ), ft.Slider( min=0, value=100, max=100, label="Volume = {value}%", divisions=10, width=400, on_change=handle_volume_change, ), ft.Slider( min=1, value=1, max=3, label="PlaybackRate = {value}X", divisions=6, width=400, on_change=handle_playback_rate_change, ), ) ft.app(target=main) ``` I changed from http to "./video/movie.mp4". But it was not work. Environment : Mac Language : Python Library : flet
Can I use local resources for mp4 playback?
|python-3.x|video|flet|
null
You change `display` of `td` thus breaking its `display: table-cell`. Just select a different way, for example, position the input absolutely or add a wrapper DIV: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-css --> td{ border: 1px solid gray; width:100px; height:40px; } .checkbox-cell{ position:relative; } .checkbox-cell input{ position: absolute; top:50%; left:50%; margin-top:-6px; margin-left:-6px; } .checkbox-cell2{ position:relative; } .checkbox-cell2 > div{ position: absolute; inset: 0; display:flex; align-items: center; justify-content: center; } <!-- language: lang-html --> <table> <tr><td class="checkbox-cell"><input type="checkbox"></td></tr> </table> <table> <tr><td class="checkbox-cell2"><div><input type="checkbox"></div></td></tr> </table> <!-- end snippet -->
The state is not changing when the focus is changed, therefore the text color doesn't change. You must listen to the `FocusNode` changes and `setState` after any changes. Update your widget like this: ```dart FocusNode emailText = FocusNode(); Color _emailTextColor = Colors.black; _onEmailFocusChange() { setState(() { _emailTextColor = emailText.hasFocus ? Colors.blue : Colors.black; }); } @override void initState() { emailText.addListener(_onEmailFocusChange); super.initState(); } @override void dispose() { super.dispose(); emailText.removeListener(_onEmailFocusChange); emailText.dispose(); } ``` Use `_emailTextColor` as your text color inside `TextStyle`.
YES, Organization structured data is like a special tag we can add to our website to tell search engines more about our organization. It helps them understand who we are and what we do, which can make our website more visible to people searching online. So yeah, having Organization schema on every page is a good idea because it helps search engines connect better with our site.
I am looking for an operation that creates a matrix from a colwise operation in Eigen. I could not find an appropriate operation in [VectorwiseOp](https://eigen.tuxfamily.org/dox/classEigen_1_1VectorwiseOp.html) (sorry if I overlooked one). It seems that it is supported for some operations. First output compiles fine, second output gives an error. (https://www.godbolt.org/z/qrrfa1brx) ```c++ #include <Eigen/Core> #include <iostream> int main() { Eigen::Matrix3d m; m << 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0; std::cout << m + m.rowwise().sum().replicate(1, 3) << std::endl; // OK std::cout << m + m.rowwise() << std::endl; // Failure: operator + not found. } ``` In the context I want to apply this, it is not possible for me to use `rowwise` as an lhs operator. I want to apply other matrix operations on the result. Maybe an `matri()` or `array()` method in the `VectorwiseOp` would solve this gap.
{"Voters":[{"Id":9098759,"DisplayName":"Akash Singh"}]}
When I execute a Selenium Script using Firefox, the Firefox opens up but it doesn't redirect to the URL. Below is the error which is displayed on the Eclipse Console: ``` org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output: console.error: JsonSchemaValidator.jsm ``` my script is below : ```java package testCases; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Authentication { public static void main(String[] args) { System.setProperty("webdriver.gecko.driver","C:/usine-dev/workdir/workspace/test-bleu-horizon/src/test/resources/drivers/geckodriver.exe" ); WebDriver driver = new FirefoxDriver(); driver.get("https://github.com/"); } } ``` I am using `selenium-java-4.10.0.jar`, and `geckodriver (v0.32.0 ) ` `firefox 102.9.0esr (32 bits)`, `windows 10` And I have tried all the version but I usually have the same error
The default headers are explicitly added by Netty when a request is prepared for sending. The main point of interest is here: ```java // io.netty.handler.codec.http.HttpHeaders public interface HttpHeaders extends Iterable<Map.Entry<String, String>> { HttpHeaders add(String name, Object value); // ... } ``` As you might know, Spring's `WebClient` uses Project Reactor and Netty under the hood for making web requests. When you create a `WebClient` instance and build a request with it, the headers do not appear immediately. However, once the request is about to be sent out (when Netty's `HttpClientOperations` comes into play), Netty adds these default headers (like HOST, Accept-Encoding, etc) even if none were explicitly set by you. Here's a look into part of `HttpClientOperations` from Netty on GitHub: ```java // io.netty.handler.codec.http.HttpClientOperations @Override protected void onOutboundSubscribe(Subscriber<? super ByteBuf> s) { if (!HttpRequestEncoder.encoderHeader(headers(), method(), uri())) { if (log.isDebugEnabled()) { log.debug(format(ctx.channel(), "Dropped {}"), this); } return; } //... } ``` The `HttpRequestEncoder.encoderHeader(...)` part is where the headers are prepared and added if they don't exist. You might take a look at the `encodeHeaders` method too for deeper insights. Here is the point-in-time in `HttpClientOperations` where headers are added: ```java // io.netty.handler.codec.http.HttpHeaders public interface HttpHeaders extends Iterable<Map.Entry<String, String>> { HttpHeaders add(String name, Object value); // ... } ``` Unfortunately, `WebClient` does not provide an out-of-the-box solution to prevent Netty from adding these headers. However, you can create a custom filter and add it to your `WebClient` to intentionally remove these headers each time a request is built: ```java WebClient.builder() .baseUrl("https://httpbin.org") .filter((clientRequest, next) -> { ClientRequest mutatedRequest = ClientRequest.from(clientRequest) .headers(httpHeaders -> { httpHeaders.remove("Host"); // remove other headers if needed }) .build(); return next.exchange(mutatedRequest); }) .build() .get() // continue with your code for .uri, etc. ``` This way, each time you build a request, the filter will remove the Host header (and others if you wish) before sending it off. Please note that this might not be the best practice as some servers might require the `Host` header or others for processing the request.
Creating a Google Login-In Extension for a personal project so I've set up funtionality that allows me to log in to the extension with my Google account and it works. I'm using an initial HTML file called "popup.html" to hold the logic of Google's Authentication by calling "popup.js" as the backend script, displaying a "Waiting for Log-in" message, and then setting that <div> attribute to display the contents of another HTML file called "authorized.html" after succesful sign-in by setting its contents as the innerHTML property of "popup.html". The issue is that "authorization.html" own script "authorized.js" will not print anything to either my console nor will it even throw an error on the console despite the other contents of "authorized.html" succefully being displayed. Only the relevant parts of my code are below but I'd like to know why I'm having this issue and how to circumvent it. Thank you popup.html: ``` <!DOCTYPE html> <html> <head> <title>Google OAuth Sign-In</title> <script src="popup.js"></script> </head> <body> <div id="Sign-In TempUI" class="content-body">Waiting for Google Sign-In</div > </body> </html> ``` popup.html: ``` console.log('popup.js loaded'); document.addEventListener('DOMContentLoaded', function () { const NewGUI = document.getElementById('Sign-In TempUI'); chrome.identity.getAuthToken({ interactive: true }, function (token) { if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError.message); return; } console.log('Token acquired:', token); loadAuthorizedUI(token); }); function loadAuthorizedUI(token) { console.log('Debug:', token); fetch('authorized.html') .then(response => response.text()) .then(html => { console.log('HTML content:', html); NewGUI.innerHTML = html; }) .catch(error => console.error('Error fetching or processing HTML:', error)); } }); ``` authorized.html: ``` <!-- Page Displayed after recieving token from OAuthetication. Should display GUI for Email handling --> <!DOCTYPE html> <html> <head> <title>Authorized UI</title> </head> <body> <h1>Welcome! You are now authorized.</h1> <ul id="emailList"> </ul> <script src="authorized.js"></script> <div>Hit end</div> </body> </html> ``` authorized.js: ``` //throw new Error('This is a test error from authorized.js'); console.log('authorized.js loaded'); ``` I'm using Chrome DevTool to dubug so before I was starting another document.addEventListener('DOMContentLoaded', function ()) and then trying to replace the contents of emailList after trying to get its element by Id, but it wont even open authorized.js. Console.log doesnt print anything and the exception doesnt actually display anything on the console. However when I move the authorized.js script to popup.html, it'll suddenly display albiet errors. My biggest confusion is that "<h1>Welcome! You are now authorized.<h1>" and "<div>Hit end</div>" will display on my GUI but the script wont even print, as if its skipping it
|python|tensorflow|
I'm using Premake to manage the build configuration of my project, which consists of two static libraries ("Engine" and "Game") and an executable ("Launcher"). But when I attempt to integrate/link GLFW into my Engine library, I'm encountering linking errors. I should mention I'm trying to link GLFW statically. I'm also using visual studio 2022 on a windows platform. 2>------ Build started: Project: Launcher, Configuration: Debug x64 ------ 2>LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library 2>LINK : warning LNK4217: symbol 'strncmp' defined in 'libucrtd.lib(strncmp.obj)' is imported by 'Engine.lib(init.obj)' in function '_glfwParseUriList' 2>LINK : warning LNK4286: symbol 'strncmp' defined in 'libucrtd.lib(strncmp.obj)' is imported by 'Engine.lib(input.obj)' 2>LINK : warning LNK4286: symbol 'strncmp' defined in 'libucrtd.lib(strncmp.obj)' is imported by 'Engine.lib(context.obj)' 2>LINK : warning LNK4286: symbol 'strncmp' defined in 'libucrtd.lib(strncmp.obj)' is imported by 'Engine.lib(egl_context.obj)' 2>LINK : warning LNK4217: symbol 'free' defined in 'libucrtd.lib(free.obj)' is imported by 'Engine.lib(init.obj)' in function 'defaultDeallocate' 2>LINK : warning LNK4217: symbol 'free' defined in 'libucrtd.lib(free.obj)' is imported by 'Engine.lib(null_init.obj)' in function '_glfwConnectNull' 2>LINK : warning LNK4217: symbol 'malloc' defined in 'libucrtd.lib(malloc.obj)' is imported by 'Engine.lib(init.obj)' in function 'defaultAllocate' 2>LINK : warning LNK4217: symbol 'strtol' defined in 'libucrtd.lib(strtox.obj)' is imported by 'Engine.lib(init.obj)' in function '_glfwParseUriList' 2>LINK : warning LNK4217: symbol '__stdio_common_vsprintf' defined in 'libucrtd.lib(output.obj)' is imported by 'Engine.lib(init.obj)' in function '_glfwInputError' 2>LINK : warning LNK4217: symbol '__stdio_common_vsprintf' defined in 'libucrtd.lib(output.obj)' is imported by 'Engine.lib(win32_joystick.obj)' in function '_glfwDetectJoystickConnectionWin32' 2>LINK : warning LNK4217: symbol 'strcspn' defined in 'libucrtd.lib(strcspn.obj)' is imported by 'Engine.lib(input.obj)' in function 'glfwUpdateGamepadMappings' 2>LINK : warning LNK4217: symbol 'strtoul' defined in 'libucrtd.lib(strtox.obj)' is imported by 'Engine.lib(input.obj)' in function 'parseMapping' 2>LINK : warning LNK4217: symbol 'qsort' defined in 'libucrtd.lib(qsort.obj)' is imported by 'Engine.lib(monitor.obj)' in function 'refreshVideoModes' 2>LINK : warning LNK4217: symbol 'qsort' defined in 'libucrtd.lib(qsort.obj)' is imported by 'Engine.lib(win32_joystick.obj)' in function 'deviceCallback' 2>Engine.lib(init.obj) : error LNK2019: unresolved external symbol __imp_strtok referenced in function _glfwParseUriList 2>Engine.lib(init.obj) : error LNK2019: unresolved external symbol __imp_realloc referenced in function defaultReallocate 2>Engine.lib(window.obj) : error LNK2019: unresolved external symbol __imp_strncpy referenced in function glfwWindowHintString 2>Engine.lib(input.obj) : error LNK2001: unresolved external symbol __imp_strncpy 2>Engine.lib(monitor.obj) : error LNK2001: unresolved external symbol __imp_strncpy 2>Engine.lib(win32_joystick.obj) : error LNK2001: unresolved external symbol __imp_strncpy 2>Engine.lib(input.obj) : error LNK2019: unresolved external symbol __imp_strspn referenced in function glfwUpdateGamepadMappings 2>Engine.lib(input.obj) : error LNK2019: unresolved external symbol __imp_fmaxf referenced in function glfwGetGamepadState 2>Engine.lib(input.obj) : error LNK2019: unresolved external symbol __imp_fminf referenced in function glfwGetGamepadState 2>Engine.lib(monitor.obj) : error LNK2001: unresolved external symbol __imp_fminf 2>Engine.lib(null_monitor.obj) : error LNK2001: unresolved external symbol __imp_fminf 2>Engine.lib(context.obj) : error LNK2019: unresolved external symbol __imp___stdio_common_vsscanf referenced in function sscanf 2>..\bin\Debug-windows-x86_64\Launcher\Launcher.exe : fatal error LNK1120: 7 unresolved externals 2>Done building project "Launcher.vcxproj" -- FAILED. This is my current premake script (premake 5): workspace "A_Seaside_Resort" configurations { "Debug", "Release" } architecture "x64" startproject "Launcher" outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" project "Engine" location "Engine" kind "StaticLib" language "C++" cppdialect "C++20" staticruntime "on" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "%{prj.name}/Source/**.h", "%{prj.name}/Source/**.hpp", "%{prj.name}/Source/**.cpp" } defines { "GLEW_STATIC" } includedirs { "ThirdParty/GLFW/include" } libdirs { "ThirdParty/GLFW/lib-vc2022" } links { "glfw3", "opengl32", "gdi32", -- For GLFW on Windows "user32", -- For GLFW on Windows "kernel32", -- For GLFW on Windows "ole32" -- For GLFW on Windows } filter "system:windows" systemversion "latest" filter "configurations:Debug" runtime "Debug" symbols "on" filter "configurations:Release" runtime "Release" optimize "on" project "Game" location "Game" kind "StaticLib" language "C++" cppdialect "C++20" staticruntime "On" --targetname ("%{prj.name}") targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "%{prj.name}/Source/**.h", "%{prj.name}/Source/**.hpp", "%{prj.name}/Source/**.cpp" } includedirs { "Engine/Source" } links { "Engine" } filter "system:windows" systemversion "latest" filter "configurations:Debug" defines "Debug" symbols "on" filter "configurations:Release" defines "Release" optimize "on" project "Launcher" location "Launcher" kind "ConsoleApp" language "C++" cppdialect "C++20" staticruntime "on" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "%{prj.name}/Source/**.h", "%{prj.name}/Source/**.hpp", "%{prj.name}/Source/**.cpp" } includedirs { "Engine/Source", "Game/Source" } links { "Engine", "Game" } filter "system:windows" systemversion "latest" filter "configurations:Debug" defines "Debug" symbols "on" filter "configurations:Release" defines "Release" optimize "on" I'm new to using Premake, so I'm not entirely sure what I'm doing wrong. I've noticed that some developers integrate GLFW directly as a project within their solution, but if possible I would like to avoid that since I'm planning on adding additional libraries in the future and want to avoid the bloat.
Linking GLFW with a static library using Premake
|c++|glfw|static-linking|premake|
I'm trying to simulate the CSMA/CD protocol using ns3 software for a course project. However, after installing ns3, I've checked the official documentation and asked the teaching assistant, but I couldn't find specific implementation details. I even saw some answers stating that ns3 does not support simulating collision detection and backoff logic. Is this true? If not, how can I implement the CSMA/CD protocol in ns3?
How to simulate CSMA/CD protocol in ns3?
|c++|networking|ns-3|
null
{"Voters":[{"Id":17562044,"DisplayName":"Sunderam Dubey"},{"Id":476,"DisplayName":"deceze"}],"SiteSpecificCloseReasonIds":[19]}
No, this is not possible. Quarto contains tools to generate PDF, but not to parse PDFs. The latter would be required to include PDFs the way you imagine, adjusted to the style of the document. The [pdfpages](https://www.ctan.org/pkg/pdfpages) package (of which you already mentioned the `\includepdf` command) is likely the closed you can get.
Bom dia pessoal, feliz Páscoa!! Estou fazendo um curso de JavaScript com o Gustavo Guanabara e estou tento problemas no resultado da function em um exercício. Alguém por favor poderia me ajudar a achar o erro? obs: Minha primeira vez aqui na plataforma. ``` <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="assets/main.css"> </head> <body> <header> <h1>Verificador de idade</h1> </header> <section> <div> <p> Ano de Nascimento: <input type="number" name="txtano" id="txtano"> </p> <p> Sexo: <input type="radio" name="radsex" id="mas" checked> <label for="masc">Masculino</label> <input type="radio" name="radsex" id="fem"> <label for="fem">Feminino</label> </p> <p> <input type="button" value="Verificar" onclick="verificar()"> </p> </div> <div id="res"></div> </section> <footer> <p> &copy; Todos os direitos reservados 2024 </p> </footer> <script src="assets/script.js"></script> </body> </html> function verificar() { let data = new Date() let anoAtual = data.getFullYear() let fAno = document.getElementsByName('txtano') let res = window.document.querySelector('div#res') if (fAno == 0 || fAno > anoAtual) { window.alert ('Verifique os dados e tente novamente!') } else { let fSex = window.document.getElementsByName( 'radsex' ) let idade = anoAtual - Number(fAno) res.innerHTML = `Idade calculada: ${idade}` } } ``` [enter image description here][1] [1]: https://i.stack.imgur.com/mDwb8.png
The problem is that it takes a long time to index web pages.؟
|google-maps|web|google-search-console|
null
Instances of classes that have private members cannot be appropriately proxied. See - https://lea.verou.me/blog/2023/04/private-fields-considered-harmful/ - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#no_private_property_forwarding
Three bugs that I can see, including some spotted in comments. ---- ``` MOV AH, 09H LEA AX, msg3 INT 21H ``` Looks like a typo for `LEA DX, msg3`. As it stands you will have a random value in AH (the high byte of the address of `msg3` and will be executing some random DOS function. That might be what crashes DosBox. Also, more efficient than `LEA` here (and in the other similar instances) would be `MOV DX, OFFSET msg3` which has the same effect and saves one byte. ---- ``` XOR AX, AX MOV DX, 10H DIV DX ``` First, you zeroed out `AX` thus discarding the total value you so carefully computed (remember, `AX` emcompasses both `AH` and `AL`). Second, `DIV r/m16` is a 32 by 16 bit division: it divides the 32-bit unsigned value in `DX:AX` by the value in `r/m16`, with the quotient placed in `AX` and the remainder in `DX`. So here you are dividing `100000H` by `10H`; the quotient is `10000h` which overflows 16 bits, and so you will get a divide overflow exception. This could also be the cause of the crash, though I seem to recall that real MS-DOS had a handler for the divide overflow interrupt that would print a message and terminate the program, without crashing the system. I'm not sure if DosBox provides that, however. Anyway, I think you probably meant ``` XOR AH, AH ; zero-extend AL into AX MOV DL, 10H DIV DL ``` to do a 16 by 8 bit divide of the number from `AL` (extended with zeros to produce a 16-bit value in `AX`) by `10H`, placing the quotient in `AL` and the remainder in `AH`. ---- ``` MOV AH, 02H MOV DL, Q INT 21H ``` You need to add `0` to the values `Q` and `R` to create printable ASCII characters for output.
Given this example... { "A-B": { "x": { "name": "x A-B" }, "y": { "level": 6 } }, "B-C": { "x": { "name": "x B-C" }, "y": { "level": 9 } }, "A-C": { "x": { "name": "x A-C" } } } Where "A", "B" and "C" are states and "x" and "y" are different dicts. "x" can have a "name" key with a string value amd "y" can have a "level" key with an integer value. Both "x" and "y" are optional. I've create the schemas for "x" and "y"... def X_Schema( Schema ): name = fields.String( required = True ) def Y_Schema( Schema ): level = fields.Integer( required = True ) I know I need to use some nesting but I can't work out how this is going to work when the top level "key" is not fixed. i.e. it can be "A-B", "A-C", "B-C" etc. "x" and "y" can only occur once within a top level value, both are optional. I'd like to do something like... def StateSchema( Schema ): ???? = fields.Dict( keys = < "x" or "y" >, values = <X_Schema or Y_Schema> ) Personally, I don't think this is possible using marshmallow. I do not control this input so I'm pretty much stuck not validating it if can't be done using marshmallow. I've got this far... class StateSchema( Schema ) a_b = fields.Dict( keys = fields.String(), values = fields.Nested( X_Schema() ), required = False, data_key = "A-B" ) b_c = fields.Dict( keys = fields.String(), values = fields.Nested( X_Schema() ), required = False, data_key = "B-C" ) but I feel this is sub-optimal as I need to create fields for all of the possible states.... :(
Switch to v3 :) v3 came up because v2 was relatively easy to hack with ia the method you mentioned, and generally weak. That's why it hasn't been, most likely, updated for new strategies of robots. When you do the switch, you'll be able to set the minimum trustworthiness threshold in reCAPTCHA v3 admin console.
null
null
null
null
First of all, your `useImage` hook is not doing anything except loading the image, then set a state. If this is only for demonstration purposes, that's fine, otherwise, you should look into what you are trying to achieve with that hook. Regarding the test, if you are using `jest` and `jsdom` to test. Then `jsdom` [only fire load events when they actually load something][1]. Meaning you must use a real image in the `src` AND change some jest configuration like this: In `package.json`, if you use jest.config.js, then please refer to the official doc for the equivalent. "jest": { "preset": "ts-jest", "testEnvironment": "jsdom", // we need this line "transform": { "node_modules/variables/.+\\.(j|t)sx?$": "ts-jest" }, "testEnvironmentOptions": { "resources": "usable" // we need this line }, "transformIgnorePatterns": [ "node_modules/(?!variables/.*)" ] }, You'll also need to install [canvas][2] npm i canvas Then your test is going to pass now. But, if you find this is a bit problematic to install a new dependency and change how the default test framework works, then you can [mock the Image object implementation][3] instead, personally, I would prefer this way: const LOAD_FAILURE_SRC = 'LOAD_FAILURE_SRC'; const LOAD_SUCCESS_SRC = 'LOAD_SUCCESS_SRC'; beforeAll(() => { Object.defineProperty(global.Image.prototype, 'src', { set(src) { if (src === LOAD_FAILURE_SRC) { setTimeout(() => this.onerror(new Error('mocked error'))); } else if (src === LOAD_SUCCESS_SRC) { setTimeout(() => this.onload()); } }, }); }); [1]: https://github.com/jsdom/jsdom/issues/1816#issuecomment-310106280 [2]: https://www.npmjs.com/package/canvas [3]: https://github.com/jsdom/jsdom/issues/1816#issuecomment-432496573
I've successfully installed Node.js and NPM on my machine, but I'm encountering an issue when trying to create a new React Native app. After entering the command in the terminal, nothing happens, despite having a stable internet connection. Can anyone provide guidance on how to troubleshoot and resolve this issue? Your assistance would be greatly appreciated, and sharing any insights could benefit others facing similar challenges. Thank you in advance! [![Terminal View](https://i.stack.imgur.com/DpA3L.png)](https://i.stack.imgur.com/DpA3L.png)
Are there any known issues with NPM or Node.js when creating a new app?
|npm|expo|node-modules|npm-install|
null
I am plotting histograms showing distributions of an angle `tau`. I used a random normal distribution as shown: import numpy as np N = 100000 tau = np.arccos(np.random.normal(-1, 1, N)) I got the error `"RuntimeWarning: invalid value encountered in arccos tau = np.arccos(np.random.normal(-1, 1, N))"`. This did not pop up with a uniform distribution. Why did this happened with the normal distribution?
Flutter CI CD Pipeline Using Github Actions. When running **xcodebuild -workspace Runner.xcworkspace -scheme Runner -configuration "Release-staging" DEVELOPMENT_TEAM=XXXXXXXX -sdk 'iphoneos' -destination 'generic/platform=iOS' -archivePath build-output/app.xcarchive clean archive CODE_SIGN_IDENTITY="Apple Development"** /Users/runner/work/AppName/AppName/ios/Pods/Pods.xcodeproj: error: No signing certificate "iOS Development" found: No "iOS Development" signing certificate matching team ID "XXXXXXXXX" with a private key was found. (in target 'firebase_core' from project 'Pods') /Users/runner/work/AppName/AppName/ios/Pods/Pods.xcodeproj: error: No signing certificate "iOS Development" found: No "iOS Development" signing certificate matching team ID "XXXXXXXX" with a private key was found. (in target 'flutter_phone_direct_caller' from project 'Pods') /Users/runner/work/AppName/AppName/ios/Pods/Pods.xcodeproj: error: No signing certificate "iOS Development" found: No "iOS Development" signing certificate matching team ID "XXXXXXX" with a private key was found. (in target 'device_info' from project 'Pods') . . . . (For all other 3rd party dependencies) . . ** ARCHIVE FAILED ** Error: Process completed with exit code 65. **Full Pipeline .yml** name: Deploy iOS to Firebase App Distribution on merge on: push: branches: - dev jobs: build-ios: runs-on: macos-latest defaults: run: working-directory: ios steps: - uses: actions/checkout@v3 - uses: subosito/flutter-action@v2 - name: Install Dependencies run: flutter packages get - name: Install the Apple certificate and provisioning profile env: BUILD_CERTIFICATE_BASE64: ${{ secrets.STAGING_BUILD_CERTIFICATE_BASE64 }} P12_PASSWORD: ${{ secrets.STAGING_P12_PASSWORD }} BUILD_PROVISION_PROFILE_BASE64: ${{ secrets.STAGING_BUILD_PROVISION_PROFILE_BASE64 }} KEYCHAIN_PASSWORD: ${{ secrets.STAGING_KEYCHAIN_PASSWORD }} run: | # create variables CERTIFICATE_PATH=$RUNNER_TEMP/build_certificate.p12 PP_PATH=$RUNNER_TEMP/build_pp.mobileprovision KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db # import certificate and provisioning profile from secrets echo -n "$BUILD_CERTIFICATE_BASE64" | base64 --decode --output $CERTIFICATE_PATH echo -n "$BUILD_PROVISION_PROFILE_BASE64" | base64 --decode --output $PP_PATH # create temporary keychain security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH security set-keychain-settings -lut 21600 $KEYCHAIN_PATH security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH # import certificate to keychain security import $CERTIFICATE_PATH -P "$P12_PASSWORD" -A -t cert -f pkcs12 -k $KEYCHAIN_PATH security list-keychain -d user -s $KEYCHAIN_PATH # apply provisioning profile mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles cp $PP_PATH ~/Library/MobileDevice/Provisioning\ Profiles - name: Build run: flutter build ios --release --no-codesign - name: Build resolve Swift dependencies run: xcodebuild -resolvePackageDependencies -workspace Runner.xcworkspace -scheme Runner -configuration "Release" - name: Build xArchive run: | xcodebuild -workspace Runner.xcworkspace -scheme Runner -configuration "Release-staging" DEVELOPMENT_TEAM=XXXXXXXXXX -sdk 'iphoneos' -destination 'generic/platform=iOS' -archivePath build-output/app.xcarchive clean archive CODE_SIGN_IDENTITY="Apple Development" - name: Export ipa run: | xcodebuild -exportArchive -archivePath build-output/app.xcarchive -exportPath build-output/ios -exportOptionsPlist ios/ExportOption.plist - name: Upload artifact uses: actions/upload-artifact@v2 with: name: App.ipa path: /Users/runner/work/MyMobileApp/MyMobileApp/app/build-output/ios/MyMobileApp.ipa retention-days: 1 if-no-files-found: error - name: Clean up keychain and provisioning profile if: ${{ always() }} run: | security delete-keychain $RUNNER_TEMP/app-signing.keychain-db rm ~/Library/MobileDevice/Provisioning\ Profiles/build_pp.mobileprovision distribute-ios: needs: build-ios runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/download-artifact@v2 with: name: App.ipa - name: Firebase App Distribution uses: wzieba/Firebase-Distribution-Github-Action@v1.3.2 with: appId: ${{secrets.IOS_FIREBASE_APP_ID_STAGING}} token: ${{secrets.FIREBASE_TOKEN}} groups: internal-testing-ios file: MyMobileApp.ipa
While Running Github Actions Pipeline: No Signing Certificate "iOS Development" found: No "iOS Development" signing certificate matching team ID
|ios|flutter|github-actions|cicd|firebase-app-distribution|
null
I permant use this javascript code for webrtc (aiortc) communication: ``` var port = 8080 var ip_address = "192.168.1.10" var main_pc = { "name":"", "surname":"", "pc":null, "dc":null, "uid":null, "local_audio":null, "local_video":null, "remote_audio":null, "remote_video":null }; var peer_connections = []; var closing = false var controller = null; var signal; var stop_time_out = null; function start(name,surname) { $("#control_call_button").addClass("d-none"); $("#stop_call_button").removeClass("d-none"); $("#signal-audio").trigger("play"); main_pc = createPeerConnection(main_pc); main_pc["name"] = name; main_pc["surname"] = surname; main_pc["dc"] = main_pc["pc"].createDataChannel('chat', {"ordered": true}); main_pc["dc"].onmessage = function(evt) { data = JSON.parse(evt.data); if(data["type"] == "closing"){ if (main_pc["uid"] == "uid"){ stop_peer_connection(); }else{ //stop_client_peer_connection(data["uid"]); } } if (data["type"] == "uid"){ uid = data["uid"]; main_pc["uid"] = uid; console.log(main_pc); } if (data["type"] == "new-client"){ var uid = data["uid"]; var client_name = data["name"]; var client_surname = data["surname"]; console.log("New client:"); console.log(uid); console.log(client_name); console.log(client_surname); //start_client(uid,client_name,client_surname); } }; main_pc["pc"].onconnectionstatechange = (event) => { let newCS = main_pc["pc"].connectionState; if (newCS == "disconnected" || newCS == "failed" || newCS == "closed") { stop_time_out = setTimeout(stop_with_time_out, 7000); }else{ if (stop_time_out != null){ clearTimeout(stop_time_out); stop_time_out = null; } } } main_pc["pc"].onclose = function() { closing = true; stop_peer_connection(); // close data channel if (main_pc["dc"]) { main_pc["dc"].close(); } // close local audio / video main_pc["pc"].getSenders().forEach(function(sender) { sender.track.stop(); }); // close transceivers if (main_pc["pc"].getTransceivers) { main_pc["pc"].getTransceivers().forEach(function(transceiver) { if (transceiver.stop) { transceiver.stop(); } }); } main_pc["pc"] = null; $("#control_call_button").removeClass("d-none"); $("#stop_call_button").addClass("d-none"); }; constraints = {audio:true,video:true}; navigator.mediaDevices.getUserMedia(constraints).then(function(stream) { stream.getTracks().forEach(function(track) { try { main_pc["pc"].addTrack(track, stream); if (track.kind == "video"){ //correct main_pc["local_video"] = stream; document.getElementById('client-video-1').srcObject = stream; }else{ main_pc["local_audio"] = stream; } } catch(e){ } }); return negotiate(); }, function(err) { alert('Could not acquire media: ' + err); }); } function createPeerConnection(pc) { var config = { sdpSemantics: 'unified-plan' }; config.iceServers = [{ urls: ['stun:stun.l.google.com:19302'] }]; pc["pc"] = new RTCPeerConnection(config); // connect audio pc["pc"].addEventListener('track', function(evt) { if (evt.track.kind == 'audio'){ $("#signal-audio").trigger("pause"); $("#signal-audio").currentTime = 0; // Reset time document.getElementById('server-audio').srcObject = evt.streams[0]; $("#control_call_button").addClass("d-none") $("#stop_call_button").removeClass("d-none") pc["remote_audio"] = evt.streams[0]; }else if (evt.track.kind == 'video'){ document.getElementById('server-video').srcObject = evt.streams[0]; pc["remote_video"] = evt.streams[0]; } }); return pc; } function negotiate() { return main_pc["pc"].createOffer({"offerToReceiveAudio":true,"offerToReceiveVideo":true}).then(function(offer) { return main_pc["pc"].setLocalDescription(offer); }).then(function() { // wait for ICE gathering to complete return new Promise(function(resolve) { if (main_pc["pc"].iceGatheringState === 'complete') { resolve(); } else { function checkState() { if (main_pc["pc"].iceGatheringState === 'complete') { main_pc["pc"].removeEventListener('icegatheringstatechange', checkState); resolve(); } } main_pc["pc"].addEventListener('icegatheringstatechange', checkState); } }); }).then(function() { var offer = main_pc["pc"].localDescription; controller = new AbortController(); signal = controller.signal; try{ promise = timeoutPromise(60000, fetch('http://'+ip_address+':'+port+'/offer', { body: JSON.stringify({ sdp: offer.sdp, type: offer.type, "name":name, "surname":surname }), headers: { 'Content-Type': 'application/json' }, method: 'POST', signal })); return promise; }catch (error){ console.log(error); stop_peer_connection(); } }).then(function(response) { if (response.ok){ return response.json(); }else{ stop_peer_connection(); } }).then(function(answer) { console.log(answer); if (answer.sdp == "" && answer.type == ""){ stop_peer_connection(); return null; }else{ return main_pc["pc"].setRemoteDescription(answer); } }).catch(function(e) { console.log(e); stop_peer_connection(); return null; }); } function timeoutPromise(ms, promise) { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => { reject(new Error("promise timeout")) }, ms); promise.then( (res) => { clearTimeout(timeoutId); resolve(res); }, (err) => { clearTimeout(timeoutId); reject(err); } ); }) } function stop_peer_connection(dc_message=true) { $("#signal-audio").trigger("pause"); $("#signal-audio").currentTime = 0; // Reset time // send disconnect message because iceconnectionstate slow to go in failed or in closed state try{ if (main_pc["dc"].readyState == "open"){ if (dc_message){ main_pc["dc"].send(JSON.stringify({"type":"disconnected"})); } } }catch (e){ } try{ if (main_pc["local_audio"] != null){ main_pc["local_audio"].stop(); main_pc["local_video"].stop(); main_pc["local_audio"] = null; main_pc["local_video"] = null; //main_pc["remote_audio"].stop(); //main_pc["remote_video"].stop(); //main_pc["remote_audio"] = null; //main_pc["remote_video"] = null; } } catch (e){ } document.getElementById('client-video-1').srcObject = null; document.getElementById('server-video').srcObject = null; document.getElementById('server-audio').srcObject = null; document.getElementById('client-audio-2').srcObject = null; document.getElementById('client-video-2').srcObject = null; document.getElementById('client-audio-3').srcObject = null; document.getElementById('client-video-3').srcObject = null; try{ if (controller != null){ controller.abort(); } if (main_pc["dc"].readyState != "open"){ main_pc["pc"].close(); } }catch (e){ } $("#control_call_button").removeClass("d-none") $("#stop_call_button").addClass("d-none") } function stop_with_time_out(){ stop_peer_connection(false); stop_time_out = null; } $(document).ready(function(){ $("#control_call_button").on( "click", function() { name = $("#name").val(); surname = $("#surname").val(); $("#me-name").html(name+" "+surname) closing = false; controller = null; start(name,surname); }); $("#stop_call_button").on( "click", function() { closing = true; stop_peer_connection(); }); }) ``` I just want when the connection is closed the camera led will also close. Is there something i can do about?
WebRTC close navigator.getUserMedia correctly
|javascript|webrtc|getusermedia|
I am trying to download file on click of notification button but when application is in background then api call is not working. Notification Code: func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo as! [String: AnyObject] switch response.actionIdentifier { case "DownloadDutyPlanAction": print("Download tap") downloadDutyPlanFromNotification(fetchCompletionHandler: nil) completionHandler() case "CancelAction": print("Cancel tap") default: completionHandler() } } func downloadFromNotification(fetchCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)?) { let downloadPDFOperation = PDFDownloadOperation.init() { result in switch result { case .success: DispatchQueue.main.async { } completionHandler?(UIBackgroundFetchResult.newData) case .failure: completionHandler?(UIBackgroundFetchResult.newData) } } QueueManager.shared.enqueueNotification(downloadPDFOperation) } Network class: private var task: URLSessionTask? private var session = URLSession.init(configuration: URLSessionConfiguration.default, delegate: NSURLSessionPinningDelegate(), delegateQueue: nil) func request(forDownloadUrl route: EndPoint, completion: @escaping NetworkDownloadRouterCompletion) { do { let request = try self.buildRequest(from: route) task = session.downloadTask(with: request) { localURL, response, error in if let tempLocation = localURL { completion(response, error, tempLocation) } else { completion(response, error, nil) } } } catch { completion(nil, error, nil) } self.task?.resume() }
I'm currently working on optimizing a kernel, and one of the most time-consuming loops, despite optimization efforts, still accounts for 80% of the benchmark's execution time. The loop's performance bottleneck stems from its memory-bound nature, primarily due to an indirect memory access pattern that hampers prefetching. I'm seeking guidance on how to hint to the compiler to perform indirect prefetching without compromising other optimizations. Here's the relevant snippet of the source code: ``` for (j = 0; j < lastrow - firstrow + 1; j++) { sum = 0.0; for (k = rowstr[j]; k < rowstr[j+1]; k++) { sum = sum + a[k] * p[colidx[k]]; } q[j] = sum; } ``` The bottleneck arises from the indirect memory access pattern, particularly in accessing the `p` array at the `colidx[k]` position. After compiling with the Intel compiler using the following flags: `-O3 -xhost -mcmodel=medium -qopt-prefetch=5 -xCOMMON-AVX512` It seems the compiler unrolled the loop by 8-factor, vectorized and added some prefetch instructions due to high `qopt-prefetch` level. ``` Block 1: vmovupdy (%r11,%r10,4), %ymm15 kxnorw %k0, %k0, %k1 vpxord %zmm16, %zmm16, %zmm16 vgatherdpdq (%r9,%ymm15,8), %k1, %zmm16 vfmadd231pdz (%rbx,%r10,8), %zmm16, %zmm14 prefetcht0z 0x900(%rbx,%r10,8) prefetcht0z 0x480(%r11,%r10,4) add $0x8, %r10 cmp %rsi, %r10 jbe 0x403370 <Block 1> ``` I've experimented with hints and tried using the volatile keyword, but it seems like I'm forced to choose between vectorization and prefetching `p[colidx[k+PREFETCH_FACTOR]]`. However, I believe it's possible to leverage both for optimal performance. Would appreciate any insights or suggestions on how to achieve this balance. Thank you!
I'm working on a Symfony project where I need to generate PDF files from HTML templates that include a map element. However, I'm having trouble centering the map element on the PDF without using any specific PDF generation tools or libraries. I have a Twig template called carte.html.twig that contains the map element. I want to position the map element in the center of the PDF page. I've tried adjusting the CSS styles within the template, but the map element doesn't appear centered on the generated PDF. Here's a simplified snippet from my carte.html.twig template: ``` <!DOCTYPE html> <html> <head> <style> /* CSS styles for the map element */ #map { /* Styles for the map */ } </style> </head> <body> <div id="map"> <!-- Map content goes here --> </div> </body> </html> ``` (https://i.stack.imgur.com/mE6fU.jpg) I'm seeking guidance on how to properly center the map element on the PDF generated from this Twig template without relying on any specific PDF generation tools or libraries. Are there any alternative approaches or techniques that I can use to achieve this? Any help or suggestions would be greatly appreciated. Thank you!
Centering a map element on a PDF generated from a Twig template in Symfony
|pdf|twig|
null
I handle anchor problem by this way without jQuery: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> let aWithHref = document.querySelectorAll('a[href*="#"]'); aWithHref.forEach(function(el) { el.addEventListener("click", function(e) { e.preventDefault(); if (el.hash) window.scrollTo({ top: document.querySelector(el.hash).offsetTop }); }) }); <!-- end snippet -->
Suppose A is a symmetric matrix whose SVD is A= USV^T, and let B = U\sqrt{S}V^T, then B^2 should be equal to A. But when I implemented it using tensorflow, B^2 and A does not match. Highly appreciated if you could give some advice!
Matrix reconstruction by SVD in tensorflow
|tensorflow|matrix|svd|symmetric|matrix-decomposition|
null
It is expected that your code throws an error. [As indicated in the "state" property of StateNotifier][1] it is `@protected` and `@visibleForTesting`, which implies that it can only be accessed from child classes and test. As recommended by the Riverpod documentation, if you want to reactively get a provided value, i.e. rebuild you widgets on changes of the provider, you shall use "watch" instead of "read". ```dart final value = ref.watch(myCustomStateProvider); ``` [1]: https://pub.dev/documentation/state_notifier/latest/state_notifier/StateNotifier/state.html
I am busy with creating a REST API where you can load company details and then load products for each company each with their own enpoint POST /company-details POST /products Company details have a request body companyName uniqueCode description contact location Products has a request body uniqueCpyCode productName skuNo Each one will create a record with an auto generated id in a MySQL db. Then I also have a delete endpoint to delete products ( i also have one for companies) DELETE /products/{id} One of the issues i have, i want users to delete all products for a company, but would like to know what is the best practice for mass deletions in my use case. I am thinking of having an endpoint DELETE /products/{uniqueCpyCode} I.e. delete products where cpyCode = request id. But i want to know is that best practice to mass delete resources like that or do i need an endpoint where i need to pass all ids although the number of products can potentially be close to a 1000 products. Or is it better to only have the one delete endpoint and let the user call it multiple times. Then another question i have, what if you want to delete the whole company. What is in general the better approach? 1) Call both Delete enspoints. DELETE /products DELETE /company 2) the user only call DELETE /company Which internally also call the DELETE /products enpoint.
So I am using the Vuetify 2 VCalendar and I was wonder if it would be possible to exclude the events from show in previous and next months in the view, so this is what I am talking about: [enter image description here][1] Currently, I am viewing "March 2024", but I am seeing "April 2024" events as shown in the screenshot. This is the vcalendar code call: ```Javascript <v-calendar ref="calendar" v-model="focus" :type="type" :events="shifts" event-color="#f1f3f4" event-text-color="#333" :event-margin-bottom="5" :event-height="155" :events-more="false" :show-week="false" @click:event="handleClickEvent" @click:date="!isDateBeforeToday($event) && isLoggedIn ? prepareAndOpenShiftCreationDialog($event) : null" @click:day="!isDateBeforeToday($event) && isLoggedIn ? prepareAndOpenShiftCreationDialog($event) : null" @change="loadAndUpdateShifts" > <template v-slot:event="{ event }"> <calendar-day :event="event" :is-logged-in="isLoggedIn"></calendar-day> </template> </v-calendar> ``` I am not sure if there is an appropriate prop or anything, but I would love to know. [1]: https://i.stack.imgur.com/CWq5s.png
Vuetify Calendar exclude events that are in the next and previous months from view
|vuejs2|vuetify.js|
### Summary There is a difference between `any` in type parameter and `any` in regular function parameter. Your case is the former one for generics. So you need to instantiate `T` first when assigning it to the concrete variables Ref. https://stackoverflow.com/questions/71628061/difference-between-any-interface-as-constraint-vs-type-of-argument ### In detail It's because in `GetAllProducts`, type `T` is not decided yet. So it is impossible to assign `[]models.Products` to `T`. ```golang func (db *DbConnection[T]) GetAllProducts() { var re []models.Products re, _ = db.GetAll() } ``` But you can assign `models.Products` to `T` if `T` is decided as `models.Products`, like this. ```golang db := DbConnection[models.Products]{} var re []models.Products re, _ = db.GetAll() ``` I reproduce your problem in the simplified version(https://go.dev/play/p/GHkDThFLOKG). You can find the same error `GetAllProducts()` but in the main code, it works.
I used a combination of `REDUCE` and `SEQUENCE` to iterate through each date column. =LET( data;L4#; dateRow;DATE(YEAR(ParamStartDate);SEQUENCE(1;DATEDIF(ParamStartDate;ParamEndDate;"M")+1;MONTH(ParamStartDate);1);1); headers;HSTACK("";dateRow); date;dateRow; res;INDEX(data;;1); comp;INDEX(data;;2); q;INDEX(data;;3); lab;UNIQUE(res); cost;q*fxCompCost(comp;date); reducer;REDUCE("";SEQUENCE(COLUMNS(date));LAMBDA(acc;curr;HSTACK(acc;MAP(lab;LAMBDA(a; SUMPRODUCT((res=a)*CHOOSECOLS(cost;curr))))))); result;VSTACK(headers;HSTACK(lab;DROP(reducer;;1))); result ) Names added to the worksheet: ParamStartDate: `Q2` ParamEndDate: `Q3` Final: [![enter image description here][1]][1] If someone comes up with a better solution even to process the BOM please post it. Hope this helps somebody else. [1]: https://i.stack.imgur.com/ks1bj.png
I am plotting some lines with Seaborn: ```python import matplotlib.pyplot as plt import seaborn as sns import pandas as pd # dfs: dict[str, DataFrame] fig, ax = plt.subplots() for label, df in dfs.items(): sns.lineplot( data=df, x="Time step", y="Loss", errorbar="sd", label=label, ax=ax, ) ax.set(xscale='log', yscale='log') ``` The result looks like [this](https://i.stack.imgur.com/FanHR.png). Note the clipped negative values in the `effector_final_velocity` curve, since the standard deviation of the loss between runs is larger than its mean, in this case. However, if `ax.set(xscale='log', yscale='log')` is called *before* the looped calls to `sns.lineplot`, the result looks like [this](https://i.stack.imgur.com/JVGG4.png). I'm not sure where the unclipped values are arising. Looking at the source of `seaborn.relational`: at the end of `lineplot`, the `plot` method of a `_LinePlotter` instance is called. It plots the error bands by passing the already-computed standard deviation bounds to `ax.fill_between`. Inspecting the values of these bounds right before they are passed to `ax.fill_between`, the negative values (which would be clipped) are still present. Thus I had assumed that the "unclipping" behaviour must be something matplotlib is doing during the call to `ax.fill_between`, since `_LinePlotter.plot` appears to do no other relevant post-transformations of any data before it returns, and `lineplot` returns immediately. However, consider a small example that calls `fill_between` where some of the lower bounds are negative: ```python import numpy as np fig, ax = plt.subplots(1, 1, figsize=(5, 5)) np.random.seed(5678) ax.fill_between( np.arange(10), np.random.random((10,)) - 0.2, np.random.random((10,)) + 0.75, ) ax.hlines(0, 0, 10, color='black', linestyle='--') ax.set_yscale('log') ``` Then it makes no difference if `ax.set_yscale('log')` is called before `ax.fill_between`; in both cases the result is [this](https://i.stack.imgur.com/ctRUi.png). I've spent some time searching for answers about this in the Seaborn and matplotlib documentation, and looked for answers on SA and elsewhere, but I haven't found any information about what is going on here.
{"OriginalQuestionIds":[12004603],"Voters":[{"Id":5389997,"DisplayName":"Shadow","BindingReason":{"GoldTagBadge":"mysql"}}]}
Given the following C program (MSVC does not optimize away the "work" for me, for other compilers you may need to add an `asm` statement): ```c #include <inttypes.h> #include <stdlib.h> #define SIZE 10000 typedef struct { int32_t a, b, c; } Struct; void do_work(Struct* data) { int32_t* a = malloc(sizeof(int32_t) * SIZE), * b = malloc(sizeof(int32_t) * SIZE), * c = malloc(sizeof(int32_t) * SIZE); int32_t* a_ptr = a, * b_ptr = b, * c_ptr = c; for (size_t i = 0; i < SIZE; i++, a_ptr++, b_ptr++, c_ptr++, data++) { *a_ptr = data->a; *b_ptr = data->b; *c_ptr = data->c; } free(a); free(b); free(c); } int main() { Struct* data = malloc(sizeof(Struct) * SIZE); for (size_t i = 0; i < SIZE; i++) { data[i].a = i; data[i].b = i; data[i].c = i; } for (int i = 0; i < 500000; i++) { do_work(data); } free(data); } ``` (I have a similar program in Rust with the same conclusions). Intel VTune reports that this program is 63.1% memory bound, and 52.4% store bound, with store latency of 26%. It recommends to search for false sharing, but I fail to see how there could be false sharing here. There is no concurrency, all data is owned by one core, the access patterns should be easily predicted and prefetched. I don't see why the CPU needs to stall on the stores here. I thought that maybe the low and high bits of the addresses of the three allocations are the same and that causes them to be mapped to the same cache lines, but I remember reading that modern CPUs don't just drop some bits to assign a cache line but do more complex calculations. Another thought was that maybe after the allocations are freed the CPU is still busy flushing the stores, and in the next run they are assigned the same address (or a close one) by the allocator and that brings problems for the CPU as it has to wait before storing new data. So I tried to not free the allocations, but that caused the code to be much slower. I'm on Windows 11, laptop Intel Core i9-13900HX, 32 logical cores, 8 Performance Cores and 16 Efficient Cores.
In your case the find command is replaced with `"./? ./*"`. So the loop iterates only once with `f="./? ./?"`. In `echo "$f"` `$f` is expanded (parameter expansion) and replaced with the value of variable `f`. Because of the double quotes the result is considered as a word and printed without further expansion. And you see `./? ./*`. In `echo $f`, `$f` is also expanded and replaced with the value of `f` but the expansion continues with the pathname expansion (there are several other expansions between parameter expansion and pathname expansion but they have no effect here). Pathname expansion replaces `./?` with all files in current directory with single character names (in your case `./?` and `./*`) and `./*` is replaced with all files in current directory (in your case `./?` and `./*`). So, finally what is echoed is `./? ./* ./? ./*`.
``` mpg['grade'] = np.where(mpg['total'] >= 30, 'A', np.where(mpg['total'] >= 20, 'B', 'C')) ``` code 1) ``` count_grade = mpg['grade'].value_counts() count_grade.plot.bar(rot=0) plt.show() ``` code 2) ``` count_grade = mpg['grade'].value_counts().sort_index() # method chaining count_grade.plot.bar(rot=0) plt.show() ``` reference) count_grade -> 'A' : 10, 'B' : 118, 'C' : 106 **(in VSCode)** The execution result is different with and without the code 1). When I only run code 2) without code 1), A is more than 120 instead of 10 (in graph) [enter image description here](https://i.stack.imgur.com/JRHEp.png) However, when the two codes are executed together, the result is normally output as a result of only 'A', 'B', and 'C' being sorted. [enter image description here](https://i.stack.imgur.com/sxG6B.png) **(in Colab)** ``` mpg['grade'] = np.where(mpg['total'] >= 30, 'A', np.where(mpg['total'] >=20, 'B', 'C')) count_grade = mpg['grade'].value_counts().sort_index() print(count_grade) count_grade.plot.bar(rot=0) ``` When I put this code in one block and run it, the results are output strangely. [enter image description here](https://i.stack.imgur.com/KLC1Z.png) However, running the last line separately solves the problem [enter image description here](https://i.stack.imgur.com/IMFDI.png) I'd like to know what the problem is. please help me expecting : [enter image description here](https://i.stack.imgur.com/7u58B.png) but my result : [enter image description here](https://i.stack.imgur.com/V2bK7.png)
python pandas plot.bar something wrong
|python|pandas|dataframe|data-science|bar-chart|
null