text
string
meta
dict
Q: Get a boolean of a map I have a private final Map<Long, Boolean> rpenabled = new HashMap<>(); and did this so it sets it to true when the bot is online or got added to a server: public void onGuildReady(@NotNull GuildReadyEvent event) { rpenabled.get(event.getGuild().getIdLong()); rpenabled.get(event.getGuild().getIdLong()); rpenabled.put(event.getGuild().getIdLong(), true); gifenabled.put(event.getGuild().getIdLong(), false); } after that i wanted to use the map in an onMessageReceivedEvent and tried that with if (rpenabled.values().contains(true)) { rpenabled.put(event.getGuild().getIdLong(), false); event.getChannel().sendMessage("<:relationships_true:1075825708355555578> The `Roleplay Commands` module has successfully been **disabled**.").queue(); } and if (rpenabled.containsKey(true)) { rpenabled.put(event.getGuild().getIdLong(), false); event.getChannel().sendMessage("<:relationships_true:1075825708355555578> The `Roleplay Commands` module has successfully been **disabled**.").queue(); } after I implemented the maps with public void onMessageReceived(@NotNull MessageReceivedEvent event) { rpenabled.get(event.getGuild().getIdLong()); gifenabled.get(event.getGuild().getIdLong()); It's not working properly though. Does anyone know why and how I can fix that? A: rpenabled.containsKey(true) will always return false because the keys in your map are Long. And rpenabled.values().contains(true) will return true if any of your map entries has a true value. You probably want to query the map with rpenabled.get(event.getGuild().getIdLong()) which will return the boolean value associated with the id of the events guild. Basically a Map<Long, Boolean> is not that different from a Map<Long, Int>: you can use put(key, value) to store a value into the map and you use get(key) to retrieve the value associated with a key. The only distinction is the type of the value. Additional note: I don't understand what you want to achieve with rpenabled.get(event.getGuild().getIdLong()); gifenabled.get(event.getGuild().getIdLong()); in the onMessageReceived() method or with the repeated rpenabled.get(event.getGuild().getIdLong()); rpenabled.get(event.getGuild().getIdLong()); in the onGuildReady() method. Those statements access the map but throw away the result.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: how to uncheck checkbox that has specific dynamic value in javascript I have many checkboxes that when user checks one of them, it makes a span with ajax with 'tag' attribiute . I want that when a user click in this spans again, unchecks the checked checkbox, but when I put 't' var in front of value its not working, can anybody help me? $(document).on('click', '.clear-tags', function() { var t = $(this).attr('tag'); $(":checkbox[value=t]").prop("checked", "false"); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="tags-res"> <span class="clear-tags" tag="wb=38"></span> <span class="clear-tags" tag="attr=33|998"></span> </div> A: You are not using t as a variable. Also you need to quote the value of the attribute to use in a selector when it has special characters in the selector. You may even have to escape some characters using CSS-Escape Here I toggle the checkbox on click of the span and quote it using template literals $(document).on('click', '.clear-tags', function() { const t = $(this).attr('tag'); const $chk = $(`:checkbox[value="${t}"]`); $chk.prop("checked", !$chk.prop("checked")); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="tags-res"> <span class="clear-tags" tag="wb=38">wb=38</span> <span class="clear-tags" tag="attr=33|998">attr=33|998</span> </div> <input type="checkbox" value="wb=38" /> <input type="checkbox" value="attr=33|998" /> A: You are using t as a string. You have to concatenate it instead and use as a variable. $(document).on('click', '.clear-tags', function() { var t = $(this).attr('tag'); $(`:checkbox[value="${t}"]`).prop("checked", "false"); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="tags-res"> <span class="clear-tags" tag="wb=38"></span> <span class="clear-tags" tag="attr=33|998"></span> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/75635520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to access phpmyadmin & mysql db in it enter image description here I am unable access my db in phpmyadmin , so i tried various tricks and i lost access to phpmyadmin as well. pls someone help me with this.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Awaiting a non-async function in python I was looking at some python tutorial for asyncio package. A paradigmatic example is the following: import asyncio async def first_function(): print("Before") await asyncio.sleep(1) print("After") async def second_function(): print("Hello") async def main(): await asyncio.gather(first_function(), second_function()) if __name__ == "__main__": asyncio.run(main()) Even in more complex examples, the innermost async function one is awaiting is either asyncio.sleep or some function coming from some "async library". But how are these function made of in terms of non-async functions? To me more concrete: suppose I have a non-async function coming from an external library whose execution time is quite long long_function. (This function do not contain any await, it may be written in another language, for example). How can I write an async function wrapper out of it (maybe with a future) so that I can write import asyncio async def long_function_wrapper(): ... #something with long_function() ... async def first_function(): print("Before") await long_functin_wrapper() print("After") async def second_function(): print("Hello") async def main(): await asyncio.gather(waiting_function(), short_function()) if __name__ == "__main__": asyncio.run(main()) and the behavior is the same as in the former example? (i.e. the order of the output is the same) A: All asynchronous primitives (asyncio.sleep, aiohttp.get, etc.) are based on low level concurrency primitives usually provided by the operating system and thus are generally not made of other nested async function calls. Those methods rely on threads, locks (mutexes), OS timers, network port listening, etc. In a nutshell, the OS notifies your program when the the task is done. This answer could also be relevant. There are numerous ways to create an async function, the most obvious one being to compose other async functions. If the function you want to make async is IO-bound (network, file reading, sleep, etc.), you can just wrap in in asyncio.to_thread which will run it in a separate thread: import asyncio import requests def io_bound_task(): return requests.get("https://some/url.com") async def main(): return await asyncio.to_thread(io_bound_task) if __name__ == "__main__": asyncio.run(main()) If your task is CPU-bound (heavy computations), then you will want to offload it to a thread pool (for GIL-releasing tasks) or process pool (for other tasks): import asyncio from concurrent.futures import ProcessPoolExecutor from math import sqrt def cpu_bound_task(): result = 0 for _ in range(100_000_000): result = sqrt(result + 1) return result async def main(): loop = asyncio.get_running_loop() with ProcessPoolExecutor() as p: return await loop.run_in_executor(p, cpu_bound_task) if __name__ == "__main__": asyncio.run(main()) A: If you are interested in the actual concepts behind the async/await syntax, I'd refer you to PEP 492. To understand this more deeply, you should familiarize yourself with the ideas behind coroutines and - underlying that - iterators. Lastly, you should understand the purpose of the event loop (and schedulers more broadly) and how that ties into iterators/generators. It is technically possible to deconstruct existing "regular" functions and turn them into coroutines, but it is not at all trivial. Generally speaking, since the event loop runs in a single thread, unless your long_function is asynchronous (i.e. yields control back to the scheduler at some point), executing it in an async context will simply block the event loop until it is finished. There are third-party libraries that attempt to do what you describe, i.e. "async-ify" non-async functions. I cannot speak to how well this works in practice and what limitations those have. If you have no control over that long_function, it is non-async, and you want it to execute concurrently with something else, you might be better off just running it in a separate thread or process (depending on what it does). The distinctions between these three built-in concurrency options in Python have been discussed at length on this site and elsewhere. Here is a sample: multiprocessing vs multithreading vs asyncio
{ "language": "en", "url": "https://stackoverflow.com/questions/75635522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Text invisible after setting Template in WPF TextBox Style I Have a WPF Text Box , that works Normal when I override its Template directly in the window or user Control, but when I use a Style for it in a resource dictionary all properties work fine but when I set the template in the style , the text becomes invisible. Here is the Style <Style x:Key="InputTextBoxes" TargetType="TextBox"> <Setter Property="IsEnabled" Value="True"/> <Setter Property="Foreground" Value="{StaticResource foregroundcolor1}"/> <Setter Property="Background" Value="{StaticResource foregroundcolor3}"/> <Setter Property="FontSize" Value="16"/> <Setter Property="FontWeight" Value="SemiBold"/> <Setter Property="HorizontalContentAlignment" Value="Left"/> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Cursor" Value="Hand"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="OverridesDefaultStyle" Value="True"/> <!-- Here Comes the Issue--> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBox}"> <Border Name="Border" CornerRadius="9" Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding Foreground}"> <ContentPresenter/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> Here is the Implementation of the style in the Text box <TextBox Grid.Row="0" Grid.Column="1" Name="RevokeUserNameBox" Margin="6" Style="{StaticResource InputTextBoxes}" Text="{Binding RevokeAdminModel.UserName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> I tried adding ContentPresenter and removing it, but still no success. I even had some time chatting with ChatGPT with no Luck. A: After Some Search I found This Answer on another Question https://stackoverflow.com/a/63362942/13176802 The Trick was that I must set <ScrollViewer Margin="0" x:Name="PART_ContentHost" /> Inside the Border , as this is what is responsible for showing the text, as I understood from this https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/textbox-styles-and-templates?view=netframeworkdesktop-4.8 the Final Style should be like this <Style x:Key="InputTextBoxes" TargetType="TextBox"> <Setter Property="IsEnabled" Value="True"/> <Setter Property="Foreground" Value="{StaticResource foregroundcolor1}"/> <Setter Property="Background" Value="{StaticResource foregroundcolor3}"/> <Setter Property="FontSize" Value="16"/> <Setter Property="FontWeight" Value="SemiBold"/> <Setter Property="HorizontalContentAlignment" Value="Left"/> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Cursor" Value="Hand"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="OverridesDefaultStyle" Value="True"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBox}"> <Border Name="Border" CornerRadius="9" Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding Foreground}"> <ScrollViewer Margin="0" x:Name="PART_ContentHost" /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> I hope this can help somebody in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FileStream from the System.IO namespace instead of Get-Content -Tail I want to use a FileStream from the System.IO namespace instead of Get-Content cmd-let. How can I do that ? thanks, $fromaddress = "filemon@contoso.com" $emailto = "IT@contoso.com" $SMTPSERVER = "xx.xx.xx.xx" $global:FileChanged = $false $folder = "C:\temp" $filter = "log.log" $watcher = New-Object IO.FileSystemWatcher $folder,$filter -Property @{ IncludeSubdirectories = $false EnableRaisingEvents = $true } Register-ObjectEvent $Watcher "Changed" -Action {$global:FileChanged = $true} > $null while ($true) { while ($global:FileChanged -eq $false){ Start-Sleep -Milliseconds 100 } if($(Get-Content -Tail 1 -Path $folder\$filter).Contains("Finished.")) { Send-mailmessage -from $fromaddress -to $emailto -subject "Log changed" -smtpServer $SMTPSERVER -Encoding UTF8 -Priority High } # reset and go again $global:FileChanged = $false } EDIT 1: $fromaddress = "filemon@contoso.com" $emailto = "IT@contoso.com" $SMTPSERVER = "xx.xx.xx.xx" $global:FileChanged = $false $folder = "C:\tmp" $filter = "log.log" $watcher = New-Object IO.FileSystemWatcher $folder,$filter -Property @{ IncludeSubdirectories = $false ; EnableRaisingEvents = $true } Register-ObjectEvent $Watcher "Changed" -Action {$global:FileChanged = $true} > $null function Read-LastLine ([string]$Path) { # construct a StreamReader object $reader = [System.IO.StreamReader]::new($path) $lastLine = '' while($null -ne ($line = $reader.ReadLine())) { $lastLine = $line } # clean-up the StreamReader $reader.Dispose() # return the last line of the file $lastLine } while ($true) { while ($global:FileChanged -eq $false){ Start-Sleep -Milliseconds 100 } $logFile = $Event.SourceEventArgs.FullPath if ((Read-LastLine -Path $logFile) -match "Finished.") { write-host "mail sending" Send-mailmessage -from $fromaddress -to $emailto -subject "Log changed" -smtpServer $SMTPSERVER -Encoding UTF8 -Priority High } # reset and go again $global:FileChanged = $false } Message: MethodInvocationException: C:\monfile.ps1:15 Line | 15 | $reader = [System.IO.StreamReader]::new($path) | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Exception calling ".ctor" with "1" argument(s): "The value cannot be an empty string. (Parameter 'path')" InvalidOperation: C:\monfile.ps1:17 Line | 17 | while($null -ne ($line = $reader.ReadLine())) { | ~~~~~~~~~~~~~~~~~~~~~~~~~~ | You cannot call a method on a null-valued expression. InvalidOperation: C:\monfile.ps1:22 Line | 22 | $reader.Dispose() | ~~~~~~~~~~~~~~~~~ | You cannot call a method on a null-valued expression. A: Try following : $SourceStream = [System.IO.FileStream]::new('c:\temp\test.txt',[System.IO.FileMode]::Open); for($pos = $SourceStream.Length - 1; $pos -ge 0; $pos--) { $SourceStream.Position = $pos $b = $SourceStream.ReadByte() if(($b -eq 0x0A) -or ($b -eq 0x0D)) { break;} } $length = $SourceStream.Length - $pos $buffer = New-Object byte[]($length) $SourceStream.Read([byte[]]$buffer, 0, $length) $tail = [System.Text.Encoding]::UTF8.GetString($buffer, 0, $length) Write-Host $tail A: Not sure if this would be faster than using Get-Content -Tail 1, but you could create a helper function that uses a StreamReader to return the last line in the file. Something like function Read-LastLine ([string]$Path) { # construct a StreamReader object $reader = [System.IO.StreamReader]::new($path) $lastLine = '' while($null -ne ($line = $reader.ReadLine())) { $lastLine = $line } # clean-up the StreamReader $reader.Dispose() # return the last line of the file $lastLine } Then change your code to $logFile = Join-Path -Path $folder -ChildPath $filter # or use $logFile = $Event.SourceEventArgs.FullPath if ((Read-LastLine $logFile) -match "Finished") { Send-mailmessage ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/75635527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Optuna sample fixed parameter depending on another parameter In my setting I have an abstract situation like this the following, just note this is not about power calculation but a simple example to explain my point. base = trial.suggest_int(1, 3) power = trial.suggest_int(1, 10) As when the base==1 the power parameter becomes useless and would like to fix it to 1. Like: base = trial.suggest_int("base", 1, 3) if base == 1: power = trial.suggest_int("power", 1, 1) # Different distribution! But still inside the other. else: power = trial.suggest_int("power"1, 10) While this works it creates later problems in the form of ValueErrors because the underlying distributions are not the same. How can I suggest a fixed value with the same parameter name that depends on another value that is sampled within the trial?
{ "language": "en", "url": "https://stackoverflow.com/questions/75635528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cucumber json file not created in karate Getting an error saying - "None report file added!" I have added outputCucumberJson(true) Am I correct in assuming that this should create a cucumber.json file in target/karate-reports? There is only a txt file named - karate-summary-json.txt file and no .json file due to which it is unable to create cucumber report
{ "language": "en", "url": "https://stackoverflow.com/questions/75635529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Faing problem in doing Sigle Sign On on Windows using Qt We are doing sign-on or SSO log-in in the Qt application. We are using Qt version 5.12.4 for a desktop application and using QtWebEngine to load the Microsoft authentication page. When a request like the following goes https://login.microsoftonline.com/54b90cf0-8817-42de-893f-9d32076b4a9b/saml2?SAMLRequest=jZFPa8MwDMW%2FSvB9cf64xDNJwG1aKHQw2nWH3Uym0UBip5ZS9vGXpORUGAWdhJ70fk85mq7tlR7oYo9wHQAp%2BO1aiwUbvFXOYIPKmg5QUa1O%2Bu2gkjBSHZD5NmRYsK8KtpOiklJqna6F2MRrKUSarbTYyiSOqtctCz7BY%2BNswUbxqEEcYG%2BRjKWxFSXpSzSW%2BIhjFaUqlmG2yr6muXeD2NygYD%2BmRWCBRgRP46aNszh04E%2Fgb00N5%2BOhYBeiHhXnvfNk2qsJR%2FMEYe06juj4RMongocl7I6s5iz%2BB%2B%2B9I1e7lgU752uYc1vclfkM5p8J0CweWPmM7SXvnN9PlDl%2FfFz5Bw%3D%3D we are getting following response instead of SAMLResponse token. <!-- This jsp is designed due to caching issue in Chrome. because after login when call was redirected to home servlet at that time it was making call of cached data images/js/css to revalidate it (304 status code) --><html><head> <title>CompnayName</title> <script language="javascript" type="text/javascript"> localStorage.setItem("isFromLogin", "true"); function redirectToAdoddleHome(){ document.frmHome.action_id.value=1; document.frmHome.submit(); } </script> </head> <body onload="redirectToAdoddleHome();"> <form name="frmHome" id="frmHome" action="/adoddle/home" method="get"> <input type="hidden" id="action_id" name="action_id" value="1"> </form> </body></html> Any clue why are we not getting SAMLResponse.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GitHub Action failed due to workflow is not valid I am trying to upload my laravel application on shared hosting for auto-deployment. I have integrated the GitHub CI/CD feature with my ftp server. I want to exclude the specific files and folders when github deploys code on FTP server. So for this, I have written then main.yml file. When I push the code on repositories I always get the following error: The workflow is not valid. .github/workflows/main.yml (Line: 23, Col: 11): A sequence was not expected But when I remove the exclude option from main.yml file then it work fine but I want to exclude some files and folders. main.yml on: push: branches: - staging name: Deploy website on push jobs: web-deploy: name: Deploy runs-on: ubuntu-latest timeout-minutes: 5 # time out after 15 minutes (default is 360 minutes) steps: - name: Get latest code uses: actions/checkout@v3 - name: Sync files uses: SamKirkland/FTP-Deploy-Action@4.3.3 with: server: ${{ secrets.ftp_server }} username: ${{ secrets.ftp_username }} password: ${{ secrets.ftp_password }} server-dir: /public_html/admin-test-com/ exclude: - public/** - vendor/** - crons/** - storage/** - .github - .github/** - .env - composer.json - composer.lock - .htaccess I don't know that what is the issue with this file. Is there any other way that I only upload the changed files instead of all files? A: Github inputs cannot be arrays, and please refer to the action's documentation, what you want to do is: - name: Sync files uses: SamKirkland/FTP-Deploy-Action@4.3.3 with: server: ${{ secrets.ftp_server }} username: ${{ secrets.ftp_username }} password: ${{ secrets.ftp_password }} server-dir: /public_html/admin-test-com/ exclude: | public/** vendor/** crons/** storage/** .github .github/** .env composer.json composer.lock .htaccess
{ "language": "en", "url": "https://stackoverflow.com/questions/75635531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Show Variation Name Else Simple Product Title I'm using this code on the cart page to conditionally show the variation name otherwise the simple product name but it only shows the variation parent name and not the child. function product_title_or_variation_name( $product ) { foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $_product = $cart_item['data']; $product_id = $cart_item['product_id']; $variation_id = $cart_item['variation_id']; if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) { $product_permalink = apply_filters( 'woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink( $cart_item ) : '', $cart_item, $cart_item_key ); if ( ! $product_permalink && $_product->is_type( 'variation' ) ) { $variation = wc_get_product( $variation_id ); return $variation->get_formatted_name(); } elseif ( ! $product_permalink && $_product->is_type( 'simple' ) ) { return wp_kses_post( apply_filters( 'woocommerce_cart_item_name', get_the_title( $product['product_id'] ), $cart_item, $cart_item_key ) . '&nbsp;' ); } else { return wp_kses_post( apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $_product->get_name() ), $cart_item, $cart_item_key ) ); } } } } I need it to show the entire variation name/title, not just the parent title. I have tested this code but it gets the parent not the child https://stackoverflow.com/a/48418215/4643292 Update : I've also written this code which doesn't return the variation name or simple product title : function simple_or_variable( $product ) { $product_id = $product['product_id']; $variation_id = $product['variation_id']; if ( is_product() && has_term( 'variable', 'product_type', $variable_id ) ) { $title = get_the_title( $product[ 'variable_id' ] ); return $title; } elseif ( is_product() && has_term( 'simple', 'product_type', $product_id ) ) { $title = get_the_title( $product[ 'product_id' ] ); return $title; } } And using the function like this : foreach( $products as $product ) { wc_add_notice( sprintf( __( '%s requires a minimum quantity of %d. You currently have %d in cart', 'woocommerce' ), simple_or_variable( $product ), $product['min_req'], $product['in_cart'], ), 'error' ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/75635532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bracketing in awk patterns I have seen regex patterns using either character classes (e.g. [:alpha:], [:digit:]) or directly specifying the characters themselves (e.g. [a-zA-Z], [0-9]). Are the enclosing square brackets [...] always required when using [:alpha:] and [:digit:]. Are the enclosing square brackets [...] simply the enclosing square brackets in [a-zA-Z] and [0-9] ? A: just try it out yourself, running through ASCII characters from "!" to "~" : jot -c - 33 126 | mawk '/[:digit:]/' : d g i t jot -c - 33 126 | mawk '/[[:digit:]]/' 0 1 2 3 4 5 6 7 8 9 jot -c - 33 126 | mawk '/[0-9]/' 0 1 2 3 4 5 6 7 8 9 jot -c - 33 126 | mawk '/[[0-9]]/' ** absolutely nothing matches **, but would print 2 out of 4 if this were the input : echo '][\n[]\n[-9+]\n8]' | gtee >( gcat -n >&2; ) | mawk '/[[0-9]]/' 1 ][ 2 [] 3 [-9+] 4 8] [] 8] since [[0-9]] matches : * *literal "[" or any "0-9", *immediately followed by one literal "]"
{ "language": "en", "url": "https://stackoverflow.com/questions/75635533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display field from controller inside thymeleaf In my controller I have some calculations and at the end I have a double balance that returns me a desired output. This is how its look: @GetMapping("/userTransactions/{user_id}") public String getUserTransactions(@PathVariable("user_id") long user_id, TransactionGroup transactionGroup, Model model) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal(); long userId = user.getId(); model.addAttribute("userId", userId); List<Transaction> transactions = transactionRepository.getTransactionsByUserId(user_id); List<TransactionGroup> transactionByDate = new ArrayList<>(); List<Transaction> transOnSingleDate = new ArrayList<>(); boolean currDates = transactions.stream().findFirst().isPresent(); if (currDates) { LocalDate currDate = transactions.get(0).getDate(); TransactionGroup transGroup = new TransactionGroup(); for (Transaction t : transactions) { if (!currDate.isEqual(t.getDate())) { transGroup.setDate(currDate); transGroup.setTransactions(transOnSingleDate); transactionByDate.add(transGroup); transGroup = new TransactionGroup(); transOnSingleDate = new ArrayList<>(); } transOnSingleDate.add(t); currDate = t.getDate(); } transGroup.setDate(currDate); transGroup.setTransactions(transOnSingleDate); transactionByDate.add(transGroup); for (TransactionGroup group: transactionByDate) { LocalDate date = group.getDate(); transactions = group.getTransactions(); double income = transactions.stream() .filter(trans -> trans.getTransactionType().getDisplayName().equalsIgnoreCase("income")) .mapToDouble(Transaction::getAmount) .sum(); double expense = transactions.stream() .filter(trans -> trans.getTransactionType().getDisplayName().equalsIgnoreCase("expense")) .mapToDouble(Transaction::getAmount) .sum(); double balance = income - expense; model.addAttribute("balance", balance); System.out.println("date:" + date + ",income:" + income + ",expense:" + expense + ",balance:" + balance); } } else { System.out.println("Empty"); } model.addAttribute("transactionGroup", transactionByDate); return "transactions"; } You should see: double balance = income - expense; model.addAttribute("balance", balance); And this is my thymeleaf: <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" th:href="@{/css/transaction.css}"/> <meta name="viewport" content="width=device-width"/> <script src="http://localhost:35729/livereload.js"></script> <script src="https://kit.fontawesome.com/9ab80cc16b.js" crossorigin="anonymous"></script> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Users</title> </head> <body> <header> <h1 class="logo">Spender</h1> <input type="checkbox" class="nav-toggle" id="nav-toggle"> <nav> <ul> <li><a th:href="@{/api/test/homePage}">Homepage</a></li> <li><a id="wallets" th:href="@{/api/wallet/userWallet/balance/{userId} (userId=${userId})}">Wallets</a></li> <li><a href="javascript: document.logoutForm.submit()" role="menuitem">Logout</a></li> </ul> </nav> <label for="nav-toggle" class="nav-toggle-label"> <span></span> </label> </header> <br> <br> <br> <br> <br> <br> <br> <br> <div class="date" th:each="singleGroup : ${transactionGroup}"> <h1 th:text="${singleGroup .date}"></h1><h1 th:text="${balance}"></h1> <div class="transaction" th:each="singleTrans : ${singleGroup.transactions}"> <h2>Amount: <span th:text="${singleTrans.amount}"></span></h2><br> <h2>Note: <span th:text="${singleTrans.note}"></span></h2><br> <h2>Wallet name: <span th:text="${singleTrans .walletName}"></span></h2><br> <h2>Expense Category: <span th:text="${singleTrans .expenseCategories}"></span></h2><br> <h2>IncomeCategory: <span th:text="${singleTrans .incomeCategories}"></span></h2> <a class="card__link" th:href="@{/api/transaction/delete/{id}(id=${singleTrans.id})}" th:data-confirm-delete="|Are you sure you want to delete ${singleTrans.walletName} wallet?|" onclick="if (!confirm(this.getAttribute('data-confirm-delete'))) return false">Delete</a> <a class="card__link" th:href="@{/api/transaction/showFormForUpdate/{id}(id=${singleTrans.id})}">Update</a> <hr> </div> </div> <div style="text-align:center" th:if="${#lists.isEmpty(transactionGroup)}"><h1>You don't have any transaction</h1> <a th:href="@{/api/wallet/userWallet/balance/{userId} (userId=${userId})}">Wallets</a> </div> <form name="logoutForm" th:action="@{/api/auth/signout}" method="post" th:hidden="true"> <input hidden type="submit" value="Sign Out"/> </form> </body> </html> I want to display that value right after <h1 th:text="${singleGroup .date}"></h1> And I tried like: <h1 th:text="${singleGroup .date}"></h1><h1 th:text="${balance}"></h1> What is the problem? For example, my output in the console from the controller is good, and looks like this: date:2023-03-03,income:100.0,expense:50.0,balance:50.0 date:2023-03-16,income:100.0,expense:15.0,balance:85.0 But on page, I have like in console, two dates and for both dates are printed 85 instead 50 for date 03/03/2023 and 85 for date 03/16/2023, value 85 is printed for both of them. How I can extract this double value in my thymeleaf to show appropiate value like in console? A: Your balance attribute is not part of transaction group. So, when you call model.addAttribute("balance", balance); in loop, your previous value is overwritten. Add balance attribute to transaction group instead
{ "language": "en", "url": "https://stackoverflow.com/questions/75635534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Other method to create indentation in alert JS object alert(JSON.stringify(student, null, 4)); Why is null used in this code, what is the use of the 4 and how do we use it in an array? Please explain to me the above JS code and the output.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-7" }
Q: Should httpClient be injected Maui c# or should the service be a singleton I am building a mobile app and I need to make http calls to apis, naturally I thought I would inject the httpclient but then reading articles like https://github.com/dotnet/runtime/issues/66863 I decided against it, I have always read the HttpClient should be instantiated only once when starting up the app but after reading that article I will make private readonly HttpClient httpClient; public MyService() { this.httpClient = new HttpClient() { BaseAddress = new Uri(Config.APIUrl) }; httpClient.DefaultRequestHeaders.Add("api-version", "1.0"); } How and when do you instantiate the httpClient?
{ "language": "en", "url": "https://stackoverflow.com/questions/75635536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: lifecycleScope.launchWhenResumed {} deprecated I've been using lifecyclesScope's launchWhenResumed for a long time now, but it seems to be deprecated. The documentation sais to use repeatOnLifecycle() but I only want the code to run once, just as it works with the old method. A: below code do the same functionality as viewLifeCycleOwner.launchWhenResumed lifecycleScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) { // do your work here } }
{ "language": "en", "url": "https://stackoverflow.com/questions/75635538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gitlab - Omniauth ldap sync users I'm setting up OmniAuth on my self-managed Gitlab. I have a SAML provider setup on Authentik. The SSO is working correctly. I would like to have all users in the Authentik managed group to be in the Gitlab users database. I currently have to wait for the user to login in Gitlab to be able to assign him to any project. It'll be useful to assign users to projects directly from Gitlab before he login in Gitlab. Is there any possibility to sync the users directly from the gitlab OmniAuth config? Gitlab also have a LDAP synchronization for users and groups. Does that means I have to also setup the LDAP integration in my gitlab.rb ? My gitlab.rb configuration look like this: gitlab_rails['omniauth_enabled'] = true gitlab_rails['omniauth_allow_single_sign_on'] = ['saml'] gitlab_rails['omniauth_sync_email_from_provider'] = 'saml' gitlab_rails['omniauth_sync_profile_from_provider'] = ['saml'] gitlab_rails['omniauth_sync_profile_attributes'] = ['email'] gitlab_rails['omniauth_auto_sign_in_with_provider'] = 'saml' gitlab_rails['omniauth_block_auto_created_users'] = false gitlab_rails['omniauth_auto_link_saml_user'] = true gitlab_rails['omniauth_providers'] = [ { name: 'saml', // APPEARS TO BE SPAM? label: 'authentik' } ] I tried the following values without success: gitlab_rails['omniauth_auto_link_ldap_user'] = false gitlab_rails['omniauth_auto_link_user'] = ['saml']
{ "language": "en", "url": "https://stackoverflow.com/questions/75635540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drawer (Mobile view) only opens to the height of the Navbar and does not cover the full page I have a Header and Footer (High order component) that has all the other pages in between these components; a layout to be precise. For mobile view, I have created a drawer that opens by clicking on the hamburger menu icon. However, the drawer only opens to the height of the Navbar and does not cover the complete page. and when I open the drawer. I tried putting the highest value or z-index and it still opens below the main content. I am putting the codes as I am lost on what to do here. Someone, please point out my mistake. The code for Navbar: import React, {useState} from 'react'; import {GiHamburgerMenu} from 'react-icons/gi'; import {MdClose} from "react-icons/md"; import {ImSun} from 'react-icons/im'; import {BsFillMoonFill} from 'react-icons/bs'; import logo from '../../Assets/logo.png'; import { Link } from 'react-router-dom'; import {RiHomeHeartFill} from "react-icons/ri" const Navbar = ({changeTheme, currentTheme}) => { const [navState, setNavState] = useState(false); return ( <nav> <div className="brand-container"> <div className='brand'> <Link to="/"><img src={logo} alt="logo"/></Link> </div> <div className='toggle-container'> <div className='toggle'> { navState ? (<MdClose onClick={() => setNavState (false)} />) : (<GiHamburgerMenu onClick={() => setNavState(true)} />) } </div> <div className='mode' onClick={changeTheme}> {currentTheme === "light" ? (<BsFillMoonFill className='dark'/>) : (<ImSun className='light'/>)} </div> </div> </div> <div className={`links-container ${navState ? "nav-visible" : ""}`}> <div className="links-container"> <ul className='links'> <li> <Link to="/"><RiHomeHeartFill style={{fontSize: '20px', color: '#bc414b'}}/></Link> </li> <li> <div className="dropdown"> <Link to="/about">Qui Sommes-Nous</Link> <div className="dropdown-content"> <Link to="/about">Presentation du COS</Link> <Link to="/terms">Nos Journalistes</Link> <Link to="/legal">Nous Rejoindre</Link> </div> </div> </li> <li> <div className="dropdown"> <Link to="/blog">Articles</Link> </div> </li> <li> <div className="dropdown"> <Link to="/podcasts">Podcasts</Link> </div> </li> <li> <div className="dropdown"> <Link to="/contact">Gallery</Link> </div> </li> <li> <div className="dropdown"> <Link to="/contact">Contacts</Link> <div className="dropdown-content"> <Link to="/press">Nous Contacter</Link> <Link to="/support">Localisation</Link> </div> </div> </li> <li onClick={changeTheme}> {currentTheme === "light" ? (<BsFillMoonFill className='dark'/>) : (<ImSun className='light'/>)} </li> </ul> </div> </div> </nav> ) } export default Navbar; The SCSS file: nav{ display: flex; justify-content: space-between; align-items: center; padding: 1rem 2rem 1rem 2rem; background-color: var(--background); font-family: var(--font-family); font-size: 16px; overflow-x: hidden; transition: 0.2s ease-in-out; .brand-container{ .brand { img{ height: 12vh; } } .toggle-container{ display: none; .mode{ .dark{ color: black } .light { color: yellow } } } } .links-container{ .links{ list-style-type: none; display: flex; gap: 3rem; li{ .dropdown { float: left; overflow: hidden; } .dropdown-content { display: none; position: absolute; background-color: var(--background); border-radius: 6px; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 2; } .dropdown-content a { float: none; color: var(--accent-color1); padding: 12px 16px; text-decoration: none; display: block; text-align: left; } .dropdown-content a:hover { background-color: rgba(190, 65, 75, 0.6); border-radius: 6px; color: #fff; } .dropdown:hover .dropdown-content { display: block; } a{ color: var(--accent-color1); text-decoration: none !important; } &:nth-last-child(2){ a{ color: var(--pink); } } .dark{ color: black; text-decoration: none; } .light { color: yellow; text-decoration: none; } } } } @media screen and (min-width:280px) and (max-width:1080px){ position: relative; padding: 1rem 2rem; .brand-container{ display: flex; justify-content: space-between; align-items: center; width: 100%; .brand{ img{ height: 3.5rem } } .toggle-container{ display: block; color: var(--accent-color1); display: flex; flex-direction: row-reverse; gap: 1rem; z-index: 2; .toggle{ z-index: 2; display: block } } } .links-container{ position: absolute; top: 0; right: 0; opacity: 0; display: flex; padding-top: 15vh; justify-content: left; padding-left: 5vw; height:100vh; transition: 0.6s ease-in-out; background-image: linear-gradient(rgba(255,255,255,0), rgba(255,255,255,0)), linear-gradient(101deg, var(--pink), var(--orange)); .links{ flex-direction: column; li{ a{ color: var(--background); } &:last-of-type{ display: none; } &:nth-last-child(2){ a{ color: var(--background); } } } } } .nav-visible{ width: 80vw; visibility: visible; opacity: 1; } } } and the layout file: import React, {useState, useEffect} from 'react'; import scrollreveal from 'scrollreveal'; import { Outlet } from 'react-router-dom'; import Navbar from '../Header/Header'; import Footer from '../Footer/Footer'; const Layout = () => { const [theme, setTheme] = useState('light'); const changeTheme = () => { theme === 'light' ? setTheme("dark") : setTheme("light") }; useEffect(()=> { const registerAnimations= () => { const sr = scrollreveal({ origin: "bottom", distance: "20px", duration: 1000, reset: false, }); sr.reveal( `.free, .clients, .super-rare, .releases, .like, .signup, footer`, {interval: 500} ); }; registerAnimations(); }, []); window.setTimeout(() => { const home = document.getElementsByClassName("home"); home[0].style.transform = "none"; const nav = document.getElementsByTagName("nav"); nav[0].style.transform = 'none' }, 1500); return ( <> <div data-theme={theme} className="page-container"> <div> <Navbar changeTheme={changeTheme} currentTheme= {theme}/> </div> <div> <Outlet/> </div> <div> <Footer/> </div> </div> </> ) } export default Layout I am also adding the GitHub link if there are any problems with other components. https://github.com/Iamthewaseem/CADA Here is what I want to be displayed that is getting hidden below the main body content. A: add height: 100vh to the nav nav{ display: flex; min-height: 100vh; /* the rest of scss code!*/ Change this part of code: .links-container{ .links{ li{ overflow:hidden;
{ "language": "en", "url": "https://stackoverflow.com/questions/75635541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the meaning of the sqlite Blob literal x'007800'? Sqlite has the blob datatype which stores data as hex-strings. You can write blob literals using the x'<hexadecimal numbers>' notation. The docs about this: BLOB literals are string literals containing hexadecimal data and preceded by a single "x" or "X" character. Example: X'53514C697465' This way you can write for example in the sqlite CLI sqlite> SELECT x'313233'; 123 sqlite> As SQLite will automatically transform the hexadecimal numbers 31-32-33 into their ASCII counterparts for the decimal numbers 49, 50 and 51, which are "1", "2" and "3". Now as part of a test-suite I am maintaining from somebody else there is a test that uses x'007800' and claims it to be a NULL value of some sort. In fact, running that value in an sqlite console returns nothing: sqlite> SELECT x'007800'; sqlite> I am somewhat confused as to what the meaning behind that hexadecimal is (?). Googling around, I could find no special meaning attached to that particular number. It appears to be a representation of "\0x\0", which I similarly can't extract any meaning from. What is the meaning of x'007800' and/or "\0x\0" ? A: What is the meaning of x'007800' and/or "\0x\0" ? The blob literal x'007800' means three bytes 00, 78 and 00 in hexadecimal, which are equal to ASCII characters null (\0) and x. You can refer the table here. CharacterName Char Code Decimal Binary Hex Null NUL Ctrl@ 0 00000000 00 Lower-case X x X 120 01111000 78
{ "language": "en", "url": "https://stackoverflow.com/questions/75635542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: ReactJS based web app doesn't render on Facebook and IG's in app browser I have a site written in ReactJS (CRA). It runs fine on Chrome, Safari, and FF, but clicking on our URL from inside the native mobile FB/IG app renders a blank screen. Does anyone know what's going on? Or, how to debug this?
{ "language": "en", "url": "https://stackoverflow.com/questions/75635546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fetch rows only if primary ids are available in another table as a comma separated value I have two tables - * *blog_categories *blog Values of blog_categories table are - id category cat_slug 1 News news 2 Travel travel 3 Sports sports 4 Food food 5 Politics politics Values of blog table are - id blog_category_ids blog slug 1 1,2 This is a demo blog demo-blog 2 1,3 This is another blog another-blog Now, I want to fetch only those blog categories that are available in the column blog_category_ids of the blog table. So my expected result should be - id category cat_slug 1 News news 2 Travel travel 3 Sports sports How should I write the MYSQL query to achieve this?
{ "language": "en", "url": "https://stackoverflow.com/questions/75635547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to correctly initialise a tRPC router for NextJS I've currently started migrating a NextJS and Express app to use tRPC. However, I'm having trouble initialising the NextApiHandler. In the backend folder, I have the following files: trpc.ts import { initTRPC } from '@trpc/server'; const t = initTRPC.create(); export const router = t.router; export const procedure = t.procedure; _app.ts import { z } from 'zod'; import { procedure, router } from '../trpc'; export const appRouter = router({ hello: procedure .input( z.object({ text: z.string(), }), ) .query(({ input }) => ({ greeting: `hello ${input.text}`, })), }); // export type definition of API export type AppRouter = typeof appRouter; However, when I try to set up the tRPC HTTP handle in [trpc].ts which lives in my frontend folder import * as trpcNext from '@trpc/server/adapters/next'; import { appRouter } from '../../../../backend/src/routers/_app'; export default trpcNext.createNextApiHandler({ router: appRouter, createContext: () => ({}), }); I get the following error The expected type comes from property 'router' which is declared here on type 'NodeHTTPHandlerOptions<AnyRouter, NextApiRequest, NextApiResponse>' Similarly, when I try to set up my hooks in the frontend in trpc.ts like the following, I also get the same error. import { httpBatchLink } from "@trpc/client"; import { createTRPCNext } from "@trpc/next"; import type { AppRouter } from '../backend/src/routers/_app'; const getBaseURL = () => { if (process.env.API_BASE_URL) { return process.env.API_BASE_URL; } return ...; } export const trpc = createTRPCNext<AppRouter>({ config({ ctx }) { return { links: [ httpBatchLink({ /** * If you want to use SSR, you need to use the server's full URL * @link https://trpc.io/docs/ **/ url: `${getBaseURL()}/api/trpc`, }), ], /** * @link https://tanstack.com/query/v4/docs/reference/QueryClient **/ // queryClientConfig: { defaultOptions: { queries: { staleTime: 60 } } }, }; }, /** * @link https://trpc.io/docs/ssr **/ ssr: false, }); Note: I've mostly copied my code from the tRPC v10 documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to write html elements using javascript after "window.history.go(-1)"? I want to print the validation message on the div box after "window.history.go(-1)". I wrote a function writediv() to write the message on the div element but I think It's not working because the previous page is displaying when writediv() implement for the present page. I haven't a clear idea to write on div after "window.history.go(-1)". Can you give me some assistance? It's very helpful. Here is the function function writediv(){ document.getElementById("message").innerHTML ="Invalid Credintials"; } Here is the code, <?php session_start(); if(isset($_POST['username']) && isset($_POST['password']) ){ $username=$_POST['username']; $password=$_POST['password']; $conn= new mysqli('localhost','root','','shop'); if($conn->connect_error){ die('Connection Failed : '.$conn->connect_error); }else{ $stmt=$conn->prepare("select customer_id,username from customer where username=? and password=?"); $stmt->bind_param("ss",$username,$password); $stmt->execute(); $result = mysqli_stmt_get_result($stmt); echo mysqli_num_rows($result); if(mysqli_num_rows($result)!=0) { while($row = mysqli_fetch_assoc($result)) { $_SESSION['user_id'] = $row['customer_id']; header("Location:home.php"); exit(); } } else{ //$_SESSION["errorMessage"] = "Invalid Credentials"; ?> <script type="text/javascript"> window.history.go(-1); //document.getElementById("message").outerHTML = "*required"; writediv(); </script> <?php } } } ?> <html> <head> <title>Cake Easy</title> <link rel="stylesheet" type="text/css" href="login.css"> <script> function validateform(){ var username=document.login.username.value; var password=document.login.password.value; if (username==null || username==""){ document.getElementById("user_info").innerHTML = "*required"; //alert("Password must be at least 6 characters long."); return false; } if (password==null || password==""){ document.getElementById("password_info").innerHTML = "*required"; //alert("Password must be at least 6 characters long."); return false; } } function writediv(){ document.getElementById("message").innerHTML ="Invalid Credintials"; } </script> </head> <header>Welcome to Cake Easy </header> <body> <form onsubmit="return validateform()" action="login3.php" method="post" class="formbox" name="login"> <div id="message" class="label1"></div> Username <span id="user_info" style="color:red"></span><br> <input type="text" name="username" id="username"></input><br><br> Password <span id="password_info" style="color:red"></span><br> <input type="password" name="password" id="password"></input><br><br> forgotten your username or password?<br> <input type="submit" name="submit" value="Log in"></input><br><br> New member? <a href="registration.html">Register</a> here. </form> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/75635553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rotate a 2d array of any size counterclockwise cell by cell I need to be able to rotate a 2d array of data both clockwise and counterclockwise (right and left), in 2 separated functions. I was able to make the first function which does clockwise rotation to work well but I'm having modifying my code for the second function which should turn counterclockwise. This is my function for clockwise rotation in Typescript: function rotateClockwise<T>(arr: T[][]) { const ret: any[][] = arr.map(c => c.map(v => "")); // blank copy const rows = arr.length; if (rows === 0) return ret; const cols = arr[0].length; if (!arr.every(l => l.length === cols)) throw new Error("Not rectangular"); const stationaryRing = (rows % 2 !== 0) && (cols % 2 !== 0) ? (Math.min(rows, cols) - 1)/2:-1 console.log('stationaryRingx = ', stationaryRing) for (let r = 0; r < rows; r++) { let nr = rows - 1 - r; for (let c = 0; c < cols; c++) { let nc = cols - 1 - c; const ring = Math.min(r, nr, c, nc); let [rNew, cNew] = [r, c]; if (ring !== stationaryRing) { if (r === ring && nc !== ring) cNew++; // top row moves right (except for rightmost) else if (c === ring) rNew--; // left column moves up else if (nr === ring) cNew--; // bottom row moves left else rNew++; // right column moves down } ret[rNew][cNew] = arr[r][c]; } } return ret; } for the following input table: 1 2 3 4 5 6 7 8 9 The code above produces this table: 4 1 2 7 5 3 8 9 6 I need to change the code in order for it rotate to the left so if I use the same input table above I should get: 2 3 6 1 5 9 4 7 8 I thought that by changing the conditions as described below I would be able to make a counterclockwise rotation but it did not work: if (ring !== stationaryRing) { if (r === ring && nc !== 0) rNew-- ; // top row moves left (except for leftmost) else if (c === ring) rNew++; // left column moves down else if (nr === ring) cNew++; // bottom row moves right else cNew--; // right column moves up } Any ideas? Thanks! A: Some issues: * *nc !== 0 is certainly wrong, as you should compare with ring (for all except the outermost ring, no column will ever be 0). *rNew-- does not do what the comment next to it says. *cNew-- does not do what the comment next to it says. A correct way to "mirror" the functioning code, is to mirror bottom and top (i.e. exchange r and nr), and up and down (i.e. exchange rNew++ and rNew--), but not left and right. So that results in this correction: if (ring !== stationaryRing) { if (nr === ring && nc !== ring) cNew++; // bottom row moves right (except for rightmost) else if (c === ring) rNew++; // left column moves down else if (r === ring) cNew--; // top row moves left else rNew--; // right column moves up }
{ "language": "en", "url": "https://stackoverflow.com/questions/75635555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get Second/Third Best Hyperparameters for comparison (keras tuner) i want to ask about keras tuner method. I know that get_best_hyperparameters() return the value of the best hyperparameters. How about a method to return the second/third/etc best hyperparameters. Is there any other method to use to get their value? I only tried get_best_hyperparameters A: From Keras API Reference: Returns List of HyperParameter objects sorted from the best to the worst. Use [1], [2], etc. on the return value.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to count the sum of NaN's before the first occurrence of a string in a given column? Suppose I have a df like, column1 | column2 | column3 | 1 | 2023-02-21 | NaN | 1 | 2023-02-22 | NaN | 1 | 2023-02-23 | 8 | 1 | 2023-02-24 | NaN | 1 | 2023-02-24 | NaN | 1 | 2023-02-24 | NaN | 1 | 2023-02-24 | NaN | 1 | 2023-02-24 | 10 | 2 | 2023-02-25 | NaN | 2 | 2023-02-26 | 9 | Is there a way to achieve the following df, Result df, column1 | column2 | column3 | result 1 | 2023-02-21 | NaN | 3 1 | 2023-02-22 | NaN | 3 1 | 2023-02-23 | 8 | 3 1 | 2023-02-24 | NaN | 3 1 | 2023-02-24 | NaN | 3 1 | 2023-02-24 | NaN | 3 1 | 2023-02-24 | NaN | 3 1 | 2023-02-24 | 10 | 3 2 | 2023-02-23 | NaN | 2 2 | 2023-02-24 | 9 | 2 I cannot think of a way to achieve this output other than counting column3 NaN's for a given column1 value using pandas. Any help would be greatly appreciated. Thanks. A: Not sure if your exact logic, but maybe: df['result'] = (df['column3'].isna() .groupby(df['column1']) .transform(lambda x: x.cummin().sum()+1) )
{ "language": "en", "url": "https://stackoverflow.com/questions/75635562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Perform a two sample t-test on a dataset with a binary independent variable I am using the standard function t.test to perform a t-test on two variables, one (FC01) being an ordinally ranked variable (Likert scale from 1 to 5) and the other (joko) one being a nominally scaled binary variable (TRUE or FALSE). ## Dummy data ds <- data.frame(FC01 = c(3, 3, 4, 2, 3, 1, 2, 4, 3, 3, 2), joko = c(TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE)) ds$FC01 = factor(ds$FC01, levels = c("1", "2", "3", "4", "5", "-9"), labels = c("1", "2", "3", "4", "5", "[NA] Not answered"), ordered = FALSE) ## t-test t.test(ds$FC01, ds$joko, var.equal = TRUE) But t.test throws this error: > t.test(ds$FC01, ds$joko, var.equal = TRUE) Error in var(x) : Calling var(x) on a factor x is defunct. Use something like 'all(duplicated(x)[-1L])' to test for a constant vector. In addition: Warning message: In mean.default(x) : Argument ist weder numerisch noch boolesch: gebe NA zurück EDIT I also ran all(duplicated(ds$FC01)[-1L]) all(duplicated(ds$joko)[-1L]) which resulted in > all(duplicated(ds$FC01)[-1L]) [1] FALSE > all(duplicated(ds$joko)[-1L]) [1] FALSE but I do not understand what that is supposed to tell me.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what details can you include that will help someone identify and solve your problem? am trying to run yarn add node-sass sass-loader and is giving me this error message yarn: The term 'yarn' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. yarn add node-sass sass-loader i was expecting it to loader and make me able to use scss A: Install yarn in your windows! Try using CMD instead of PowerShell. https://classic.yarnpkg.com/lang/en/docs/install/#windows-stable
{ "language": "en", "url": "https://stackoverflow.com/questions/75635564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Threaded Excel File Processing in Delphi I created a TThread to handle some critical issues in an Excel file, however, I'm currently experiencing some challenges as the thread doesn't seem to be working in parallel with my application. Despite my best efforts to identify the root cause of the issue, I have been unsuccessful thus far. In an attempt to resolve the problem, I have experimented with defining a TThread Type with an overridden Execute method and also attempted to switch from Synchronize to Queue methods, but neither approach has yielded positive results so far. procedure TForm2.Button1Click(Sender: TObject); begin TThread.CreateAnonymousThread(proc).Start; end; procedure TForm2.Proc; var refSheet: Integer; RowCount,varGridRow:Integer; i, j,k: Integer; desc, refDesc, refRate: string; delta: Integer; OldValue:String; ws: Variant; ExcelApp: Variant; begin Tthread.Synchronize(nil,procedure ()begin if OpenDialog1.Execute then begin ExcelApp := CreateOleObject('Excel.Application'); ExcelApp.Workbooks.Open(OpenDialog1.FileName); end; end); Tthread.Synchronize(nil,procedure () begin refSheet :=StrToInt(InputBox('','','3')); if (refSheet <= 0) or (refSheet > ExcelApp.Worksheets.Count) then begin ShowMessage('Invalid sheet number'); Exit; end; end); Tthread.Queue(nil,procedure ()var i,j,k:Integer; begin IssamProgressBar1.Max:= ExcelApp.Worksheets[refSheet].UsedRange.Rows.Count; RowCount:=1; varGridRow := 1; for i := 2 to ExcelApp.Worksheets[refSheet].UsedRange.Rows.Count do begin IssamProgressBar1.Progress:=i-2; IssamProgressBar1.Refresh; if (not VarIsEmpty(ExcelApp.Worksheets[refSheet].Cells[i, 2].Value))and (not VarIsEmpty(ExcelApp.Worksheets[refSheet].Cells[i, 1].Value)) then begin refDesc := ExcelApp.Worksheets[refSheet].Cells[i, 2].Text; refRate := ExcelApp.Worksheets[refSheet].Cells[i, 5].Text; Label3.Caption:=refDesc; Label3.Refresh; // Loop through other sheets for j := 1 to ExcelApp.ActiveWorkbook.Sheets.Count do begin ws := ExcelApp.ActiveWorkbook.Sheets[j]; if ws.Index <> refSheet then begin // Loop through rows in current sheet Label1.Caption:='Checking Sheet : '+ExcelApp.Worksheets[j].name; Label1.Refresh; for k := 2 to ws.UsedRange.Rows.Count do begin // Check if description matches approximately desc := ws.Cells[k, 2].Value; if (not VarIsEmpty(desc)) and (Not VarIsEmpty(ws.Cells[k, 1].Value)) then begin Label5.Caption:=desc; Label5.Refresh; if (refDesc = desc) and (refDesc <> 'Set of spare parts;') and (refDesc <> 'Set of tools and instruments;') then begin // Update rate if (ws.Cells[k, 5].Value <> refRate) and VarIsNumeric(ws.Cells[k, 5].Value) then begin ws.Cells[k, 7].Value := ws.Cells[k, 5].Value; OldValue:=ws.Cells[k, 5].Value; ws.Cells[k, 5].Value := refRate; delta := delta + 1; ws.Cells[k, 5].Font.Color := RGB(255, 0, 0); with StringGrid1 do begin RowCount := RowCount + 1; Cells[0, varGridRow] := IntToStr(varGridRow); Cells[1, varGridRow] := refDesc; Cells[2, varGridRow] := OldValue; Cells[3, varGridRow] := refRate; Cells[4, varGridRow] := ExcelApp.Worksheets[j].Name; Cells[5, varGridRow] := IntToStr(j); Inc(varGridRow); end; end; end; end; end; end; end; end; end; end); IssamProgressBar1.Progress:=0; Label1.Caption:=''; Label3.Caption:=''; Label5.Caption:=''; ExcelApp.ActiveWorkbook.Close(False); ExcelApp.Quit; end; My question is how to make my Proc procedure works in parallel with my app . A: You can't use the Excel COM object across thread boundaries. Your whole thread design is wrong. You need to create the COM object in the worker thread, not in the main thread. Then sync with the main thread only to get the filename (or ask for it before starting the thread), and then load and process the file entirely in the worker thread, not in the main thread. Sync with the main thread only when accessing the UI as needed. In other words, all of your COM object processing should be only in the worker thread, not in the main thread. You are syncing way too much work, defeating the whole point of using a thread. Try something more like this: procedure TForm2.Button1Click(Sender: TObject); begin if OpenDialog1.Execute then ProcessFileInThread(OpenDialog1.FileName); end; procedure TForm2.ProcessFileInThread(const AFileName: string); begin TThread.CreateAnonymousThread( procedure begin InitThreadProc(AFileName); end ).Start; end; procedure TForm2.InitThreadProc(const AFileName: string); begin CoInitialize(nil); try ProcessFile(AFileName); finally CoUninitialize; end; end; procedure TForm2.ProcessFile(const AFileName: string); var refSheet, sheetCount, usedRowCount, RowCount: Integer; i, j, k: Integer; desc, refDesc, refRate, oldValue: string; ExcelApp, refWorksheet, curWorksheet, tmpValue: Variant; begin ExcelApp := CreateOleObject('Excel.Application'); try ExcelApp.Workbooks.Open(AFileName); try sheetCount := ExcelApp.Worksheets.Count; TThread.Synchronize(nil, procedure begin refSheet := StrToIntDef(InputBox('','','3'), -1); if (refSheet <= 0) or (refSheet > sheetCount) then begin ShowMessage('Invalid sheet number'); Abort; end; end ); refWorksheet := ExcelApp.Worksheets[refSheet]; usedRowCount := refWorksheet.UsedRange.Rows.Count; ClearGrid; UpdateProgress(0, usedRowCount); for i := 2 to usedRowCount do begin UpdateProgress(i-2); if VarIsEmpty(refWorksheet.Cells[i, 2].Value) or VarIsEmpty(refWorksheet.Cells[i, 1].Value) then Continue; refDesc := refWorksheet.Cells[i, 2].Text; refRate := refWorksheet.Cells[i, 5].Text; UpdateLabel(Label3, refDesc); // Loop through other sheets for j := 1 to ExcelApp.ActiveWorkbook.Sheets.Count do begin curWorksheet := ExcelApp.ActiveWorkbook.Sheets[j]; if curWorksheet.Index = refSheet then Continue; UpdateLabel(Label1, 'Checking Sheet : ' + curWorksheet.name); // Loop through rows in current sheet for k := 2 to curWorksheet.UsedRange.Rows.Count do begin // Check if description matches approximately tmpValue := curWorksheet.Cells[k, 2].Value; if VarIsEmpty(tmpValue) or VarIsEmpty(curWorksheet.Cells[k, 1].Value) then Continue; desc := VarToStr(tmpValue); UpdateLabel(Label5, desc); if (refDesc <> desc) or (refDesc = 'Set of spare parts;') or (refDesc = 'Set of tools and instruments;') or (curWorksheet.Cells[k, 5].Value = refRate) or (not VarIsNumeric(curWorksheet.Cells[k, 5].Value)) then Continue; // Update rate curWorksheet.Cells[k, 7].Value := curWorksheet.Cells[k, 5].Value; oldValue := curWorksheet.Cells[k, 5].Value; curWorksheet.Cells[k, 5].Value := refRate; curWorksheet.Cells[k, 5].Font.Color := RGB(255, 0, 0); AddToGrid(refDesc, oldValue, refRate, curWorksheet.Name, j); end; end; end; ClearStatus; finally ExcelApp.ActiveWorkbook.Close(False); end; finally ExcelApp.Quit; end; end; procedure TForm2.UpdateProgress(AValue: Integer; AMax: Integer = -1); begin TThread.Queue(nil, procedure begin if AMax > -1 then IssamProgressBar1.Max := AValue; IssamProgressBar1.Progress := AValue; end ); end; procedure TForm2.UpdateLabel(ALabel: TLabel; const AText: string); begin TThread.Queue(nil, procedure begin ALabel.Caption := AText; end ); end; procedure TForm1.AddToGrid( const ADesc, AOldValue, ARate, ASheetName: string; ASheetIndex: Integer); var Row: Integer; begin TThread.Queue(nil, procedure begin Row := StringGrid1.RowCount; StringGrid1.RowCount := Row + 1; StringGrid1.Cells[0, Row] := IntToStr(Row); StringGrid1.Cells[1, Row] := ADesc; StringGrid1.Cells[2, Row] := AOldValue; StringGrid1.Cells[3, Row] := ARate; StringGrid1.Cells[4, Row] := ASheetName; StringGrid1.Cells[5, Row] := IntToStr(ASheetIndex); end ); end; procedure TForm2.ClearGrid; begin TThread.Queue(nil, procedure var i: Integer; begin StringGrid1.RowCount := 1; for i := 0 to StringGrid1.ColCount-1 do StringGrid1.Cells[i, 0] = ''; end; ); end; procedure TForm2.ClearStatus; begin TThread.Queue(nil, procedure begin IssamProgressBar1.Progress := 0; Label1.Caption := ''; Label3.Caption := ''; Label5.Caption := ''; end ); end;
{ "language": "en", "url": "https://stackoverflow.com/questions/75635566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multipart form value post in api in c# asp.net web application Error throw: HTTP Validation: unparsable request content Details:No boundary define for multipart request Method for post api call: string xml = ""; string Type = "", EventName = "", EventPath = "", UserName = "", Password = ""; Type = "POST"; EventName = "PREAPPROVALSUBMISSION"; EventPath = "https://www.devapi.anoudapps.com/api/medical/hospital-service/v3/pre-approval"; UserName = "nova_api"; Password = "nova_api123"; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; var encoding = System.Text.Encoding.GetEncoding("ISO-8859-1"); byte[] headerBytes = encoding.GetBytes(UserName + ":" + Password); string headerValue = Convert.ToBase64String(headerBytes); CookieContainer cookies = new CookieContainer(); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(EventPath); webRequest.Credentials = new NetworkCredential(UserName, Password); webRequest.Method = Type; webRequest.Headers.Add("company", "009"); webRequest.Headers.Add("Authorization", "Basic " + headerValue); webRequest.ContentType = "multipart/form-data"; webRequest.CookieContainer = cookies; webRequest.KeepAlive = true; webRequest.Accept = "application/json"; //please use below data for post var formdata = "{{\"policyNo\":\"P2209000174\"}, {\"memberId\":\"MEM21341411\"}, {\"category\":\"001\"},{\"illness\":\"001\"},{\"priority\":\"2\"}, {\"primaryDiagnosis\":\"R93.421\"},{\"medicalRecordNo\":\"0115731\"},{\"serviceType\":\"O\"}, {\"admissionType\":\"M\"},{\"visitDate\":\"19/02/2023\"},{\"doctorLicenseNo\":\"D8622\"} {\"currency\":\"QAR\"},{\"mobileNo\":\"55849898\"},{\"illnessDetails\":\"follow up after treatment of UTI\"},{\"treatmentsData\":\" {\"treatType\":\"O\",\"treatCode\":\"51741\",\"quantity\":\"1\",\"treatDesc\":\"Urine flow study\",\"estimatedAmount\":\"600.0000\",\"remarks\":\"\"}, {\"treatType\":\"O\",\"treatCode\":\"74183\",\"quantity\":\"1\",\"treatDesc\":\"MRI Abdomen without and with contrast \",\"estimatedAmount\":\"3450.0000\",\"remarks\":\"\"}, {\"treatType\":\"O\",\"treatCode\":\"99242\",\"quantity\":\"1\",\"treatDesc\":\"Consultation - Specialist (All)\",\"estimatedAmount\":\"300.0000\",\"remarks\":\"\"}\"} {\"visitNo\":\"6461204\"},{\"medicalHistory\":\"Diabetes, dyslipidemia\"}}"; string inputJson = (new JavaScriptSerializer()).Serialize(formdata); using (var streamWriter = new StreamWriter(webRequest.GetRequestStream())) { streamWriter.Write(inputJson); streamWriter.Flush(); streamWriter.Close(); var webResponse = (HttpWebResponse)webRequest.GetResponse(); using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream())) { DataSet dsXml = new DataSet(); xml = streamReader.ReadLine(); StringReader sr = new StringReader(xml); dsXml.ReadXml(sr); if (dsXml.Tables[0].Rows.Count > 0) { if (common.myStr(dsXml.Tables[0].Rows[0]["messageType"]) != "S") { Alert.ShowAjaxMsg("Invalid Qatar Id", Page); return; } } dsXml.Dispose(); } } Still throw below error: HTTP Validation: unparsable request content Details:No boundary define for multipart request please share solution i am still struggling to find solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Animations in Phaser JS are not playing when 'not' set to loop I want to create an animation that will be triggered by certain event, play once and then terminate. This code isn't doing it for me even if I tried setting repeat: 0 and the 2nd parameter of anims.play() function as false/blank but it just completely stops the animation and does nothing at all. Animation Code this.anims.create({ key: 'die', frames: this.anims.generateFrameNumbers('player', { start: 91, end: 97 }), frameRate: 10, repeat: 0 }); Trigger Code if (gameOver) { player.setVelocityX(0); player.anims.play('die',true); return; } A: I assume you must be setting the a different animation in the update function or so. Just track if the player/sprite is alive. if the player/sprite is dead, prevent starting a different animation on the "dead" sprite. Here a small Demo, showcasing this: (to recreate the issue you are having, just remove the marked if/else - block in the updatefunction) document.body.style = 'margin:0;'; var config = { width: 536, height: 183, physics: { default: 'arcade', }, scene: { preload, create, update } }; var keys; var player; var player_is_dead = false function preload(){ this.load.spritesheet( 'brawler', 'https://labs.phaser.io/assets/animations/brawler48x48.png', { frameWidth: 48, frameHeight: 48 } ); } function update(){ let speed = 50; // remove this if statment to simulate the issue if(player_is_dead){ return; } if(keys.left.isDown){ player.body.setVelocityX(-speed); player.play('walk', true); player.setFlipX(false); } else if(keys.right.isDown){ player.body.setVelocityX(speed); player.play('walk', true); player.setFlipX(true); } else { player.body.setVelocity(0) player.play('idle', true); } } function create () { this.add.text(10,10, [ 'A - Key move left', 'S - Key move right', 'SPACE - Key to kill', 'ENTER - Key to reset' ]) .setScale(1.5) .setOrigin(0) .setStyle({fontStyle: 'bold', fontFamily: 'Arial'}); this.anims.create({ key: 'walk', frames: this.anims.generateFrameNumbers('brawler', { frames: [ 0, 1, 2, 3 ] }), frameRate: 8, repeat: -1 }); this.anims.create({ key: 'die', frames: this.anims.generateFrameNumbers('brawler', { frames: [ 35, 36, 37 ] }), frameRate: 8, }); this.anims.create({ key: 'idle', frames: this.anims.generateFrameNumbers('brawler', { frames: [ 5, 6, 7, 8 ] }), frameRate: 8, repeat: -1 }); player = this.physics.add.sprite(300, 70); player.setScale(3.5); this.input.keyboard.on('keydown-SPACE', _ => { player_is_dead = true; player.play('die'); }); this.input.keyboard.on('keydown-ENTER', function (event) { player_is_dead = false; }); keys = this.input.keyboard.addKeys({ left: Phaser.Input.Keyboard.KeyCodes.A, right: Phaser.Input.Keyboard.KeyCodes.D }); } new Phaser.Game(config); <script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script> This example is based of this official demo
{ "language": "en", "url": "https://stackoverflow.com/questions/75635570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When i create new project in Apache NetBeans IDE 15 with simple (Java with Ant) than it shows me an error I install JDK-13 with NetBeans-15 but after installation during creating a project I faced a problem that it shows the following message Project Folder already exists and is not empty. When I am facing that particular issue then I don't switch the path folder and set it on C: drive and also create a new folder in that drive but the same message shows.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I'm trying to generate the apk of my application using EXPO can someone help me to solve these problems? I've done several installations and it doesn't solve the problems, sometimes it even increases. I'm using the command "eas build -p android --profile preview" build errors package.json I already did some research to see if anyone had any problems, then I ran the install, update command and it only increased the errors. Thank you for your help.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Renaming a file with a name already being downloaded through an (javascript) My problem is that it doesn't give it the names, it just stays the name that the assetdelivery has (which is just random characters). I've tried doing it with HttpGet, renaming the link, and rewriting it in another language. The code gets JSON from an API, parses it, iterates over it, and downloads the files. I run this in snippets because verification things var groupid = 12345 function httpGet(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", theUrl, false); xmlHttp.send(null); return xmlHttp.responseText; } function downloadURI(uri, name) { var link = document.createElement("a"); link.download = "tesitnging.rbxl"; link.href = uri; link.download = "tesitnging.rbxl"; document.body.appendChild(link); link.download = "tesitnging.rbxl"; link.click(); link.download = "tesitnging.rbxl"; document.body.removeChild(link); link.download = "tesitnging.rbxl"; console.log() delete link; } var trytable = httpGet("https://games.roblox.com/v2/groups/"+ groupid + "/games?accessFilter=1&limit=10&sortOrder=Asc") var data2 = JSON.parse(trytable); console.log(data2.data); var current = 0 for(let thing of data2.data){ current++; (function(ind) { setTimeout(function(){console.log(thing.name); downloadURI("https://assetdelivery.roblox.com/v1/asset/?id=" + thing.rootPlace.id, thing.creator.id +"_"+ thing.name);}, 3000 + (3000 * ind)); })(current); }
{ "language": "en", "url": "https://stackoverflow.com/questions/75635574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: res.locals returns nothing, undefined * *auth middleware code in which I defined app.locals.user and it shows the right details // middlewares/auth-middleware.js const jwt = require("jsonwebtoken"); const User = require("../schemas/user"); const express = require("express"); const app = express(); // auth middleware module.exports = async (req, res, next) => { const { Authorization } = req.cookies; const [authType, authToken] = (Authorization ?? "").split(" "); if (!authToken || authType !== "Bearer") { res.status(401).send({ errorMessage: "(1)require sign-in.", }); return; } try { const { userId } = jwt.verify(authToken, "customized-secret-key"); const user = await User.findById(userId); app.locals.user = user; console.log(app.locals.user) next(); } catch (err) { console.error(err); res.status(401).send({ errorMessage: "(2)require sign-in.", }); } }; *posts code(here is the problem. I get undefined from res.locals.user). I tried several options suggested here. Nothing worked. // routes/post.js router.post("/", authMiddleware, async (req, res) => { console.log(res.locals.user) //const { user } = app.locals.user; console.log(user) const { title, content } = req.body; console.log(title, content) const user_registered = await User.find({userId: user}).exec(); console.log(user_registered) if (user_registered) await Post.create({ title, content }); res.json({ result: "success" }); }); *login code i checked if jwt.sign works and it does. No issues here. ` router.post('/login', async (req, res) => { //const salt = await bcrypt.genSalt(10); //const hashedPass = await bcrypt.hash(req.body.password, salt) const { username, password } = req.body; const user = await User.findOne({ username }); if (!user || password !== user.password) { res.status(400).json({ errorMessage: "message.", }); return; } const token = jwt.sign( { userId: user._id }, "customized-secret-key", {expiresIn: '24h' // expires in 24 hours } ); res.cookie("Authorization", `Bearer ${token}`); res.status(200).json({ token }); }) I tried app.locals, req.locals etc. nothing worked. Probably wrong routes?
{ "language": "en", "url": "https://stackoverflow.com/questions/75635576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: clCreateProgramWithBinary(): CL_INVALID_BINARY * Device #1: Kernel /usr/share/hashcat/OpenCL/m13600-pure.cl build failed I am getting this error when trying to crack password with hash.enter image description here i want to crack password with hashcat.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: ASP.NET UserService methods are not identified in favor of I UserService here im using [HttpPost] public async Task<IActionResult> Login(LoginRequest request) { var user = await _userService.GetUserByEmail(request.Email); the GetUserByEmail method is not recognized depsite clearly being present public async Task<User> GetUserByEmail(string email) { return await _context.Users.FirstOrDefaultAsync(u => u.Email == email); } i tried fixing it with microsoft suggestion, and for some reason it tries to build the method in IUserService, remind you, _userService is an instance of UserService how do i fix this? thank you edit, in sake of accuracy heres the full error script Severity Code Description Project File Line Suppression State Error CS1061 'UserService' does not contain a definition for 'GetUserByEmail' and no accessible extension method 'GetUserByEmail' accepting a first argument of type 'UserService' could be found (are you missing a using directive or an assembly reference?) LuxusCoffee2.0 C:\Users\User\source\repos\LuxusCoffee2.0\Controllers\LoginController.cs 25 Active edit 2 per request namespace LuxusCoffee2._0.Controllers { [Route("api/[controller]")] [ApiController] public class LoginController : ControllerBase { private readonly UserService _userService; public LoginController(UserService userService) { _userService = userService; } [HttpPost] public async Task<IActionResult> Login(LoginRequest request) { var user = await _userService.GetUserByEmail(request.Email); if (user == null) { return BadRequest("Email or password is incorrect."); } A: So im dumb inside of IUserService.cs it appears i already defined a UserService that Inherits from IUserService and the reason it didnt recognize the method inside UserService is because it was using the UserService inside IUserService IUserService.cs using LuxusCoffee2._0.Models; using Microsoft.EntityFrameworkCore; public interface IUserService { Task<IEnumerable<User>> GetAllUsers(); Task<User> GetUserById(Guid id); Task AddUser(User user); Task UpdateUser(User user); Task DeleteUser(Guid id); Task<bool> UserExists(Guid id); } public class UserService : IUserService { private readonly LuxusCoffeeDbContext _dbContext; public UserService(LuxusCoffeeDbContext dbContext) { _dbContext = dbContext; } public async Task<IEnumerable<User>> GetAllUsers() { return await _dbContext.Users.ToListAsync(); } public async Task<User> GetUserById(Guid id) { return await _dbContext.Users.FindAsync(id); } public async Task AddUser(User user) { _dbContext.Users.Add(user); await _dbContext.SaveChangesAsync(); } public async Task UpdateUser(User user) { _dbContext.Users.Update(user); await _dbContext.SaveChangesAsync(); } public async Task DeleteUser(Guid id) { var user = await _dbContext.Users.FindAsync(id); if (user != null) { _dbContext.Users.Remove(user); await _dbContext.SaveChangesAsync(); } } public async Task<bool> UserExists(Guid id) // Implement the method in the service class { return await _dbContext.Users.AnyAsync(e => e.guid == id); } } UserService.cs using System.Collections.Generic; using System.Linq; using LuxusCoffee2._0.Models; using Microsoft.EntityFrameworkCore; namespace LuxusCoffee2._0.Services { public class UserService { private readonly LuxusCoffeeDbContext _context; public UserService(LuxusCoffeeDbContext context) { _context = context; } public List<User> GetAllUsers() { return _context.Users.ToList(); } public User GetUserById(int id) { return _context.Users.Find(id); } public void AddUser(User user) { _context.Users.Add(user); _context.SaveChanges(); } public async Task<User> GetUserByEmail(string email) { return await _context.Users.FirstOrDefaultAsync(u => u.Email == email); } public void UpdateUser(User user) { _context.Users.Update(user); _context.SaveChanges(); } public void DeleteUser(int id) { var user = _context.Users.Find(id); _context.Users.Remove(user); _context.SaveChanges(); } } } I fixed it by deleting UserService.cs and added the missing methods to the UserService present in IUserService.cs IUserService.cs using System.Collections.Generic; using System.Threading.Tasks; using LuxusCoffee2._0.Models; using Microsoft.EntityFrameworkCore; namespace LuxusCoffee2._0.Services { public interface IUserService { Task<IEnumerable<User>> GetAllUsers(); Task<User> GetUserById(Guid id); Task AddUser(User user); Task UpdateUser(User user); Task DeleteUser(Guid id); Task<bool> UserExists(Guid id); Task<User> GetUserByEmail(string email); } public class UserService : IUserService { private readonly LuxusCoffeeDbContext _dbContext; public UserService(LuxusCoffeeDbContext dbContext) { _dbContext = dbContext; } public async Task<IEnumerable<User>> GetAllUsers() { return await _dbContext.Users.ToListAsync(); } public async Task<User> GetUserById(Guid id) { return await _dbContext.Users.FindAsync(id); } public async Task AddUser(User user) { _dbContext.Users.Add(user); await _dbContext.SaveChangesAsync(); } public async Task UpdateUser(User user) { _dbContext.Users.Update(user); await _dbContext.SaveChangesAsync(); } public async Task DeleteUser(Guid id) { var user = await _dbContext.Users.FindAsync(id); if (user != null) { _dbContext.Users.Remove(user); await _dbContext.SaveChangesAsync(); } } public async Task<bool> UserExists(Guid id) { return await _dbContext.Users.AnyAsync(e => e.guid == id); } public async Task<User> GetUserByEmail(string email) { return await _dbContext.Users.FirstOrDefaultAsync(u => u.Email == email); } } } Im Dumb, yall smart, ty
{ "language": "en", "url": "https://stackoverflow.com/questions/75635579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hosting MySQL database on ec2 instance I'm new to AWS and I want to know how can I upload a MySQL database to an EC2 instance. I watched some tutorials and created new instances and set group rules like this: SSH - TCP - PORT 20 MySql/Aurora - TCP - PORT 3306 but It doesn't work and I can't even get the command line of the instance. A: SSH port is 22. Why are you using 20? allow HTTPS from anywhere for now. Install all required applications & then see if you can use mysql. Once you install mysql, you can use the dump option to make it running in your EC2
{ "language": "en", "url": "https://stackoverflow.com/questions/75635582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Vscode include errors detected. Please update includePath but path is updated/Windows11 I recently installed vscode for programming in c++ but i cant solve this error. https://i.stack.imgur.com/Opx0v.png * *I have installed mingw-w64 and msys2 *Set up path environment variable in the System Variable as "C:\msys64\mingw64\bin" *Installed vscode with the c++ and code runner extensions *The file is in a folder gcc is installed corectly
{ "language": "en", "url": "https://stackoverflow.com/questions/75635583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: I got this error " Data truncation: Incorrect date value: '1/1/2000' for column `schooldb`.`student`.`DOB` at row 1" I am trying to fetch data from my drag and dropped form, but the date entered in the date field can't be accepted by the database. String s1 = stdid.getText(); String s2 = name.getText(); String s3 = dob.getText(); String s6 = (String) combogender.getSelectedItem(); String s4 = email.getText(); String s7 = txtpassword.getText(); String s5 = contact.getText(); try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(cs,user,password); st = con.createStatement(); query = "INSERT INTO student(studentid,Name,DOB,gender,email,password,contact) values('"+s1+"','"+s2+"',DATE'"+s3+"','"+s6+"','"+s4+"','"+s7+"','"+s5+"')"; st.executeUpdate(query);
{ "language": "en", "url": "https://stackoverflow.com/questions/75635588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Subplots with common x and y labels and a common legend under the x-axis I am trying to plot a subplot with a common legend displayed at the bottom of the figure below a common x axis label, and with a common y-axis label. I have two ways of almost getting it working, except the first has the common y-axis label overlapping the axis tick labels, while with the second I can't figure out how to get the legend to show on the plot (it hangs off the page). Option 2, using the newer supx/ylabel, puts too much space between the subplots and the labels as well - but I think that is fixable (quite a few questions on that one). These are just example plots, actual plots use more decimals places in the labels, so the overlap is considerable. I will likely also be setting the figure sizes to print (and save) the plots was well. MWE import numpy as np import matplotlib.pyplot as plt # Some points to plot x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2) z = np.sin((1.03* x) ** 2) #option 1 - problem is with my real data the common y label is over the labels of the left hand plot fig, axs = plt.subplots(2, 2) axs[0, 0].plot(x, y) axs[0, 0].plot(x, z, '--') axs[0, 1].plot(x, y) axs[0, 1].plot(x, z, '--') axs[1, 0].plot(x, -y) axs[1, 0].plot(x, -z, '--') axs[1, 1].plot(x, -y) axs[1, 1].plot(x, -z, '--') fig.add_subplot(111, frameon=False) plt.tick_params(labelcolor='none', which='both', top=False, bottom=False, left=False, right=False) plt.xlabel("The X label") plt.ylabel("The Y label") fig.subplots_adjust(bottom=0.2) labels = ["A","B"] fig.legend(labels,loc='lower center', ncol=len(labels), bbox_to_anchor=(0.55, 0)) fig.tight_layout() # Option 2 - problem is I can't get the legend to show (it is off the page) fig, axs = plt.subplots(2, 2) axs[0, 0].plot(x, y) axs[0, 0].plot(x, z, '--') axs[0, 1].plot(x, y) axs[0, 1].plot(x, z, '--') axs[1, 0].plot(x, -y) axs[1, 0].plot(x, -z, '--') axs[1, 1].plot(x, -y) axs[1, 1].plot(x, -z, '--') fig.supxlabel("The X label") fig.supylabel("The Y label") fig.subplots_adjust(bottom=0.2) labels = ["A","B"] fig.legend(labels,loc='lower center', ncol=len(labels), bbox_to_anchor=(0.55, 0)) fig.tight_layout() A: You were almost there with your first option, adding labelpad to the ax.set_xlabel() and ax.set_ylabel() calls should fix your issue. Here is an updated version. # [...] fig, axs = plt.subplots(2, 2, figsize=(16, 8), tight_layout=True) # [...] # Create the new axis for marginal X and Y labels ax = fig.add_subplot(111, frameon=False) # Disable ticks. using ax.tick_params() works as well ax.set_xticks([]) ax.set_yticks([]) # Set X and Y label. Add labelpad so that the text does not overlap the ticks ax.set_xlabel("The X label", labelpad=20, fontsize=12) ax.set_ylabel("The Y label", labelpad=40, fontsize=12) # Set fig legend as you did labels = ["A","B"] fig.legend(labels, loc='lower center', ncol=len(labels), bbox_to_anchor=(0.55, 0))
{ "language": "en", "url": "https://stackoverflow.com/questions/75635590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to interpolate volatility's skew using spline in Pytho I have two lists to describe the function y(x) that represents strikes and the relative value of the skew of a volatility surface: x_points = [22.56, 27.07, 31.58, 36.10, 40.61, 45.12, 49.63, 54.14, 58.66, 63.17, 67.68] %strikes value y_points = [97.44, 87.32, 79.73, 75.47, 73.58, 74.53, 78.61, 83.64, 88.03, 92.26, 96.44] %vol value I would like to perform cubic spline interpolation to retrieve the range 0;200 of the skew but, using the below code, i get some negative values (not consistent solution): def f(x): x = np.linspace(0, 200, 399) tck = interpolate.splrep(x_points, y_points) return interpolate.splev(x, tck) Can you please give me some feedback and help to get the problem solved? Maybe the curve should not be fit with Cubic Spline or i should add some constraints to the optimization problem (no idea at all ...)
{ "language": "en", "url": "https://stackoverflow.com/questions/75635591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ : Is it possible to add multiple gRPC service definition in single proto file I am trying to understand how the gRPC services are created and servers are linked to them, if multiple services are defined in 1 proto file. (pls excuse for the long message) With example from this documentation, I created basic server (1 service defined in 1 proto file) and was able to run the client application. Service Definition in route_services.proto service RouteGuide { rpc GetFeature(Point) returns (Feature) {} } message Feature { // The name of the feature. string name = 1; // The point where the feature is detected. Point location = 2; } Sample Server Code Snippet in route_guide_server.cc class RouteGuideImpl : public RouteGuide::Service { ... // implement the service GetFeature ... } However, I am wondering if it's possible to have more than 1 service in 1 proto file and implement it's interface in Server like this below. Update Service Definition in route_services.proto (note: RouteGuidanceV2 service and NewFeature message) service RouteGuide { rpc GetFeature(Point) returns (Feature) {} } message Feature { // The name of the feature. string name = 1; // The point where the feature is detected. Point location = 2; } /////////////////// Newly Added Service /////////////////// service RouteGuideV2 { rpc GetFeature(Point) returns (NewFeature) {} } message NewFeature { // The point where the feature is detected. Point location = 1; } Update Server Code Snippet in route_guide_server.cc (note: RouteGuideV2 class is inherited here) class RouteGuideImpl : public RouteGuide::Service, public RouteGuideV2::Service { ... // implement the service GetFeature (coming from RouteGuide interface) // implement V2 service GetFeature (coming from RouteGuideV2 interface) ... } However, I am seeing this error : ‘grpc::Service’ is an ambiguous base. It occurs when compiling the server file (particularly at line where I am calling builder->RegisterService(this) to register my class RouteGuideImpl) From protoc compiler stand point, the updated proto file is also valid, and it generates the server and client code without any issue. Assuming that, defining 1 service in 1 proto file seems to be an ideal way and works just fine, I would like to ask few questions on this topic to understand the common practices from gRPC users. * *Is it not possible to derive multiple gRPC service class into single class to implement it's service methods ?? It may not be the best way to do it but I mean technically, it should be possible to override and implement gRPC virtual methods coming from 2 different service interfaces (1 each). *If RouteGuideV2 service GetFeature is functionally same with minor change in response message (Feature --> NewFeature), then doesn't it makes sense to define it in same proto file route_guide.proto instead of separate route_guide_v2.proto file? *If it's not correct to define several services, then what's the recommended way to add similar services ?? (or is there any limitations on how services should be define and run by server) Thanks for reading, waiting for responses...!!
{ "language": "en", "url": "https://stackoverflow.com/questions/75635592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a new Tensor to support batching from the input tensor in a custom layer in tensorflow functional API model I am working on a problem in which I have to create a custom layer in keras, which takes, output of a conv layer of a pre-trained model as an input. This custom layer work is to select K best feature maps based on shannon entropy for each images in that input tensor and then outputs the final tensor with k feature maps or each images. So that this output tensor is passed to other conv layer in the model. Let input tensor from a conv layer has shape = (None, 224,224, 128) and I want to take 64 best feature maps out of 128 based on shannon entropy . So the output tensor shape should be = (None, 224,224, 64). Below is the code snippet : class select_k_fmap(tf.keras.layers.Layer): def __init__(self): super(select_k_fmap, self).__init__() def build(self, input_shape): pass def call(self, inputs): shape = tf.shape(inputs) batch_size = shape[0] print('batch size **** ', batch_size) num_filters = shape[-1] img_height = shape[1] img_width = shape[2] k = 5 final_tensor = tf.zeros_like(inputs) def shanon_entropy(image): """ returns entropy of a single image with single channel """ value_ranges = [0.0, 1.0] nbins = 256 histogram_bin_indexes = tf.histogram_fixed_width_bins(image, value_ranges, nbins) _, _, count = tf.unique_with_counts(histogram_bin_indexes) prob = count/tf.reduce_sum(count) prob = tf.cast(prob, tf.float32) entropy = (-tf.reduce_sum(prob * tf.math.log(prob)))/(tf.math.log(2.0)) return entropy for i in range(int(batch_size)): entropy = [] for j in range(int(num_filters)): image_ith_filter = inputs[i,:,:,j] image_ith_filter_entropy = shanon_entropy(image_ith_filter) entropy.append(tf.get_static_value(image_ith_filter_entropy).item()) entropy_array = tf.argsort(entropy, direction='DESCENDING') k_best_entropy_sort_index = tf.get_static_value(entropy_sort_index[:k]).tolist() for index, element in enumerate(k_best_entropy_sort_index): final_tensor[i,:,:,index] = inputs[i,:,:,element] output_tensor = final_tensor[:,:,:,:k] return output_tensor # keras functional api x1 = resnet_152V2t.layers[5].output custom = select_k_fmap()(x1) x = keras.layers.MaxPooling2D(pool_size=(2, 2))(custom) . . . But when I ran this code I got error : enter image description here I have tried many solutions available on the internet. But nothing worked. I think this error is due to the shape of input tensor having None as first value in its shape (None, 224,224, 128). But I am unable to resolve this error. And also I don't want to fix batch size during defining Input(shape, batch_size). I want dynamic batch. It would be a great help for me if anyone of you could assist me. Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fix webpack postcss-preset-env is not optimized error I created a website a while ago using webpack and want to update it now. Unfortunately, when I run the project it will throw some errors out. One that I can't solve is that the version of postcss-preset-env is not optimised to work with PostCSS 8. I did already npm install postcss-loader --save-dev but then it will tell: 50 packages are looking for funding run npm fund for details I also did run npm fund, but I still get the same error. My package.json: { "name": "webpack-config", "version": "0.0.0", "description": "", "keywords": [], "author": "", "license": "ISC", "scripts": { "start": "webpack --config config/webpack.dev.js", "build": "webpack --config config/webpack.prod.js" }, "devDependencies": { "@babel/core": "^7.16.0", "@babel/preset-env": "^7.16.0", "babel-loader": "^8.2.3", "copy-webpack-plugin": "^10.2.4", "css-loader": "^6.5.1", "html-loader": "^3.1.0", "html-webpack-plugin": "^5.5.0", "mini-css-extract-plugin": "^2.4.4", "postcss": "^8.3.11", "postcss-loader": "^6.2.1", "postcss-preset-env": "^6.7.0", "sass": "^1.43.4", "sass-loader": "^12.3.0", "webpack": "^5.64.0", "webpack-cli": "^4.9.1" }, "dependencies": { "gsap": "^3.9.1" } } Hope someone can help me out.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Connect binance testnet futures user stream using python-binance I'm going to connect binance testnet futures user stream data using python-binance library. I tried following code: async def update_crypto_user_websocket(): async_client = get_async_client(True) socket_manager = get_binance_socket_manager(async_client) user_stream = socket_manager.futures_user_socket() # then start receiving messages async with user_stream as ts: while True: res = await ts.recv() print(res) async def main(): await asyncio.gather(update_crypto_user_websocket()) if __name__ == "__main__": asyncio.run(main()) get_async_client and get_binance_socket_manager are defined as below: async_client = None binance_socket_manager = None def get_async_client(is_testnet: bool, api_key: str = 'API_KEY', secret_key: str = 'SECRET_KEY'): try: global async_client if async_client is None: async_client = AsyncClient(api_key, secret_key, testnet=is_testnet) return async_client except Exception as err: print(err) raise HTTPException(status_code=404, detail="Binance not reachable") def get_binance_socket_manager(async_client_arg: AsyncClient): try: global binance_socket_manager if binance_socket_manager is None: binance_socket_manager = BinanceSocketManager(async_client_arg) return binance_socket_manager except Exception as err: print(err) raise HTTPException(status_code=404, detail="Binance not reachable") This socket waits until any change happens in account but when I run this code, nothing happens even if I submit or cancel order in binance testnet futures. What are the problems with this code and how can I get user socket data?
{ "language": "en", "url": "https://stackoverflow.com/questions/75635598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Knowledge Panel Scraper I'm trying to scrape the information that is in the google knowledge panels. The information I want is the Name, Bio, Born, and Education. Collecting this data is achievable when I have just one. Here I have used different scrapers and python scripts. My problem however is that I want to collect this data from a list of different people. So that the google search changes from an input file I gave the script to search through. I have tried tweaking two scripts from GitHub that does this for business. But it didn't work. Original Git: https://github.com/jnovak98/knowledge-panel-scraper.git My Git: https://github.com/Hovrud/Masters-.git Installation: Use git to clone the repository, then install the required libraries with the package manager pip. git clone https://github.com/Hovrud/Masters-.git cd Google_Knowledge_Panel_Person pip install -r requirements.txt Usage: python Google_Knowledge_Panel_Person.py inputfile_short.csv inputfile_short.csv should be a plain text CSV file with each row containing data to generate a search query for a person. For example: "Fred Wilson" "Chamath Palihapitiya" "Alexis Ohanian" "Benjamin Ling" "Andrew Marks" "Jeff Fagnan" "Bill Gurley" "Amy Wu" "Tench Coxe" "Aileen Lee" "Rashaun Williams" "Sam Teller" import csv, json, re, sys import requests # Set the headers for the GET request to Google headers_Get = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'DNT': '1', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1' } # Define HTML tags used in parsing the search results html_tags = { 'knowledge_panel': 'kno-ecr-pt', 'name': "kno-ecr-pt kno-fb-ctx", 'occupation':'wx62f PZPZlf x7XAkb', 'bio': 'Uo8X3b OhScic zsYMMe', 'born': 'LrzXr kno-fv wHYlTd z8gr9e', 'education': 'LrzXr kno-fv wHYlTd z8gr9e' } # Define regular expressions used in parsing the search results html_regexes = { 'name': '<span>(.*)</span>', 'occupation':'<span>(.*)</span>', 'bio': '<span>(.*)</span>', 'born': '<span class="LrzXr kno-fv wHYlTd z8gr9e">([\w\s]+),\s<a[^>]+>([\w\s,]+)<\/a>', 'education': '<span>(.*)</span>' } # Function to make a Google search and return the HTML results def google(q): s = requests.Session() q = '+'.join(q.split()) url = 'https://www.google.com/search?q=' + q + '&ie=utf-8&oe=utf-8' r = s.get(url, headers=headers_Get) return r.text # Function to extract text from an HTML tag using a regular expression def get_string_after_tag(string, tag, regex, distance): if tag not in string: return '' index = string.find(tag) substr = string[index:index+distance] match = re.search(regex, substr) if match: return match.group(1).strip() else: return '' # Function to extract information from the search results for a given query def get_details(query): html_results = google(query) results = {'query':query} has_knowledge_panel = html_tags['knowledge_panel'] in html_results if has_knowledge_panel: results['exists'] = True results['name'] = get_string_after_tag(html_results, html_tags['name'],html_regexes['name'],500) occupation = get_string_after_tag(html_results, html_tags['occupation'],html_regexes['occupation'],500) if(occupation): results['occupation'] = occupation ## The 1000 in the get_string_after_tag function call represents the maximum number of characters to search for after the HTML tag that matches the bio regex. bio = get_string_after_tag(html_results, html_tags['bio'],html_regexes['bio'],1000) if(bio): results['bio'] = bio born = get_string_after_tag(html_results, html_tags['born'],html_regexes['born'],500) if(born): results['born'] = born education = get_string_after_tag(html_results, html_tags['education '],html_regexes['education '],500) if(education): results['education '] = education else: results['exists'] = False return results # Open the CSV file specified by the first command-line argument, and create a new file called 'results.csv' # to store the results. if __name__ == "__main__": with open(sys.argv[1], newline='') as csvfile: with open('results.csv', 'w', newline='') as results: reader = csv.reader(csvfile) fieldnames = ['query','exists', 'name','occupation', 'bio', 'born', 'education'] writer = csv.DictWriter(results, fieldnames=fieldnames) writer.writeheader() for row in reader: print(reader.line_num) writer.writerow(get_details(u" ".join(row)))
{ "language": "en", "url": "https://stackoverflow.com/questions/75635601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Python stop iterative deepening search based on time I am currently developing an iterative deepening search and would like to stop it based on time. My code looks like this: def __init__(self, name='Agent', time_limit_s=5): self.name = name self.time_limit_s = time_limit_s self.stop_event = threading.Event() def move(self, board): ''' This method is called by the game engine to get the next move from the bot. It is time-limited, and uses the update_best_move method to get the best move. ''' # Perform the iterative deepening search # Set up a shared variable to store the best result found best_move = None best_result_lock = threading.Lock() # Set up a separate thread to run the search loop search_thread = threading.Thread(target=self.run_search, args=(board, best_move, best_result_lock)) # Start the search thread and run the search search_thread.start() # Wait for the search thread to finish or raise a TimeoutException search_thread.join(timeout=self.time_limit_s) # timeout does not end the execution, merely waits for this long if search_thread.is_alive(): print('Thread still alive') self.stop_event.set() # Set the stop event to signal the search thread to stop running return best_move def run_search(self, board, best_move, best_result_lock): ''' This method is called by the iterative_deepening_search method to run the search loop. ''' cur_best_move = None depth = 1 try: while not self.stop_event.is_set(): cur_best_move, done = self.update_best_move(board, depth, cur_best_move) with best_result_lock: # set the value of best_move in thread safe manner best_move = cur_best_move if done or self.stop_event.is_set(): break depth += 1 except TimeoutException: print('Time limit reached') with best_result_lock: # set the value of best_move in thread safe manner best_move = cur_best_move However, the following scenario keeps happening: Time limit: 5 seconds * *Iteration 1: 0 seconds *Iteration 2: 0 seconds *Iteration 3: 1 second *Iteration 4: 3 seconds Now we almost maxed out the available 5 seconds, but because 5 seconds have not elapsed, another iteration is started * *Iteration 5: 12 seconds In total we have now let 16 seconds pass by instead of 5. And you can imagine that the scenario could be even worse. How can i adjust my code so that it definetly stops after the set time_limit_s seconds? Solutions are gladly appreciated. I tried using time and threading.Event() to signal the code to stop, but it kept going over the time limit as explained above. A: This can be difficult as you need to check if time has elapsed. As you check after or before every iteration, you only check after iteration_time which does vary. What you could do is make another thread which has one function: checking elapsed time, and stopping the other thread if needed. Even this won't stop after exactly the time you want, BUT the difference will be so small you won't even notice it. This is a solution, I hope answers your questions, if any more questions please hit me up.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: angular not sending antiforgytoken I want to use AntiForge Token in an Angular project I have also written the back-end with ASP.NET Core middleware code is if (path != null) { var tokens = _antiforgery.GetAndStoreTokens(context); context.Response.Cookies.Append( key: "XSRF-TOKEN", value: tokens.RequestToken, options: new CookieOptions { Path="/", HttpOnly = false // Now JavaScript is able to read the cookie }); } return _next(context); \\startup app.UseAntiforgeryToken(); services.AddAntiforgery(x => x.HeaderName = "X-XSRF-TOKEN"); But what happens if I use ValidateAntiForgeryToken, my function does not run because the XSRF-TOKEN cookie is not sent to it. headers = headers.set('Content-Type', 'application/json; charset=utf-8'); return this._httpClient.post(environment.authUrl+ 'api/Account/login',credentials,{headers: headers }).pipe( switchMap((response: any) => { // Store the access token in the local storage this.accessToken = response.access_token; this.refreshToken = response.refresh_token; // Set the authenticated flag to true this._authenticated = true; //Store the user on the user service this._userService.user = response.user; // Return a new observable with the response return of(response); }) ); When I checked, I noticed that XSRF-TOKEN cookies are returned at the time of the first request, but they are not saved in the browser There is a point that if I call the API directly and not with Ajax, this token is saved in the browser. After this, the tokens will be stored in the cookie, but the XSRF-TOKEN will not be sent in the request
{ "language": "en", "url": "https://stackoverflow.com/questions/75635604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which architecture should I use for Apache Superset: AMD64 or ARM64? I'm planning to use Apache Superset for data visualization and analysis, but I'm not sure which architecture to choose: AMD64 or ARM64. I'm running my applications on a cloud server and I have the option to choose either architecture. I've read that AMD64 is the most common architecture for server applications, but I've also heard that ARM64 is becoming more popular for cloud servers due to its energy efficiency and lower cost. Which architecture do you recommend for running Apache Superset on a cloud server?
{ "language": "en", "url": "https://stackoverflow.com/questions/75635605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: getting error as Exception in Tkinter callback and Attribute Error: 'NoneType' Object has no attribute 'group' I am trying to create a translator with help of Tkinter and googletrans library but getting following error and I am confuse as I am not sure is this error due to library or a mistake from my side. from tkinter import * from tkinter import ttk from googletrans import Translator,LANGUAGES def change(text="Type", src="English", dest="Hindi"): text1=text src1=src dest1=dest trans= Translator() trans1= trans.translate(text,src=src1,dest=dest1) return trans1 def data(): s = comb_sor.get() d = comb_dest.get() msg= Sor_txt.get(1.0,END) textget = change(text= msg, src=s, dest=d) dest_txt.delete(1.0,END) dest_txt.insert(END,textget) root = Tk() root.title("Translator") root.geometry("500x700") root.config(bg='#f1f3f5') lab_txt=Label(root, text="Translator", font=("Inter", 30, "bold"), bg="#f1f3f5", fg="#495057") lab_txt.place(x=100, y=40, height=50, width=300) frame = Frame(root).pack(side=BOTTOM) lab_txt=Label(root, text="Source Text", font=("Inter", 16, "bold"), bg="#f1f3f5", fg="#495057") lab_txt.place(x=100, y=100, height=30, width=300) Sor_txt = Text(frame, font=("Inter", 18, "bold"), bg="#f1f3f5", wrap=WORD) Sor_txt.place(x=10, y=130, height=150, width=480) list_text = list(LANGUAGES.values()) comb_sor = ttk.Combobox(frame, value=list_text) comb_sor.place(x=10, y=300, height=40, width=150) comb_sor.set("English") button_change = Button(frame, text="Translate", relief=RAISED, command=data) button_change.place(x=170, y=300, height=40, width=150) comb_dest = ttk.Combobox(frame, value=list_text) comb_dest.place(x=330, y=300, height=40, width=150) comb_dest.set("English") lab_txt=Label(root, text="Destination Text", font=("Inter", 16, "bold"), bg="#f1f3f5", fg="#495057") lab_txt.place(x=100, y=360, height=30, width=300) dest_txt = Text(frame, font=("Inter", 18, "bold"), bg="#f1f3f5", wrap=WORD) dest_txt.place(x=10, y=400, height=150, width=480) root.mainloop() Please find the snippet of error below Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1921, in __call__ return self.func(*args) File "e:\AWS Cloud Practioner\Translator\main.py", line 17, in data textget = change(text= msg, src=s, dest=d) File "e:\AWS Cloud Practioner\Translator\main.py", line 10, in change trans1= trans.translate(text,src=src1,dest=dest1) File "C:\Users\ghago\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googletrans\client.py", line 182, in translate data = self._translate(text, dest, src, kwargs) File "C:\Users\ghago\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googletrans\client.py", line 78, in _translate token = self.token_acquirer.do(text) File "C:\Users\ghago\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googletrans\gtoken.py", line 194, in do self._update() File "C:\Users\ghago\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googletrans\gtoken.py", line 62, in _update code = self.RE_TKK.search(r.text).group(1).replace('var ', '') AttributeError: 'NoneType' object has no attribute 'group' I tries installing mttinker (new to me) and changing google translate version as well but no solution is found
{ "language": "en", "url": "https://stackoverflow.com/questions/75635608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pacman game with Pygame I am making a pacman game with python. Currently, the player moves continuously if I hold a certain key. So, for example, if I hold the left key, the player moves continuously to the left. But in the original pacman game, you can just press a key 1 time to move continuously instead of holding it. So I want to make the player be able to move continuously if the key is pressed, not if the key is holded. This part is responsible for the player: class Player(pygame.sprite.Sprite): # Set speed vector change_x=0 change_y=0 # Constructor function def __init__(self,x,y, filename): # Call the parent's constructor pygame.sprite.Sprite.__init__(self) # Set height, width self.image = pygame.image.load(filename).convert() # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.top = y self.rect.left = x self.prev_x = x self.prev_y = y # Clear the speed of the player def prevdirection(self): self.prev_x = self.change_x self.prev_y = self.change_y # Change the speed of the player def changespeed(self,x,y): self.change_x+=x self.change_y+=y # Find a new position for the player def update(self,walls,gate): # Get the old position, in case we need to go back to it old_x=self.rect.left new_x=old_x+self.change_x prev_x=old_x+self.prev_x self.rect.left = new_x old_y=self.rect.top new_y=old_y+self.change_y prev_y=old_y+self.prev_y # Did this update cause us to hit a wall? x_collide = pygame.sprite.spritecollide(self, walls, False) if x_collide: # Whoops, hit a wall. Go back to the old position self.rect.left=old_x # self.rect.top=prev_y # y_collide = pygame.sprite.spritecollide(self, walls, False) # if y_collide: # # Whoops, hit a wall. Go back to the old position # self.rect.top=old_y # print('a') else: self.rect.top = new_y # Did this update cause us to hit a wall? y_collide = pygame.sprite.spritecollide(self, walls, False) if y_collide: # Whoops, hit a wall. Go back to the old position self.rect.top=old_y # self.rect.left=prev_x # x_collide = pygame.sprite.spritecollide(self, walls, False) # if x_collide: # # Whoops, hit a wall. Go back to the old position # self.rect.left=old_x # print('b') if gate != False: gate_hit = pygame.sprite.spritecollide(self, gate, False) if gate_hit: self.rect.left=old_x self.rect.top=old_y This is event proccessing: bll = len(block_list) score = 0 done = False i = 0 while done == False: # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT for event in pygame.event.get(): if event.type == pygame.QUIT: done=True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: Pacman.changespeed(-30,0) if event.key == pygame.K_RIGHT: Pacman.changespeed(30,0) if event.key == pygame.K_UP: Pacman.changespeed(0,-30) if event.key == pygame.K_DOWN: Pacman.changespeed(0,30) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: Pacman.changespeed(30,0) if event.key == pygame.K_RIGHT: Pacman.changespeed(-30,0) if event.key == pygame.K_UP: Pacman.changespeed(0,30) if event.key == pygame.K_DOWN: Pacman.changespeed(0,-30) # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT Pacman.update(wall_list,gate) returned = Pinky.changespeed(Pinky_directions,False,p_turn,p_steps,pl) p_turn = returned[0] p_steps = returned[1] Pinky.changespeed(Pinky_directions,False,p_turn,p_steps,pl) Pinky.update(wall_list,False) returned = Blinky.changespeed(Blinky_directions,False,b_turn,b_steps,bl) b_turn = returned[0] b_steps = returned[1] Blinky.changespeed(Blinky_directions,False,b_turn,b_steps,bl) Blinky.update(wall_list,False) returned = Inky.changespeed(Inky_directions,False,i_turn,i_steps,il) i_turn = returned[0] i_steps = returned[1] Inky.changespeed(Inky_directions,False,i_turn,i_steps,il) Inky.update(wall_list,False) returned = Clyde.changespeed(Clyde_directions,"clyde",c_turn,c_steps,cl) c_turn = returned[0] c_steps = returned[1] Clyde.changespeed(Clyde_directions,"clyde",c_turn,c_steps,cl) Clyde.update(wall_list,False) # See if the Pacman block has collided with anything. blocks_hit_list = pygame.sprite.spritecollide(Pacman, block_list, True) # Check the list of collisions. if len(blocks_hit_list) > 0: score +=len(blocks_hit_list) # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT screen.fill(black) wall_list.draw(screen) gate.draw(screen) all_sprites_list.draw(screen) monsta_list.draw(screen) text=font.render("Score: "+str(score)+"/"+str(bll), True, red) screen.blit(text, [10, 10]) if score == bll: doNext("Congratulations, you won!",145,all_sprites_list,block_list,monsta_list,pacman_collide,wall_list,gate) monsta_hit_list = pygame.sprite.spritecollide(Pacman, monsta_list, False) if monsta_hit_list: doNext("Game Over",235,all_sprites_list,block_list,monsta_list,pacman_collide,wall_list,gate) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT pygame.display.flip() clock.tick(10) This is the full code: #Pacman in Python with PyGame #https://github.com/hbokmann/Pacman import pygame black = (0,0,0) white = (255,255,255) blue = (0,0,255) green = (0,255,0) red = (255,0,0) purple = (255,0,255) yellow = ( 255, 255, 0) Trollicon=pygame.image.load('images/Trollman.png') pygame.display.set_icon(Trollicon) #Add music pygame.mixer.init() pygame.mixer.music.load('pacman.mp3') pygame.mixer.music.play(-1, 0.0) # This class represents the bar at the bottom that the player controls class Wall(pygame.sprite.Sprite): # Constructor function def __init__(self,x,y,width,height, color): # Call the parent's constructor pygame.sprite.Sprite.__init__(self) # Make a blue wall, of the size specified in the parameters self.image = pygame.Surface([width, height]) self.image.fill(color) # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.top = y self.rect.left = x # This creates all the walls in room 1 def setupRoomOne(all_sprites_list): # Make the walls. (x_pos, y_pos, width, height) wall_list=pygame.sprite.RenderPlain() # This is a list of walls. Each is in the form [x, y, width, height] walls = [ [0,0,6,600], [0,0,600,6], [0,600,606,6], [600,0,6,606], [300,0,6,66], [60,60,186,6], [360,60,186,6], [60,120,66,6], [60,120,6,126], [180,120,246,6], [300,120,6,66], [480,120,66,6], [540,120,6,126], [120,180,126,6], [120,180,6,126], [360,180,126,6], [480,180,6,126], [180,240,6,126], [180,360,246,6], [420,240,6,126], [240,240,42,6], [324,240,42,6], [240,240,6,66], [240,300,126,6], [360,240,6,66], [0,300,66,6], [540,300,66,6], [60,360,66,6], [60,360,6,186], [480,360,66,6], [540,360,6,186], [120,420,366,6], [120,420,6,66], [480,420,6,66], [180,480,246,6], [300,480,6,66], [120,540,126,6], [360,540,126,6] ] # Loop through the list. Create the wall, add it to the list for item in walls: wall=Wall(item[0],item[1],item[2],item[3],blue) wall_list.add(wall) all_sprites_list.add(wall) # return our new list return wall_list def setupGate(all_sprites_list): gate = pygame.sprite.RenderPlain() gate.add(Wall(282,242,42,2,white)) all_sprites_list.add(gate) return gate # This class represents the ball # It derives from the "Sprite" class in Pygame class Block(pygame.sprite.Sprite): # Constructor. Pass in the color of the block, # and its x and y position def __init__(self, color, width, height): # Call the parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self) # Create an image of the block, and fill it with a color. # This could also be an image loaded from the disk. self.image = pygame.Surface([width, height]) self.image.fill(white) self.image.set_colorkey(white) pygame.draw.ellipse(self.image,color,[0,0,width,height]) # Fetch the rectangle object that has the dimensions of the image # image. # Update the position of this object by setting the values # of rect.x and rect.y self.rect = self.image.get_rect() # This class represents the bar at the bottom that the player controls class Player(pygame.sprite.Sprite): # Set speed vector change_x=0 change_y=0 # Constructor function def __init__(self,x,y, filename): # Call the parent's constructor pygame.sprite.Sprite.__init__(self) # Set height, width self.image = pygame.image.load(filename).convert() # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.top = y self.rect.left = x self.prev_x = x self.prev_y = y # Clear the speed of the player def prevdirection(self): self.prev_x = self.change_x self.prev_y = self.change_y # Change the speed of the player def changespeed(self,x,y): self.change_x+=x self.change_y+=y # Find a new position for the player def update(self,walls,gate): # Get the old position, in case we need to go back to it old_x=self.rect.left new_x=old_x+self.change_x prev_x=old_x+self.prev_x self.rect.left = new_x old_y=self.rect.top new_y=old_y+self.change_y prev_y=old_y+self.prev_y # Did this update cause us to hit a wall? x_collide = pygame.sprite.spritecollide(self, walls, False) if x_collide: # Whoops, hit a wall. Go back to the old position self.rect.left=old_x # self.rect.top=prev_y # y_collide = pygame.sprite.spritecollide(self, walls, False) # if y_collide: # # Whoops, hit a wall. Go back to the old position # self.rect.top=old_y # print('a') else: self.rect.top = new_y # Did this update cause us to hit a wall? y_collide = pygame.sprite.spritecollide(self, walls, False) if y_collide: # Whoops, hit a wall. Go back to the old position self.rect.top=old_y # self.rect.left=prev_x # x_collide = pygame.sprite.spritecollide(self, walls, False) # if x_collide: # # Whoops, hit a wall. Go back to the old position # self.rect.left=old_x # print('b') if gate != False: gate_hit = pygame.sprite.spritecollide(self, gate, False) if gate_hit: self.rect.left=old_x self.rect.top=old_y #Inheritime Player klassist class Ghost(Player): # Change the speed of the ghost def changespeed(self,list,ghost,turn,steps,l): try: z=list[turn][2] if steps < z: self.change_x=list[turn][0] self.change_y=list[turn][1] steps+=1 else: if turn < l: turn+=1 elif ghost == "clyde": turn = 2 else: turn = 0 self.change_x=list[turn][0] self.change_y=list[turn][1] steps = 0 return [turn,steps] except IndexError: return [0,0] Pinky_directions = [ [0,-30,4], [15,0,9], [0,15,11], [-15,0,23], [0,15,7], [15,0,3], [0,-15,3], [15,0,19], [0,15,3], [15,0,3], [0,15,3], [15,0,3], [0,-15,15], [-15,0,7], [0,15,3], [-15,0,19], [0,-15,11], [15,0,9] ] Blinky_directions = [ [0,-15,4], [15,0,9], [0,15,11], [15,0,3], [0,15,7], [-15,0,11], [0,15,3], [15,0,15], [0,-15,15], [15,0,3], [0,-15,11], [-15,0,3], [0,-15,11], [-15,0,3], [0,-15,3], [-15,0,7], [0,-15,3], [15,0,15], [0,15,15], [-15,0,3], [0,15,3], [-15,0,3], [0,-15,7], [-15,0,3], [0,15,7], [-15,0,11], [0,-15,7], [15,0,5] ] Inky_directions = [ [30,0,2], [0,-15,4], [15,0,10], [0,15,7], [15,0,3], [0,-15,3], [15,0,3], [0,-15,15], [-15,0,15], [0,15,3], [15,0,15], [0,15,11], [-15,0,3], [0,-15,7], [-15,0,11], [0,15,3], [-15,0,11], [0,15,7], [-15,0,3], [0,-15,3], [-15,0,3], [0,-15,15], [15,0,15], [0,15,3], [-15,0,15], [0,15,11], [15,0,3], [0,-15,11], [15,0,11], [0,15,3], [15,0,1], ] Clyde_directions = [ [-30,0,2], [0,-15,4], [15,0,5], [0,15,7], [-15,0,11], [0,-15,7], [-15,0,3], [0,15,7], [-15,0,7], [0,15,15], [15,0,15], [0,-15,3], [-15,0,11], [0,-15,7], [15,0,3], [0,-15,11], [15,0,9], ] pl = len(Pinky_directions)-1 bl = len(Blinky_directions)-1 il = len(Inky_directions)-1 cl = len(Clyde_directions)-1 # Call this function so the Pygame library can initialize itself pygame.init() # Create an 606x606 sized screen screen = pygame.display.set_mode([606, 606]) # This is a list of 'sprites.' Each block in the program is # added to this list. The list is managed by a class called 'RenderPlain.' # Set the title of the window pygame.display.set_caption('Pacman') # Create a surface we can draw on background = pygame.Surface(screen.get_size()) # Used for converting color maps and such background = background.convert() # Fill the screen with a black background background.fill(black) clock = pygame.time.Clock() pygame.font.init() font = pygame.font.Font("freesansbold.ttf", 24) #default locations for Pacman and monstas w = 303-16 #Width p_h = (7*60)+19 #Pacman height m_h = (4*60)+19 #Monster height b_h = (3*60)+19 #Binky height i_w = 303-16-32 #Inky width c_w = 303+(32-16) #Clyde width def startGame(): all_sprites_list = pygame.sprite.RenderPlain() block_list = pygame.sprite.RenderPlain() monsta_list = pygame.sprite.RenderPlain() pacman_collide = pygame.sprite.RenderPlain() wall_list = setupRoomOne(all_sprites_list) gate = setupGate(all_sprites_list) p_turn = 0 p_steps = 0 b_turn = 0 b_steps = 0 i_turn = 0 i_steps = 0 c_turn = 0 c_steps = 0 # Create the player paddle object Pacman = Player( w, p_h, "images/Trollman.png" ) all_sprites_list.add(Pacman) pacman_collide.add(Pacman) Blinky=Ghost( w, b_h, "images/Blinky.png" ) monsta_list.add(Blinky) all_sprites_list.add(Blinky) Pinky=Ghost( w, m_h, "images/Pinky.png" ) monsta_list.add(Pinky) all_sprites_list.add(Pinky) Inky=Ghost( i_w, m_h, "images/Inky.png" ) monsta_list.add(Inky) all_sprites_list.add(Inky) Clyde=Ghost( c_w, m_h, "images/Clyde.png" ) monsta_list.add(Clyde) all_sprites_list.add(Clyde) # Draw the grid for row in range(19): for column in range(19): if (row == 7 or row == 8) and (column == 8 or column == 9 or column == 10): continue else: block = Block(yellow, 4, 4) # Set a random location for the block block.rect.x = (30*column+6)+26 block.rect.y = (30*row+6)+26 b_collide = pygame.sprite.spritecollide(block, wall_list, False) p_collide = pygame.sprite.spritecollide(block, pacman_collide, False) if b_collide: continue elif p_collide: continue else: # Add the block to the list of objects block_list.add(block) all_sprites_list.add(block) bll = len(block_list) score = 0 done = False i = 0 while done == False: # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT for event in pygame.event.get(): if event.type == pygame.QUIT: done=True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: Pacman.changespeed(-30,0) if event.key == pygame.K_RIGHT: Pacman.changespeed(30,0) if event.key == pygame.K_UP: Pacman.changespeed(0,-30) if event.key == pygame.K_DOWN: Pacman.changespeed(0,30) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: Pacman.changespeed(30,0) if event.key == pygame.K_RIGHT: Pacman.changespeed(-30,0) if event.key == pygame.K_UP: Pacman.changespeed(0,30) if event.key == pygame.K_DOWN: Pacman.changespeed(0,-30) # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT Pacman.update(wall_list,gate) returned = Pinky.changespeed(Pinky_directions,False,p_turn,p_steps,pl) p_turn = returned[0] p_steps = returned[1] Pinky.changespeed(Pinky_directions,False,p_turn,p_steps,pl) Pinky.update(wall_list,False) returned = Blinky.changespeed(Blinky_directions,False,b_turn,b_steps,bl) b_turn = returned[0] b_steps = returned[1] Blinky.changespeed(Blinky_directions,False,b_turn,b_steps,bl) Blinky.update(wall_list,False) returned = Inky.changespeed(Inky_directions,False,i_turn,i_steps,il) i_turn = returned[0] i_steps = returned[1] Inky.changespeed(Inky_directions,False,i_turn,i_steps,il) Inky.update(wall_list,False) returned = Clyde.changespeed(Clyde_directions,"clyde",c_turn,c_steps,cl) c_turn = returned[0] c_steps = returned[1] Clyde.changespeed(Clyde_directions,"clyde",c_turn,c_steps,cl) Clyde.update(wall_list,False) # See if the Pacman block has collided with anything. blocks_hit_list = pygame.sprite.spritecollide(Pacman, block_list, True) # Check the list of collisions. if len(blocks_hit_list) > 0: score +=len(blocks_hit_list) # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT screen.fill(black) wall_list.draw(screen) gate.draw(screen) all_sprites_list.draw(screen) monsta_list.draw(screen) text=font.render("Score: "+str(score)+"/"+str(bll), True, red) screen.blit(text, [10, 10]) if score == bll: doNext("Congratulations, you won!",145,all_sprites_list,block_list,monsta_list,pacman_collide,wall_list,gate) monsta_hit_list = pygame.sprite.spritecollide(Pacman, monsta_list, False) if monsta_hit_list: doNext("Game Over",235,all_sprites_list,block_list,monsta_list,pacman_collide,wall_list,gate) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT pygame.display.flip() clock.tick(10) def doNext(message,left,all_sprites_list,block_list,monsta_list,pacman_collide,wall_list,gate): while True: # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() if event.key == pygame.K_RETURN: del all_sprites_list del block_list del monsta_list del pacman_collide del wall_list del gate startGame() #Grey background w = pygame.Surface((400,200)) # the size of your rect w.set_alpha(10) # alpha level w.fill((128,128,128)) # this fills the entire surface screen.blit(w, (100,200)) # (0,0) are the top-left coordinates #Won or lost text1=font.render(message, True, white) screen.blit(text1, [left, 233]) text2=font.render("To play again, press ENTER.", True, white) screen.blit(text2, [135, 303]) text3=font.render("To quit, press ESCAPE.", True, white) screen.blit(text3, [165, 333]) pygame.display.flip() clock.tick(10) startGame() pygame.quit()
{ "language": "en", "url": "https://stackoverflow.com/questions/75635611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding a reactive object to an array of my Vue component I am trying to get my Vue component to handle a list of objects with variable length with a date and boolean attribute. The list is a list of vacation days for employees. I want to add vacation days and marks them as repeating every year. <template> <div> <b-row v-for="vacation in employee.vacations" :key="vacation.id"> <b-col> <b-input type="date" v-model="vacation.date"></b-input> </b-col> <b-col> <b-form-checkbox :v-model="vacation.yearlyRepetition"> Jährlich wiederholend </b-form-checkbox> </b-col> </b-row> <b-button @click="addVacation"> <b-icon-plus /> </b-button> </div> </template> <script> export default { data() { return { employee: this.value, }; }, props: { value: { type: Object, default: () => { return { vacations: [ { id: "vac-1", date: "2022-12-23", yearlyRepetition: true, }, ], }; }, }, }, methods: { addVacation() { this.employee.vacations.push({ id: "vac-2", date: "2022-12-24", yearlyRepetition: false, }); }, }, }; </script> My problem is that for some reason when the second checkbox is clicked, the value for the first checkbox changes. GIF of the error This is probably some faulty combination of connections between * *props *reactive objects *List rendering What can I do to fix this? I've tried using this.$set, but I don't quite get it and nothing seemed to work. When logging the data of the component, all values seem to be set correctly, but when I logged only the vacations, I realized that the originally (first) vacation day in the array is an Observer and the second one is a regular object. I don't understand the difference...
{ "language": "en", "url": "https://stackoverflow.com/questions/75635613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular: get notified when jwt expired / isAuthenticated should change to false i have got an Angular Application with JWT Authentication. I check the status in the token-auth.service.ts public isAuthenticated(): boolean { const token = localStorage.getItem('auth_token'); if (token) { if(this.jwtHelper.isTokenExpired(token)){ return false; } return true; }else{ //this.destroyToken(); return false; } } To get notified when the status changes, i added this to the service private loggedIn = new BehaviorSubject<boolean>(this.isAuthenticated()); get LoggedInChanged(){ return this.isAuthenticated().asObservable(); } in the app.component.ts is subscribe to observable: ngOnInit() { this.tokenAuthService.LoggedInChanged.subscribe(res => { console.log(res) if (res) { console.log('eingeloggt '+ res) ; } else { console.log('ausgeloggt '+ res); } }); But when the JWT expires, i dont get a log on the console. Do you have any idea? A: I think this has nothing to do with the JWT, you are setting a current value in behaviour subject but he doesn't know that the function return another value, it just setted up a value, you will need to check the function all the time and detect it this way... Can you try and change this isAuthenticated() function: public isAuthenticated(): Observable<boolean> { const token = localStorage.getItem('auth_token'); return of(!!token && !this.jwtHelper.isTokenExpired(token) ? true : false); } And after that you will need only: public loggedInChanged: Observable<boolean> = this.isAuthenticated(); Now when you subscribe to loggedInChange I think you will detect the changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want to drag and drop item to AntDesign Tree from outside of the tree! how to achieve this? I have implemented Ant Design Tree, In that, I have enabled drag-and-drop feature. DnD from outside the tree is not responding or showing anything while dragging. any Idea how to tackle this link to Ant Design Tree
{ "language": "en", "url": "https://stackoverflow.com/questions/75635615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I have an angle that changes based on player input using lerp, but it doesnt lerp when the target is zero This few lines of code apply 25 degrees to the players rotation by using the x_value it either gives 1,0 or -1, it works fine if I am pressing left or right but when I let go the player.target_value should be set to 0, which it is from my debugging but it doesn't lerp to 0 making the player stay in its previous angle, I have scratched my head for a few moments and I cant figure it out why it doesn't change, I could be missing something completely but I have no clue. -- Check if the player is moving along the x axis, if not we set its angle to 0 if x_value ~= 0 then -- Check if the target angle has changed if player.target_angle ~= 25 * x_value then player.target_angle = 25 * x_value player.target_angle_changed = true end else -- if the player isnt moving left or right set angle to zero and angle changed to true player.target_angle = 0 player.target_angle_changed = true end -- Check if the target angle has changed if player.target_angle_changed then progress = 0 player.target_angle_changed = false else -- if the target angle has not changed we start moving the value with progress + dt progress = math.min(progress + dt / duration, 1) end -- Apply the rotation to the player with lerp player.angle = lerp(player.angle, player.target_angle, progress) -- DEBUG to see the progress value = "Target_Value: " .. player.target_angle .. " Player_Angle" .. player.angle The lerp function: function lerp(a, b, t) return a + (b - a) * t end A: If you are not moving, you set target_angle_changed = true. if player.target_angle_changed you set progress = 0. When progress is zero, lerp only uses the first input, which is the previous angle. Therefore, when you are not moving, you do not change the angle. I need more context for a solution, but right now it's definitely not what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pycharm SSH and visualization I have successfully connected to the SFTP server following this link. However, when using matplotlib for visualization, it doesn't work without any warning. This indicates that the figure has been generated but not displayed. Is there any way to solve this? Many thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Add a checkmark to a toggle switch using HTML and CSS I can't seem to get a checkmark to display in the toggle. I have the following CSS: /* CSS for toggle checkbox */ #toggle { display: none; } .toggle-checkbox label, .toggle-checkbox label, .toggle-checkbox label { transition: 400ms all ease-in-out 50ms; box-sizing: border-box; backface-visibility: hidden; } .toggle-checkbox { height: 25px; width: 50px; background: rgba(43, 43, 43, 1); position: relative; box-shadow: 0 0 2px rgba(43, 43, 43, 1); border-radius: 50px; transition: background 0.5s ease-out, box-shadow 0.5s ease-out; } #toggle:checked~.toggle-checkbox { background: rgba(73, 168, 68, 1); box-shadow: 0 0 2px rgba(73, 168, 68, 1); } .toggle-checkbox label::before { content: ''; height: 10px; width: 2px; position: absolute; top: calc(50% - 5px); left: calc(50% - 1px); transform: rotate(45deg); background: rgba(43, 43, 43, 1); border-radius: 5px; } .toggle-checkbox label::after { content: ''; height: 2px; width: 10px; position: absolute; top: calc(50% - 1px); left: calc(50% - 5px); transform: rotate(45deg); background: rgba(43, 43, 43, 1); border-radius: 5px; } .toggle-checkbox label { height: 20px; width: 20px; background: rgba(255, 255, 255, 1); position: absolute; top: 2.5px; left: 2.5px; cursor: pointer; border-radius: 50px; } #toggle:checked~.toggle-checkbox label { left: 25px; transform: rotate(360deg); } #toggle:checked~.toggle-checkbox label::before { content: ''; height: 8px; width: 2px; position: absolute; top: calc(50% - 4px); left: calc(50% - 1px); transform: rotate(45deg); background: rgba(73, 168, 68, 1); border-radius: 5px; } #toggle:checked~.toggle-checkbox label::after { content: ''; height: 15px; width: 1px; position: absolute; top: calc(50% - 7.5px); left: calc(50% - 5px); transform: rotate(-45deg); background: rgba(73, 168, 68, 1); border-radius: 5px; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <h2>rolling toggle</h2> <input type="checkbox" id="toggle" /> <div class="toggle-checkbox"> <label for="toggle"></label> </div> I would like to add a checkmark to the switch when it is toggled on. I have tried adding a checkmark using CSS, but I'm having trouble positioning it correctly. Can someone tell me how to add a checkmark to the toggle switch, and make it displays correctly? Thank you for your help! A: It seems it had some position-related issue and nothing else ( If I understood your problem though) #toggle:checked~.toggle-checkbox label::after { content: ''; height: 15px; width: 1px; position: absolute; top: calc(50% - 6.5px); left: calc(50% - -1px); transform: rotate(240deg); background: rgba(73, 168, 68, 1); border-radius: 5px; } #toggle:checked~.toggle-checkbox label::before { content: ''; height: 8px; width: 2px; position: absolute; top: calc(50% - 3px); left: calc(50% - 6px); transform: rotate(159deg); background: rgba(73, 168, 68, 1); border-radius: 5px; } A: I do not know if this is the result you wanted but I managed to obtain a centered checkmark. I just played around with the position's and rotate's values. /* CSS for toggle checkbox */ #toggle { display: none; } .toggle-checkbox label, .toggle-checkbox label, .toggle-checkbox label { transition: 400ms all ease-in-out 50ms; box-sizing: border-box; backface-visibility: hidden; } .toggle-checkbox { height: 25px; width: 50px; background: rgba(43, 43, 43, 1); position: relative; box-shadow: 0 0 2px rgba(43, 43, 43, 1); border-radius: 50px; transition: background 0.5s ease-out, box-shadow 0.5s ease-out; } #toggle:checked~.toggle-checkbox { background: rgba(73, 168, 68, 1); box-shadow: 0 0 2px rgba(73, 168, 68, 1); } .toggle-checkbox label::before { content: ''; height: 10px; width: 2px; position: absolute; top: calc(50% - 5px); left: calc(50% - 1px); transform: rotate(45deg); background: rgba(43, 43, 43, 1); border-radius: 5px; } .toggle-checkbox label::after { content: ''; height: 2px; width: 10px; position: absolute; top: calc(50% - 1px); left: calc(50% - 5px); transform: rotate(45deg); background: rgba(43, 43, 43, 1); border-radius: 5px; } .toggle-checkbox label { height: 20px; width: 20px; background: rgba(255, 255, 255, 1); position: absolute; top: 2.5px; left: 2.5px; cursor: pointer; border-radius: 50px; } #toggle:checked~.toggle-checkbox label { left: 25px; transform: rotate(360deg); } #toggle:checked~.toggle-checkbox label::before { position: absolute; top: calc(50%); left: 50%; transform: translateY(-50%) rotate(45deg); background: rgba(73, 168, 68, 1); } #toggle:checked~.toggle-checkbox label::after { height: 6px; width: 2px; position: absolute; top: calc(55%); left: calc(30%); transform: translateY(-50%) rotate(-40deg); background: rgba(73, 168, 68, 1); } <h2>rolling toggle</h2> <input type="checkbox" id="toggle" /> <div class="toggle-checkbox"> <label for="toggle"></label> </div> I took the liberty of refactoring what you wrote in order to remove redundant code.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does the private class C IP address range start from 192.168.0.0 rather than 192.0.0.0 like the public counterpart? I am curious regarding why the private IP address range starts from 192.168.0.0 rather than 192.0.0.0 like the public IP address range for class C networks. Is 192.0.0.0 - 192.167.255.255 reserved for other uses or is there another explanation for it? I have tried searching for an explanation online but can't seem to find one (might be due to my inability to word the question properly)
{ "language": "en", "url": "https://stackoverflow.com/questions/75635622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Upload file using Azure Blob Put and ADLS Gen 2 Update (REST API)? I am in the middle of exploring whether to use the Azure Blob REST API or the ADLS Gen2 REST API for uploading a file to a Blob / ADLS Gen2 account. Given some storageaccount, some container and some/path/file.csv, I think I have come to realize that I can do one of the following: * *I can use a combination of two ADLS Gen 2 REST APIs (Path - Create and Path - Update) to upload the desired file: First PUT https://storageaccount.dfs.core.windows.net/container/some/path/file.csv?resource=file to create the file Then PATCH https://storageaccount.dfs.core.windows.net/container/some/path/file.csv?action=append&flush=true&position=0 to append content and flush it to the file. *Alternatively, I seem to be able to able to achieve the same thing in one step using Put Blob by doing the following: PUT https://storageaccount.blob.core.windows.net/container/some/path/file.csv My question is: Is there a subtle difference between these two approaches? Is any of them considered better practice than the other, and if so, why?
{ "language": "en", "url": "https://stackoverflow.com/questions/75635624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Plotting line plots in for loop: try to create a color transition but color remains the same for all lines I'm trying to create a line plot using Matplotlib with a color transition. df_MBPS_GT100_groupy_land_jahr_mean is a pandas.core.frame.DataFrame of shape (288, 1). The x values represent years, the y values percentages for each year. Each line represents a differnt country. I'm trying generate a color transition in the code below but it prints all lines in one color: blue. Yet if I print the numerical values for color they all fiffer as intended. import matplotlib.pyplot as plt import numpy as np import pandas as pd fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(30, 10)) i = 0 for country in (df_MBPS_GT100_groupy_land_jahr_mean.index.levels[0]): red = i / (len(df_MBPS_GT100_groupy_land_jahr_mean) - 1) green = 0 blue = 1 - (i / (len(df_MBPS_GT100_groupy_land_jahr_mean) - 1)) color = (red, green, blue) ax[0].plot(list((df_MBPS_GT100_groupy_land_jahr_mean.loc[country]).index), list(df_MBPS_GT100_groupy_land_jahr_mean.loc[country, 'percentage']), label=country, color=color, lw=2) i += 1 # rest of code is only labeling axis etc The code above produces yet I'd like the colors to be something like this: Do you guys have any idea what went wrong? I'd really appreciate any hint! A: This may or may not be what you're looking for, but the following code creates an iterator to run through colours from a defined gradient, in this case I used 'cool', but you can see more at https://matplotlib.org/stable/tutorials/colors/colormaps.html linspace breaks this gradient up based on the number of lines you have. import matplotlib.pyplot as plt from matplotlib.pyplot import cm import numpy as np num_of_lines = len(df_MBPS_GT100_groupy_land_jahr_mean.index.levels[0]) color=iter(cm.cool(np.linspace(0,1,num_of_lines))) for country in (df_MBPS_GT100_groupy_land_jahr_mean.index.levels[0]): c=next(color) #Change colour for each line in plot #Do whatever else you need here plt.plot(x, y, 'o', c=c, label=key) #Plot all data for each week
{ "language": "en", "url": "https://stackoverflow.com/questions/75635625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I install library's on Micropython? How can I install the python library requests on micropython? If yes, how? I tryed upip but in upip is no library named requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Automate Codeartifact login for npm AWS Codeartifact auth token expires after 12hrs, we need to create new token again. But how can we automate this authentication token update instead of running the command again manually? I've tried setting the command in ~/.bashrc, but this is running everytime the terminal is opened, need to reduce this command executions. A: According to this, the maximum is 43200 seconds (12h). Your question says that you already know how to re-new the token, so no advice needed on this. You could: * *Just run the login command manually *Run codefactory login command before the cpm commands by adjusting your build shortcuts (like this question did) *Update the bashrc to only run 12h after the last login execution, by remembering when the last login command was executed. I personal like the second method the best.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to scrape only specific rows based on filter instead getting all rows with BeautifulSoup? I am trying to scrape this site "https://takipcimerkezi.net/services" and for example as a starter I wanted to scrape 'minimum siparis' column. This is my code: from bs4 import BeautifulSoup import requests url='https://takipcimerkezi.net/services' page= requests.get(url) table=BeautifulSoup(page.content, 'html.parser') min_sipariş= table.find_all(attrs={"data-label":"Minimum Sipariş"}) for i in min_sipariş: value=i.text print(f'Minimum Sipariş={value}') When i try to scrape it im getting this kind of output: Minimum Sipariş=100 Minimum Sipariş=50 Minimum Sipariş=10000 Minimum Sipariş=10 Minimum Sipariş=1000 Minimum Sipariş=10 Minimum Sipariş=20 Minimum Sipariş=50 Minimum Sipariş=10 Minimum Sipariş=20 Minimum Sipariş=100 Minimum Sipariş=10 My problem is, in the real site and HTML code 6th row actually an another entry and it's 'minimum siparis' = 20. But in beautifulsoup there are another entry which is not found in the inspect code and not in the site's entries. But somehow beautifulsoup getting more code from the inspect HTML code how can I solve it and scrape the data as in the exact order in the site? EDIT: There is a line such as this when I print table and look the code i n my text editor in vscode: </tr> <tr data-filter-table-category-id="1"> <td data-filter-table-service-id="1387" data-label="ID">1387</td> <td class="table-service" data-filter-table-service-name="true" data-label="Servis">4034-❤️ S4 - Instagram Türk Beğeni | Max 15K | %80 Türk | Hızlı Başlar</td> <td data-label="1000 adet fiyatı "> 13.01 TL </td> <td data-label="Minimum Sipariş">10</td> <td data-label="Maksimum Sipariş">8000</td> <td class="services-list__description" data-label=""> <div class="component_button_view"> <div class=""> <button class="btn btn-actions btn-view-service-description" data-content-id="#service-description-id-2-1387" data-max="8000" data-min="10" data-service-id="1387" data-service-name="4034-❤️ S4 - Instagram Türk Beğeni | Max 15K | %80 Türk | Hızlı Başlar" data-target="#service-description-2" data-toggle="modal"> Açıklama </button> </div> </div> <div class="d-none" id="service-description-id-2-1387"> ℹ️ Kategori Yöneticisinden Özel Bilgi<br/>️ Son Bilgi Tarihi: 3.1.2023 - 10:30<br/>️ Servis saatte ortalama 2-3K gönderim yapmakta en hızlı beğeni servislerinden biridir. Datası Türk profil fotoğraflı nadiren fotoğrafsız hesaplardır. <br/><br/> Min: 10<br/> Max: 5.000<br/> Link: Paylaşım Linki<br/> Kalite: %100 Türk<br/> Beğeni sayısı gizli gönderilere işlem sağlar.<br/> Hız: Anlık Başlar<br/><br/>Notlar: <br/> Servis yoğun olduğu zamanlarda işleme başlama hızı değişmektedir. <br/> Verdiğiniz sipariş sistemde tamamlanmadan aynı linke 2. siparişi vermeyiniz. </div> </td> </tr> but this lines does not exist in the source code. A: Due to the limited information on the concrete settings of the OP, it is difficult to define a precise answer, so this is only intended to point in one direction and clarify the specifics. If filter settings are made after the page call, this will only have an effect on the result in your browser. requests only knows the initial data, everything that happens afterwards in terms of rendering, filtering or anything else has no influence on this data, so you have to take the filtering of the data into account independently. Issue#1: Select your elements based on entries that have a corresponding relation to the filter, e.g. via the data-filter-table-category-id: soup.select('#service-tbody [data-filter-table-category-id="1473"]:has([data-label="Minimum Sipariş"])') Issue#2: To get the values in euro you have to send your cookies with the request, cause the information about currency is saved there: cookies={'user_currency':'27d210f1c3ff7fe5d18b5b41f9b8bb351dd29922d175e2a144af68924e3064d1a%3A2%3A%7Bi%3A0%3Bs%3A13%3A%22user_currency%22%3Bi%3A1%3Bs%3A3%3A%22EUR%22%3B%7D;'} Example from bs4 import BeautifulSoup import requests url='https://takipcimerkezi.net/services' soup = BeautifulSoup( requests.get( url, cookies={'user_currency':'27d210f1c3ff7fe5d18b5b41f9b8bb351dd29922d175e2a144af68924e3064d1a%3A2%3A%7Bi%3A0%3Bs%3A13%3A%22user_currency%22%3Bi%3A1%3Bs%3A3%3A%22EUR%22%3B%7D;'} ).text ) data = [ dict(zip(e.find_previous('thead').stripped_strings,e.stripped_strings)) for e in soup.select('#service-tbody [data-filter-table-category-id="1473"]:has([data-label="Minimum Sipariş"])') ] Output of data [{'ID': '1537', 'Servis': '4755- Instagram Türk Takipçi | Max 2K | %100 Gerçek Kullanıcılar | Düşme Olmaz |\xa0Hızlı Başlar', '1000 adet fiyatı': '≈ 25.1955 €', 'Minimum Sipariş': '5', 'Maksimum Sipariş': '3000', 'Açıklama': 'Açıklama'}, {'ID': '1538', 'Servis': '4759- Instagram Global Takipçi | Max 3K | %100 Gerçek Kullanıcılar | Düşme Olmaz | Hızlı Başlar', '1000 adet fiyatı': '≈ 8.2339 €', 'Minimum Sipariş': '50', 'Maksimum Sipariş': '3000', 'Açıklama': 'Açıklama'}, {'ID': '1539', 'Servis': '4761- ━━━━━━━━━━━━━ Beğeni ━━━━━━━━━━━━━', '1000 adet fiyatı': '≈ 4990.1436 €', 'Minimum Sipariş': '99999', 'Maksimum Sipariş': '99999'}, {'ID': '1540', 'Servis': '4757-❤️ Instagram Türk Beğeni | Max 1K | %100 Gerçek Kullanıcılar | Düşme Olmaz | Hızlı Başlar', '1000 adet fiyatı': '≈ 12.2834 €', 'Minimum Sipariş': '10', 'Maksimum Sipariş': '1000', 'Açıklama': 'Açıklama'}, {'ID': '1541', 'Servis': '4758-❤️ Instagram Türk Kadın Beğeni | Max 500 | %100 Gerçek Kullanıcılar | Düşme Olmaz | Hızlı Başlar', '1000 adet fiyatı': '≈ 13.6477 €', 'Minimum Sipariş': '5', 'Maksimum Sipariş': '500', 'Açıklama': 'Açıklama'}, {'ID': '1542', 'Servis': '4760-❤️ Instagram Global Beğeni | Max 2K | %100 Gerçek Kullanıcılar | Düşme Olmaz | Hızlı Başlar', '1000 adet fiyatı': '≈ 3.6609 €', 'Minimum Sipariş': '20', 'Maksimum Sipariş': '3000', 'Açıklama': 'Açıklama'}, {'ID': '1543', 'Servis': '4756- Instagram Türk Yorum | Max 200 | %100 Gerçek Kullanıcılar | Düşme Olmaz | Hızlı Başlar', '1000 adet fiyatı': '≈ 28.3453 €', 'Minimum Sipariş': '5', 'Maksimum Sipariş': '500', 'Açıklama': 'Açıklama'}]
{ "language": "en", "url": "https://stackoverflow.com/questions/75635630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to allow a Python program to fix itself by downloading and installing/updating all libraries needed? I have sudo on a machine at my disposal, now I want to do something like this: * *Let a python program to have sudo privilege, run a piece of code (also in python), the 2nd one will break sometimes due to outdated/conflicting dependencies (edit: or an outdated 3rd party API) *With the help of AI (chatGPT and what's not), I want the 1st to call OpenAI API (https://platform.openai.com/examples/default-fix-python-bugs) to figure out the error itself, then do whatever the API tell it to do to fix the 2nd python code, then rerun. Is the 1st point do-able? Thanks (The machine is disposable, a VM anyway, so no need to advise me on security stuff) Edit: On the broken dependencies: my code run on GPU, one day a devops updated Cuda of the machine and it stopped, Googling around pointing to just changing a few lines of code. On the 3rd-party API, I once consumed an API that required a tuple (x1, y1, x2, y2) to denote top, left, bottom, right of an area. One day they suddenly didn't support that and change to (x1, y1, l1, l2) to denote top, left, width, height of an area. Quite pointless but they changed anyway. I hated to update tidbit code like that, hence the motivation. A: You can call pip from python code using subprocess. You can also use semantic versioning to (hopefully) not allow breaking changes to sneak into the code when updating. ChatGPT only have knowledge up to 2021, so you're likely not going to get the information you need. However, using the requests module, you can query for errors. import os import sys import subprocess from pathlib import Path import requests REQUIRED_LIBRARIES = [ 'dependency1 >= 1.1.0, < 2.0.0', 'dependency2 >= 2.8.0, < 3.0.0', 'dependency3 >= 2.2.0, < 3.0.0', ] def install_libraries_with_pip(libraries): for library in libraries: subprocess.call([sys.executable, '-m', 'pip', 'install', library]) def uninstall_libraries_with_pip(libraries): for library in libraries: subprocess.call([sys.executable, '-m', 'pip', 'uninstall', library]) if __name__ == '__main__': # Make the request to gtp and make sure it formats it like the ones above. r = requests.post('<gtp-url>') other_to_install = r.text install_libraries_with_pip(REQUIRED_LIBRARIES + other_to_install.split('\n')
{ "language": "en", "url": "https://stackoverflow.com/questions/75635632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Initialize string enum member with other string enum member I noticed this sentence, "In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member.", then I writed some examples. Following is one of examples. enum RIGHT { VALUE = 'Right', } enum Direction { Up = "UP", Down = "DOWN", Left = "LEFT", Right = RIGHT.VALUE, // Computed values are not permitted in an enum with string valued members. } // additional example enum Direction { Up = "UP", Down = "DOWN", Left = "LEFT", // Reference itself member. Right = Direction.Up, // Computed values are not permitted in an enum with string valued members. } This is strange about "or with another string enum member.". Then, following is another example, I removed other members besides Right. enum RIGHT { VALUE = 'Right', } enum Direction { Right = RIGHT.VALUE // Why is it right? } Enum members are always readonly, why does referenced to it become a computed value?? They can't be modified, So I think the first example should be correct.. A: It is simply a TypeScript implementation detail for enums. All enum members are considered either constant or computed. The definitions for this can be found in the documentation. The section on this is Computed and constant members in Enums (emphasis mine) Each enum member has a value associated with it which can be either constant or computed. An enum member is considered constant if: It is the first member in the enum and it has no initializer, in which case it’s assigned the value 0: It does not have an initializer and the preceding enum member was a numeric constant. In this case the value of the current enum member will be the value of the preceding enum member plus one. The enum member is initialized with a constant enum expression. A constant enum expression is a subset of TypeScript expressions that can be fully evaluated at compile time. An expression is a constant enum expression if it is: * *a literal enum expression (basically a string literal or a numeric literal) *a reference to previously defined constant enum member (which can originate from a different enum) *a parenthesized constant enum expression *one of the +, -, ~ unary operators applied to constant enum expression *+, -, *, /, %, <<, >>, >>>, &, |, ^ binary operators with constant enum expressions as operands In all other cases enum member is considered computed. When you remove the other string members in your enum, your enum suddenly only has non-computed members in it A: See ts PR. An enum member has a unique and opaque enum member type when it is initialized by a non-constant expression. Non-constant initializer expressions must be assignable to type number and are not permitted in const enum declarations. Following is correct. enum RIGHT { VALUE = 20, } enum Direction { Up = 1, Down = 2, Left = 3, Right = RIGHT.VALUE, // correct! } E.C denotes a unique enum member type representing the value computed by the non-constant initializer expression. This unique type is assignable to type number, but otherwise incompatible with other types. enum E { A = 10 * 10, // Numeric literal enum member B = "foo", // String literal enum member C = bar(42) // Opaque computed enum member }
{ "language": "en", "url": "https://stackoverflow.com/questions/75635641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Layering Queries I created a query to view the order of customers' purchase history, and want to build upon it based on the first purchase item to see if there are common ordering patterns. I used the following partition by statement to determine the order and then added an inner join to find common 2nd purchase categories. -- Query for Finding 2nd Purchase Product Category -- SELECT COUNT (DISTINCT "user_id") AS CUSTOMERS ,"product_cateogry" FROM ( SELECT ROW_NUMBER () OVER ( PARTITION BY GR."user_id" ORDER BY "event_date" ASC) AS PURCHASE_ORDER ,GR."user_id" ,GR."product_category" FROM CUSTOMER_ORDERS AS GR INNER JOIN ( SELECT "user_id" ,"product_category" FROM ( SELECT *, ROW_NUMBER () OVER ( PARTITION BY "user_id" ORDER BY "event_date" ASC) AS PUR_O FROM CUSTOMER_ORDERS QUALIFY PUR_O = 1) WHERE "product_category" = 'purchase_1_cateogry' AND "event_date" > '2022-01-01 ) AS SR ON GR."user_id" = SR."user_id" WHERE GR."product_category" NOT IN ('purchase_1_category') AND "event_date" > '2022-01-01' QUALIFY PURCHASE_ORDER = 1) GROUP BY "product_cateogry" ORDER BY CUSTOMERS DESC ; I am getting stuck trying to determine the 3rd purchase and beyond. I've tried doing multiple joins (see below) on the same condition that "user_id' is the same, but it is not yielding the results I was intending. The 2nd inner join is pulling users who made a 2nd purchase in the respective category, but it's not joining the same users who also made a 1st purchase within the 1st purchase category originally outlined. Any ideas? -- Attempted Query for 3rd Purchase Product Category -- SELECT COUNT (DISTINCT "user_id") AS CUSTOMERS ,"product_category" FROM ( SELECT ROW_NUMBER () OVER ( PARTITION BY "user_id" ORDER BY "event_date" ASC) AS PURCHASE_ORDER ,GR."user_id" ,GR."product_category" FROM CUSTOMER ORDERS AS GR INNER JOIN ( SELECT "user_id" ,"product_category" FROM ( SELECT *, ROW_NUMBER () OVER ( PARTITION BY "user_id" ORDER BY "event_date" ASC) AS PUR_O FROM CUSTOMER_ORDERS QUALIFY PUR_O = 1) WHERE "product_category" = 'purchase_1_category' AND "event_date" > '2022-01-01' ) AS SR ON GR."user_id" = SR."user_id" INNER JOIN ( SELECT "user_id" ,"product_category" FROM ( SELECT *, ROW_NUMBER () OVER ( PARTITION BY "user_id" ORDER BY "event_date" ASC) AS PUR_O FROM CUSTOMER_ORDERS QUALIFY PUR_O = 2) WHERE "product_category" = 'purchase_2_category' AND "event_date" > '2022-01-01' ) AS BR ON GR."user_id" = BR."user_id" AND SR."user_id" = BR."user_id" WHERE GR."product_category" NOT IN ('purchase_1_category') AND GR."product_category" NOT IN ( 'purchase_2_category') QUALIFY PURCHASE_ORDER = 1) GROUP BY "product_category" ORDER BY CUSTOMERS DESC ;
{ "language": "en", "url": "https://stackoverflow.com/questions/75635644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: draw a binary tree based on some names I have a project with nextjs and typescript. in this mini project I implemented a binary level order tree. I want to show it like a tree in the browser as below I have two classes in tree.ts file. one class for my treeNodes and one class for implementing insert and levelOrderTraverse logics. this is my tree.ts file class Node<T> { public val: T; public left: Node<T> | null; public right: Node<T> | null; constructor(val: T) { this.val = val; this.left = null; this.right = null; } } export class LevelOrderBinaryTree<T> { private root: Node<T> | null; constructor() { this.root = null; } getRootNode() { return this.root; } insert(data: T) { const q: Node<T>[] = []; if (this.root === null) { this.root = new Node(data); } else { q.push(this.root); while (q.length) { const node = q.shift()!; if (node.left === null) { node.left = new Node(data); break; } else { q.push(node.left); } if (node.right === null) { node.right = new Node(data); break; } else { q.push(node.right); } } } } levelOrderTraverse(root: Node<T>) { const result: T[][] = []; const queue: Node<T>[] = []; queue.push(root); while (queue.length) { const lvlSize = queue.length; const currentLvl: T[] = []; for (let i = 0; i < lvlSize; i++) { const currentNode = queue.shift()!; currentLvl.push(currentNode.val); if (currentNode.left) { queue.push(currentNode.left); } if (currentNode.right) { queue.push(currentNode.right); } } result.push(currentLvl); } return result; } } this is my Tree.tsx component import React, { useEffect, useState } from 'react'; import classes from './Tree.module.scss'; import { LevelOrderBinaryTree } from '../../utils/tree'; const Tree = () => { const [nodes, setNodes] = useState<null | string[][]>(null); useEffect(() => { const LBT = new LevelOrderBinaryTree<string>(); LBT.insert('Mike'); LBT.insert('Daniel'); LBT.insert('Christin'); LBT.insert('Sara'); LBT.insert('Ben'); LBT.insert('Leo'); const sequenceNodes = LBT.levelOrderTraverse(LBT.getRootNode()!); setNodes(sequenceNodes); }, []); if (!nodes) { return; } return ( <div> <ul className={`${classes.tree} ${classes.vertical}`}> <li> <div>Node</div> <ul> <li> <div>node</div> <ul> <li> <div>node</div> </li> <li> <div>node</div> </li> </ul> </li> <li> <div>node</div> <ul> <li> <div>node</div> </li> <li> <div>node</div> </li> </ul> </li> </ul> </li> </ul> </div> ); }; export default Tree; and this is my styles for creating this tree .tree { $color: #222; $border-color: #ddd; $background-color: #eee; $border-weight: 1px; $margin: 12px; margin: $margin * 1.5; padding: 0; &:not(:empty):before, &:not(:empty):after, ul:not(:empty):before, ul:not(:empty):after, li:not(:empty):before, li:not(:empty):after { display:block; position:absolute; content:""; } ul, li { position: relative; margin:0; padding:0; } li>div { background-color:$background-color; color:$color; padding:5px; display:inline-block; } &.vertical { display:flex; ul { display:flex; justify-content: center; } li { display:flex; flex-direction: column; align-items: center; div { margin: $margin $margin/2; } &:before { border-left: $border-weight solid $border-color; height: $margin; width: 0; top: 0; } &:after { border-top: $border-weight solid $border-color; height: 0; width: 100%; } &:first-child:after { border-top: $border-weight solid $border-color; height: 0; width: 50%; left: 50%; } &:last-child:after { border-top: $border-weight solid $border-color; height: 0; width: 50%; right: 50%; } &:only-child:after { content:none; } ul:before { border-left: $border-weight solid $border-color; height: $margin; width: 0; top: -$margin; } } &>li { &:only-child:before, &:only-child:after { content:none; } } } } when levelOrderTraverse method get being called by this inputs the output is like this [ ['Mike'], ['Daniel', 'Christin'], ['Sara', 'Ben', 'Leo'] ] and I want create my tree based on this result. It should be like this but I couldn't find any solution to create this. thanks in advance for any effort
{ "language": "en", "url": "https://stackoverflow.com/questions/75635647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use partial tag inside a plugin in OctoberCMS? Inside my plugin in /plugins/acme/blog/views/mytemplate.htm I have this code {% partial 'test' vars=values} this returns Unknown "partial" tag and it's called by an internal code with return View::make('acme.blog::mytemplates', $values); since it's not called by the CMS it's missing some functionality I guess. Is there a way to include a partial inside a view and still pass data to the partial? I also tried the include function from twig https://twig.symfony.com/doc/3.x/tags/include.html but I'm not sure what location path to use since I'm getting "file not found" for every combination
{ "language": "en", "url": "https://stackoverflow.com/questions/75635649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How install only files from sourceDir with no directories I have two source folders "hml" and "prod" with files that has the same name. * *source-files\hml\prop.txt *source-files\prod\prop.txt According to an environment variable, the hml or prod folder is installed WXS File generated from heat.exe <?xml version="1.0" encoding="utf-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Fragment> <DirectoryRef Id="DRTest"> <Directory Id="dir955DBF4D2285F2E21C32C59406B537CE" Name="hml" /> <Directory Id="dirD719650CC1B2842144EDDEE82C74F4F8" Name="prod" /> </DirectoryRef> </Fragment> <Fragment> <ComponentGroup Id="CGTest"> <Component Id="cmpEFE4E22AB34DA3EB5B946F5BB2C9607F" Directory="dir955DBF4D2285F2E21C32C59406B537CE" Guid="{34608A80-DED6-4CE1-B270-D74A4EC672D1}"> <Condition><![CDATA[ENVIRONMENT="H"]]></Condition> <File Id="fil6762F479FB1087BFED02566F581D8DC3" KeyPath="yes" Source="SourceDir\hml\prop.txt" /> </Component> <Component Id="cmpC8F54E05FD0D1FEB5D23E8E250BDC3CC" Directory="dirD719650CC1B2842144EDDEE82C74F4F8" Guid="{3A60E929-C1CC-4317-9486-05DB5D03EA36}"> <Condition><![CDATA[ENVIRONMENT="P"]]></Condition> <File Id="fil81946DAEA8CB358FB28F167A00902CAC" KeyPath="yes" Source="SourceDir\prod\prop.txt" /> </Component> <Component Id="cmp892267248C5EB88377233E323E9CBC61" Directory="dirD719650CC1B2842144EDDEE82C74F4F8" Guid="{3FD22301-A44E-4BB6-AD7C-A91F0AF9E4D7}"> <Condition><![CDATA[ENVIRONMENT="P"]]></Condition> <File Id="fil83C6A493C601DC451F7D48B8005B7489" KeyPath="yes" Source="SourceDir\prod\prop2.txt" /> </Component> </ComponentGroup> <Property Id="ENVIRONMENT"> <RegistrySearch Id="ENVIRONMENT" Root="HKCU" Key="System\CurrentControlSet\Policies" Name="ENVIRONMENT" Type="raw" /> </Property> </Fragment> </Wix> WXS File with Installer properties <?xml version="1.0" encoding="utf-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Product Id="a09e1fd5-abb0-4a1e-ba61-aa087b8691e7" Name="NameTest" Version="1.0.0" Manufacturer="Manufacturer" UpgradeCode="a09e1fd5-abb0-4a1e-ba61-aa087b8691e6" Language="1033"> <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" Manufacturer="Manufacturer" /> <Media Id="1" Cabinet="installer.cab" EmbedCab="yes"/> <MajorUpgrade DowngradeErrorMessage="A newer version is already installed"/> <Feature Id="ProductFeature" Title="TitleTeste" Level="1"> <ComponentGroupRef Id="CGTest"/> </Feature> </Product> <Fragment> <SetDirectory Id="INSTALLFOLDER" Value="C:\test"/> <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="INSTALLFOLDER" > <Directory Id="DRTest"/> </Directory> </Directory> </Fragment> </Wix> XSLT <xsl:template match='//wix:Wix/wix:Fragment/wix:ComponentGroup/wix:Component[wix:File[@Source and (contains(@Source, "hml"))]]'> <xsl:copy> <xsl:apply-templates select="@*"/> <xsl:element name="Condition" namespace="http://schemas.microsoft.com/wix/2006/wi"> <xsl:text disable-output-escaping="yes">&lt;![CDATA[ENVIRONMENT="H"</xsl:text> <xsl:text disable-output-escaping="yes">]]&gt;</xsl:text> </xsl:element> <xsl:apply-templates select="node()"/> </xsl:copy> </xsl:template> <xsl:template match='//wix:Wix/wix:Fragment/wix:ComponentGroup/wix:Component[wix:File[@Source and (contains(@Source, "prod"))]]'> <xsl:copy> <xsl:apply-templates select="@*"/> <xsl:element name="Condition" namespace="http://schemas.microsoft.com/wix/2006/wi"> <xsl:text disable-output-escaping="yes">&lt;![CDATA[ENVIRONMENT="P"</xsl:text> <xsl:text disable-output-escaping="yes">]]&gt;</xsl:text> </xsl:element> <xsl:apply-templates select="node()"/> </xsl:copy> </xsl:template> When I run the installer, the target folder looks like this: c:\test\hml\prop.txt And I expected c:\test\prop.txt I expect just the files from sourceDir be installed A: Your code does not match your expectations. You have a prop.txt in two different directories: dir955DBF4D2285F2E21C32C59406B537CE or dirD719650CC1B2842144EDDEE82C74F4F8. Those two directories are: <Directory Id="dir955DBF4D2285F2E21C32C59406B537CE" Name="hml" /> <Directory Id="dirD719650CC1B2842144EDDEE82C74F4F8" Name="prod" /> And those two directories are parented into DRTest and INSTALLFOLDER, which are fallthroughs, but you have a custom action setting INSTALLFOLDER to C:\test. So the results you'll get will be: * *C:\test\hml\prop.txt *C:\test\prod\prod.txt *Nothing installed Based on the value of the registry key (note: you can access environment variables in MSI without searching for them). Everything is working exactly as you have written. If you don't want the hml or prod directories included, then parent the Components to the INSTALLFOLDER (or the fallthrough DRTest) directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jetpack compose how to reduce amount of arguments in a Composable function (clean-code)? In my application I've hoisted every major functionality and after that I've ended up with a huge Composable function: HomeScreen.kt TopSection( filterParametersState = filterParametersState, itineraryCount = flightsFromApiResponse.result?.itineraryCount ?: 0, buttonNames = viewModel.buttonNames, buttonNamesFilters = viewModel.buttonNamesFilters, selectedButtonIndex = viewModel.selectedButtonIndex.value, selectedButtonName = viewModel.selectedButtonName.value, isThemeSwitchChecked = themeViewModel.isDarkTheme, selectedSort = viewModel.selectedSort.value, updateSelectedSort = { sortName -> viewModel.updateSelectedSort(sortName) }, getLocation = { cityName -> viewModel.getLocation(cityName) }, updateFlightSearchDepartureTime = { date -> viewModel.updateFlightSearchDepartureTime( date = date ) }, updateFlightSearchCityDeparture = { viewModel.updateFlightSearchCityDeparture( city = viewModel.location.value.cityCode ?: "WAR" ) }, updateFlightSearchCityArrival = { viewModel.updateFlightSearchCityArrival( city = viewModel.location.value.cityCode ?: "PAR" ) }, updateFlightSearchPassengersCount = { passengerCount -> viewModel.updateFlightSearchPassengersCount( passengers = passengerCount ) }, onDisableNextDayArrivalsClicked = { isDisabled -> viewModel.updateFilterDisableNextDayArrivals( isDisabled ) }, onDurationButtonClicked = { buttonName -> viewModel.updateFilterMaxDuration( buttonName ) }, onThemeSwitchClicked = { themeViewModel.switchTheme() }, onSliderValueChange = { valueFromSlider -> viewModel.updateFilterMaxPrice( valueFromSlider ) }, onParamsUpperClicked = { buttonIndex, buttonName -> viewModel.updateSelectedButtonIndex(buttonIndex) viewModel.updateSelectedButtonName(buttonName) }, onParamsBottomClicked = { buttonName -> if (buttonName != "SAVE") { viewModel.updateSelectedButtonName(buttonName) } else { commonViewModel.updateCurrentFlightParams(flightSearchParametersState) viewModel.getFlights() } } ) How can I avoid this? I know that technically I could separate TopSection into other smaller Composable functions, but in my case I feel like the apporach I've applied is appropriate. To be precise, TopSection is a section in HomeScreen in which I handle couple of small functionalities. A: You can incapsulate your data in data class this way: In your ViewModel: class MyViewModel : ViewModel() { private val _buttonUiState = MutableStateFlow(ButtonUiState()) val buttonUiState: StateFlow<ButtonUiState> get() = _buttonUiState.asStateFlow() fun setNewState(index: Int) { _buttonUiState.update { it.copy( buttonIndex = index ) } } } data class ButtonUiState( val buttonIndex: Int = 0, val buttonNames: List<String> = listOf() ... ) And in your composable function you can collect buttonUiState this way: @Composable fun ParentComposable( viewModel: MyViewModel ) { val buttonUiState by viewModel.buttonUiState.collectAsState() TopSection( buttonUiState = buttonUiState ... ) } A: First make data class or normal class and add some parameters data class SomeContent( ... ... ) after that pass this data class in TopSection composable function TopSection( someContent:SomeContent ){ .... .... } you can also take reference from Text composable function , where it takes TextStyle as a parameter for color , font , fontWeight etc and it's a class Text(text = "Hey", style = TextStyle( color = Color.Red, fontWeight = FontWeight.SemiBold, fontSize = 20.sp )) Hope you understood this thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pygubu how to make a button change what is in the frame next to it I am trying to make a program where several buttons change what is in the frame next to them based on which button is clicked last. So far is what happens currently where it opens in a seperate window. However I want it to open in that large open space in the window with all of the buttons to look something like this What I want the end result to look like So I was wondering how do I make pygubu do that and also have it so that I can change what is in the main window based off of what button is pressed last.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it a bad idea to navigate in a custom hook? I want to make a custom fetch hook to help me handle some http error in general. When the response.status is 401, then navigate to the main page. const useFetch = (url, fetchOpts) => { // reducer here..... const [state, dispatch] = useReducer(fetchReducer, initialState); useEffect(() => { if (!url) return; cancelRequest.current = false; const fetchData = async () => { dispatch({ type: 'loading' }); try { const response = await fetch(url, fetchOpts); if (!response.ok) { if (response.status === 401) return navigate('/'); } const data = await response.json(); if (cancelRequest.current) return; dispatch({ type: 'fetched', payload: data }); } catch (error) { if (cancelRequest.current) return; dispatch({ type: 'error', payload: error }); } }; fetchData(); return () => { cancelRequest.current = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [url]); return state; }; although It's work, but I'm wondering is it alright if I just leave my previous component and not handle the rest of it? A: I think that separate your function useFetch will be a better approach. Why ? In computer science there is a design pattern called separation of concerns, in simple words this design pattern tells us we need to separate our functions into small ones that do only one thing. My advice to you is to make your function useFetch return status, and make another function that checks if the status is 401 then you navigate the user to the main page
{ "language": "en", "url": "https://stackoverflow.com/questions/75635657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php and sql unidentified variable errors Warning: Undefined variable $account in C:\xampp\htdocs\advanced-ticketing-system\tickets.php on line 22 Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\advanced-ticketing-system\tickets.php on line 22 Warning: Undefined variable $account in C:\xampp\htdocs\advanced-ticketing-system\tickets.php on line 40 Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\advanced-ticketing-system\tickets.php on line 40 messages when i try to run this code i want to show the tickets for the current shop that is logged into the session using $_SESSION['account_shop'] == $account['shop'] main php code include 'functions.php'; // Connect to MySQL using the below function $pdo = pdo_connect_mysql(); // Fetch all the category names from the categories MySQL table $categories = $pdo->query('SELECT * FROM categories')->fetchAll(PDO::FETCH_ASSOC); // MySQL query that selects all the tickets from the databse $status = isset($_GET['status']) ? $_GET['status'] : 'all'; $category = isset($_GET['category']) ? $_GET['category'] : 'all'; $priority = isset($_GET['priority']) ? $_GET['priority'] : 'all'; $search = isset($_GET['search']) ? $_GET['search'] : ''; // The current pagination page $page = isset($_GET['page']) ? $_GET['page'] : 1; // The maximum amount of tickets per page $num_tickets_per_page = num_tickets_per_page; // Build the SQL string $sql = ''; $sql .= $status != 'all' ? ' status = :status AND' : ''; $sql .= $category != 'all' ? ' category_id = :category AND' : ''; $sql .= $priority != 'all' ? ' priority = :priority AND' : ''; $sql .= $search ? ' title LIKE :search AND' : ''; $sql .= isset($_SESSION['account_loggedin']) && $_SESSION['account_shop'] == $account['shop'] ? ' shop = :shop AND' : ''; $sql = !empty($sql) ? rtrim('WHERE ' . $sql, 'AND') : ''; // Fetch the tickets from the database $stmt = $pdo->prepare('SELECT * FROM tickets ' . $sql . ' ORDER BY created DESC LIMIT :current_page, :tickets_per_page'); // Bind params if ($status != 'all') { $stmt->bindParam(':status', $status); } if ($category != 'all') { $stmt->bindParam(':category', $category); } if ($priority != 'all') { $stmt->bindParam(':priority', $priority); } if ($search) { $s = '%' . $search . '%'; $stmt->bindParam(':search', $s); } if (isset($_SESSION['account_loggedin']) && $_SESSION['account_shop'] == $account['shop']) { $stmt->bindParam(':shop', $_SESSION['account_shop']); } $stmt->bindValue(':current_page', ($page-1)*(int)$num_tickets_per_page, PDO::PARAM_INT); $stmt->bindValue(':tickets_per_page', (int)$num_tickets_per_page, PDO::PARAM_INT); $stmt->execute(); // Fetch all tickets $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC); // Fetch tickets associated with the user's account if (isset($_SESSION['account_loggedin'])) { $stmt = $pdo->prepare('SELECT * FROM tickets ORDER BY created DESC LIMIT 3'); $stmt = $pdo->prepare('SELECT * FROM tickets WHERE status = "open" ORDER BY created DESC LIMIT 3'); $stmt = $pdo->prepare('SELECT * FROM accounts WHERE shop = ?'); $stmt->execute([ $_SESSION['account_shop'] ]); $account = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->execute(); } // Below queries will get the total number of tickets if (isset($_SESSION['account_loggedin']) && ($_SESSION['account_shop'] == $account['shop'])) { $stmt = $pdo->prepare('SELECT COUNT(*) FROM tickets WHERE shop = ?'); $num_tickets = $stmt->fetchColumn(); $stmt = $pdo->prepare('SELECT COUNT(*) FROM tickets WHERE status = "open" AND shop = ?'); $stmt->execute([ $_SESSION['account_shop'] ]); $num_open_tickets = $stmt->fetchColumn(); $stmt = $pdo->prepare('SELECT COUNT(*) FROM tickets WHERE status = "closed" AND shop = ?'); $stmt->execute([ $_SESSION['account_shop'] ]); $num_closed_tickets = $stmt->fetchColumn(); $stmt = $pdo->prepare('SELECT COUNT(*) FROM tickets WHERE status = "resolved" AND shop = ?'); $stmt->execute([ $_SESSION['account_shop'] ]); $num_resolved_tickets = $stmt->fetchColumn(); } ?> html code <?=template_header('Tickets')?> <div class="content tickets"> <h2><?=ucfirst($status)?> Tickets</h2> <form action="" method="get"> <div> <label for="status">Status</label> <select name="status" id="status" onchange="this.parentElement.parentElement.submit()"> <option value="all"<?=$status=='all'?' selected':''?>>All (<?=number_format($num_tickets)?>)</option> <option value="open"<?=$status=='open'?' selected':''?>>Open (<?=number_format($num_open_tickets)?>)</option> <option value="resolved"<?=$status=='resolved'?' selected':''?>>Resolved (<?=number_format($num_resolved_tickets)?>)</option> <option value="closed"<?=$status=='closed'?' selected':''?>>Closed (<?=number_format($num_closed_tickets)?>)</option> </select> <label for="category">Category</label> <select name="category" id="category" onchange="this.parentElement.parentElement.submit()"> <option value="all"<?=$category=='all'?' selected':''?>>All</option> <?php foreach($categories as $c): ?> <option value="<?=$c['id']?>"<?=$c['id']==$category?' selected':''?>><?=$c['name']?></option> <?php endforeach; ?> </select> <label for="priority">Priority</label> <select name="priority" id="priority" onchange="this.parentElement.parentElement.submit()"> <option value="all"<?=$priority=='all'?' selected':''?>>All</option> <option value="low"<?=$priority=='low'?' selected':''?>>Low</option> <option value="medium"<?=$priority=='medium'?' selected':''?>>Medium</option> <option value="high"<?=$priority=='high'?' selected':''?>>High</option> </select> </div> <input name="search" type="text" placeholder="Search..." value="<?=htmlspecialchars(trim($search, '%'), ENT_QUOTES)?>" onkeypress="if(event.keyCode == 13) this.parentElement.submit()"> </form> <div class="tickets-list"> <?php foreach ($tickets as $ticket): ?> <a href="view.php?id=<?=$ticket['id']?><?=isset($_SESSION['account_loggedin']) && $ticket['status'] ? '&code=' . md5($ticket['id'] . $ticket['shop']) : ''?>" class="ticket"> <span class="con"> <?php if ($ticket['status'] == 'open' && $ticket['shop'] == $_SESSION['account_shop']): ?> <i class="far fa-clock fa-2x"></i> <?php elseif ($ticket['status'] == 'resolved'&& $ticket['shop'] == $_SESSION['account_shop']): ?> <i class="fas fa-check fa-2x"></i> <?php elseif ($ticket['status'] == 'closed'&& $ticket['shop'] == $_SESSION['account_shop']): ?> <i class="fas fa-times fa-2x"></i> <?php endif; ?> </span> <span class="con"> <span class="title"><?=htmlspecialchars($ticket['title'], ENT_QUOTES)?></span> <span class="msg responsive-hidden"><?=htmlspecialchars($ticket['msg'], ENT_QUOTES)?></span> </span> <span class="con2"> <span class="created responsive-hidden"><?=date('F dS, G:ia', strtotime($ticket['created']))?></span> <span class="priority <?=$ticket['priority']?>"><?=$ticket['priority']?></span> </span> </a> <?php endforeach; ?> <?php if (!$tickets): ?> <p>There are no tickets.</p> <?php endif; ?> </div> <div class="pagination"> <?php if ($page > 1): ?> <a href="tickets.php?status=<?=$status?>&category=<?=$category?>&priority=<?=$priority?>&search=<?=$search?>&page=<?=$page-1?>">Prev</a> <?php endif; ?> <?php if (count($tickets) >= $num_tickets_per_page): ?> <a href="tickets.php?status=<?=$status?>&category=<?=$category?>&priority=<?=$priority?>&search=<?=$search?>&page=<?=$page+1?>">Next</a> <?php endif; ?> </div> </div> <?=template_footer()?> when i go to view all it shows me all the tickets that are logged into the sql database instead of just viewing the individual ones according to the session account shop
{ "language": "en", "url": "https://stackoverflow.com/questions/75635658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to NOT duplicate (in a new variable) an array and to SORT IT? I have an array: var givenCountry =["ALBANIA", "BOLIVIA", "CANADA","ICELAND", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"] I need to sort this array but I don't want any mutation. I tried this way by creating a duplicate array and sorting it and then displaying the result but I don't want to use any additional duplicate arrays. and sort the original array without mutation. var givenCountry =["ALBANIA", "BOLIVIA", "CANADA","ICELAND", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"] var coppiedarr = [] for(const element of givenCountry){ coppiedarr.push(element) } var sortedCountries = coppiedarr.sort() console.log(givenCountry) console.log(coppiedarr) console.log(sortedCountries) If there's anything in your mind? Thnx A: You could get an array of indices and sort it. const countries = ["ALBANIA", "BOLIVIA", "CANADA", "ICELAND", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"], keys = [...countries.keys()] .sort((a, b) => countries[a].localeCompare(countries[b])); for (const i of keys) console.log(countries[i]); .as-console-wrapper { max-height: 100% !important; top: 0; } A: If you want a simple one-liner with console.log, console.log(givenCountry.slice().sort()) The call to 'slice()' will create a shallow copy. Then it will sort that copy and log it. Then the copy will be garbage-collected. Another possibility for creating shallow copy and immediately sort and log it: console.log([...givenCountry].sort()) No difference, but you may have a preference for readability or ease of typing. A: Use spread oprator .... You don't have to create new variable. The synatx is short. It will return new array with the same elements as old one const givenCountry =["ALBANIA", "BOLIVIA", "CANADA","ICELAND", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"] console.log( [...givenCountry].sort()) A: Maybe something like that ? const givenCountry = [ 'ALBANIA', 'BOLIVIA', 'CANADA', 'ICELAND' , 'DENMARK', 'ETHIOPIA', 'FINLAND', 'GERMANY' , 'HUNGARY', 'IRELAND', 'JAPAN', 'KENYA' ]; cLogStrArrSorted( givenCountry ); function cLogStrArrSorted( arr ) { let ref = Array.from(({length:arr.length}),(_,i)=>i) .sort((a,b)=> arr[a].localeCompare(arr[b]) ); for (let i of ref) console.log( arr[i]); } .as-console-wrapper {max-height: 100% !important;top: 0;} .as-console-row::after {display: none !important;}
{ "language": "en", "url": "https://stackoverflow.com/questions/75635660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Recorded video showing black screen but audio is audible using cameraX lib. in android studio This is the code of my main activity public class MainActivity extends AppCompatActivity { private static final int REQUEST_CODE_PERMISSIONS = 10; private static final String[] REQUIRED_PERMISSIONS = {android.Manifest.permission.CAMERA, android.Manifest.permission.RECORD_AUDIO, android.Manifest.permission.WRITE_EXTERNAL_STORAGE}; private PreviewView mPreviewView; private Button mButtonRecord; private boolean mIsRecording = false; private Executor mExecutor; private MediaRecorder mMediaRecorder; private File mOutputFile; private ProcessCameraProvider mCameraProvider; private Size mVideoSize; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPreviewView = findViewById(R.id.preview_view); mButtonRecord = findViewById(R.id.recordButton); mExecutor = ContextCompat.getMainExecutor(this); if (allPermissionsGranted()) { startCamera(); } else { ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS); } mButtonRecord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("MainActivity", "Button clicked"); if (mIsRecording) { mButtonRecord.setEnabled(false); stopRecording(); mButtonRecord.setEnabled(true); } else { mButtonRecord.setEnabled(false); startRecording(); // Re-enable button once recording has started mButtonRecord.setEnabled(true); } } private void stopRecording() { // stop recording try { mMediaRecorder.stop(); } catch (RuntimeException e) { e.printStackTrace(); } releaseMediaRecorder(); } }); } private boolean allPermissionsGranted() { for (String permission : REQUIRED_PERMISSIONS) { if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } private void requestPermissions() { ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS); } private void startCamera() { ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this); cameraProviderFuture.addListener(new Runnable() { @SuppressLint("RestrictedApi") @Override public void run() { try { mCameraProvider = cameraProviderFuture.get(); Preview preview = new Preview.Builder().build(); CameraSelector cameraSelector = new CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build(); preview.setSurfaceProvider(mPreviewView.getSurfaceProvider()); mCameraProvider.bindToLifecycle(MainActivity.this, cameraSelector, preview); mVideoSize = new Size(preview.getAttachedSurfaceResolution().getWidth(), preview.getAttachedSurfaceResolution().getHeight()); } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); } } }, mExecutor); } private void releaseMediaRecorder() { if (mMediaRecorder != null) { mMediaRecorder.reset(); mMediaRecorder.release(); mMediaRecorder = null; } } private void startRecording() { mMediaRecorder = new MediaRecorder(); mOutputFile = getOutputFile(); if (mOutputFile == null) { Toast.makeText(this, "Failed to create output file", Toast.LENGTH_SHORT).show(); return; } // Set up MediaRecorder mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE); mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH); mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate); mMediaRecorder.setVideoFrameRate(profile.videoFrameRate); mMediaRecorder.setOutputFile(getOutputFile().getAbsolutePath()); if (mVideoSize != null) { mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight()); } else { Log.e(TAG, "mVideoSize is null"); } try { mMediaRecorder.prepare(); } catch (IOException e) { Log.e(TAG, "MediaRecorder prepare failed: " + e.getMessage()); Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show(); } mMediaRecorder.start(); } private File getOutputFile() { // Get the directory for storing video files File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM), "Camera"); // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.e(TAG, "Failed to create directory"); return null; } } String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); return new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); } } And this dependency I have added in build.gradle file I have excluded kotlin-stdlib because it giving error duplicate kotlin class dependencies { def camerax_version = "1.3.0-alpha04" implementation ("androidx.camera:camera-lifecycle:$camerax_version"){ exclude group: 'org.jetbrains.kotlin', module: 'kotlin-stdlib' } implementation ("androidx.camera:camera-view:$camerax_version"){ exclude group: 'org.jetbrains.kotlin', module: 'kotlin-stdlib' } implementation ("androidx.camera:camera-core:$camerax_version"){ exclude group: 'org.jetbrains.kotlin', module: 'kotlin-stdlib' } implementation ("androidx.camera:camera-camera2:$camerax_version"){ exclude group: 'org.jetbrains.kotlin', module: 'kotlin-stdlib' } implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.8.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' } I have added permission to my manifest file <uses-permission android:name="android.permission.RECORD_AUDIO"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera.autofocus"/> I expected that this code Record video on Clicking Record and save it to phone I have 2 problems: * *When I click on record button to stop recording it stops previous one but starts new recording. *Saved Video showing black screen but audio is audible.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In SwiftUI, how to prevent '.refreshable()' of child View in List View? in SwiftUI, if child view of List View that refreshable has ScrollView. the child view also '.refreshable' . example) var body: some View { List { ScrollView(.horizontal) { LazyHStack{ ..... } } } .refreshable{ ... } } I want to prevent child View's refreshable. but, child View ( ScrollView(.horizontal) { LazyHstack{ ... }} ) also refreshable. how to prevent child view's refreshable ?
{ "language": "en", "url": "https://stackoverflow.com/questions/75635665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is this jenkin file is okay? can you please check this stage and tell wheather this is correctly written or not stage('Deploy to Kubernetes'){ steps{ script{ withCredentials([string(credentialsID: 'KUBECONFIG', variable: 'KUBECONFIG')]){ sh ''' export KUBECONFIG=$KUBECONFIG kubectl config use-context <context-name> kubectl set image deployment/myapp myapp=<nexus ip and port>/springapp:${VERSION} helm upgrade myapp kubernetes/myapp/ --version ${helmversion} --set image.repository=<nexus ip and port>/springapp --set image.tag=${VERSION} ''' } } } } } I have confusion in k8 stage
{ "language": "en", "url": "https://stackoverflow.com/questions/75635674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Unable to install SQL Server (setup.exe) - exit code decimal: -2061893606? This is what happens when the installation is completed: Error description: Wait on Database Engine recovery handle failed. Check the SQL Server error log for potential causes. Please help me guys. How to solve this problem ? I've tried deleting every residual file from previous installations and I've even restarted my laptop and tried installing the express version as well, but I got the same results.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Google My Business API server to server without Workspace/G-Suite i would like to achieve that the website of my PHP website can fetch business location data (name, address, contact, openings, ...) from the Google APIs, so that i do not have to insert the information twice. I tried to create a service account and use it to authenticate against the My Business API. It did not work, as Google requires an OAuth2 token for this API. How can i obtain a Oauth2 token using the service account without having a Google Workspace or G-Suite? A: You need to actually own or manage a location on Google Business Profile in order to be able to retrieve data for it. So for this you need a Google account. An alternative for your usecase might be the Places API. In order to use it, you need to create an API key via the Google Cloud console.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adobe AEM 6.5 Cloud: wildcard in SlingServletPaths? We want to build a single proxy servlet which will serve a number of different paths, such as /api/register /api/player/1234/ /api/player/12312/transactions Basically, any and every path below /api/ Currently we are using this pattern, which only allows a single or list of fixed paths: @SlingServletPaths(value="/bin/somepath") private class MyServlet extends SlingAllMethodsServlet Any suggestions on how to handle variable paths? I found a potential solution here using a custom ResourceResolver, but it wont compile unfortunately (the annotations and imports etc are no longer available in AEM 6.5): https://stackoverflow.com/a/41990177/1072187 A: You cannot do this with Sling-Servlets. BUT you could have an OSGi Whiteboard-Pattern Servlet next to the Sling MainServlet. The simplest for your case is to use the same context-name as Sling. I also like to use a proxy servlets for some external services (e.g. Solr, Commerce-System, ...). For development it is much simpler, than setting up extra infrastructure on every developer machine. BUT: * *Use this approach only for local development (or maybe bug-analysis on PROD) *Use a type of Semaphore to limit the number of requests. If your proxy is slow, or doesn't work - it can easily eat up all of the 100 parallel requests, until Sling blocks incoming requests. This would completely kill your AEM instance. For me a limit to 4/5 parallel proxy-requests and a wait time of 200-500ms was good enough. @Component( service = Servlet.class, scope = ServiceScope.PROTOTYPE, property = { HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN + "=/api/*", HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT + "=(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=org.apache.sling)"}) public class OsgiProxyServlet extends HttpServlet { public static final Logger LOGGER = LoggerFactory.getLogger(OsgiProxyServlet.class); private final Semaphore semaphore; @Activate public OsgiProxyServlet() { this.semaphore = new Semaphore(/* max. parallel requests */ 5, true); LOGGER.info("Proxy Servlet instantiated"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { LOGGER.info("Got API Request: {}", request.getRequestURL()); boolean permitAcquired = false; try { permitAcquired = semaphore.tryAcquire(/* timeout */ 500, TimeUnit.MILLISECONDS); if (permitAcquired) { doProxyGet(request, response); } else { respond(response, SC_REQUEST_TIMEOUT, "Failed to acquire a proxy connection"); } } catch (InterruptedException e) { // in the Servlet.doGet()-method we cannot propagate the InterruptedException, // so we have to set the flag back to true Thread.currentThread().interrupt(); } finally { if (permitAcquired) { semaphore.release(); } } } private void doProxyGet(HttpServletRequest request, HttpServletResponse response) { // put your proxy code here LOGGER.info("Proxy request {}", request.getRequestURI()); respond(response, SC_OK, "Proxy request for path " + request.getPathInfo()); } private static void respond(HttpServletResponse response, int status, String message) { response.setContentType("text/plain"); response.setCharacterEncoding("utf-8"); response.setStatus(status); try { response.getWriter().print(message); } catch (IOException e) { LOGGER.error("Failed to write output", e); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/75635677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Move only single nav items to the right in Bootstrap 5 I have a navbar programmed with bootstrap 5 and as you can see in the picture I just want to move the last three nav-items to the right. I have already tried ms-auto, which resulted in all my nav-items being moved to the right, but I only want to move three to the right. A: Try using 2 ul classes: <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.2/font/bootstrap-icons.css" rel="stylesheet"/> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"/> <!-- Navigation--> <nav class="navbar navbar-expand-md navbar-dark bg-primary"> <div class="container-fluid"> <a class="navbar-brand abs" href="#">Navbar 1</a> <button class="navbar-toggler ms-auto" type="button" data-bs-toggle="collapse" data-bs-target="#collapseNavbar"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse" id="collapseNavbar"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="//codeply.com">Codeply</a> </li> <li class="nav-item"> <a class="nav-link" href="#myAlert" data-bs-toggle="collapse">Link</a> </li> </ul> <ul class="navbar-nav ms-auto"> <li class="nav-item"> <a class="nav-link" href="" data-bs-target="#myModal" data-bs-toggle="modal">About</a> </li> <li class="nav-item active"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="//codeply.com">Codeply</a> </li> </ul> </div> </div> </nav> A: To move the last three navigation items to the right, you can split the navigation items into two separate ul elements. The ul containing the right-aligned items should have the class ms-auto. <nav class="navbar navbar-expand-lg"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <!-- left aligned items --> </ul> <ul class="navbar-nav ms-auto"> <!-- right aligned items --> </ul> </div> </div> </nav>
{ "language": "en", "url": "https://stackoverflow.com/questions/75635680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I search for the newest result with arguments, regarding no duplicate by condition and sum this There is a possibility to enter numerical values in a table, suitable for group and name, with information of the range, and a numerical value (zw), with this it should be indicated, who has when how many places available. timestamp group name zw r_start r_end 01/01/2022 0:00:01 Group1 Player1 30 01/01/2022 01/20/2022 01/01/2022 0:00:02 Group2 Player2 30 01/01/2022 01/20/2022 01/01/2022 0:00:03 Group1 Player3 30 01/01/2022 01/20/2022 01/01/2022 0:00:04 Group1 Player1 40 01/01/2022 01/20/2022 01/01/2022 0:00:05 Group1 Player3 50 01/01/2022 01/20/2022 01/01/2022 0:00:06 Group1 Player1 20 01/01/2022 01/20/2022 01/01/2022 0:00:07 Group1 Player3 30 01/01/2022 01/20/2022 01/02/2022 0:00:01 Group1 Player1 30 01/01/2022 01/20/2022 01/02/2022 0:00:02 Group2 Player2 30 01/01/2022 01/20/2022 01/02/2022 0:00:03 Group1 Player3 30 01/01/2022 01/20/2022 01/02/2022 0:00:04 Group1 Player1 40 01/12/2022 01/20/2022 01/02/2022 0:00:05 Group1 Player3 50 01/12/2022 01/20/2022 01/02/2022 0:00:06 Group1 Player1 20 01/01/2022 01/20/2022 01/02/2022 0:00:07 Group1 Player3 30 01/08/2022 01/20/2022 I want the numerical value, added, of group1 from 01/03/2022. How do I get the numerical value "zw" of group 1 added so that always only the newest numerical value (zw) to the player of the day (timestamp) is considered, and the searched date fits into the range "r_start" - "r_end"? The result here is: 100 Is there a possibility, for example if you have the list of players matching the group, to process the players dynamically in a formula, for example, a query formula, which normally could give you the numerical value (zw) fitting to the tag, isolated with limit/offset etc, but now in a loop with the name and team as dynamic criteria? Maybe something faster than the query formula? A formula that can take one or more arrays as criterion, and this formula repeats itself as long as the array has places, and can read a certain list, focus on a column, and for example add the newest entry.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can I find names of functions based on --trace-opt output node --trace-opt and --trace-deopt outputs hex and sfi, but not always names of functions. so I wanted to know if there is any other flags I can set to know which function are getting optimized/deoptimaized. (such subjects are above my knowledge level but I'm really curious) I looked at other available flags of --v8-options, checked outputs of other trace and log flags.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gradle Building Errors in flutter I'm trying to solve the Gradle error but not solve this error so you can find this solution. * *What went wrong: `A problem occurred evaluating project ':app'. No signature of method: build_7ddlmucs2j5kiypgoiym6wbeo.android() is applicable for argument types: (build_7ddlmucs2j5kiypgoiym6wbeo$_run_closure2) values: [build_7ddlmucs2j5kiypgoiym6wbeo$_run_closure2@7a5f345e] * *Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * *Get more help at https://help.gradle.org BUILD FAILED in 624ms Running Gradle task 'bundleRelease'... 1,242ms Gradle task bundleRelease failed with exit code 1` I've been receiving the following error: This is my current dependency. I have been trying to figure out how to resolve this error but I just can not figure it out. Any suggestions or help will be greatly appreciated. buildscript { ext.kotlin_version = '1.5.21' repositories { google() jcenter() maven { url "https://maven.google.com" } } dependencies { classpath 'com.android.tools.build:gradle:7.0.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { google() jcenter() maven { url "https://maven.google.com" } } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir } And this is my other build.gradle apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion 31 sourceSets { main.java.srcDirs += 'src/main/kotlin' } lintOptions { disable 'InvalidPackage' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.example.flutter_auth" minSdkVersion 16 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' } A: I don't know if this is gonna work to you but it worked for me. try going to android/gradle folder then find the wrapper and edit it to the latest version e.g 7.6-bin ,then go to app gradle and rename the kotlin version to 1.7.0 and the build tools to 7.4.0 like this. #Fri Jan 20 16:18:48 SAST 2023 distributionBase=GRADLE_USER_HOME distributionUrl=https\://services.gradle.org/distributions/gradle-7.6- bin.zip distributionPath=wrapper/dists zipStorePath=wrapper/dists zipStoreBase=GRADLE_USER_HOME buildscript { ext.kotlin_version = '1.7.0' repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.4.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } Hope its gonna help
{ "language": "en", "url": "https://stackoverflow.com/questions/75635686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copy selected columns from source excel in a active workbook and copy them into specific column I'm trying to use an active workbook to select some specific columns from a source workbook and copy them to the specific location in a new excel workbook Here is my source workbook I want to copy columns F and G into a new workbook Here is my active workbook example If I type 'Hello' in type, 'Hi' in Code, and '20230302' in Date, it should have the same amount of rows as the copied data. And cell B7 is my source excel path The Header order of the output excel should exactly be the same as the active book. Type Code Date Title Person My code: Sub copy_column() Dim wbActive As Workbook, wbSource As Workbook, wbNew As Workbook Dim wsActive As Worksheet, wsSource As Worksheet, wsNew As Worksheet Dim rngCopy As Range Dim lastRow As Long, nlstclm As Long Dim clm As Range Set wbActive = ThisWorkbook Set wsActive = wbActive.Sheets("Sheet1") 'rename to suit If WorksheetFunction.CountA(wsActive.Range("B2:B6")) = 0 Then MsgBox "No column to copy." Exit Sub End If Set wbSource = Workbooks.Open(wsActive.Range("B7")) 'rename to suit Set wsSource = wbSource.Sheets("Sheet1") 'rename to suit Set wbNew = Workbooks.Add Set wsNew = wbNew.Sheets("Sheet1") For Each clm In wsActive.Range("B2:B6") If clm <> Empty Then lastRow = wsSource.Cells(Rows.Count, CStr(clm)).End(xlUp).Row Set rngCopy = wsSource.Range(CStr(clm) & "2:" & CStr(clm) & lastRow) If wsNew.Cells(1, 1) = Empty Then nlstclm = wsNew.Cells(1, Columns.Count).End(xlToLeft).Column Else nlstclm = wsNew.Cells(1, Columns.Count).End(xlToLeft).Column + 1 End If wsNew.Cells(1, nlstclm) = clm.Offset(0, -1) rngCopy.Copy wsNew.Cells(2, nlstclm) End If Next wbNew.SaveAs wsActive.Cells(7, 2) & "Output.xlsx" 'rename to suit wbNew.Close False wbSource.Close False Set wbActive = Nothing Set wbSource = Nothing Set wbNew = Nothing MsgBox "Copy completed." End Sub I can copy my column to cell A1 but not in the specific location. Also, how to add the specific tag that has the same amount of rows as the copied column? And here is a link to my expected outputs A: If I understand you correctly, the sub below is not complete but maybe can help you to get started. Sub test() 'Set shSrc = Workbooks("source.xlsm").Sheets(1) Set wbActive = ThisWorkbook Set wsActive = wbActive.Sheets("Sheet1") 'rename to suit Set wbSource = Workbooks.Open(wsActive.Range("B7")) 'rename to suit Set wsSource = wbSource.Sheets("Sheet1") 'rename to suit 'With ActiveSheet With wsActive Set c = .Range("B2") cnt = Application.CountA(wsSource.Columns(Cells(1, .Range("B5").Value).Column)) - 1 End With Set wbNew = Workbooks.Add With wbNew.Sheets(1) .Range("A1").Resize(1, 6).Value = Array("Type", "Code", "Date", "Title", "Person", "Number") LR = .Range("A" & Rows.Count).End(xlUp).Row + 1 For i = 1 To 6 Set rg = c If i = 6 Then .Cells(LR, i).Resize(cnt, 1).Value = 1 Else If i = 4 Or i = 5 Then _ Set rg = wsSource.Cells(2, c.Value): Set rg = Range(rg, rg.End(xlDown)):wbSource.activate:wsSource.activate:rg.select:wbNew.activate .Cells(LR, i).Resize(cnt, 1).Value = rg.Value Set c = c.Offset(1, 0) End If Next i End With End Sub The c variable it to get the cell value in the active sheet to be copied to the new workbook. cnt is to count how many item in the source sheet which column is coming from activesheet cell B5 value. So the code assumed that the active sheet cell B5 is fixed will always be a column letter refferencing to the source sheet. The code also assumed that the source sheet which column is coming from activesheet cell B6 value has the same count. After it create a new workbook as wbNew, within wbNew sheets(1) : * *create a 6 columns header starting from cell A1. *get the row number of the last row of data in column A. *Loop for six times as i variable where within the loop : *it set rg variable from c *it check if i = 6 then it fill the last column with 1 *if i = 4 or 5, it get the rg from shSrc *then it fill each column with rg value For the rest of the code to save the newWb I'm sure you can do it. I add a "checking" code line which later it can be removed : original code : Set rg = wsSource.Cells(2, c.Value): Set rg = Range(rg, rg.End(xlDown)) after adding "checking" code : Set rg = wsSource.Cells(2, c.Value): Set rg = Range(rg, rg.End(xlDown)): wbSource.activate:wsSource.activate:rg.select:wbNew.activate ---> Does it give a correct result for rg selection? And before .Cells(LR, i).Resize(cnt, 1).Value = rg.Value ... try to add .Cells(LR, i).Resize(cnt, 1).select. In the first iteration, does it select a blank cells in column A with rows as many as the cnt ?
{ "language": "en", "url": "https://stackoverflow.com/questions/75635688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to set the profile status of users in my slack workspace using the slack python SDK (users_profile_set), however I am getting "invalid_user" I am trying to create an App for my workspace which would set the user's presence at appropriate moments. I wrote the following test function: from slack_sdk import WebClient client = WebClient(token=SLACK_USER_TOKEN) email = 'test.email=test.com' response = client.users_lookupByEmail(email=email) user_id = response["user"]["id"] client.users_setPresence(user=user_id, presence="away") status_message = "deactivated" status_emoji = ":x:" client.users_profile_set( user=user_id, profile={ "status_text": status_message, "status_emoji": status_emoji } ) But upon executing this code, I get: The request to the Slack API failed. (url: https://www.slack.com/api/users.profile.set) The server responded with: {'ok': False, 'error': 'invalid_user'} I have the following scopes active for SLACK_USER_TOKEN: users.profile:read users.profile:write users:read users:read.email users:write Why am I getting Invalid ID? I double checked and the user_id is correct and belongs to an actual user... I expected the status of the user changed with a message showing on their slack profile. Instead, I got the error I mentioned above.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find the stock coverage month in Excel I have below data where I am trying to find till which month the available stocks are good. I have demands from March to June and Stocks in various stages in FG/WIP/RM, the formula should compare the demands with stock levels and show till which month the actual coverage happens. Example : FH+WIP+RM total stock is 10+15+20=45 , This can cover march, april and May, so the result should be may Similarly for part 2 result would be march. I need help to find a formula in Coverage until column, which will sum FG+WIP & RM and calculate till which month the stock covers. part name march april may june FG WIP RM Coverage until Part 1 10 11 23 36 10 15 20 Result : May Part 2 12 14 13 18 8 12 0 Result:March Part 3 I know this can be achieve through Index and match but someone i am struck at formula to get the running total and corresponding column name. A: Try this: I2: =INDEX(Sheet4!$B$1:$E$1,MATCH(2,1/(SUM(Sheet4!$F2:$H2)-SUBTOTAL(9,OFFSET(Sheet4!$B2,0,0,,SEQUENCE(4)))>0))) A: You can try the following array formula (spill the entire result for all rows), assuming no Excel version constraints as per the tags listed in the question. In cell J2, put the following formula: =LET(dem, F2:F3+G2:G3+H2:H3, in, B2:E3, h, B1:E1, BYROW(HSTACK(in,dem),LAMBDA(x, INDEX(h, SUM(N(SCAN(0, DROP(x,,-1), LAMBDA(ac,y, ac+y)) <= TAKE(x,,-1))))))) or without LET function (shorter, but more difficult to read/explain it): =BYROW(HSTACK(B2:E3, F2:F3+G2:G3+H2:H3), LAMBDA(x, INDEX(B1:E1, SUM(N(SCAN(0, DROP(x,,-1), LAMBDA(ac,y, ac+y)) <= TAKE(x,,-1)))))) Here is the output: where dem is the demand. We iterate over all rows using BYROW but adding as last column the demand. For each row (x) we calculate the cumulative sum via SCAN of the first columns removing the demand (DROP(x,,-1), then we do the comparison with the demand (last column, i.e. TAKE(x,,-1)) and sum the number of times it satisfies the condition, which corresponds with the index position of the header (h). Finally, we use INDEX to find the corresponding header value. Note: It is also possible using MMULT and the unit lower triangular matrix (tri) instead of SCAN for doing the cumulative sum, but it is a more verbose approach: =LET(dem, F2:F3+G2:G3+H2:H3, in,B2:E3, h, B1:E1, n, COLUMNS(h), tri, N(SEQUENCE(n) >= SEQUENCE(,n)), BYROW(HSTACK(in,dem), LAMBDA(x, INDEX(h, SUM(N(MMULT(tri, TOCOL(DROP(x,,-1))) <= TAKE(x,,-1)))))))
{ "language": "en", "url": "https://stackoverflow.com/questions/75635693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove an element from a list in R while maintaining the original list print formatting? I've searched far and wide on Stack Overflow and online generally on how to remove specific elements from a list and I've partly figured out how to do this. However, when I remove an element from this example list, I lose the original nice formatting of the list. Let me explain in the image that follows. How do I remove the "Call" element and the text that follows it ("survdiff(formula = Surv(time, status) ~ sex, data = lung)"), while retaining the original formatting? Example code is posted at the bottom. Example code: library(survival) library(survmine) fit <- survfit(Surv(time, status) ~ sex, data = lung) surv_diff <- survdiff(Surv(time, status) ~ sex, data = lung) surv_diff str(surv_diff) test <- surv_diff[-7] # trying to remove the "Call" element and all its text A: When you remove that element, you remove the class attribute. You can place it back like this: class(test) <- "survdiff" A: I ran your example code and it gives me a list of 6 items (no pvalue). So in my case I am working on the 6th element - you might need to work on the 7th. # remove sixth list item (keeping the class attribute) surv_diff[6] <- NULL # look at the resulting list str(surv_diff) List of 5 $ n : 'table' int [1:2(1d)] 138 90 ..- attr(*, "dimnames")=List of 1 .. ..$ groups: chr [1:2] "sex=1" "sex=2" $ obs : num [1:2] 112 53 $ exp : num [1:2] 91.6 73.4 $ var : num [1:2, 1:2] 40.4 -40.4 -40.4 40.4 $ chisq: num 10.3 - attr(*, "class")= chr "survdiff" # print surv_diff N Observed Expected (O-E)^2/E (O-E)^2/V sex=1 138 112 91.6 4.55 10.3 sex=2 90 53 73.4 5.68 10.3 Chisq= 10.3 on 1 degrees of freedom, p= 0.001 Please bear in mind that removing parts from object probably will implicate some type of mal behaviour when further processing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using nestjs/axios GET request set encoding for xml I am trying to retrieve a XML via axios (for nestjs) from an external HTTP service. Unfortunately the encoding does not seem to work correctly, because the special characters (ü, ö, ä, etc.) are not are not delivered correctly. How can I set the encoding correctly in the header of a GET request, so that it works ? When I open the url directly in the browser, the encoding works correctly. For XML parsing I use the fast-xml-parser. return this.httpService.get(`mycoolurl`, { headers: { 'Content-Type': 'text/xml;charset=UTF-8', }, }, ) .pipe(map((res) => { ... });
{ "language": "en", "url": "https://stackoverflow.com/questions/75635697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java card polling reader with reactor I've built the following function to execute a CardTerminal for reading the ICCID of a SIM Cards. Goal: * *Terminal Polling and wait for a CardTerminal connect *Card Polling and wait for a Card connect *if terminal & card connected read out iccid and write to file (already implemented) *if terminal or card has been removed go back to initial point and wait for connections (infinite loop) This is my code. When a terminal is not connected, it waits. After a terminal is connected it waits until a card is present. After a card is present It reads the iccid and write it to a file but only once (goal is that it will loop inifinite until application stop). When I remove the card or the terminal is disconnected the application stops (which is not desired). public void run() { Mono.defer(cardTerminalFactory::getTerminal) .retry() .doOnSuccess(t -> { System.out.println("connected with terminal: " + t.getName()); Mono.defer(() -> cardTerminalFactory.waitForCard(t)) .doOnSuccess(x -> { System.out.println("connected with card"); try { // wait for card insert if (t.waitForCardPresent(0)) { // just some logic here (read out iccid and print to file) var iccid = cardTerminalFactory.readIccid(x.getBasicChannel()).blockOptional(); iccid.ifPresent(bigInteger -> Writer.write(bigInteger.toString())); //continue when a card removed t.waitForCardAbsent(0); } } catch (CardException e) { Mono.error(Exception::new); } }).block(); } ) .onErrorResume(error -> Mono.empty()) .block(); } Can you help me?
{ "language": "en", "url": "https://stackoverflow.com/questions/75635698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I found strange data reshaping method in MATLAB doc... Help me My goal is to build forecasting model with RNN. I'm stuck at reshaping time series data. There were some methods I could not figure out. Time series forecasting using MATLAB Time series forecasting using python If you take a look at this example in MATLAB documentation, the target is 1-step shifted value. for n = 1:numel(dataTrain) X = dataTrain{n}; XTrain{n} = X(:,1:end-1); TTrain{n} = X(:,2:end); end Also, in the second code, target is just shifted values. Yt = data[None,initLen+1:trainLen+1] What is this method called? I would be glad to know any documentations about these reshaping methods. Thanks. After reading a lot of papers and internet blogs, I figured out that most of them uses sliding window approach. * *Sliding window (Tumbling window/Hopping window) Sliding window
{ "language": "en", "url": "https://stackoverflow.com/questions/75635699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to start up Vue method? I'm new in Vue-CLI and don't understand how can I call methods in onMounted. So I have a method, which get some variables, then calculate and return result. I want to launch this method every 5 seconds. My IDE tells that in onMounted "Cannot find name 'checkStatus'." So, could you tell me how to solve this problem? Component: <script> export default defineComponent({ setup() { const message = ref({ text: '', isConnected: false, isError: {}, camID: '', }); onMounted(() => { const check = ()=>{ checkStatus(); setTimeout(check, 5000); } check(); }); return { message checkStatus: (row:any) => { message.value.isError = {...row.error}; message.value.text = (message.value.isError == false || Object.keys(message.value.isError).length == 0) ? 'Loading' : 'Error!'; message.value.isConnected = {...row.connected}; message.value.camID = ((Object.values({...row.id})).toString()).split(',').join(''); console.log(message); return message; }, }; }, }); </script> A: You should define all function in the setup and then return them. Here is the playground const { createApp, ref, onMounted } = Vue const MyComp = { setup() { const message = ref({ text: '' }); const checkStatus = () => { console.log('checkStatus()'); message.value.text = `Current time is ${new Date().toLocaleTimeString()}`; } const check = () => { console.log('check()'); checkStatus(); setTimeout(check, 5000); } onMounted(() => { check(); }); return { message, checkStatus, check } }, template: '{{message}}' } const App = { components: { MyComp } } const app = createApp(App) app.mount('#app') #app { line-height: 1.75; } [v-cloak] { display: none; } <div id="app" v-cloak> <b>MyComp:</b><br/> <my-comp></my-comp> </div> <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/75635701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why embarassingly parallel jobs go much slower on a server based on slurm than locally when using R? I run the following R script both on my personal computer and a computing facility based on slurm queuing system foo = function(size){ sample = rnorm(size) mean = mean(sample) sd = sd(sample) vOut = c("mean" = mean, "sd" = sd) return(vOut) } # nonparallel case begin = Sys.time() for(i in rep(1e7, 80)){ foo(i) } end = Sys.time() print("nopar") print(end - begin) # parallel case library(foreach) library(doParallel) cores = 16 cl <- makeCluster(cores[1], outfile = "") registerDoParallel(cl, cores = ncor) begin = Sys.time() foreach(x = rep(1e7, 80)) %dopar% { foo(x) } end = Sys.time() print("Par") print(end - begin) To launch it on the server I use the following batch file named run #!/bin/bash #sbatch - -ntasks=16 #sbatch --cpus-per-task=1 #sbatch - -output=/scratch/user/out.txt Rscript --vanilla Programs/Valid4_parallel_norm.R which I call from the console via sbatch ./run Running it on my own computer it takes 45 seconds on a single core and 6 seconds on multiple (16 cores). Whereas when running it on the server it takes in both cases around 1 minute. What could it be the reason? Could it be an issue with the server? It also does not seem to me that the program requires much memory to be allocated and transferred across cores.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hostinger transferred my website to another server and I cannot generate PDF files Hostinger transferred my website to another server, and I cannot generate PDF files since then. I get the following error with dompdf: Fatal error: Uncaught exception 'DOMPDF_Exception' with message 'No block-level parent found. Not good.' in /home/u347702159/domains/egytrans.net/public_html/clients/application/helpers/dompdf/include/inline_positioner.cls.php:68 Stack trace: #0 /home/u347702159/domains/egytrans.net/public_html/clients/application/helpers/dompdf/include/frame_decorator.cls.php(382): Inline_Positioner->position() #1 /home/u347702159/domains/egytrans.net/public_html/clients/application/helpers/dompdf/include/text_frame_reflower.cls.php(330): Frame_Decorator->position() #2 /home/u347702159/domains/egytrans.net/public_html/clients/application/helpers/dompdf/include/frame_decorator.cls.php(388): Text_Frame_Reflower->reflow() #3 /home/u347702159/domains/egytrans.net/public_html/clients/application/helpers/dompdf/include/page_frame_reflower.cls.php(96): Frame_Decorator->reflow() #4 /home/u347702159/domains/egytrans.net/public_html/clients/application/helpers/dompdf/include/frame_decorator.cls.php(388): Page_Frame_Reflower->reflow() #5 /home/u34 in /home/u347702159/domains/egytrans.net/public_html/clients/application/helpers/dompdf/include/inline_positioner.cls.php on line 68 I am not well-versed with Php. I do appreciate your help. Tried to generate Pdfs but it does not work.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to link to a library with a .dll and .def file I just want to apologize in advance if there are a similar thread to this one. I've spent hours googling and searching for an answer which helps me, I've even tried using chat-gpt for help. I want to use the sqlite library for my c++ project. I downloaded the precompiled binaries which consisted of a .dll and a .def file. I've never linked a library using only a .dll a .def file before and is mighty confused about it. I'm using vs code and also a makefile. See below for details. Could someone please explain how I link the lib with this method and also how I'm supposed to reference the methods of the library without having a header to include. Thank you. I've tried to link to the library by using these flags: "CFLAGS := -Wall -I include/ -L lib/ -lsqlite3 -lraylib -lopengl32 -lgdi32 -lwinmm" When trying to compile the code i get this message: "skipping incompatible lib//sqlite3.dll when searching for -lsqlite3 skipping incompatible lib//sqlite3.dll when searching for -lsqlite3 cannot find -lsqlite3: No such file or directory skipping incompatible lib//sqlite3.dll when searching for -lsqlite3" Here's a screenshot of my project
{ "language": "en", "url": "https://stackoverflow.com/questions/75635706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Android WebView and TalkBack Accessibility I am developing an android app where accessibility is critical. App uses latest WebView(109) to bring various content to the user. These content could be Epubs and can contain MathML/LaTex expressions and so on. By default, I would like to piggy back on TalkBack to provide the accessibility service, however, when it comes to technical content (read MathML/Latex) etc, much left to be desired with talkback. I would like to either create a custom accessibility service or intercept the creation of accessibility tree as regards to the WebView on android to provide a custom virtual tree with translated content descriptions etc for talkback to deal with. Is this possible ? I have poured over various documentation and videos etc but havent been successful. Can someone point me in the right direction to achieve this , maybe a sample piece of code , repository etc? I tried setting AccessibilityDelegate on webview instance etc. I would like to retain the WebView/TalkBack combo to keep things standard except for the accessibility tree part. Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/75635707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Could not find or load main class com.example.ServingWebContentApplication When I run my program in IntelliJ IDEA, I have that error Error: Could not find or load main class com.example.ServingWebContentApplication Caused by: java.lang.ClassNotFoundException: com.example.ServingWebContentApplication There is screen my Intellij IDEA: This is my pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>LetsCodeSpringSweater</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>19</maven.compiler.source> <maven.compiler.target>19</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.0.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
{ "language": "en", "url": "https://stackoverflow.com/questions/75635710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How could make dynamically element focus? In javascript when press 'add button', button will be created and added on the list. My question is, how could I reduce code for focus function and make it dynamically? According to the code below I have to make focus function for every single created button, but program should work for every new button of course if does it possible. There is what I try to do. var i = 0; function buttonClick() { i++; document.getElementById('number').value = "Button" + i; const addbuton = document.getElementById('addbuton'); const a = document.getElementById('dropdown-content'); const button1 = document.createElement("button"); button1.setAttribute("id", document.getElementById('number').value); button1.setAttribute("class", "name"); var linkButton = document.createElement('a'); linkButton.innerHTML = document.getElementById('number').value; linkButton.setAttribute("onclick", "getfocus" + i + "()"); a.appendChild(linkButton); const body = document.getElementById('preview'); button1.innerHTML = document.getElementById('number').value; button1.style.display = "block"; button1.style.width = "100px"; button1.style.borderRadius = '5px'; button1.style.border = 'none'; button1.style.margin = '10px'; body.appendChild(button1); }; function myFunction() { const element = document.activeElement.id; document.getElementById("output-element").innerHTML = element; } function getfocus1() { document.getElementById("Button1").focus(); } function getfocus2() { document.getElementById("Button2").focus(); } function getfocus3() { document.getElementById("Button3").focus(); } function getfocus4() { document.getElementById("Button4").focus(); } .dropbtn { background-color: grey; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropdown { display: inline-block; } .dropbtn { width: 120px; } .dropdown-content { display: block; position: absolute; background-color: #f9f9f9; width: 120px; z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover { background-color: #f1f1f1 } .dropdown:hover .dropbtn { background-color: grey; } .container { display: flex; } .dropbtn { background-color: grey; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropdown { display: inline-block; } .dropbtn { width: 120px; } .dropdown-content { display: block; position: absolute; background-color: #f9f9f9; width: 120px; z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover { background-color: #f1f1f1 } .dropdown:hover .dropbtn { background-color: grey; } .container { display: flex; } <body onclick="myFunction()"> <div class="container"> <div class="dropdown"> <button class="dropbtn">Button List</button> <div id="dropdown-content" class="dropdown-content"></div> </div> <div id="preview"> <input type="text" for="addbuton" id="number" value="" style="display: none;"> <input type="button" onclick="buttonClick();" id="addbuton" value="Add Button"> <p>Active element ID: <em id="output-element"></em></p> </div> </div> </body> A: You can pass the number of the button as a parameter to the getFocus() function. Change linkButton.setAttribute("onclick", "getfocus(" + i + ")"); and function getfocus(n) { document.getElementById("Button"+n).focus(); } The new code: var i = 0; function buttonClick() { i++; document.getElementById('number').value = "Button" + i; const addbuton = document.getElementById('addbuton'); const a = document.getElementById('dropdown-content'); const button1 = document.createElement("button"); button1.setAttribute("id", document.getElementById('number').value); button1.setAttribute("class", "name"); var linkButton = document.createElement('a'); linkButton.innerHTML = document.getElementById('number').value; linkButton.setAttribute("onclick", "getfocus(" + i + ")"); a.appendChild(linkButton); const body = document.getElementById('preview'); button1.innerHTML = document.getElementById('number').value; button1.style.display = "block"; button1.style.width = "100px"; button1.style.borderRadius = '5px'; button1.style.border = 'none'; button1.style.margin = '10px'; body.appendChild(button1); }; function myFunction() { const element = document.activeElement.id; document.getElementById("output-element").innerHTML = element; } function getfocus(n) { document.getElementById("Button"+n).focus(); } .dropbtn { background-color: grey; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropdown { display: inline-block; } .dropbtn { width: 120px; } .dropdown-content { display: block; position: absolute; background-color: #f9f9f9; width: 120px; z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover { background-color: #f1f1f1 } .dropdown:hover .dropbtn { background-color: grey; } .container { display: flex; } .dropbtn { background-color: grey; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropdown { display: inline-block; } .dropbtn { width: 120px; } .dropdown-content { display: block; position: absolute; background-color: #f9f9f9; width: 120px; z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover { background-color: #f1f1f1 } .dropdown:hover .dropbtn { background-color: grey; } .container { display: flex; } <body onclick="myFunction()"> <div class="container"> <div class="dropdown"> <button class="dropbtn">Button List</button> <div id="dropdown-content" class="dropdown-content"></div> </div> <div id="preview"> <input type="text" for="addbuton" id="number" value="" style="display: none;"> <input type="button" onclick="buttonClick();" id="addbuton" value="Add Button"> <p>Active element ID: <em id="output-element"></em></p> </div> </div> </body> A: Based on your code snippet, it looks like you're trying to generate a function for each button. Instead, you can use querySelectorAll to select the container of the buttons, and attach one event handler function to it. This will give you access to the event object, and you can use the target property to access the clicked button and perform any desired actions on it. This way, you don't have to generate a new function for each button, which can be more efficient and easier to manage.
{ "language": "en", "url": "https://stackoverflow.com/questions/75635711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: I get nullsafety error when I try to add firebase package to pubsec.yaml file I am trying to add Firebase to my Flutter App named biletsatis . But when I try pub get, I get this error. [biletsatis] flutter pub get Running "flutter pub get" in biletsatis... Resolving dependencies... Because firebase_core >=0.7.0 <0.8.0-1.0.nullsafety.0 depends on firebase_core_platform_interface ^3.0.1 and cloud_firestore >=4.3.2 depends on firebase_core_platform_interface ^4.5.3, firebase_core >=0.7.0 <0.8.0-1.0.nullsafety.0 is incompatible with cloud_firestore >=4.3.2. So, because biletsatis depends on both cloud_firestore ^4.4.3 and firebase_core ^0.7.0, version solving failed. pub get failed command: "C:\Users\USER\flutter\bin\cache\dart-sdk\bin\dart __deprecated_pub --directory . get --example" pub env: { "FLUTTER_ROOT": "C:\Users\USER\flutter", "PUB_ENVIRONMENT": "vscode.dart-code:flutter_cli:get", "PUB_CACHE": "C:\Users\USER\AppData\Local\Pub\Cache", } exit code: 1 exit code 1 Here is my dependencies section in pubsec.yaml file flutter: sdk: flutter flutter_form_bloc: ^0.30.1 cupertino_icons: ^1.0.2 cloud_firestore: ^4.4.3 firebase_core: ^0.7.0
{ "language": "en", "url": "https://stackoverflow.com/questions/75635714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }