QuestionId
stringlengths
8
8
AnswerId
stringlengths
8
8
QuestionBody
stringlengths
91
22.3k
QuestionTitle
stringlengths
17
149
AnswerBody
stringlengths
48
20.9k
76396002
76396544
There is a simple ASP.NET app as an event handler Server: WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services .AddWebPubSub(options => options.ServiceEndpoint = new ServiceEndpoint(WebPubSubConnectionString)) .AddWebPubSubServiceClient<WebPubSubHub>(); WebApplication app = buil...
Authentication between Azure Web PubSub and server
One possible way is to use AddEndpointFilter app.MapWebPubSubHub<WebPubSubHub>("/eventhandler").AddEndpointFilter(new ApiKeyFilter(builder.Configuration)); the implementation could look like this: public class ApiKeyFilter : IEndpointFilter { private readonly string _apiKey; public ApiKeyFilter(IConfiguration...
76394476
76394841
How to convert milliseconds to seconds units? For example the seekBar values are from 100 to 1000 and I want to display the units if they are under 1000(second) as 0.1 0.2 0.3....0.9 then 1 private var counter: Long = 0 @RequiresApi(Build.VERSION_CODES.O) override fun onCreate(savedInstanceState: Bundle?) { ...
How to convert milliseconds to seconds units and display them in textView?
Change the data type of counter from Long to Float or Double. Long only allows integer values. private var counter: Float = 0.0F ... counter = seek.progress.toFloat()
76396150
76396550
I am trying to learn some OCaml, I created a very simple example to open and then close a sqlite file. let () = let db = Sqlite3.db_open "test.db" in Sqlite3.db_close db I did an opam install sqlite3 and I see the .opam/default/lib/sqlite3 files in place. I would expect this means that the package is installed. Wh...
Unbound module Sqlite3
Using ocamlfind to compile a trivial demonstration program that opens the Sqlite3 module. $ cat test.ml open Sqlite3 let () = print_endline "hello" $ ocamlc test.ml File "test.ml", line 1, characters 5-12: 1 | open Sqlite3 ^^^^^^^ Error: Unbound module Sqlite3 $ ocamlfind ocamlc test.ml -package sqlite3 -link...
76397627
76397651
I am plotting a bar graph. However, the axes x show in different month order. Using the command reoder_within, doesn't work for the purpose. Follow below the ME. ggplot(de, aes(fill=Cidade, y = Leitura , x = Mes ))+geom_bar(position='dodge', stat='identity') Generate the follow plot: Plot My purpose is modify the axe...
ggplot - reorder_within - Order month
We can use fct_inorder here: ggplot will order x axis alphapetically. To get the order in your table use fct_inorder: library(ggplot2) library(forcats) library(dplyr) de %>% mutate(Mes = fct_inorder(Mes)) %>% ggplot(aes(fill = Cidade, y = Leitura, x = Mes)) + geom_bar(position = 'dodge', stat = 'identity')
76396027
76396561
I need to define an alias for this: Select-String -NotMatch -Pattern "^[\t ]+\d" so that I can use the alias instead of writing that long string each time. After googling for 5 minutes and doing some experiments I came up with this: filter foo { $_ | Select-String -NotMatch -Pattern "^[\t ]+\d" } So now my script ...
How to define a command alias in PowerShell for filtering output?
Is the foo filter acting as a transparent alias of the longer command line, or is it creating an entire new pipe or buffer or something? The latter, your current implementation is invoking Select-String per pipeline input object instead of invoking it once and processing all input. If you care about performance you s...
76396418
76396580
I'm currently learning c++ and I'm working on my first game using SFML/TGUI. I have tried making a function that creates a button, which in turn calls on a function when pressed. In an effort to make the button creator smarter and more versitile, I have made it so that it takes an object pointer and a function pointer ...
Why do I receive an access violation error in my SFML C++ project when passing object and function pointers?
Your lambda is capturing by reference, all the local variables it captures references to will cause undefined behaviour when the button is pressed as the local variables will have gone out of scope. You should capture by value instead: button->onPress([object, functionPointer, guiPointer, button]() { (object->*function...
76394772
76394849
Remove whitespace from an array of string. While creating an array of string from a sentence, I'm encountering multiple spaces and need to remove them in order to create a new reverse sentence from the given sentence. How do I remove extra spaces in the middle of two words? Example: a good example How do I remove two...
Remove whitespace from an array of string
The parameter to method split (of class java.lang.String) is a regular expression. Just add a + (i.e. "plus" symbol – which means one or more) to the value of the parameter. import java.util.ArrayList; import java.util.List; public class ReverseString { public static void main(String[] args) { String s = ...
76381579
76394860
Is it possible to bind a function that gets called every time user chooses between matchOption of p-columnFilter. <p-columnFilter type="date"> ... </p-columnFilter> example: https://stackblitz.com/edit/owuvzd?file=src%2Fapp%2Fdemo%2Ftable-filter-menu-demo.html
Is there a way to listen for changes in p-columnFilter match options and call a function in Angular and PrimeNG?
I was able to find a workaround to this, by creating my own matchModeOptions and their filter functions. To do this I made use of FilterService public dateIsFilter: string = "is-date"; public matchModeOptions: any[] = [ { label: "Date is", value: this.dateIsFilter } ] constructor(private filterService: FilterServic...
76397575
76397661
I want to fix an error regarding an unassigned variable, but I don't know where to define it: Use of unassigned variable '$userInfo'PHP(PHP1412) The error is occuring in this line $accessToken = $userInfo->createToken(uniqid())->plainTextToken;. This is my code: public function createUser(Request $request) { try ...
Laravel issue creating new user
The variable $userInfo is not defined before the line where the error is occurring. To fix this issue, you need to define $userInfo before using it. Replace the variable $userInfo with $user in the last part of the code. public function createUser(Request $request) { try { // Validated $validateUser...
76394425
76394893
Converting an array [fields => values] to one [fields, values] If I have an array like this: [ field1 => value1, field2 => value2, field3 => value3 ]; and I want to convert it to an array like this: [ [field1, field2, field3], [value1, value2, value3] ]; now I just took the keys and values and put them in another arr...
How can I convert an array with key-value pairs to an array with separate sub-arrays for the keys and values in PHP?
Before considering "elegant", first consider output consistency. If you always want to create an array with two first level elements, your approach is suitable. However, if you want an empty output array when your input array is empty, you'll need a different approach where the result array is only deepened when neces...
76396496
76396581
I am trying to find out how to have a child element that has position: absolute that is positioned outside of its parent element that does not trigger the parent's :hover effect. Since the parent has a hover effect, the child elements will trigger the parent element, even though that child is outside of the parent ele...
How to have child div not trigger hover effect of parent div?
You can use following solutions for this. You can use pointer-events: none on the child element. But remember that this will block all types of pointer events on that, and not just hover event. So any sort of click events will also not work on that child element. Another option is to use :has() method in the css. :ha...
76392269
76397689
I am attempting to execute multiple functions consecutively by defining them in an array (specifically for an Angular APP_INITIALIZER function). I have this array: const obsArray = [ myService1.init(), myService2.init(), ... myServiceN.init() ] Each of these init() methods returns Observable<void>. Her...
Executing RXJS Functions in Sequence Defined By Array
You can also put all the observables from the array into an observable, essentially converting Array<Observable<T>> to Observable<Observable<T>> and then use the higher order function concatAll: from(obsArray).pipe(concatAll()) Here's a live demo.
76396395
76396624
I'm trying to extract data from a .txt file and while my regex did work for the most part, it fails when it comes across single quotes within the text I'm trying to extract. {'pro_id':'1692423', 'pro_model':'SKUF42051', 'pro_category':'accessories', 'pro_name':'Gants tactiques Escalade en plein air Gants antidérapants ...
How can I extract text from single quotes, even if the text itself contains single quotes, using regex in Python?
Your string is malformed. Strings containing literal single quotes should be enclosed in double quotes, else it can't be parsed correctly. It is extremely difficult to use regex to sort this out, and also by using a for loop. But I have discovered a way, I have found simple patterns. Since all strings are enclosed in s...
76394871
76394902
I'm trying to animate a collapsing list with React/Joy-UI Here is my Transition element <Transition nodeRef={nodeRef} in={browseOpen} timeout={1000}> {(state: string) => (<List aria-labelledby="nav-list-browse" sx={{ '& .JoyListItemButton-root': { p: '8px' }, transition: '...
Cubic-bezier fixes exiting animation but breaks entering animation
Found the answer: The transition needed to be set like this: transition: `1000ms ${state === "exiting" ? "cubic-bezier(0, 1, 0, 1)" : "ease-out"}` For any other novices out there, note the backticks `` around the string rather than ''
76394248
76394918
I've coded beyond my ability and managed to get MSAL authentication working for my Browser Extension. I'm ready to push code to GitHub. Is it ok to push code with the Client ID in it? Can someone else use my Client ID? If I can't safely push this to a public GitHub, how do I handle it? // Microsoft Authentication Libra...
Can I publish client ID?
Technically, it should be okay. Is it ok to push code with the Client ID in it? The question you should ask yourself is, what information does the client ID give away? According to the Microsoft identity platform and the OAuth 2.0 client credentials flow a client_id is, The Application (client) ID that the Azure por...
76397713
76397738
I have the following HTML with a CSS grid <div id="grid"> <div class="main-item">Main</div> </div> #grid { display: grid; grid-template-columns: repeat(5, auto); text-align: center; } #grid > * { border: 1px solid blue; padding: 20px; } #grid > .main-item { grid-row: 3; grid-column: 3...
Mixing grid auto layout with a fixed row-column position
You can give the grid a relative position and position that specific grid item absolutely. const grid = document.querySelector("#grid"); for (let i = 0; i < 25; i++) { const item = document.createElement("div"); item.innerText = i; grid.append(item); } #grid { display: grid; grid-template-columns:...
76394958
76394976
due to these bracket { and } in Hourly Status','{',''),'}','') causing the syntax error in query .How to pass these bracket as string in a f-string format? query = f"""Select fd.serial_number,txidkey,cast(replace(replace(data->>'Hourly Status','{',''),'}','') as text) as description,TO_TIMESTAMP(TIME/1000+19800) as dat...
How to pass curly bracket ({) as a string in f-string python?
just use double curly braces {{: query = f"""\ Select fd.serial_number, txidkey, cast(\ replace(replace(data->>'Hourly Status','{{',''),'}}','') as text) \ as description,TO_TIMESTAMP(TIME/1000+19800) as date_time,time,total_min \ from filter_data fd , total_sum ts \ where fd.serial_number = ts.serial_number \ and time...
76396569
76396655
I have the following table Function Department Start Date End Date Const Const 1 2023-03-01 2023-03-05 Const Const 2 2023-03-02 2023-03-03 Mining Mining 1 2023-03-02 2023-03-05 Mining Mining 2 2023-03-01 2023-03-06 Const Const 1 2023-03-03 2023-03-07 Const Const 2 2023-03-02 2023-03-05 Mining Mining...
Calculating Collective Count of departments on individual dates from a given date range
df['Start Date'] = pd.to_datetime(df['Start Date']) df['End Date'] = pd.to_datetime(df['End Date']) dates = pd.date_range(df['Start Date'].min(), df['End Date'].max()) #get the complete dates in data set final_df = pd.DataFrame({'Date': dates}) final_df = final_df.set_index('Date') departments = df['Department'].uniq...
76397698
76397757
I'm writing game for project in VS Community 2017 in c++. I can see that coloring text works well in windows terminal, but I'm not sure if it'll be working on every windows compiler? Is there any safer way to print colored text? Example code: #include <iostream> #include <Windows.h> using namespace std; int main() {...
Displaying colored text in windows console by linux codes (C++)
The compiler has little (if anything) to do with this. Your code just sends data. It's up to the terminal program to do something with that data. There are some terminal programs that do, and others that don't interpret them well. Prior to Windows 10, the default Windows console didn't, so if you care about supporting ...
76394719
76394978
I have files URLs text like these examples: http://xxxxx.pdf http://xxxxxxxxxxx.doc http://xxxxxxxxxxxxx.xls The delimiter between each URL is not a space, it may be separated by vbTab , vbLf or what ever. But in all cases the URLs start with the same prefix "http:" and end with a dot+three characters. I need to extrac...
Extract predefined URL text (starts with the same prefix) into an Array
You asked (yesterday) about a way to extract URLs from a string, separated by no any separator... The next function will do it: Function SplitByStartOfString(strTxt As String, strDelim As String) As Variant Dim arr: arr = Split(strTxt, strDelim) arr(0) = "@#$%^": arr = filter(arr, "@#$%^", False) 'eliminate th...
76387096
76394984
I am confused about the difference in the fitting results of the Arima() function and glm() function. I want to fit an AR(1) model with an exogeneous variable. Here is the equation: $$ x_{t} = \alpha_{0} + \alpha_{1}x_{t-1} + \beta_{1}z_{t} + \epsilon_{t} $$ Now I estimate this model using the Arima() function and glm...
Why are the fitting results of the Arima() and glm() function different?
First, Arima() does not fit the model given in your equation. It fits a regression with ARIMA errors like this: x_{t} = \alpha_{0} + \beta_{1}z_{t} + \eta_{t} where \eta_t = \phi_{1}\eta_{t-1}+\varepsilon_{t}. We can rearrange this to give x_{t} = (1-\phi_{1})\alpha_{0} + \phi_{1}x_{t-1} + \beta_{1}z_{t} - \beta_{1}\...
76397650
76397766
I'm trying to figure out a better solution to fill a vector with another vector whill avoiding loops. Is it even possible? Maybe using address range or something else? This is my working code which does exactly what I need but slowly: #include <iostream> #include <vector> #include <string> typedef std::vector<std::vec...
Is there a better/faster way to fill one vector with contents of another (smaller) vector than using a for loop?
As with all performance questions, the solution is going to depend heavily on the hardware and software being used and the particulars of the test conditions. In this case, for example, the dataset size is relevant. With that caveat, I was able to improve the performance by over 4x on my platform (M1, MacOSX, clang). Y...
76394895
76395000
I have the following class with a function that returns a boolean value using alamofire. class Productos: Codable{ // MARK: Propiedades de los productos var id_producto : String = "" var producto_es : String = "" var id_seccion : String = "" init(id_producto : String = "", producto_es : Str...
Problems with Alamofire and Swift closures
This approach is wrong, you cannot put the model which is used in an array containing multiple instances and the controller to load the data in the same object. Well actually you can do it but then you have to create static APIs which is bad practice though. First of all declare the object representing a product as s...
76396627
76396665
I'm new to using the fragment shader. Why does my code raise a syntax error? I can't understand why it doesn't work. This is the piece of code that raises the error: if ((int) pos.y % 9 == 1) shade = 1; Both pos.y and shade are floats. I've put (int) before pos.y so that I could use modulo on it. The error message say...
Why am I getting a syntax error when using modulo on floats in my fragment shader?
GLSL is not C. As stated in the GLSL specification: There is no typecast operator; constructors are used instead. As such, (int) is not a thing in GLSL. If you want to convert some float to an int, you use constructor syntax: int(pos.y).
76397759
76397790
I have the following code: <div class="accordion mobile ui-accordion ui-widget ui-helper-reset" role="tablist"> <h3 class="accord-**19** **ui-state-active**"><span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-s">Title 1</h3> <div style="" class="ui-accordion-content ui-corner-bottom ui-helper-...
How to find a specific class that contains another class?
When you tried to retrieve the class name .find was not the correct way to do it. To find the attributes of an element you should use .attr, and then specify .attr("class") to find classes. Then from there use regex to find the correct accord-id. var classname = $("div.accordion h3.ui-state-active").attr("class"); var...
76396594
76396668
I am trying to access data from a parent to a child via a foreign key. WHAT WORKS - the views The data in the child is not "ready to be used" and need to be processed, to be represented in a progress bar in %. The data processing is handled in the views. When I print it on the console, it seems to work and stored into ...
Nested for loop - model.id in parent for loop does not match model.id in nested for loop (django)
You are overcomplicating things, which makes the template very complex (which often will only introduce extra bugs), and makes it even quite slow because of an N+1 problem in the view. def list_venues(request): venues = ( Venue.objects.filter(venue_active=True) .annotate( total_points=Su...
76394285
76395019
need help creating an example script of tool tip Scenario : when i held down / press down CTRL a tooltip will appear , the tooltip will only dissappear if the CTRL modifier is released when CTRL key is held down then ANY KEYS is triggered / combine ( ex. Ctrl + A B C so forth ) or any modifier keys like ( Ctrl + SHIFT...
Show Tool Tip When a certain Button is Held down & Removetool Tip when button is Released / Up
~LControl:: ToolTip, LControl,,, 1 SetTimer RemoveTooltip1, 50 return ~LControl Up:: SetTimer RemoveTooltip1, off ToolTip,,,, 1 return RemoveTooltip1: If (A_PriorKey != "LControl") ToolTip,,,, 1 return For all modifier keys: ; List of keys to bind keys := "LControl,RControl,LShift,RShift...
76397770
76397841
Say I have a macro: #define SUBST(MAGIC, ...) __VA_ARGS__ /* this won't work*/ And I want to call it like: SUBST(int, MAGIC a = 1); // expected output: int a = 1; Is there some set of wild indirections and expansions that I can use to force the expansion of MAGIC within the second argument with a value which depend...
Is it possible to replace a word used within an argument to a preprocessor macro?
Is it possible to replace a word used within an argument to a preprocessor macro? No, it is not possible to replace a word used within an argument to a preprocessor macro. SUBST(int, MAGIC a = 1); // expected output: int a = 1; That is not possible. Is there some set of wild indirections and expansions that I can...
76396589
76396678
Sorry as I know I must sound stupid here but how do I add/import a namespace to my project? Microsoft.Exchange.Data.Mime is what i need but I cannot find the way to add in visual studio? Thanks
Add namespace Microsoft.Exchange.Data.Mime to project?
You have to install the 'Microsoft.Exchange.Data.Common' nuget package first. Then try to import it into your file. I would suggest using MimeKit, which is a more sophisticated Mime tool for .NET.
76396616
76396679
I have some text which should wrap around a toolbox in the top right corner. The total height should be limited, therefore the text should be scroll-able. The corner box should stay in the corner, not scrolling with the text. How can I achieve this? I have a box and some text, but when adding overflow-y: scroll it will...
Wrapping text around a box in the corner but keep scroll possibility
You can add a div as a parent for the box and text and set the blue box position to sticky position: sticky; I hope This is what you want .box { width:100px; height:40px; float:right; clear: both; } #blue { background-color:blue; position: sticky; top: 0; } #text { } .container{ height:...
76394915
76395044
I'm trying to format date in this below format 20230201T103000Z i tried this method in angular moment(utctime).format('YYYYMMDDTHHmmsssZ') this is returning following date format 20230523T1900000+05:30
Convert to ISO time format in Angular using moment.js
'Z' is a token witch will show time zone. You can add your 'Z' as part of string https://momentjs.com/docs/#/displaying/format/ console.log(moment().format('YYYYMMDDTHHmmss') + 'Z'); The second option is Escaping characters using [] console.log(moment().format('YYYYMMDDTHHmmss[Z]'));
76397802
76397843
I have a little table where i like to get the latest content for each groupId. This is the Table with my data: This is my try to get it. SELECT *, MAX(highest_datetime.creattionDate) FROM highest_datetime GROUP BY highest_datetime.groupId; The MAX(highest_datetime.creattionDate) includes the latest content witch is ...
SQL MAX mixes up lines
You are probably running MySQL in its notorious cheat mode, i.e. you haven't SET sql_mode = 'ONLY_FULL_GROUP_BY', and the DBMS allows invalid aggregation queries. You have: SELECT *, MAX(highest_datetime.creationDate) FROM highest_datetime GROUP BY highest_datetime.groupId; So you want one result row per groupid, with...
76397864
76397894
My app in Swift Playgrounds has tabs. I want to add multiple lines of text to one tab, but I don’t know how. I can’t find an answer anywhere. Text("Developer").tabItem { Text("Settings").tag(5) VStack { Image(systemName: "gear") ...
How do I add multiple lines of text to tabs in Swift Playgrounds?
I think you need to specify the text you would like to add, and where you would like to add it. This can work to add more text within the main content area of the tab: TabView { VStack { Text("Line 1") Text("Line 2") Text("Line 3") } .tabItem { VStack { Image(syst...
76396628
76396680
I am figuring out a way to program a kinda of FunctionalInterface - Java's similar ones - in C++ (although it already provides these features). I am practicing with Predicate for the moment. Actually I have already done it: namespace _utils{ namespace _functional{ template <typename T> class Predi...
Cast lambda expression to class object whose constructor accept that lambda (Brief lambda)
The problem with foo( [] (int x) -> bool{return x == 2;} ); is that it tries to perform two implicit conversions (lambda to std::function and std::function to Predicate). C++ doesn't allow you to do that. Instead, you can state explicitly that you are initialising Predicate by adding braces: foo( { [] (int x) -> bool{r...
76394826
76395095
I have the following data (fiddle), id datec event 1 2022-09-19 12:16:38 EVENTA 2 2022-09-19 12:16:38 A 3 2022-09-19 12:21:08 B 4 2022-09-19 12:21:12 EVENTD 5 2022-09-19 12:25:18 C 6 2022-09-19 12:25:18 D 7 2022-09-19 12:25:28 E 8 2022-09-19 12:25:29 F 9 2022-09-19 12:25:38 EVENTA 10 2022-09-1...
Matching records between EventA and the first EventB before the next EventA, in a specific order
Here's one approach: compute running counts of armed events and disarmed events, ordering by date compute a ranking order of records for each armed event count, by ordering on the amount of disarmed events At this point you should note that this ranking value we generated, assumes value 0 when there's not yet an Even...
76394665
76395111
I need to generalize functions to pass an Executor trait for SQLX code. In the code below with a concrete &mut SqliteConnection parameter, main can call process, or it can call process_twice which calls process 2x times. All sqlx functions require arg type E: Executor. I need to make my code generic so that conn: &mut...
How to pass SQLX connection - a `&mut Trait` as a fn parameter in Rust
The trick is to not parametrize the whole E but just the type behind the reference: async fn process_twice<T>(conn: &mut T) -> anyhow::Result<()> where for<'e> &'e mut T: Executor<'e, Database = Sqlite>, { process(&mut *conn).await?; process(conn).await } That way you can still reborrow the reference. That...
76397789
76397903
I tried to research before asking here, but I coun't find any answers. Just for context, I'm using old version of bootstrap v2.0.2. I doubled checked if my paths are correct, and they are. This is the order of imported scripts that produce the errors above. If I load bootstrap.min.js first, I will get a different erro...
Issue with loading jquery after bootstrap
You cannot use jQuery versions starting with 1.9 with Bootstrap 2.0.2. jQuery 1.8.3 does work as shown below (note that jQuery must still be loaded before Bootstrap's JavaScript): <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js" integrity="sha512-J9QfbPuFlqGD2CYVCa6zn8/7PEgZnGpM5qtFOBZg...
76396498
76396696
I would like to clear everything in each sheet starting from the first empty cell in the 10th row (Microsoft Excel) but .End property skip the empty cell between filled ones. I tried such code: Sub clearRange() Dim ws As Worksheet Dim lastColumn As Long, i As Long For i = 2 To Worksheets.Count - 1...
Finding first empty cell in a row problem
The statement lastColumn = ws.Cells(10, ws.Columns.Count).End(xlToLeft).Column will take you to column J as the last column in your picture (lastColumn = 10), NOT to column D. To find the first empty cell, start in column A and use end-right, if A10:B10 are both non-empty. If either can be empty, you'll have to addres...
76396524
76396697
I am getting following error in Build Output when running a Kotlin module :- Execution failed for task ':Test:compileKotlin'. > 'compileJava' task (current target is 1.7) and 'compileKotlin' task (current target is 17) jvm target compatibility should be set to the same Java version. Consider using JVM toolchain: https:...
Execution failed while running a Kotlin module in Android Studio
try to make java version 17 not 1.7 like this: plugins { id 'java-library' id 'org.jetbrains.kotlin.jvm' } java { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 }
76391066
76397917
This is a follow-up question to a previous (solved) question about Altair with the same toy dataset. In the code below, we have a dataset that can be read as: "two cooks cook1, cook2 are doing a competition. They have to make four dishes, each time with two given ingredients ingredient1, ingredient2. A jury has scored ...
Altair: only show related field on hover, not all of them
I ended up modifying my DataFrame so that every row contains the dish name and the scores separately as well. That way I could target those items within the tooltip. import altair as alt import pandas as pd alt.renderers.enable("altair_viewer") df = pd.DataFrame({ "ingredient1": ["potato", "onion", "carrot", "beet...
76396585
76396706
PHP Post doesn't receive jQuery ajax post value I have created an ajax POST with jQuery to obtain the ID of a div and pass it to a PHP function. The function of php is in a folder phpFunction taht contains the file phpFunc.php in the same root of index.php. The post request is: $(document).ready(function() { ...
How to pass a div ID to a PHP function using jQuery AJAX?
you need to call the FetchIdNumber function in your PHP code. function FetchIdNumber(){ if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Verifica se il parametro "divId" è stato inviato tramite POST if (isset($_POST['divId'])) { $id = $_POST['divId']; echo "ID: " . $id; ...
76396634
76396739
I have an array arr in which I would like to zero the interval (over the last dim) around every max value. Here's what I'm generally trying to do (this code doesn't work): assume that interval_size is some positive odd integer. argmax = np.argmax(arr, axis=-1) half_interval = (interval_size - 1) // 2 # assume the int...
Numpy interval of indices around max value on the last dimension
Given that the intervals could be different sizes, I'd go for boolean indexing: import numpy as np arr = np.random.randint(10, size=(8, 8)) half_interval = 2 # Use keepdims=True for easy broadcasting argmax = arr.argmax(axis=-1, keepdims=True) # "Normal" indices for the last axis idx = np.arange(arr.shape[-1]) # Tr...
76395036
76395145
I have many NumPy arrays of dtype np.int16 that I need to convert to torch.Tensor within a torch.utils.data.Dataset. This np.int16 ideally gets converted to a torch.ShortTensor of size torch.int16 (docs). torch.from_numpy(array) will convert the data to torch.float64, which takes up 4X more memory than torch.int16 (64...
Converting np.int16 to torch.ShortTensor
Converting a numpy array to torch tensor: array = np.ones((1000, 1000), dtype=np.int16) print("NP Array size: {}".format(array.nbytes)) t = torch.as_tensor(array) # as_tensor avoids copying of array print("Torch tensor type: {}".format(t.dtype)) print("Torch tensor size: {}".format(t.storage().nbytes())) NP Array siz...
76397906
76397930
Both +page.js/ts and the <script><script/> tags within +page.svelte files are for processing client side code. What's the typical convention for choosing between these 2 files?
In sveltekit, what's the convention for splitting client side code between route files?
The question has been clearly answered in the Documentation. The separate file is for loading and constructing data that is required by your route, the script tag is for DOM manipulation and client side logic. That is the convention as per the docs but you are free to use both methods as per your preference but +page.s...
76396256
76396740
I am new to Perl Tk. I have option menu. In its callback, I want to pass a table object which is created later. As per the selection of the option, I want to render specific data into the table. Since my optionmenu is created before, how can I send the table object to it? In the code, I have commented it as 'HOW TO PA...
How to send a widget object created later to callback in Tk?
Since my optionmenu is created before, how can I send the table object to it? Just declare the $table variable before it is used in the callback. Even if the variable has not been defined when the callback is compiled, it will be defined when the callback is called at runtime. Example: use feature qw(say); use strict...
76394556
76395167
xml code <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" and...
Android need fullwidth drawerlayout. it should appear and disappear when hamburger icon is clicked
you can add negative margin for the sides of your drawer layout to fill the whole screen. android:layout_marginRight="-64dp"
76397897
76397934
bpython by default has a really nice blue theme, but it doesn't go well with light backgrounds. How can I disable its colour output and have it give just plain black (on Arch Linux)?
How do I disable bpython colored output?
You could create a theme that only uses black as an output color. That might look like: [syntax] keyword = k name = k comment = k string = k error = k number = K operator = K punctuation = k token = K paren = K [interface] background = d output = k main = k prompt = k prompt_more = k right_arrow_suggestion = K This i...
76396610
76396741
I'd like to removing everything that is is brackets () if (and only if) they are at the end and not do match the following pattern \(\d{4}\p{Pd}\d{4}\) *. This pattern is nothing more than date range in brackets, eg. (1920-2988). For instance, I'd like to match/capture (for removing, ie. string.replaceAll(my_regex_here...
Remove everything in brackets at the end
Use negative look ahead to avoid date ranges, then actually match it using [^()]+?: \s*\( # Match 0+ spaces, a '(', (?!\d{4}\p{Pd}\d{4}\)) # which is not followed by a date range and a ')', [^()]+ # 1+ non-parenthesis characters and \)\s*$ # ')' then 0+ spaces right befo...
76397679
76397939
I replaced my TrackBar with another TrackBar but when I look for the Scroll event of the new TrackBar I can't find it. Here is the cole of the old TrackBar: private void TrackBar_Scroll(object sender, ScrollEventArgs e) How can I create the Scroll event for the new TrackBar, as it doesn't exist in the event list?
TrackBar: no Scroll events in the list
Looking at the code of the HZH_Controls in their Github, it would appear you need to handle the ValueChanged event. /// <summary> /// Occurs when [value changed]. /// </summary> [Description("值改变事件"), Category("自定义")] public event EventHandler ValueChanged; Other parts of the code suggest that this event is raised Scr...
76394788
76395179
I have a table organization as below where temperature measurements are all stored in one column and there are 14 different temperature samples at different depths per timestamp. select * from water_temp order by unixtimestamp desc limit 28; id unixtimestamp depthname depth temperature 481042727209 1685770037 ...
Reorder data from multiplexed column values to rows
Is there some reason to organize data in a DB in the manner? I am tying to understand. Seems to me the more intuitive/useful way would be to have one column per temperature depth and one row per timestamp. You organize data in a way so that your queries are faster or to make data more consumable for your purposes. If...
76396158
76396782
I'm writing python code to use instagram graph api/business discovery to get data. But I get "Invalid OAuth access token" error but I could not figure out how to solve this problam, please enlighten me. Following code works fine on Graph Api Explorer IgUserId?fields=business_discovery.username(bluebottle){followers_cou...
"instagram api" business discovery api on python return 'Invalid OAuth access token - Cannot parse access token' error
I am not a Python guy, but just to help you I modified your Python script and while doing that, I saw many issues with your script. Use the below script which I tested with my IG User ID and access_token and is working perfectly fine. import requests import pandas as pd pd.set_option('display.max_rows', None) # inform...
76397787
76397970
i'm trying to rename dataframe columns through User Defined Function without success. In particular it seems that doesn't exist "rename" method when called inside a UDF. Following an example to better explain my problem: import pandas as pd` data = {'Age': [21, 19, 20, 18,80,90],'Stream': [88, 65,99, 765,65,55],'Perce...
Renaming dataframe columns via User Defined Function via Pandas
Instead of doing: df=df.apply(modname) You should do: df = modname(df)
76395115
76395187
In Eclipse I can just type /* and enter, and it would form a perfect comment block for complex comments above the code: /* * */ How to do the same or similar in Visual Studio?
How to create comment block in visual studio fast?
What language? I'm going to assume C++. Tools > Options > Text Editor > C/C++ > Advanced > Brace Completion > Complete Multiline Comments > True This setting will do exactly what you describe. Typing /* will auto-complete the */ and any new line entered after /* will auto-insert a new * at the beginning of the line. Al...
76396291
76396797
I am doing conditional inference tree analysis using the partykit package in R. I want to plot any tree that is extracted from the forest grown by cforest(). But I got an error message when I am trying with the plot function. The following is a chunk of codes that may produce the like error message with the iris data. ...
Error encountered when trying to plot individual trees from cforest() forest using the partykit package in R
I have got an answer after researching into it. Since plot works well with ctree() objects, I compared the extracted tree from cforest and the tree generated by ctree() and found the following difference in their data structure. For ctree object, which can be plotted: $ fitted:'data.frame': 150 obs. of 3 variables: ...
76397687
76397971
Please tell me how to sort in PostgreSQL (15+) such a table: id | name | next_id 1 | Test01 | 2 2 | Test02 | 3 3 | Test03 | 6 4 | Test04 | 5 5 | Test05 | null 6 | Test06 | 4 7 | Test07 | null It takes an SQL query to order by the next_id column - it's a pointer to the next row. The result I expect is: ...
SQL ORDER BY next
The following demonstrates an approach to sorting as requested: WITH RECURSIVE t(id, name, next_id) AS ( VALUES (1 , 'Test01', 2), (2 , 'Test02', 3), (3 , 'Test03', 6), (4 , 'Test04', 5), (5 , 'Test05', NULL), (6 , 'Test06', 4), (7 , 'Test07', ...
76394209
76395234
I want to create the following AWS security group in Terraform, using Hashi Corp Language. In this configuration the second ingress rule contains the range of ports, but such a syntax is not supported by Terraform. In current implementation Terraform treats port's range as the math expression and computes the differenc...
Creating AWS Security Group for a range of ports in Terraform
If you look at AWS docs https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules.html they support port range. The way to do it with terraform is: from_port = 4011 and to_port = 4999 See also the terraform docs: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group#f...
76396441
76396804
I'm writing a library in C to abstract multiple graphics APIs including Vulkan behind the same interface. Currently, the library allows for the creation of multiple 'renderer' objects, which contain a whole 'state' of a graphics API - as it stands, this translates to having one Vulkan instance per renderer, for example...
Best practice for allowing multiple Vulkan instances as part of 'renderer' objects
Function pointers obtained through a particular VkInstance object (through vkGetInstanceProcAddr) cannot be used with different instance objects. This is just as true of the Vulkan SDK as it is of Volk. That is, a function pointer obtained as the result of calling volkLoadInstance(some_instance) can only be used on oth...
76397780
76397994
I am experiencing an issue with the BackButton in a Compose WebView. The current code works well with the WebView backstack. However, when the backstack is empty and the back button is pressed, it causes the application to close, which is not the desired behavior. @Composable fun StatScreen(zeusPrefManager: ZeusPrefMan...
Compose WebView - avoid closing application when I press button back, but save ability go back in web view
you can make use of the onBackPressedDispatcher in your activity. Change your code as below- @Composable fun StatScreen(zeusPrefManager: ZeusPrefManager, onBackPressed: () -> Unit) { BackHandler(enabled = backEnabled) { if (webView!!.canGoBack()) { webView?.goBack() } else { ...
76395225
76395250
Hello to everyone guys! I've got a problem with the code below; my purpose is to retrieve all the .csv file in a google drive folder and put them all in sequence in a specific sheet in Google. The error code that it get is: "Exception: Cannot convert 'function () { [native code] }1' to int." Could you please help me so...
Happend multiple .csv file from Drive Folder to Unique Sheet in Google
Modification points: In your script, sheet.getLastRow of sheet.getRange(sheet.getLastRow +1, 1, csvData.length, csvData[0].length).setValues(csvData); should be sheet.getLastRow(). I thought that this might be the reason for your current issue of Exception: Cannot convert 'function () { [native code] }1' to int.. In ...
76397874
76398005
I am having some issues getting all the appointments from specific month. Problem is with appointments that has been scheduled with recurring setting. Is there some way to get all appointments present in outlook calendar recurring and not recurring? The best so far I was able to achieve is to check for is appointment.I...
Get all appointments for the month (including recurring appointments that are scheduled in previous months)
You are almost there - you need to set the Items.IncludeRecurrences property to true and call Items.Sort on the Start property to tell Items.Restrict to expand the recurrences. See https://learn.microsoft.com/en-us/office/vba/api/outlook.items.includerecurrences for more details and an example Outlook.Items calendarI...
76396574
76396831
I have two classes: first one is the main QMainWindow class, and the second one is my custom class. For example, I want to make a connection in the constructor of my custom class where when I press a TestButton (which is a part of the ui of main class), it calls a function from my custom class. Here are code: Program.h...
Qt QObject::connect receiver and slot of different classes
The line Custom custom = Custom(this); creates a local object which "dies immediately" after exit from Program constructor, that's not what you want to do. This is what you have to do for an instance of Custom to persist: Custom *custom = new Custom(this); You can even make pointer named custom a member variable if ...
76397857
76398007
My application in total has 5 routes, out of these 5 for four of them I need a condition to be true first to let user access those routes. So I wanted to create checks for said routes. I made PublicRoute and PrivateRoute Components import { Route } from 'react-router-dom'; const PublicRoute = ({ component: Component,...
React Router DOM: Custom Route component not working
The Routes component needs a literal Route component as the child. This worked for me - PublicRoute import { Route } from "react-router-dom"; const PublicRoute = ({ component: Component, ...rest }) => ( <Component {...rest} /> ); export default PublicRoute; App.js import { BrowserRouter, Routes, Route } from "rea...
76395133
76395272
I want increase font size of label that appears on hover in chart.js,I am trying to give custom text to label but am not able to increase it's font. var myPieChart = new Chart(ctxP, { type: 'pie', data: { labels: datas.labels, ...
To increase the font size of label that appears on hover in chart.js
To change the font size of tooltips in Chart.js 3.x, just use options.plugins.tooltip.titleFont.size or options.plugins.tooltip.bodyFont.size. let ctxP=document.getElementById('mychart').getContext('2d'); let datas={ value: [10, 15, 20, 25], labels: ['A', 'B', 'C', 'D'] }; var myPieChart=new Chart(ctxP, { ...
76396771
76396836
I have some code below to check if a checkbox is checked or not. Even if the checkbox is checked, it says that its not. Why does the code fail and how to fix it? function isChecked(locator : string) : boolean { let checked : boolean = false; cy.get(locator).then(el){ if(el.val() === "on"){ checked = true;//Is ac...
Cypress - How to check if a checkbox is checked or not?
function isChecked(locator) : Promise<boolean>{ return new Cypress.Promise((resolve) => { cy.get(locator).then((el) => { resolve(el.prop('checked')); }); }); } isChecked('#myCheckbox').then((checked) => { if (checked) { // Checkbox is checked } else { // Checkbox is not checked } });
76397886
76398014
There is a table that stores account data for everyday. I want to find out the difference in data between today and yesterday. The query for table creation and insert statements are below : CREATE TABLE daily_account_data (id varchar(6), Name varchar (20), DS_DW_Id varchar(4), flag_1 varchar(5), flag_2 varchar(5), Inse...
Query to find difference between today and yesterday's data along with a pseudo column
You can join the table and subtract the date. If the order of the record is correct (the previous day must be the previous record, you can use the window function(LEAD )) select a.id ,a.Name ,a.DS_DW_Id ,a.flag_1 ,a.flag_2 ,iif(a.Name=b.Name ,'',' Name Change') ...
76394491
76395303
I want to load data including an image from a Userform onto an excel worksheet. I want to specify the image width and to maintain the aspect ratio. The line .LockASpectRatio = MsoTrue shows as an error. Can anyone help with the syntax? 'Save image to Cell Dim FileNAme As Variant Dim Img As Picture If FileNA...
Why is my .LockAspectRatio=msoTrue showing as an error
I'm sure it should be .ShapeRange.LockAspectRatio = msoTrue Another observation, If FileNAme <> "" Then FileNAme = Me.TextBox_5 You are checking if Textbox is not empty before you set the text box variable. Therefore FileNAme would always empty.
76396783
76396846
I`ve just started to learn my first coding language, python. And I want to give to print() informations in my program, depending from user choice. I am very fresh so pls be forgiving. the code: answer = input("Do You like it?" + " Yes/No") if answer = (yes) print("That`s great!\nThank You" + name + ".") els...
How to use 'if' and 'else' function to distinguish answer 'yes' from 'no' in python3
you can try and modify this code. hope this helps def ifelse(): entername = input() #first user input print('Do you like it?') #first prompt answer = input() if answer == 'yes': print("That`s great!") print("Thank You name" ) else: # you can also use 'elif answer == 'no' ...
76395256
76395340
I want to count the amount of "items" in binary file using feof and fseek functions. I have a binary file with names of people in chars and their salaries in floats. before each name there is an int that represents the amount of chars in the name. for example my file could look like this (but without spaces and without...
I have a trouble in counting amount of "items" in binary file. C
feof doesn't check whether the file is at the EOF, it checks whether the eof-indicator of the file was set on a previous operation. fseek allows to seek to an arbitrary position (if the operating system and the file system supports this) to allow for example to write with holes inside of the file, which is useful if yo...
76396806
76396874
I have two draggable divs with position:absolute positioned inside of a position:relative div. My problem is that when I drag my divs to the edge of the position:relative parent they start to shrink. I need my draggable divs to stay the same size when they leave the parent's container, but I have no idea how to fix thi...
draggable position:absolute div shrinking after hitting edge of position:relative div?
That's totally fine since an absolute positioned element wraps its content according its relative/absolute parent. Just set the width manually: elmnt.style.width = elmnt.offsetWidth + 'px'; CODEPEN
76383000
76398016
I'm aware that this can be easily done using VBA, but I'd like a macroless solution if possible. I have 2 User rows in a Shape's ShapeSheet: User.Count and User.Loop. User.Count will simply store a number, and the While loop will be performed by User.Loop using the following basic conditional: User.Loop = IF(User.Count...
Creating a WHILE Loop in Visio ShapeSheet
because if the answer ever becomes 42 then that is the end of Life, The Universe and Everything! Paul you are right ! :) changing the loop limit to 40 and Sad, but this trick dont works… My experiment results. My example file My loop can't make it to the 1000 mark. It has to stop at 80. You can continue the loop ...
76394237
76395389
So I've been following this tutorial to make a portal shader and I understand by looking elsewhere that I'm apparently missing the expected number of arguments. Error locations indicated" fixed4 frag (v2f i) : SV_Target { fixed2 uvs = fixed2(i.uv.x, i.uv.y + (_Time.y * _Speed)); <ERROR 1> ...
incorrect number of arguments to numeric-type constructor
Could be happening because of trying to do calculations of mismatching types. Most likely it’s because you’re multiplying ‘_Time.y’ by ‘float4 _Speed’. float4 _Intensity; float4 _Speed; // vs // Incorrect arguments because // you’re implicitly calling: ‘fixed2(x, y + (a * (p, q, r, s));’ // error fixed2 uvs = fixe...
76397881
76398036
I am trying to follow the guidance in this blog about not using await when not needed. And first off, if using { ... } is involved, then yes - use await. Ok, so for the following code, why does DoItTask() not work? Is returning a Task and not using await only work if there are no uses of await in the method? privat...
Returning a Task vs using await
The following doesn't work, because you cannot use await without async. These keywords always go together when using the Task Parallel Library (TPL): private static Task<string> DoItTask() { //problem: method is not async - compiler error string one = await ReadOne(); string two = await ReadOne(); stri...
76395346
76395409
I'm facing on a trouble related to how I'm managing the edges and their weight and attributes in a MultiDiGraph. I've a list of edges like below: [ (0, 1, {'weight': {'weight': 0.8407885973127324, 'attributes': {'orig_id': 1, 'direction': 1, 'flip': 0, 'lane-length': 3181.294317920477, 'lane-width': 3.6, 'lane-shoulder...
Manage edge's weight and attributes with Netoworkx
Using add_weighted_edges_from does not have an option to add independent edge attributes. It takes a list of triples (u,v,w) and consider w as the weight. That's why, you find a nested dictionary in the weight attribute of the node. You can add shared attribute for the bunch by specifying keyword argument: graph.add_we...
76396049
76396875
I have PySpark dataframe dhl_price of the following form: +------+-----+-----+-----+------+ |Weight| A| B| C| D| +------+-----+-----+-----+------+ | 1|16.78|17.05|20.23| 40.1| | 2|16.78|17.05|20.23| 58.07| | 3|18.43|18.86| 25.0| 66.03| | 4|20.08|20.67|29.77| 73.99| So you can get the deli...
PySpark: Create a new column in dataframe based on another dataframe's cell values
Setup dhl_price.show() +------+-----+-----+-----+-----+ |Weight| A| B| C| D| +------+-----+-----+-----+-----+ | 1|16.78|17.05|20.23| 40.1| | 2|16.78|17.05|20.23|58.07| | 3|18.43|18.86| 25.0|66.03| | 4|20.08|20.67|29.77|73.99| | 30|20.08|20.67|29.77|73.99| | 40|21.08|21.67|30.77|74.99| ...
76397895
76398039
Hi im learning Sping Boot and when I compile the maven project im getting the next error: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.3.0:resources (default-resources) on project backweb-api: filtering D:\***\***\backweb\backweb-api\src\main\resources\application-test.properties to ...
Error while compiling Spring boot maven poject
Your application-test.properties contains non-UTF8 characters (e.g. the accent on the configuration o). This causes this error
76396209
76396902
I have a button and a table on my webpage. I want to view the table when I click that button. I have tried it using javascript but the table only appears for a split second and then disappears. following is the code for my table: var button = document.getElementById('BtnNextInsured'); // Assumes element with id='butt...
Table only appears for a split second on button click
as comments saying better using eventlistener. with the eventlistene, you can use the event and like here stop it to avoid double click. to appear disappear use a class 'hide' so you can toggle it, easier than than checking display none. const tableAppear = () => { document.querySelector('#BtnNextInsured').addEvent...
76395403
76395424
Take a look at this simple C# program: using System; namespace testProgram { internal class Program { static void Main(string[] args) { List<string> list = new List<string>(); list.Add("List element."); Console.WriteLine(list[0]); } } } Output: L...
Why am I able to use C# lists without writing "using System.Collections.Generic;" at the beginning of my file?
Look at your project file. I strongly suspect it will include this: <ImplicitUsings>enable</ImplicitUsings> The ImplicitUsings feature is described here: The ImplicitUsings property can be used to enable and disable implicit global using directives in C# projects that target .NET 6 or a later version and C# 10 or a l...
76396701
76396926
I want to use the Python library rapidjson in my Airflow DAG. My code repo is hosted on Git. Whenever I merge something into the master or test branch, the changes are automatically configured to reflect on the Airflow UI. My Airflow is hosted as a VM on AWS EC2. Under the EC2 instances, I see three different instances...
import python libraries (eg: rapidjson) in airflow
Have you tried using the PythonVirtualEnvOperator ? It will allow you to install the library at runtime so you don't need to make changes on the server just for one job. To run a function called my_callable, simply use the following: from airflow.operators.python import PythonVirtualenvOperator my_task = PythonVirtua...
76397951
76398063
I am working on creating a class to support a console app I am developing, and I would like to create a method within to change both the background and foreground color. Is there a way to set a ConsoleColor value (which I believe is an enum) to another variable so this can easily be changed by the user at runtime? Fo...
Is there a way to set a ConsoleColor value equal to a variable?
You don't seem to ever write to the console in your program, which you obviously need to do. Other then that you also need a way to change the colors during runtime using e.g. setters or a function like ChangeColors(). Here a working sample program for reference: namespace MyProgram; class Program { static void Ma...
76396427
76396935
I have created a script that spawns bullets/projectiles that moves forward with a certain force. However, the bullet itself does not disappear on collision. Since it is a instantiated object, how do I make it disappear? I've tried OnCollisionEnter() but to no avail. The code below is how i created the bullet. // Instan...
How to destroy an initiated GameObject on collision?
You can choose two paths to achieve this 1) Adding the script to the prefab (done in the editor) You can edit the prefab (opening it from the editor) and add the script to it. 2) Adding the script to the instance (done programmatically) In this case your first instantiate the prefab and then programmatically add the sc...
76395282
76395427
john smith 21 VETERAN 1 I have a .txt file writing this . I want to read this .txt file and take john smith as a variable . but I can't read with whitespaces. edit: I want to take john smith and print it in the console with printf("%s",name); I tried code below but didnt work. only takes smith. while (fscanf(file,...
reading input from .txt file in C
The task is not easy for beginners learning C. There can be different approaches. I can suggest the following approach. At first a full record is read from the file using standard C function fgets as for example char record[100]; fgets( record, sizeof( record ), fp ); Now let's assume that the record is already read....
76398040
76398085
I have this piece of code: [Test] public void LinqConsoleOutputTest() { Enumerable.Range(0, 10).ToList().ForEach(_ => { Thread.Sleep(500); Console.WriteLine($"Slept..."); }); } And to my surprise the code was executing around 5 seconds as expected, but it did not print to the console. It just d...
ForEach method skips Console.WriteLine() on each iteration, then dumps all the logs when loop is done. Why?
Console.WriteLine() writes to whatever is the Standard Output which might not be a console in case of a test. Run the same code in a simple "normal" C# program and it will print as expected. Consider this program: namespace MyProgram; class Program { static void Main(string[] args) { using var fileStre...
76396924
76396974
I have written this code in python. In the end I would like to use this to get the indices to cut up a 100x100 matrix into squares that overlap by 10. However, at the bottom there is a nested loop and the y values print how I think they should but not the x-values, the x-values never change... Can anyone help? Thanks x...
Nested for loop not looping on the first set, Python
zip(y_start, y_end) returns an iterator. After the first series of Xs, y_inds is exhausted and yields no more values for the subsequent values of X. Make it y_inds a list, so it can be reused on subsequence X rows: *y_inds, = zip(y_start, y_end) You could also let numpy do the iterating for you to produce a matrix of...
76387478
76395430
Building an iOS app, _inAppPurchase.queryProductDetails(productIds); returns product details in a simulator (ipad, iphone) and everything works. But if I run on a physical iPhone productDetailResponse.productDetails.isEmpty is true and my product ids are in notFoundIDs. Same if I 'flutter build ipa' and try in TestFlig...
Flutter - in_app_purchase plugin - iOS - works in sim but not on device
Getting all "Agreements, Tax and Banking" bits sorted and "Active" in App Store Connect has fixed it. Things started working the same on the device, simulator and TestFlight as soon as the forms got reviewed and approved.
76398059
76398086
I am very new to Rust. The following function: async fn create(body: String) -> impl IntoResponse { let j = match serde_json::from_str::<CreationJSON>(&body) { Ok(j) => j, Err (_) => ( StatusCode::UNPROCESSABLE_ENTITY, "body is invalid".to_string(), ), }; prin...
Not explicitly saying `return` gives error: `match` arms have incompatible types
return returns from the function. If you don't use the return keyword, then it'll "return" from the statement. In your first example, you're trying to assign the tuple to the variable j, while in the second you return from the function.
76397592
76398115
I tried to webscrape the data from the below url to get the data from the "Growth Estimates" table using beautiful soup & requests but it can't seem to pick the table up. However when using the inspection tool I can see there is a table there to pull data from and I couldn't see anything about it being pulled dynamical...
Why is the 'Growth Estimates' table not being detected by beautifulsoup on this website?
To get correct response from the server set User-Agent HTTP header in your request: import pandas as pd import requests from bs4 import BeautifulSoup url = 'https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL' headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/113.0'} s...
76396938
76397014
import pandas as pd import json mass=[] fall=[] year=[] req = requests.get("https://data.nasa.gov/resource/y77d-th95.json") response =req.json() for i in range(0,len(response)): mass.append(response[i]['mass']) fall.append(response[i]['fall']) year.append(response[i]['year']) I handle keyEr...
OptInt type function in Python
You can use dict.get to provide a default value as the second argument. For example: from math import nan for obj in response: mass.append(obj.get('mass', nan)) fall.append(obj.get('fall', nan)) year.append(obj.get('year', nan))
76396255
76397019
I am using get_blob using the python API. All kinds of information about the blob is available, but owner is set to None. My application needs to know who last updated the file in GCS. Any help would be appreciated! I tried calling reload with projection set to full, as suggested elsewhere, but it didn’t help. I tried...
Owner information not available from Google Cloud Storage blob
In Google Cloud Storage, buckets are owned by the project. Users (IAM principals) are not owners of a bucket. Permissions are granted to users to access a bucket and its objects. The logs record who created a bucket. For updates, review Audit Logging. Google records changes to a resource's metadata. Usage logs & storag...
76395432
76395438
Just implemented RecyclerView in my code, replacing ListView. Everything works fine. The data is displayed. But error messages are being logged: RecyclerView: No adapter attached; skipping layout I have read other questions related to the same problem but none of them help.
Fix error RecyclerView: No adapter attached; skipping layout
i have this problem , a few time problem is recycleView put in ScrollView object After checking implementation, the reason appears to be the following. If RecyclerView gets put into a ScrollView, then during measure step its height is unspecified (because ScrollView allows any height) and, as a result, gets equal to mi...
76395305
76395440
get_rect() is not running I was trying to make a simple game for educational purposes using the pygame module. I encountered this error. I would be glad if you can help import pygame import random import sys import os pygame.init() balikci_konum = "E:/E/Python/Python-eski/Oyuncalismalari/balik_avlama_oyunu/textures...
Pygame get_rect() is not running
To move the objects you have to change the position with += instead of setting the position with an assignment (=): self.rect.x = self.hiz*self.yonx self.rect.y = self.hiz*self.yony self.rect.x += self.hiz*self.yonx self.rect.y += self.hiz*self.yony
76398116
76398122
I am trying to create a little javascript two way form binder using proxies. I am stuck on how I can intercept 'new' calls. I use a 'construct' trap but it doesn't fire. Here is my code, I have removed the stuff that is not relivant for my specific problem class BoundObject { constructor(object, element) {...
Javascript construct trap not working in class returning proxy
The construct trap is only called when the [[Construct]] internal method is invoked on the proxy itself. This could be caused by using the new operator. However, in this case, the Proxy is returned as a result of calling new on the BoundObject constructor; new was not called on the proxy itself. Here is an example of w...
76396518
76397042
I have the following lftp script to copy files from a remote to local: env TERM=dumb script -a $LOGSTDOUT -c "$(cat <<- EOF lftp $PROTOCOL://$URL -u ${USER},${PASS} << EOFF set dns:fatal-timeout never set sftp:auto-confirm yes set mirror:use-pget-n 50 set mirror:parallel-transfer-count 2 set mir...
How can I fix line breaks output by script(1) utility?
Try replacing ... script -a $LOGSTDOUT ... with ... script -a >(tr -d '\r' >"$LOGSTDOUT") ... See the Process Substitution section on the Bash Reference Manual for an explanation of >(...). Note that ALL_UPPERCASE variable names (like LOGSTDOUT) are best avoided because there is a danger of clashes with the large nu...
76397068
76397087
Issues connecting PySpark & Postgres I've scoured the Apache docs, Stackoverflow and watched youtube tutorials but can't seem to find an issue to my exact issue. I have clearly pointed to the postgres executable jar file but it doesn't I can't seem to be able to read from the db. Below is an extract from my script. The...
PySpark and Postgres: JDBC connection error
Seems like your URL is missing a : character. You've written jdbc:postgresql//localhost... instead of jdbc:postgresql://localhost...
76397037
76397104
My application - the basics I have a simple django application which allows for storing information about certain items and I'm trying to implement a search view/functionality. I'm using django-taggit to tag the items by their functionality/features. What I want to implement I want to implement a full text search which...
django full text search taggit
Your problem is that you're adding the tags field directly to your SearchVector Lets concatenate the tags with Django's StringAgg into a single string and then use that string in your SearchVector first we import StringAgg from django.contrib.postgres.aggregates import StringAgg then this is how you have to change you...
76398027
76398125
How do you exactly define a directive in programming? #include is a directive, and using namespace std is a directive as well, assuming that I am correct. What actually makes a sentence or word a directive? I tried reading from different sources, but all lead to no avail. I am new to programming and I hope to grasp a...
What constitutes a directive in C++, and how can I use them effectively?
You mentioned two different programming constructs in your question: 1) the #include pre-processing directive and 2) the using namespace directive. Each of these constructs is literally referred to as a "directive" in the documentation, but they are completely different things. I can see how that could cause confusion....
76395200
76395444
I am currently working on a big data set where the data is stored into list with dictionaries (format shown below) List = [{ID001: Report-1, ID002: Report-1, ID003: Report-1}, {ID001: Report-2, ID005: Report-5}…..] I am trying to group and print a list with one dictionary that contains all ID’s from all dictionaries i...
Grouping dictionary data from a list and storing in another dictionary
This way it can be done. data = [{ID001: Report-1, ID002: Report-1, ID003: Report-1}, {ID001: Report-2, ID005: Report-5}…..] d = pd.DataFrame.from_records(data) res = d.to_dict("list") print(res)
76397033
76397135
I'm not great with RegEx. I need to retrieve the issue number from the long title of a comic book that includes its name and sometimes the artist's name. Usually the issue number is the last number in the string, but not always. Here are 6 examples that capture the range of variations I'm looking at: STAR WARS: DOCT...
Retrieve issue number from string for comic
I don't know VBA, but by trying to comprehend the code I think your regex can be simplified to this: \s # Match a whitespace, #? # an optional '#', then \d\d? # 1 or 2 digits, followed by \b # a word boundary (prevents numbers with 3+ digits from being matched). Try it on regex101.com. Alternatively, ...
76395338
76395466
I have a standard HTML input form. The issue occurs when I enter something like \n in the input. I'm aware it's a regex that means newline, but a user may for example have it in their password, and it should remain unchanged. The behaviour I'm observing: const value = $('#myInput').val() console.log(value) // Console...
Why does Javascript add an extra backslash when I capture input values?
Re the code comments in the code you shared: const value = $('#myInput').val() console.log(value) // Console shows: hello\n (which is indeed what the user typed in) const outputData = { password: value } console.log(outputData) // Console shows: { password: "hello\\n"} <script src="https://cdnjs.cloudflare.com/aj...
76396891
76397169
If using FlowDirection="RightToLeft" will change the whole datagrid right to left and solves the problem. But my grid has both LTR and RTL contents. Some columns are LTR and some other column are RTL. So please help me on this that how can I only set one column as RTL? Thanks.
How to make RTL to support right to left languages only in a column in XAML WPF VB.NET
At last I found the answer. Here it is: <DataGridTextColumn ...> <DataGridTextColumn.ElementStyle> <Style TargetType="TextBlock"> <Setter Property="FlowDirection" Value="LeftToRight" /> </Style> </DataGridTextColumn.ElementStyle> <DataGridTextColumn.Edi...
76397866
76398139
I Want to change the second comboBox items based on the user select of item in another comboBox. I do have courseCB comboBox that the user have to select first and then selct from mealCB comboBox; mealCB items should change based of courseCB select item. @FXML private ComboBox<String> courseCB; @FXML pr...
make two combo box related in javaFx
This is related to these answers so also study them: Javafx Cascading dropdown based on selection combobox dependent on another combobox - JavaFX You are using a similar approach to the first referenced answer, but have a logic error in your switch statement. You don't break after every condition, instead you break o...