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 = builder.Build(); app.MapWebPubSubHub<WebPubSubHub>("/eventhandler"); app.Run(); The Azure Web PubSub has the following configuration of Webhook URL: I need to protect this endpoint somehow /eventhandler because it's public and anyone can call it. One of the options that Azure suggests is using a simple authentication code. Help me to understand where I should verify that code in my ASP.NET app? Let's say I configured the URL template in WPS like https://a9e5-92-253-212-316.ngrok-free.app/eventhandler?code=RRRRR then in the server code app.MapWebPubSubHub<WebPubSubHub>("/eventhandler?code=RRRRR") result is exception Microsoft.AspNetCore.Routing.Patterns.RoutePatternException: 'The literal section 'eventhandler?code=RRRRR' is invalid. Literal sections cannot contain the '?' character.'
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 configuration) { _apiKey = configuration.GetValue<string>("ApiKey"); } public async ValueTask<object> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) { if (!context.HttpContext.Request.Query.TryGetValue("code", out var extractedApiKey)) { return Results.Unauthorized(); } if (!_apiKey.Equals(extractedApiKey)) { return Results.Unauthorized(); } return await next(context); } } another option is to use app.MapWebPubSubHub<WebPubSubHub>`("/eventhandler").RequireAuthorization(builder => builder.AddRequirements(new ApiKeyRequirement)) where ApiKeyRequirement is your implementation of IAuthorizationRequirement
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?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val textView = findViewById<TextView>(R.id.textView) val seek = findViewById<SeekBar>(R.id.seekBar) seek.min = 100 seek.max = 1000 seek.progress = 500 counter = seek.progress.toLong() seek.setOnSeekBarChangeListener( object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged( seekBar: SeekBar?, progress: Int, fromUser: Boolean ) { counter = progress.toLong() textView.text = (counter/1000).toString() The line: textView.text = (counter/1000).toString() make it that if the bar is on the right side it will display 1 but then to the left it will display only 0. and I want that on the right end it will display 1 but then when moving it to the left it will display 0.9 then 0.8 then 0.7.....0.1 I tried: textView.text = (counter/1000).toString()
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. When I run ocaml sqltest.ml I would expect this to execute. Instead I get a Error: Unbound module Sqlite3 Even when I make it ocaml -I +sqlite3 sqltest.ml I get the same result. It's kind of hard to search for info on ocaml and most of the stuff I find is using dune or ocamlbuild or ocamlfind or something... I think that's fine, but in the interest of starting with the basics and building from there I would like to understand how all of the pieces are working. I'd imagine the basic ocaml or ocamlc should work in this simple case. How do I make it understand where these libs are and use them? Why does it not understand it's own "default libs"?
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 -linkpkg $ ./a.out hello Alternative use of ocamlfind: $ ocamlc -I `ocamlfind query sqlite3` sqlite3.cma test.ml $ ./a.out hello As a side note, your code will not compile even with proper use of the compiler and ocamlfind because Sqlite3.db_close returns a boolean, you're trying to bind that expression to (). This is a type mismatch. And you've opened Sqlite3 so you don't need to use the fully qualified names. You might want to use let& to avoid the db_close. open Sqlite3 let () = let& db = db_open "test.db" in print_endline "hello"
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 axes x to: Jan, Fev, March ..... The set of data is: Cidade Mes Leitura <chr> <chr> <dbl> 1 Petrolina Janeiro 74.2 2 Petrolina Fevereiro 73.2 3 Petrolina Março 68.7 4 Petrolina Abril 42.9 5 Petrolina Maio 9.84 6 Petrolina Junho 8.02
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 looks like this: command1 | foo command2 | foo command3 | foo command4 | foo This is apparently working as expected, but I'm concerned about the efficiency implications of doing this. 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?
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 should change your implementation for a steppable pipeline: function steppablefoo { param([Parameter(ValueFromPipeline)] $InputObject) begin { $pipe = { Select-String -NotMatch -Pattern '^[\t ]+\d' }.GetSteppablePipeline() $pipe.Begin($PSCmdlet) } process { $pipe.Process($InputObject) } end { $pipe.End() } } You can test it for yourself with this performance comparison: $tests = @{ Filter = { 0..300kb | foo } SteppablePipeline = { 0..300kb | steppablefoo } } $tests.GetEnumerator() | ForEach-Object { [pscustomobject]@{ Test = $_.Key TotalMilliseconds = (Measure-Command { & $_.Value }).TotalMilliseconds } }
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 as parameters. When the button then gets pressed, I want it to be able to call a member function from the object that was passed to it. It should also be noted that I got it working for a while, but then I changed something and now it doesn't work. In my main.cpp, I create a gui and a pointer to this gui. I then pass the pointer into my Utility class, which consists of static variables and functions: //Create gui object tgui::GuiSFML gui{ window }; //Create pointer to gui object tgui::GuiSFML* guiPointer = &gui; //Pass guiPointer into Utility class Utility::setup_getGuiPointer(guiPointer); This is what is in my Utility class: //Static gui pointer in Utility static tgui::GuiSFML* guiPointer; //Passes gui pointer from main into Utility static void Utility::setup_getGuiPointer(tgui::GuiSFML* passedGuiPointer) { guiPointer = passedGuiPointer; } The create button function in my utility class looks like this, //Takes arguments: ObjectPtr, FunctionPtr, Size, Pos and Text to create button template<typename Class> inline tgui::Button::Ptr& Utility::u_createButton(Class* object, void(Class::* functionPointer)(tgui::GuiSFML* guiPointer, tgui::Button::Ptr& button), tgui::Layout2d size, tgui::Layout2d position, std::string buttonText) { //Creates the button tgui::Button::Ptr button = tgui::Button::create(buttonText); //Sets size and position button->setSize(size); button->setPosition(position); //Adds button to gui guiPointer->add(button); //Sets onPress on the button to call the passed function from the passed objects, //passing the gui pointer and button pointer into this function. button->onPress([&]() { (object->*functionPointer)(guiPointer, button); }); //Returns button pointer if it's needed before onPress. return button; } Now, I can then create a custom button from inside any class using the following line: Utility::u_createButton(this, &ClassName::FunctionName, size, position, text; And I create a button inside one of my classes, and the function that I pass a pointer to is just: void ClassName::FunctionName(tgui::GuiSFML* guiPointer, tgui::Button::Ptr& button) { std::cout << "Button Pressed" << std::endl; //The reson behind the passed arguments is so that the function itself can delete //the button after use if needed using the following line: //guiPointer->remove(button); } When I run this, it creates a button but gives the following error when I press it: Unhandled exception at 0x85EEB600 in GUI_SFML_Template.exe: 0xC0000005: Access violation executing location 0x00000000. The current stack frame was not found in a loaded module. Source cannot be shown for this location. I don't understand why I get this error, though I believe it has something to do with my objects and functions trying to write onto the gui without the proper access to it. I would be very grateful if anybody could help me.
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->*functionPointer)(guiPointer, button); }); Generally lambdas capturing all by reference are only safe to use within the function they're declared in and shouldn't be stored for long term use.
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 spaces in between good and example ? Here is the code I'm using: public class reverseString { public static void main(String[] args) { String s = "a good example"; String ans = revString(s); System.out.println(ans); } static String revString(String s) { String[] arr = s.split(" "); List<String> list = new ArrayList<String>(); StringBuilder ans = new StringBuilder(); for (int i = arr.length - 1; i >= 0; i--) { if (arr[i] == null) { continue; } else { ans.append(arr[i].trim()); // ans.append(" "); } } String is = ans.toString(); return is.trim(); } } The expected output was: example good a The output I'm getting is: example good a Comparing the string at the I-th index with " " should result in continuation of the loop. Instead it jumps to the else condition.
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 = "a good example"; String ans = revString(s); System.out.println(ans); } static String revString(String s) { String[] arr = s.split(" +"); // CHANGE HERE - added '+' List<String> list = new ArrayList<String>(); StringBuilder ans = new StringBuilder(); for (int i = arr.length - 1; i >= 0; i--) { if (arr[i] == null) { continue; } else { ans.append(arr[i].trim()); ans.append(" "); } } String is = ans.toString(); return is.trim(); } } Running the above code produces the following output: example good a
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: FilterService){ } ngOnInit(): void { this.filterService.register(this.dateIsFilter, (value: any, filter: any) => { // code here return this.filterService.filters.dateIs(value, filter) }); } Then I changed p-columnFilter to use custom matchModeOptions. <p-columnFilter type="date" [matchModeOptions]="this.matchModeOptions"> ... </p-columnFilter>
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 { // Validate $validateUser = Validator::make($request->all(), [ 'avatar' => 'required', 'type' => 'required', 'open_id' => 'required', 'name' => 'required', 'email' => 'required|email|unique:users,email', ]); if ($validateUser->fails()) { return response()->json([ 'status' => false, 'message' => 'validation error', 'errors' => $validateUser->errors() ], 401); } // validated, will have all user field values // we can save in the database $validated = $validateUser->validated(); $map = []; // email, phone, facebook, apple $map['type'] = $validated['type']; $map['open_id'] = $validated['open_id']; // if there is user in our database $user = User::where($map)->first(); $user = User::where($map)->first(); // whether user have already logged in or not // empty means does not exist // this token is user id if (empty($user->id)) { // this certain user has never been in our website // our job is to assign the user to database // this token is user id $validated["token"] = md5(uniqid().rand(10000,99999)); // user first time created $validated['created_at'] = Carbon::now(); // returns the id of row after saving $userID = User::insertGetId($validated); // we return the userid // users all info will be here $userInfo = User::where("id", "=", $userID)->first(); $accessToken = $userInfo->createToken(uniqid())->plainTextToken; $userInfo->access_token = $accessToken; return response()->json([ 'status' => true, 'message' => 'User Created Successfully', 'data' => $userInfo ], 200); } $accessToken = $userInfo->createToken(uniqid())->plainTextToken; $userInfo->access_token = $accessToken; return response()->json([ 'status' => true, 'message' => 'User Logged In Successfully', 'token' => $userInfo ], 200); } catch (\Throwable $th) { return response()->json([ 'status' => false, 'message' => $th->getMessage() ], 500); } }
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 = Validator::make($request->all(), [ 'avatar' => 'required', 'type' => 'required', 'open_id' => 'required', 'name' => 'required', 'email' => 'required|email|unique:users,email', ]); if ($validateUser->fails()) { return response()->json([ 'status' => false, 'message' => 'validation error', 'errors' => $validateUser->errors() ], 401); } // Validated, will have all user field values // We can save in the database $validated = $validateUser->validated(); $map = []; $map['type'] = $validated['type']; $map['open_id'] = $validated['open_id']; $user = User::where($map)->first(); // Whether user has already logged in or not // Empty means does not exist // This token is user id if (empty($user->id)) { // This certain user has never been on our website // Our job is to assign the user to the database // This token is user id $validated["token"] = md5(uniqid() . rand(10000, 99999)); // User first time created $validated['created_at'] = Carbon::now(); // Returns the id of row after saving $userID = User::insertGetId($validated); // Users all info will be here $userInfo = User::where("id", "=", $userID)->first(); $accessToken = $userInfo->createToken(uniqid())->plainTextToken; $userInfo->access_token = $accessToken; return response()->json([ 'status' => true, 'message' => 'User Created Successfully', 'data' => $userInfo ], 200); } $accessToken = $user->createToken(uniqid())->plainTextToken; $user->access_token = $accessToken; return response()->json([ 'status' => true, 'message' => 'User Logged In Successfully', 'token' => $user ], 200); } catch (\Throwable $th) { return response()->json([ 'status' => false, 'message' => $th->getMessage() ], 500); } }
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 array: [ array_keys($array), array_values($array) ]; Is there a more elegant way to do this?
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 necessary such as... Code: (Demo) $result = []; foreach ($array as $k => $v) { $result[0][] = $k; $result[1][] = $v; } var_export($result); If you always want a two-element result, a body-less loop can avoid making any function calls in a concise way. (Demo) $result = [[], []]; foreach ($array as $result[0][] => $result[1][]); var_export($result); Functional programming with array_reduce() can become ugly/verbose for this task. (Demo) var_export( array_reduce( array_keys($array), function ($result, $k) use ($array) { $result[0][] = $k; $result[1][] = $array[$k]; return $result; }, [] ) ); And if you are considering array_walk(), that is just going to work like a foreach() anyhow because it doesn't deliver its result payload as a returned value. If you consider functional programming to be elegant, bear in mind that double-transposing with array-map() calls will not work when there is one element or less in your input array. Proof
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 element's boundary. Is there an attribute I am missing, or is this just the way inheritance in HTML works? Picture Example: In this image, my mouse cursor is inside the child div, but outside of the parent div. body { display: flex; align-items: center; justify-content: center; } .container { background-color: black; width: 800px; aspect-ratio: 1 / 1; } .container:hover { background-color: darkorange; } .child { position: absolute; background-color: red; width: 100px; height: 100px; transform: translate(-50px, 0px); } <div class="container"> <div class="child"></div> </div>
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. :has() allows you to target an element that meets the conditions passed to it. You can do it like this - .container:not(:has(.child:hover)):hover { background-color: darkorange; } This will prevent the hover effect on container when hovered over its child element, which is specified in the :has() method. Here is the JSFiddle example demonstrating this method. Read more about :has() in here
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>. Here's an example: init() : Observable<void> { return this.http.get(this.apiUrl) .pipe( // do something with the response switchMap(() => EMPTY) ); } The ``switchMapstatement ensures that the return type isObservable```. I've tried this: const init$ : Observable<void> = forkJoin(obsArray); But at best it executes the function but not the HTTP call inside. There is no subscribe() call since this is inside an Angular factory function assigned to the APP_INITIALIZER token. I've also tried concatMap() with no luck. Is there an rxjs function that will execute each of these consecutively, while waiting for the previous to complete? I have followed this up with this question.
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 résistants à l'usure Formation Gants de moto d'équitation', 'pro_current_price':'27.99', 'pro_raw_price':'27.99', 'pro_discount':'36', 'pro_likes_count':'11'} This is what my text in the .txt file looks like. I'm looping through and creating dicts from them. I do that by extracting the content from within the single quotes and appending the "key" and "value" pairs to a dict. I've first extracted the content from within the curly brackets, then split that at ", " to get the "items" in a list, after which I looped through the list and used the regex in the command key, value = re.findall(r"\'([^']+)\'", element) to extract the "key" and "value". I'm a regex as well as a programming novice, so I could use some expert help. I did ask ChatGPT for a regex '([^']+(?:\\'[^']+)*?)':'([^']+(?:\\'[^']+)*?)' but that fails too. I want to get a list that holds ['pro_name', 'Gants tactiques Escalade en plein air Gants antidérapants résistants à l'usure Formation Gants de moto d'équitation'] from re.findall but instead I get ['Gants tactiques Escalade en plein air Gants antidérapants résistants à l', 'équitation'].
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 single quotes, and the key value pairs are separated by commas followed by a space, and the keys are separated from values by single colons, it is easy to identify key value pairs by first split the string by "', '", then split each substring by "':'". You can then convert it to dict, with cleanup if necessary. Example: import re text = "{'pro_id':'1692423', 'pro_model':'SKUF42051', 'pro_category':'accessories', 'pro_name':'Gants tactiques Escalade en plein air Gants antidérapants résistants à l'usure Formation Gants de moto d'équitation', 'pro_current_price':'27.99', 'pro_raw_price':'27.99', 'pro_discount':'36', 'pro_likes_count':'11'}" arr = [i.split("':'") for i in text.split("', '")] def clean(s): return re.sub("^[{']+|[}']+$", '', s) {clean(a): clean(b) for a, b in arr} The result is: {'pro_id': '1692423', 'pro_model': 'SKUF42051', 'pro_category': 'accessories', 'pro_name': "Gants tactiques Escalade en plein air Gants antidérapants résistants à l'usure Formation Gants de moto d'équitation", 'pro_current_price': '27.99', 'pro_raw_price': '27.99', 'pro_discount': '36', 'pro_likes_count': '11'} Wrap it in a function: def dictify(text): arr = [i.split("':'") for i in text.split("', '")] return {clean(a): clean(b) for a, b in arr} I assume you have many more strings like the above in your text file, since I don't know the exact format, I can only demonstrate how to convert the file to a list of dicts as if it is newline separated. with open('/path/to/file', 'r') as f: text = f.read() [dictify(row) for row in text.split('\n')] You need to change the file path placeholder to the actual path. The above won't work if your file isn't newline separated. And my method won't work if your string deviates from the format, for example if there are spaces after the key-value delimiting colons, or there aren't spaces after the commas that separate key-value pairs. If that is the case I cannot help you, you need to figure out a different method, but my example does work on the example you have given.
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: '1000ms', transitionProperty: 'max-height', overflow: 'hidden', ...{ exiting: { maxHeight: '0px'}, exited: { maxHeight: '0px'}, entering: { maxHeight: '500px'}, entered: { maxHeight: '500px'}, }[state], }} > With this the list expands fine, but there appears to be a delay on collapsing. I then added "cubic-bezier(0, 1, 0, 1)" to the "transition" property, which fixes the collapsing animation, but the expand animation then seems to break entirely. How can I get both the entering and exiting working? Before adding cubic bezier (sorry for the loss-y gifs): After adding cubic bezier:
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 Library (MSAL) instance // Client ID is the Application (client) ID GUID from the Azure portal const msalInstance = new msal.PublicClientApplication({ auth: { authority: "https://login.microsoftonline.com/common/", clientId: "ffffffff-ffff-ffff-ffff-ffffffffffff", redirectUri: redirectUri, postLogoutRedirectUri: redirectUri }, cache: { cacheLocation: "localStorage" } });
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 portal – App registrations experience assigned to your app. It is essentially like your name. It won't be end of the world if you give it away but you probably should not where there is no reason to. Quoting, Should the OAuth client_id be kept confidential? Your client_id is like your username or e-mail address you use to authenticate your application/service to OAuth. It's not exactly top-secret, but putting it out in the public domain might also be undesirable. Further, Can someone else use my Client ID? Yes, but even in the confidential client apps, "The client ID is exposed through the web browser." Note that we can actually see the Thunderbird's client id exposed in their source code. It isn't really meant to be private information. If I can't safely push this to a public GitHub, how do I handle it? You can use a password manager if you are the only user of your extension.
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 / 5; background: rgba(0, 0, 0, 0.2); } The important part is .main-item has a fixed position in the grid. I now add 25 cells to the grid. const grid = document.querySelector("#grid"); for (let i = 0; i < 25; i++) { const item = document.createElement("div"); item.innerText = i.toString(); grid.append(item); } The problem is that I want these elements to ignore the position of the .main-item (treat it as if it wasn't there). However the CSS currently corrects for this and flows the elements around .main-item. I want the secondary behaviour below: I can correct by setting style.gridRow and style.gridColumn in the JavaScript item.style.gridRow = (Math.floor(i / 5) + 1).toString(); item.style.gridColumn = ((i % 5) + 1).toString(); Is there a way to do this without setting every other element in JS? Is there a CSS to prevent fixed element affecting the flow correction? Codepen Link
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: repeat(5, auto); text-align: center; position: relative; } #grid > * { border: 1px solid blue; padding: 20px; } #grid > .main-item { position: absolute; left: 0; right: 0; grid-row: 3; grid-column: 3 / 5; background: rgba(0, 0, 0, 0.2); } <div id="grid"> <div class="main-item">Main</div> </div>
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 date_time,time,total_min from filter_data fd , total_sum ts where fd.serial_number = ts.serial_number and time between {yesterday10PM*1000} and {today6AM*1000}'''
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 between {yesterday10PM*1000} and {today6AM*1000} ''' You can also read about formatted strings here: https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals
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 1 2023-03-06 2023-03-09 Mining Mining 2 2023-03-05 2023-03-08 I want to get per date the total count in each department. Both start date and end date and included in counting. It would be nice to have an intermediate output as follows Function Department Date Count Const Const1 2023-03-01 1 Const Const1 2023-03-02 1 Const Const1 2023-03-03 2 Const Const1 2023-03-04 2 Const Const1 2023-03-05 2 Const Const1 2023-03-06 1 Const Const1 2023-03-07 1 Const Const1 2023-03-08 0 Const Const1 2023-03-09 0 Const Const1 2023-03-10 0 Const Const2 2023-03-01 0 Const Const2 2023-03-02 2 Const Const2 2023-03-03 2 Const Const2 2023-03-04 1 Const Const2 2023-03-05 1 Const Const2 2023-03-06 0 Const Const2 2023-03-07 0 Const Const2 2023-03-08 0 Const Const2 2023-03-09 0 Const Const2 2023-03-10 0 Mining Mining 1 2023-03-01 0 Mining Mining 1 2023-03-02 1 Mining Mining 1 2023-03-03 1 Mining Mining 1 2023-03-04 1 Mining Mining 1 2023-03-05 1 Mining Mining 1 2023-03-06 1 Mining Mining 1 2023-03-07 1 Mining Mining 1 2023-03-08 1 Mining Mining 1 2023-03-09 1 Mining Mining 1 2023-03-10 0 Mining Mining 2 2023-03-01 1 Mining Mining 2 2023-03-02 1 Mining Mining 2 2023-03-03 1 Mining Mining 2 2023-03-04 1 Mining Mining 2 2023-03-05 2 Mining Mining 2 2023-03-06 2 Mining Mining 2 2023-03-07 1 Mining Mining 2 2023-03-08 1 Mining Mining 2 2023-03-09 0 Mining Mining 2 2023-03-10 0 The desired final output is a pandas df as follows Date Const 1 Const 2 Mining 1 Mining 2 2023-03-01 1 0 0 1 2023-03-02 1 2 1 1 2023-03-03 2 2 1 1 2023-03-04 2 1 1 1 2023-03-05 2 1 1 2
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'].unique() for department in departments: mask = (df['Department'] == department) department_counts = (df.loc[mask, 'Start Date'].value_counts() + df.loc[mask, 'End Date'].value_counts()).sort_index() final_df[department] = department_counts final_df = final_df.fillna(0)
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() { cout<<"\033[34m"<<"Hello World in blue\n"; cout<<"\033[31m"<<"Hello World in red\n"; cout<<"\033[35m"<<"Hello World in purple\n"; return 0; }
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 older versions of Windows, it's not a great choice. So, it depends on what you about. If you want portability to (current) Windows and Linux, what you're doing is fine. If you want portability to older versions of Windows...not so much. If you need something that works for older Windows and don't care about Linux, you can Windows' console functions (e.g., WriteConsoleOutputAttribute or FillConsoleOutputAttribute). My own advice would be to use some manipulators, so you'd do something like: console << blue << "Hello world in blue\n"; console << red << "Hello world in red\n"; ...and when/if you need to move code to a different platform, you can rewrite just those manipulators. For Linux can current Windows you can send the ANSI escape sequences you already know about. Supporting manipulators like this on older versions of Windows isn't trivial, at least using actual cout. You need a Windows handle to the console. But it's pretty easy to do that, with an ostream, so writing to it works about like you'd normally expect. For example: // winbuf.hpp #pragma once #include <ios> #include <ostream> #include <windows.h> class WinBuf : public std::streambuf { HANDLE h; public: WinBuf(HANDLE h) : h(h) {} WinBuf(WinBuf const &) = delete; WinBuf &operator=(WinBuf const &) = delete; HANDLE handle() const { return h; } protected: virtual int_type overflow(int_type c) override { if (c != EOF) { DWORD written; WriteConsole(h, &c, 1, &written, nullptr); } return c; } virtual std::streamsize xsputn(char_type const *s, std::streamsize count) override { DWORD written; WriteConsole(h, s, DWORD(count), &written, nullptr); return written; } }; class WinStream : public virtual std::ostream { WinBuf buf; public: WinStream(HANDLE dest = GetStdHandle(STD_OUTPUT_HANDLE)) : buf(dest), std::ostream(&buf) { } WinBuf *rdbuf() { return &buf; } }; class SetAttr { WORD attr; public: SetAttr(WORD attr) : attr(attr) {} friend WinStream &operator<<(WinStream &w, SetAttr const &c) { WinBuf *buf = w.rdbuf(); auto h = buf->handle(); SetConsoleTextAttribute(h, c.attr); return w; } SetAttr operator|(SetAttr const &r) { return SetAttr(attr | r.attr); } }; class gotoxy { COORD coord; public: gotoxy(SHORT x, SHORT y) : coord{.X = x, .Y = y} {} friend WinStream &operator<<(WinStream &w, gotoxy const &pos) { WinBuf *buf = w.rdbuf(); auto h = buf->handle(); SetConsoleCursorPosition(h, pos.coord); return w; } }; class cls { char ch; public: cls(char ch = ' ') : ch(ch) {} friend WinStream &operator<<(WinStream &os, cls const &c) { COORD tl = {0, 0}; CONSOLE_SCREEN_BUFFER_INFO s; WinBuf *w = os.rdbuf(); HANDLE console = w->handle(); GetConsoleScreenBufferInfo(console, &s); DWORD written, cells = s.dwSize.X * s.dwSize.Y; FillConsoleOutputCharacter(console, c.ch, cells, tl, &written); FillConsoleOutputAttribute(console, s.wAttributes, cells, tl, &written); SetConsoleCursorPosition(console, tl); return os; } }; extern SetAttr red; extern SetAttr green; extern SetAttr blue; extern SetAttr intense; extern SetAttr red_back; extern SetAttr blue_back; extern SetAttr green_back; extern SetAttr intense_back; Along with: // winbuf.cpp #include "winbuf.hpp" #define WIN32_LEAN_AND_MEAN #include <Windows.h> SetAttr red { FOREGROUND_RED }; SetAttr green { FOREGROUND_GREEN }; SetAttr blue { FOREGROUND_BLUE }; SetAttr intense { FOREGROUND_INTENSITY }; SetAttr red_back { BACKGROUND_RED }; SetAttr blue_back { BACKGROUND_BLUE }; SetAttr green_back { BACKGROUND_GREEN }; SetAttr intense_back { BACKGROUND_INTENSITY }; ...and a quick demo: #include "winbuf.hpp" int main() { WinStream w; auto attrib = intense | blue_back; w << attrib << cls() << "Some stuff"; w << gotoxy(0, 4) << (green | blue_back) << "This should be green"; w << gotoxy(0, 5) << attrib << "And this should be grey"; }
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 extract these predefined URLs into an Array to manipulate it later. I made the below code as a workaround, by using two arrays and also I had to start looping from the second element from the first array because I found there is extra "http" on the second array. My question, Is there another neater code? Sub Split_URLs_to_Array() Dim wDoc As Word.Document, rngSel As String Dim arrS, arrD, i As Long Set wDoc = Application.ActiveInspector.WordEditor rngSel = Trim(wDoc.Windows(1).Selection.Text) arrS = Split(rngSel, "http") ReDim arrD(0 To UBound(arrS)) For i = 1 To UBound(arrS) arrD(i) = "http" & arrS(i) Debug.Print arrD(i) Next End Sub
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 the first empty element SplitByStartOfString = Split(strDelim & Join(arr, "|" & strDelim), "|") End Function It can be tested in the next way: Sub testSplitByStartOfString() Dim x As String: x = "https://myurl1/x.pdfhttps://myurl2/y.xlsxhttps://myurl3/z.docx" Dim arr arr = SplitByStartOfString(x, "https:") Debug.Print Join(arr, "||") 'just to visually see the array result. End Sub Of course, you can use what strings you know, the delimiter will be the common prefix of each of them... And end of line separators or VbTab exists, the above code will also work, but these separators will be included of the end of the string. Which, for URL in Outlook will not count. They will only be arranged using the respective separator. 1.1 Another function, using FilterXML may be the next one: Function splitXMLByStartOfString(strText As String, strDelim As String) As Variant Dim XML As String: XML = "<t><s>" & VBA.Replace(strText, strDelim, "</s><s>" & strDelim) & "</s></t>" splitXMLByStartOfString = Application.FilterXML(XML, "//s[position()>1]") 'nodes starting from the second one... 'splitXMLByStartOfString = Application.FilterXML(XML, "//s[count(node())>0]") 'another working way (all not empty nodes) 'splitXMLByStartOfString = Application.FilterXML(XML, "//s[starts-with(., '" & strDelim & "')]") 'working way, too (nodes starting with strDelim) End Function It can be tested using the next sub: Sub TestFilterXMLHttp() Dim x As String: x = "https://myurl1/x.pdfhttps://myurl2/y.xlsxhttps://myurl3/z.docx" Dim arr: arr = splitXMLByStartOfString(x, "https:") 'It returns a 2D, 1 column array... Debug.Print Join(Application.Transpose(arr), "||") End Sub The above function works well and fast, but in Excel. The question does not mention that it should be used in Outlook VBA (but I knew about that...). So, the next solution uses an automation from Outlook, and use Excel.Application it this way. This version needs an Excel session open, but it can be easily adapted to open a new one if nothing open: Function splitXMLByStartOfString(strText As String, strDelim As String, objEx As Object) As Variant Dim XML As String: XML = "<t><s>" & VBA.Replace(strText, strDelim, "</s><s>" & strDelim) & "</s></t>" splitXMLByStartOfString = objEx.FilterXML(XML, "//s[position()>1]") 'nodes starting from the second one... 'splitXMLByStartOfString = Application.FilterXML(XML, "//s[count(node())>0]") 'another working way (all not empty nodes) 'splitXMLByStartOfString = Application.FilterXML(XML, "//s[starts-with(., '" & strDelim & "')]") 'working way, too (nodes starting with strDelim) End Function And the sub to test it, using the above mentioned automation: Sub TestFilterXMLHttp() Dim objEx As Object: Set objEx = GetObject(, "Excel.application") Dim x As String: x = "https://myurl1/x.pdfhttps://myurl2/y.xlsxhttps://myurl3/z.docx" Dim arr: arr = splitXMLByStartOfString(x, "https:", objEx) 'It returns a 2D, 1 column array... Debug.Print Join(objEx.Transpose(arr), "||") End Sub Extracting an array from string elements separated by one from more supposed separators can be extracted using the next function: Function extractFromStringSep(strText As String) As Variant Dim arrC: arrC = Array(vbTab, vbLf) 'you can extend the supposed separators... Dim El For Each El In arrC If InStr(strText, El) > 0 Then extractFromStringSep = Split(strText, El): Exit Function End If Next El End Function Of course, the string to be extracted must NOT contain the supposed separators... It can be tested like in the next sub: Sub TestextractFromStringSep() Dim x As String: x = "https://myurl1/x.pdf" & vbTab & "https://myurl2/y.xlsx" & vbTab & "https://myurl3/z.docx" 'x = "https://myurl1/x.pdf" & vbLf & "https://myurl2/y.xlsx" & vbLf & "https://myurl3/z.docx" Dim arr arr = extractFromStringSep(x) Debug.Print Join(arr, "||") 'just to visually see the array result. End Sub And a last version, also allowing part of the url string as separator (only for didactic purpose): Function extractFromStrAndSep(strText As String, strDelim As String) As Variant Dim arrC: arrC = Array(vbTab, vbLf, "myur") 'you can extend the supposed separators... Dim El For Each El In arrC If InStr(strText, El & strDelim) > 0 Then extractFromStrAndSep = Split(strText, El & strDelim): Exit Function End If Next El End Function Tested with the next (adapted) sub: Sub TestextractFromStrAndSep() Dim x As String: 'x = "https://myurl1/x.pdf" & vbTab & "https://myurl2/y.xlsx" & vbTab & "https://myurl3/z.docx" 'x = "https://myurl1/x.pd" & vbLf & "https://myurl2/y.xlsx" & vbLf & "https://myurl3/z.docx" x = "https://myurl1/x.pd" & "myur" & "https://myurl2/y.xlsx" & "myur" & "https://myurl3/z.docx" Dim arr arr = extractFromStrAndSep(x, "https:") Debug.Print Join(arr, "||") 'just to visually see the array result. End Sub
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() function and compare the results, but the results turned out to be quite different! Here is the sample data. x denotes the time-series variable, and z denotes the exogeneous variable, as shown in the equation above. library(forecast) library(tidyverse) data("Nile") df <- Nile %>% as_tibble() %>% mutate(x = as.numeric(x)) %>% mutate(z = rnorm(100)) Then fit the model using the Arima() and glm() and compare the results. fit_arima <- Arima(df$x, order = c(1, 0, 0), include.mean = TRUE, xreg = df$z) tibble(Parameters = c("x lag", "intercept", "z"), Coefficients = coef(fit_arima), Standard_Errors = sqrt(diag(vcov(fit_arima)))) fit_glm <- glm(df$x ~ lag(df$x) + df$z) tibble(Parameters = c("intercept", "x lag", "z"), Coefficients = coef(fit_glm), Standard_Errors = summary(fit_glm)$coefficients[, "Std. Error"]) The results are displayed as follows. Arima() function: # A tibble: 3 × 3 Parameters Coefficients Standard_Errors <chr> <dbl> <dbl> 1 x lag 0.510 0.0868 2 intercept 920. 29.4 3 z 5.02 12.1 glm() function: # A tibble: 3 × 3 Parameters Coefficients Standard_Errors <chr> <dbl> <dbl> 1 intercept 444. 83.4 2 x lag 0.516 0.0896 3 z 8.95 13.9 The estimated coefficient and standard error of x lag are quite close, but the values of other two variables are very different. I find this puzzling because both the Arima() and glm() function use the maximum likelihood estimator. Could you please explain why this difference happens and how can I fix this?
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}\phi_{1}z_{t-1} + \varepsilon_{t} This explains the major differences in the two results. But even if you specified exactly the same model, they would give slightly different results because Arima() uses the true likelihood whereas glm() will use a conditional likelihood because of the initial missing value due to the lag() function. See https://robjhyndman.com/hyndsight/arimax/ for a discussion of the different model specifications.
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::vector<int>> Vec2i; void Vec2DPrinter(Vec2i vec) { size_t vec_h = vec.size(); for (size_t y = 0; y < vec_h; y++) { size_t vec_w = vec.at(y).size(); for (size_t x = 0; x < vec_w; x++) { std::cout << vec.at(y).at(x); } std::cout << std::endl; } } void Vec2DFiller(Vec2i &dest, Vec2i src, int dest_x, int dest_y) { int src_h = (int)src.size(); // Loop to fill dest vector with elements of src vector at specific coords for (int y = 0; y < src_h; y++) { int src_w = (int)src.at(y).size(); int dest_h = (int)dest.size(); if ((y + dest_y) >= dest_h) { break; } if ((y + dest_y) < 0) { continue; } int dest_w = (int)dest.at(y + dest_y).size(); for (int x = 0; x < src_w; x++) { if (x + dest_x >= dest_w) { break; } if (x + dest_x < 0) { continue; } dest.at(y + dest_y).at(x + dest_x) = src.at(y).at(x); } } } int main(void) { // This is just visual example (i know how to fill vectors) Vec2i dest = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; Vec2i src = { { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 } }; std::cout << "Destination contents (before change):" << std::endl; Vec2DPrinter(dest); std::cout << "\nSurce contents:" << std::endl; Vec2DPrinter(src); // Destination coords int dest_x = 3; int dest_y = 4; // Key function to fill one vector with another Vec2DFiller(dest, src, dest_x, dest_y); std::cout << "\nDestination contents (after change):" << std::endl; Vec2DPrinter(dest); std::string exit = ""; std::getline(std::cin, exit); return 0; } Key part: // Destination coords int dest_x = 3; int dest_y = 4; int src_h = (int)src.size(); // Loop to fill dest vector with elements of src vector at specific coords for (int y = 0; y < src_h; y++) { int src_w = (int)src.at(y).size(); int dest_h = (int)dest.size(); if ((y + dest_y) >= dest_h) { break; } if ((y + dest_y) < 0) { continue; } int dest_w = (int)dest.at(y + dest_y).size(); for (int x = 0; x < src_w; x++) { if (x + dest_x >= dest_w) { break; } if (x + dest_x < 0) { continue; } dest.at(y + dest_y).at(x + dest_x) = src.at(y).at(x); } } This is the best solution I could come with. (Not the same but similar. The original one has single but wide if statement so it wouldn't fit on a single line here so that is why I changed it a bit.) The reason why I want to do this is pretty simple. I'm doing this thousand times a second and on a bigger scale, that is why. I was searching on the web and found things like std::fill and std::copy but none of them meets my requirements. (std::fill is not what I need and std::copy is an algorithm that consists of loop.)
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). Your mileage will vary. I moved the conditional checks out of the inner loop and used std::copy for the actual work. For larger dataset sizes, I suspect the speedup will be greater. I used the timer library for measuring performance. Performance could be improved further by using a native 2D storage structure like a matrix or std::mdspan instead of a std::vector of std::vector. Sample Code #include <iostream> #include <vector> #include <string> #include "core/timer/timer.h" using std::cout, std::endl; typedef std::vector<std::vector<int>> Vec2i; void Vec2DPrinter(Vec2i vec) { size_t vec_h = vec.size(); for (size_t y = 0; y < vec_h; y++) { size_t vec_w = vec.at(y).size(); for (size_t x = 0; x < vec_w; x++) std::cout << vec.at(y).at(x); std::cout << std::endl; } } void Vec2DFiller(Vec2i &dest, Vec2i src, int dest_x, int dest_y) { int src_h = (int)src.size(); // Loop to fill dest vector with elements of src vector at specific coords for (int y = 0; y < src_h; y++) { int src_w = (int)src.at(y).size(); int dest_h = (int)dest.size(); if ((y + dest_y) >= dest_h) break; if ((y + dest_y) < 0) continue; int dest_w = (int)dest.at(y + dest_y).size(); for (int x = 0; x < src_w; x++) { if (x + dest_x >= dest_w) break; if (x + dest_x < 0) continue; dest.at(y + dest_y).at(x + dest_x) = src.at(y).at(x); } } } void Vec2DFiller2(Vec2i &dest, const Vec2i& src, int dest_x, int dest_y) { int ylen = std::min(src.size(), dest.size() > dest_y ? dest.size() - dest_y : 0); if (ylen == 0) return; int xlen = std::min(src.at(0).size(), dest.at(0).size() - dest_x); if (xlen == 0) return; for (auto ydx = 0; ydx < ylen; ++ydx) { auto& ydest = dest.at(ydx + dest_y); const auto& ysrc = src.at(ydx); std::copy(ysrc.data(), ysrc.data() + xlen, ydest.data() + dest_x); } } int main(void) { // This is just visual example (i know how to fill vectors) Vec2i dest = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; Vec2i src = { { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 } }; std::cout << "Destination contents (before change):" << std::endl; Vec2DPrinter(dest); std::cout << "\nSurce contents:" << std::endl; Vec2DPrinter(src); // Destination coords int dest_x = 3; int dest_y = 4; // Key function to fill one vector with another auto ns = core::timer::Timer().run(1'000'000, [&]() { Vec2DFiller(dest, src, dest_x, dest_y); }).elapsed_per_iteration(); cout << ns << " ns / op" << endl; ns = core::timer::Timer().run(1'000'000, [&]() { Vec2DFiller2(dest, src, dest_x, dest_y); }).elapsed_per_iteration(); cout << ns << " ns / op" << endl; std::cout << "\nDestination contents (after change):" << std::endl; Vec2DPrinter(dest); return 0; } Relevant Output 142.167 ns / op 30.4702 ns / op
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 : String = "", id_seccion : String = ""){ self.id_producto = id_producto self.producto_es = producto_es self.id_seccion = id_seccion } func hayProductosNuevos(ultimoProductoEnBd: Int, completion: @escaping (Bool) -> Void) { let urlWS = Globales().urlWS//Url para la webservice AF.request(urlWS+"actualiza_productos.php?ultimo_producto=\(ultimoProductoEnBd)",method: .get).responseDecodable(of: [Productos].self) { responseConsulta in switch responseConsulta.result{ case .success(let actualizacionDeProductos): if (actualizacionDeProductos.isEmpty){ completion(false) } else { completion(true) } case .failure(let error): print("hay un error \(String(describing: error.errorDescription))") } } } } My problem is how to call it and control what is returned to me from my view: I know that within a view I cannot call it that. The idea is if I return true, perform a product update and display a ProgressView. I have tried everything I have been reading, using its init() in the view. But I get another error. I think my problem is that from Alamofire I need to know if I have to update my application's data or not, that's why it returns true or false, but I'm not clear about the use of closures, so I don't know how I have to call Alamofire from my view so I can control the data.
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 struct named in singular form and without the logic to load the data. struct Producto: Decodable { // MARK: Propiedades de los productos var id_producto : String var producto_es : String var id_seccion : String } And it's highly recommended to use camelCase struct member names, but this is beyond the question. And if the values will never change declare the struct members as constants (let). Then create a class conforming to ObservableObject for the logic to load the data with a @Published property for the products and a method to load the data. A completion handler is not needed, assign (or append) the result to the array. Actually AF is not needed either for a simple GET request, built-in URLSession and JSONDecoder can do the same. @MainActor class ViewModel : ObservableObject { @Published var productos = [Producto]() func hayProductosNuevos(ultimoProductoEnBd: Int) { let urlWS = Globales().urlWS //Url para la webservice AF.request(urlWS+"actualiza_productos.php?ultimo_producto=\(ultimoProductoEnBd)",method: .get).responseDecodable(of: [Producto].self) { responseConsulta in switch responseConsulta.result { case .success(let actualizacionDeProductos): self.productos = actualizacionDeProductos // or self.productos.append(contentsOf: actualizacionDeProductos) case .failure(let error): print("hay un error", error) } } } } In the view create an instance of ViewModel as @StateObject and load the data in onAppear struct ActualizarProductos : View { @StateObject private var viewModel = ViewModel() @State private var ultimoProductoEnBd = 0 var body: some View { NavigationView { // UI stuff } .onAppear { viewModel.hayProductosNuevos(ultimoProductoEnBd: ultimoProductoEnBd) } } } The ultimoProductoEnBd is not handled in the question, it's just an example adding a @State property.
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 says this: ERROR: 0:17: ')' : syntax error syntax error I'm taking the error to mean I have too many or to few brackets, but I checked that and my code seems fine. Why is there an error, and what can I do to solve it?
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-reset ui-widget-content ui-accordion-content-active" id="ui-id-2" aria-labelledby="ui-id-1" role="tabpanel" aria-hidden="false"> Content for title 1 </div> <h3 class="accord-41">Title 2</h3> <div style="display: none;" class="ui-accordion-content ui-corner-bottom ui-helper-reset ui-widget-content" id="ui-id-4" aria-labelledby="ui-id-3" role="tabpanel" aria-hidden="true"> Content for title 2 </div> <h3 class="accord-47">Title 3</h3> <div style="display: none;" class="ui-accordion-content ui-corner-bottom ui-helper-reset ui-widget-content" id="ui-id-6" aria-labelledby="ui-id-5" role="tabpanel" aria-hidden="true"> Content for title 3 </div> </div> What I am trying to do is: Get the h3 tag that contains the class ui-state-active and then Get the unique id (in this example, 19) that comes after the class name that starts with "accord-". Note, the above is churned out by a plugin I am using, which means I cannot set and "id" tag for h3 to be unique. I have tried: var classname = $("div.accordion h3.ui-state-active").find('class^="accord-"'); To get the name of the class, before I substring it. However, this doesn't work.
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 id = classname.match(/accord-(\d+)/)[0];
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 a variable reward_positions. Reward positions = [(<Venue: Venue_name>, reward_points, reward_position_on_bar)] So this part works. The plan is therefore to access reward_position_on_bar by calling {{reward_positions.2}} WHAT DOESNT WORK - the template But something is not working to plan in the template. The template renders the last child_model (thats rewardprogram) objects of the last parent_id (thats venue) irrespective of the actual parent_id processed in the for loop. TEST RESULT & WHERE I THINK THE PROBLEM IS I think my problem lies in my nested forloop. The parent_id in the parent forloop does not match the '{{reward_position.0}}' in the nested forloop. Doing a verification test, {{key}} should be equal to {{reward_position.0}} as they both go through the same parent forloop. However, if {{key}} does change based on venue.id (parent forloop id), {{reward_position.0}} is stuck to the same id irrespective of the parent forloop id. Can anyone seem what I am doing wrong? THE CODE models class Venue(models.Model): name = models.CharField(verbose_name="Name",max_length=100, blank=True) class RewardProgram(models.Model): venue = models.ForeignKey(Venue, null = True, blank=True, on_delete=models.CASCADE, related_name="venuerewardprogram") title = models.CharField(verbose_name="reward_title",max_length=100, null=True, blank=True) points = models.IntegerField(verbose_name = 'points', null = True, blank=True, default=0) views def list_venues(request): venue_markers = Venue.objects.filter(venue_active=True) #Progress bar per venue bar_total_lenght = 100 rewards_available_per_venue = 0 reward_position_on_bar = 0 venue_data = {} reward_positions = {} for venue in venue_markers: print(f'venue name ={venue}') #list all reward programs venue.reward_programs = venue.venuerewardprogram.all() reward_program_per_venue = venue.reward_programs #creates a list of reward points needed for each venue for each object reward_points_per_venue_test = [] #appends the points to empty list from reward program from each venue for rewardprogram in reward_program_per_venue: reward_points_per_venue_test.append(rewardprogram.points) #sorts list in descending order reward_points_per_venue_test.sort(reverse=True) #set position of highest reward to 100 (100% of bar length) if reward_points_per_venue_test: highest_reward = reward_points_per_venue_test[0] if not reward_program_per_venue: pass else: #counts reward program per venue rewards_available_per_venue = venue.reward_programs.count() if rewards_available_per_venue == 0: pass else: #position of reward on bar reward_positions = [] for rewardprogram in reward_program_per_venue: #list all points needed per reward program objects reward_points = rewardprogram.points #position each reward on bar reward_position_on_bar = reward_points/highest_reward reward_positions.append((venue, reward_points, reward_position_on_bar)) #reward_positions[venue.id] = reward_position_on_bar reward_positions = reward_positions print(f'Reward positions = {reward_positions}') context = {'reward_positions':reward_positions,'venue_data':venue_data,'venue_markers':venue_markers} return render(request,'template.html',context) template {%for venue in venue_markers%} {%for key, value in venue_data.items%} {%if key == venue.id%} #venue.id = 3 {% for reward_position in reward_positions %}#test result {{reward_position.0.id}} # = id = 7 (thats not the good result) {{key}} #id = 3 (thats the good result) {% endfor %} <div class="progress-bar bg-success" role="progressbar" style="width: {{value}}%" aria-valuenow="{{value}}" aria-valuemin="0" aria-valuemax="100"></div> {%endif%} {%endfor%} {%endfor%}
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=Sum('venuerewardprogram__points'), rewards_available=Count('venuerewardprogram'), ) .prefetch_related('venuerewardprogram') ) for venue in venues: for rewardprogram in venue.venuerewardprogram.all(): rewardprogram.position_on_bar = round( 100 * rewardprogram.reward_points / venue.total_points ) return render(request, 'template.html', {'venues': venues}) then in the template, we can render this as: {%for venue in venues %} <h1>{{ venue.name }}</h1> {% for rewardprogram in venue.venuerewardprogram.all %} <div class="progress-bar bg-success" role="progressbar" style="width: {{ rewardprogram.position_on_bar }}%" aria-valuenow="{{ rewardprogram.position_on_bar }}" aria-valuemin="0" aria-valuemax="100"></div> {% endfor %} {% endfor %} this will thus take the .position_on_bar attributes we added to the rewardPrograms that we prefetched for the Venues.
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 ) ( ctrl + alt ) ( ctrl + alt + shift ) so forth thank you
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,LAlt,RAlt,LWin,RWin" ; bind the keys to keypress_handler Loop, parse, keys, `, { hotkey, ~%A_Loopfield%, keypress_handler1 hotkey, ~%A_Loopfield% Up, keypress_handler2 } keypress_handler1: ThisKeyLabel := StrReplace(A_ThisHotkey, "~") ToolTip, %ThisKeyLabel%,,, 1 SetTimer RemoveTooltip1, 50 return keypress_handler2: SetTimer RemoveTooltip1, off ToolTip,,,, 1 return RemoveTooltip1: ThisKeyLabel := StrReplace(A_ThisHotkey, "~") If (A_PriorKey != ThisKeyLabel) ToolTip,,,, 1 return
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 depends on the call to the macro? This comes up when the other arguments come from another layer and the SUBST macro is repeated many times with different values of MAGIC. For example: #define WRAP(function, MAGIC, stuff, ...) \ void function(__VA_ARGS__) { stuff }; #define SUPERWRAP(function, stuff, ...) \ WRAP(function, uint8_t, stuff##_u8, __VA_ARGS__) \ WRAP(function, uint16_t, stuff##_u16, __VA_ARGS__) SUPERWRAP(example, EXAMPLE_IMPL, template_t<MAGIC>, int) Which cannot be solved in templates because: #define WRAP(function, stuff, ...) \ template<class MAGIC> int function(__VA_ARGS__) { stuff } WRAP(example, /*...*/, template_t<MAGIC>, int) doesn't allow for specialised implementaion, and and taking the type as a templatea argument in the specialisation is a partial specialisation which is also illegal.
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 use to force the expansion of MAGIC within the second argument with a value which depends on the call to the macro? No. For example: #define WRAP(function, MAGIC, stuff, ...) \ Using C macros to generate function definition results in hard to read, maintain and debug code that no one is ever able to fix or do anything with later. Consider writing the stuff that you want line by line. You could consider using a better preprocessor, like jinja2, m4 or php.
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 break like this: .box { width: 100px; height: 40px; float: right; clear: both; } #blue { background-color: blue; } #text { height: 120px; overflow-y: scroll; } <div id='blue' class='box'></div> <div id='text'> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div>
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: 120px; overflow-y: auto; } <div class="container"> <div id='blue' class='box'></div> <div id='text'> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div> </div>
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 a success. But the complete rest of the line does not match the MAX(highest_datetime.creattionDate). The rest of the row got mixed up. How do i prevent this? Do i use it wrong? here is the data for the Database so you can create it yourself: CREATE TABLE `test`.`highest_datetime` ( `id` INT NOT NULL AUTO_INCREMENT, `groupId` INT NOT NULL, `creationDate` DATETIME NOT NULL, `Content` VARCHAR(100) NOT NULL, PRIMARY KEY (`id`), INDEX (`groupId`) ) ENGINE = InnoDB; INSERT INTO `test`.`highest_datetime` (`groupId`, `creationDate`, `Content`) VALUES (1, '2023-05-02 00:00:00', 'Newest content'), (1, '2023-01-01 00:00:00', 'Middle Content'), (2, '2023-03-01 00:00:00', 'Middle Content'), (2, '2022-11-01 00:00:00', 'Old Content'), (2, '2023-06-01 00:00:00', 'New Content'), (1, '2022-11-20 00:00:00', 'Old Content'), (2, '2024-11-01 00:00:00', 'Future Content');
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 the maximum creation date. You also want all columns, but you don't tell the DBMS from which row. For example you select the content, but which? The first in alhabet or the last? You don't state this, and so this query is invalid. This would raise an error in about every DBMS. In MySQL's old cheat mode however, the DBMS silently applies ANY_VALUE on all non-aggregated columns. In other words it picks the content and other columns from arbitrary rows. What you want instead is to get the rows with the maximum creation dates for their group. One way to do this: SELECT id, groupid, creationdate, content FROM highest_datetime WHERE (groupid, creationdate) IN ( SELECT groupid, MAX(creationdate) FROM highest_datetime GROUP BY groupid ); Another approach: SELECT id, groupid, creationdate, content FROM ( SELECT *, MAX(creationdate) OVER (PARTITION BY groupid) as max_grp_date FROM highest_datetime ) with_max_date WHERE creationdate = max_grp_date; Add an ORDER BY clause to the queries, if you want your result rows in a particular order. Demo: https://dbfiddle.uk/FzP5oloZ
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") .font(.title) Text("Settings") } } I tried it the normal way, but it just spaced out the specific tab more than all of the other tabs.
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(systemName: "gear") .font(.title) Text("Settings") } } .tag(5) // ... other tabs ... }
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 Predicate: public FunctionalI{ protected: std::function<bool(T)> predicate; public: Predicate(std::function<bool(T)> predicate){ this->predicate = predicate; } inline bool test(T t){ return this->predicate(t); } }; } } And this is main.cpp: bool foo(_functional::Predicate<int> predicate){ return predicate.test(2); } int main(){ _functional::Predicate<int> tmp = _functional::Predicate<int>([] (int x) -> bool{ return x == 2; }); std::cout << foo(tmp); return 0; } Now, of course it works! My question is about how could I make a brief of that lambda expression? I mean, is there any way to pass "directly" the lambda expression (without give it to the Predicate constructor) and then let it construct the Predicate object with right that lambda expression. I have taken a look at using aliasing and even at functor with operator(), but they did not helped me (maybe I have not been able to do it) An example of main.cpp which I wish to reach: bool foo(_functional::Predicate<int> predicate){ return predicate.test(2); } int main(){ // To much stuff to write //std::cout<<foo(_functional::Predicate<int>( [] (int x) -> bool{ return x == 2; } )); //What I whish to reach foo([] (int x) -> bool{return x == 2;} ); return 0; } Another question to make a brief of lambda expr is: is there a way to make implicit the return type of lambda and even the keyword return?
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{return x == 2;} } ); // ^ initialise Predicate object ^ Or create a template constructor as suggested in comments: class Predicate : public FunctionalI { protected: std::function<bool(T)> predicate; public: template <typename PredType> Predicate(PredType predicate) : predicate{ std::move(predicate) } { // use member init list instead of reassigning object in constructor } // ... };
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-19 12:25:39 G 11 2022-09-19 12:25:40 H 12 2022-09-19 12:25:48 I 13 2022-09-19 12:27:18 EVENTD 14 2022-09-19 12:29:08 J I can't figure out how to select values between two others, but in a specific order. Only events between EVENTA and EVENTD should be returned, in that order. So that results should be the rows with id 1 to 4 and 9 to 13 Tried to do something like the following, but it is giving me id 1,4,9 and 13 omitting what is between them. SELECT id, datec, event FROM table1 WHERE event BETWEEN 'EVENTA' AND 'EVENTD'; I then tried to use this, SELECT id, datec, event FROM table1 WHERE (id BETWEEN (SELECT id FROM table1 WHERE event BETWEEN 'EVENTA' AND 'EVENTD' LIMIT 1) AND (SELECT id FROM table1 WHERE event BETWEEN 'EVENTA' AND 'EVENTD' LIMIT 1,1)) OR (id BETWEEN (SELECT id FROM table1 WHERE event BETWEEN 'EVENTA' AND 'EVENTD' LIMIT 2,1) AND (SELECT id FROM table1 WHERE event BETWEEN 'EVENTA' AND 'EVENTD' LIMIT 3,1)); And it gives me the results but I have many rows in my table. Can please someone guide me on how to repeat this till the end as i'm sure there is a way to do this but i can't figure out how? Regards, pierre
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 EventD in our armed_event partition. And it gets value 1 when the first EventD is found, till the successive EventD. So you can just filter accordingly inside a WHERE clause, when this ranking value is either 0 or is 1 and event is exactly "EventD". WITH cte AS ( SELECT *, SUM(`event`='EVENTA') OVER(ORDER BY datec, id) AS armed_events, SUM(`event`='EVENTD') OVER(ORDER BY datec, id) AS disarmed_events FROM Table1 ), cte2 AS ( SELECT *, DENSE_RANK() OVER(PARTITION BY armed_events ORDER BY disarmed_events) -1 AS rn FROM cte ) SELECT `id`, `datec`, `event` FROM cte2 WHERE rn = 0 OR (rn = 1 AND `event` = 'EVENTD') ORDER BY id Output: 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 9 2022-09-19 12:25:38 EVENTA 10 2022-09-19 12:25:39 G 11 2022-09-19 12:25:40 H 12 2022-09-19 12:25:48 I 13 2022-09-19 12:27:18 EVENTD Check the demo here. Note: The last ORDER BY clause is not necessary. It's there just for visualization purposes.
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 SqliteConnection arg is also written with some generic, but so i can use it more than once. Inside Sqlx, multiple structs implement Executor trait on a mutable reference, e.g. impl<'c> Executor<'c> for &'c mut SqliteConnection {...} I was able to convert a SINGLE call (the fn process), but not the fn process_twice - because executor is not copyable. async fn process<'a, E>(conn: E) -> anyhow::Result<()> where E: sqlx::Executor<'a, Database = sqlx::Sqlite> {...} Full example // [dependencies] // anyhow = "1.0" // futures = "0.3" // sqlx = { version = "0.6", features = [ "sqlite", "runtime-tokio-native-tls"] } // tokio = { version = "1.28.2", features = ["macros"] } // // //// TO RUN, must set env var: // DATABASE_URL='sqlite::memory:' cargo run use futures::TryStreamExt; use sqlx::SqliteConnection; use sqlx::{query, Connection}; #[tokio::main] async fn main() -> anyhow::Result<()> { let mut conn = SqliteConnection::connect("sqlite::memory:").await?; process(&mut conn).await?; process_twice(&mut conn).await?; Ok(()) } async fn process(conn: &mut SqliteConnection) -> anyhow::Result<()> { let sql = query!("SELECT name FROM sqlite_master"); let mut rows = sql.fetch(conn); while let Some(row) = rows.try_next().await? { println!("{row:?}") } Ok(()) } async fn process_twice(conn: &mut SqliteConnection) -> anyhow::Result<()> { process(conn).await?; process(conn).await?; Ok(()) } Similar questions: this
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 does mean that you can't take Pool<DB> any more because it only implements Executor for &Pool but should work for your usecase.
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 error. <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="lib/jquery/jquery-3.7.0.min.js"></script> <script src="lib/bootstrap/js/bootstrap.min.js"></script> <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="lib/bootstrap/css/bootstrap-responsive.min.css"> <link rel="stylesheet" href="css/app.css"> <script src="lib/angular/angular.min.js"></script> <script src="js/app.js"></script> </head> I've tried to import bootstrap.min.js first, but this the error message I get, and I'm not sure why. <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="lib/bootstrap/js/bootstrap.min.js"></script> <script src="lib/jquery/jquery-3.7.0.min.js"></script> <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="lib/bootstrap/css/bootstrap-responsive.min.css"> <link rel="stylesheet" href="css/app.css"> <script src="lib/angular/angular.min.js"></script> <script src="js/app.js"></script> </head> I expected it that this small change would resolve the issue, but it didn't.
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/7PEgZnGpM5qtFOBZgwujjDnG5w5Fjx46YzqvIh/ORstcj7luStvvIHkisQi5SKw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.0.2/bootstrap.min.js" integrity="sha512-jv0RCzX/cFYIF5KkvheT4Xk06YMyEmYAJ8mxZ0pgzwHMgIdT/KGedWD2dK2modKDyaK6DSDwh6ptzTHtfJ0Nng==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.0/css/bootstrap-responsive.min.css" integrity="sha512-c4E36NNKxeFBnGTk/nFCssF4B7gXdZ9hqBnR0fec+DiZ7EnCB2RA42O8HPdgKHFnseb4s6ieQtmT8iksW+QfWw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
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 Set ws = Worksheets(i) lastColumn = ws.Cells(10, ws.Columns.Count).End(xlToLeft).Column ws.Range(ws.Cells(10, lastColumn + 1), ws.Range("CZ200000")).ClearContents Next i End Sub Cell D10 is skipped: Sheet screenshot Thank you for help in advance.
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 address them individually. Sub clearRange() Dim ws As Worksheet Dim lastColumn As Long, i As Long For i = 2 To Worksheets.Count - 1 Set ws = Worksheets(i) lastColumn = ws.Cells(10, 1).End(xlToRight).Column + 1 ' Do this ws.Range(ws.Cells(10, lastColumn + 1), ws.Range("CZ200000")).ClearContents Next i End Sub If this does or doesn't work for you, let us know the result. And in future requests, please include a table we can copy. We can't copy a screenshot to a worksheet.
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://kotl.in/gradle/jvm/toolchain * Try: > Run with --stacktrace option to get the stack trace. > Run with --scan to get full insights. The build.gradle file for this module has the following code:- plugins { id 'java-library' id 'org.jetbrains.kotlin.jvm' } java { sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 } Kindly help me find the error and its resolution.
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 the dishes and the grades are stored in _score. My code is working well already: on the y-axis the score is given, both for cook1 and cook2 in the legend, cook1 and cook2 are separate a vertical line is drawn over the nearest x-axis item when hovering I would like to make changes to the legend. Now it shows the following properties: dish (x-axis number) ingredient 1, ingredient 2 cook1's dish, cook2's dish score of the cook that we're hovering closest to cookX_score (cook1_score, cook2_score) of the cook that we're hovering closest to Instead, I would like to change it so that the dishes (cook1 and cook2) are not both shown but that, just like with score, only the respective dish is included. So if I hover closer to a point of cook1_score I only want to show cook1 and not also cook2. My attempts to restrict this have failed, but the reason is simply because Altair does not know that cook1 and cook1_score, and cook2 and cook2_score are linked. But I am not sure how I can tell Altair that so that it only shows the relevant fields when hovering close to a point. import altair as alt import pandas as pd alt.renderers.enable("altair_viewer") df = pd.DataFrame({ "ingredient1": ["potato", "onion", "carrot", "beet"], "ingredient2": ["tomato", "pepper", "zucchini", "lettuce"], "dish": [1, 2, 3, 4], "cook1": ["cook1 dish1", "cook1 dish2", "cook1 dish3", "cook1 dish4"], "cook1_score": [0.4, 0.3, 0.7, 0.9], "cook2": ["cook2 dish1", "cook2 dish2", "cook2 dish3", "cook2 dish4"], "cook2_score": [0.6, 0.2, 0.5, 0.6], }) value_vars = [c for c in df.columns if c.endswith("_score")] cook_names = [c.replace("_score", "") for c in value_vars] id_vars = ["dish", "ingredient1", "ingredient2"] + cook_names df_melt = df.melt(id_vars=id_vars, value_vars=value_vars, var_name="cook", value_name="score") nearest_dish = alt.selection(type="single", nearest=True, on="mouseover", fields=["dish"], empty="none") # Main chart with marked circles chart = alt.Chart(df_melt).mark_circle().encode( x="dish:O", y="score:Q", color="cook:N", tooltip=id_vars + ["score", "cook"] ).add_selection( nearest_dish ) # Draw a vertical rule at the location of the selection vertical_line = alt.Chart(df_melt).mark_rule(color="gray").encode( x="dish:O", ).transform_filter( nearest_dish ) # Combine the chart and vertical_line layer = alt.layer( chart, vertical_line ).properties( width=600, height=300 ).interactive() layer.show() Note: I'm stuck on Altair<5.
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"], "ingredient2": ["tomato", "pepper", "zucchini", "lettuce"], "dish_id": [1, 2, 3, 4], "cook1": ["cook1 dish1", "cook1 dish2", "cook1 dish3", "cook1 dish4"], "cook1_score": [0.4, 0.3, 0.7, 0.9], "cook2": ["cook2 dish1", "cook2 dish2", "cook2 dish3", "cook2 dish4"], "cook2_score": [0.6, 0.2, 0.5, 0.6], }) value_vars = [c for c in df.columns if c.endswith("_score")] cook_names = [c.replace("_score", "") for c in value_vars] id_vars = ["dish_id", "ingredient1", "ingredient2"] + cook_names df_melt_score = df.melt(id_vars=["dish_id", "ingredient1", "ingredient2"], value_vars=value_vars, var_name="cook_score", value_name="score") df_melt_score["cook"] = df_melt_score["cook_score"].str.replace("_score", "") df_melt_score = df_melt_score.drop(columns=["cook_score"]) df_melt_dish = df.melt(id_vars=["dish_id", "ingredient1", "ingredient2"], value_vars=["cook1", "cook2"], var_name="cook", value_name="dish_name") df_concat = pd.merge(df_melt_score, df_melt_dish, on=["dish_id", "cook", "ingredient1", "ingredient2"], how="left").reset_index() nearest_dish = alt.selection(type="single", nearest=True, on="mouseover", fields=["dish_id"], empty="none") # Main chart with marked circles chart = alt.Chart(df_concat).mark_circle().encode( x="dish_id:O", y="score:Q", color="cook:N", tooltip=["dish_id", "ingredient1", "ingredient2", "cook", "dish_name"] ).add_selection( nearest_dish ) # Draw a vertical rule at the location of the selection vertical_line = alt.Chart(df_melt_score).mark_rule(color="gray").encode( x="dish_id:O", ).transform_filter( nearest_dish ) # Combine the chart and vertical_line layer = alt.layer( chart, vertical_line ).properties( width=600, height=300 ).interactive() layer.show()
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() { $('.openModal').click(function() { var divId = $(this).attr('id'); // Invia l'ID al server tramite richiesta AJAX $.ajax({ type: 'POST', url: 'http://localhost/icollegati/phpFunction/phpFunc.php', data: {divId: divId}, success: function(response) { // Gestisci la risposta del server console.log("Risposta",response); } }); }); }); the PHP function is: 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; return $id; } } }; Thanks in adavance for the help.
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; return $id; } } } // Call the function FetchIdNumber(); Make sure to place the function call FetchIdNumber(); after the function definition. Additionally, please ensure that the path to your PHP file is correct. In your AJAX code, you have specified the URL as http://localhost/icollegati/phpFunction/phpFunc.php. Make sure that this path is accurate and matches the actual location of the PHP file on your server.
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 interval is of odd size left_index = argmax - half_interval right_index = argmax + half_interval # fix overflow left_index[left_index < 0] = 0 right_index[right_index >= arr.shape[-1]] = arr.shape[-1] - 1 # this is just illustrative and doesn't work: arr[left_index:right_index] = 0 # zero the interval in-place
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]) # True when "normal" index is between # [argmax - half_interval, argmax + half_interval] mask = (argmax - half_interval <= idx) & (idx <= argmax + half_interval) arr[mask] = 0 # or out = np.where(mask, 0, arr) if you don't want to modify arr Results: >>> arr array([[6, 8, 5, 4, 6, 9, 3, 6], [9, 4, 9, 3, 9, 0, 3, 6], [7, 9, 7, 1, 0, 3, 0, 0], [9, 9, 4, 8, 3, 8, 3, 2], [9, 7, 6, 9, 2, 0, 9, 6], [1, 7, 9, 7, 6, 2, 9, 4], [8, 0, 8, 9, 6, 5, 0, 9], [2, 0, 9, 5, 9, 0, 2, 4]]) >>> argmax array([[5], [0], [1], [0], [0], [2], [3], [2]], dtype=int64) >>> mask array([[False, False, False, True, True, True, True, True], [ True, True, True, False, False, False, False, False], [ True, True, True, True, False, False, False, False], [ True, True, True, False, False, False, False, False], [ True, True, True, False, False, False, False, False], [ True, True, True, True, True, False, False, False], [False, True, True, True, True, True, False, False], [ True, True, True, True, True, False, False, False]]) >>> out array([[6, 8, 5, 0, 0, 0, 0, 0], [0, 0, 0, 3, 9, 0, 3, 6], [0, 0, 0, 0, 0, 3, 0, 0], [0, 0, 0, 8, 3, 8, 3, 2], [0, 0, 0, 9, 2, 0, 9, 6], [0, 0, 0, 0, 0, 2, 9, 4], [8, 0, 0, 0, 0, 0, 0, 9], [0, 0, 0, 0, 0, 0, 2, 4]]) The above should work for arrays with more than 2 axes as well due to broadcasting. But only because you argmax over the final axis.
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 bits vs 16 bits). I have a LOT of data, so I care about this. How can I convert a numpy array to a torch.Tensor minimizing memory?
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 size: 2000000 Torch tensor type: torch.int16 Torch tensor size: 2000000
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.server.js/ts is strictly for server side logic like authentication and database calls.
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 PASS ? use Tk; use Tk::Table; use Tk::NoteBook; use Tk::Optionmenu; my $data = { 'Jan' => { 'id' => 1, 'product' => 'new'} , 'Feb' => {'id'=>2, 'product'=> 'latest'} }; &tk_gui(); sub tk_gui { my $mw = MainWindow->new; $mw->geometry("500x500"); my $f = $mw->Frame()->pack(-side=>'top'); my ($var, $tvar); my $opt = $f->Optionmenu( -options => [[jan =>1], [feb =>2]], -command => sub { my @nums = @_; #HOW TO PASS ? &show_table_data($nums[0], $table) }, -variable => \$var, -textvariable => \$tvar, )->pack(-side => 'left', -anchor => 'n',); my $f2 = $mw->Frame()->pack(-side=>'bottom'); my $table = $f2->Table( -columns => 2); my @col = qw(id product); foreach my $c (0 .. 1) { if ($c) { my $t = $table->Label(-text => 'product'); $table->put(0, $c, $t); } else { my $t = $table->Label(-text => 'id'); $table->put(0, $c, $t); } } $table->pack(); MainLoop; } sub show_table_data { my $num = shift; my $table = shift; }
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; use warnings; use Tk; use Tk::Table; use Tk::NoteBook; use Tk::Optionmenu; { tk_gui(); } sub tk_gui { my $mw = MainWindow->new; $mw->geometry("500x500"); my $f = $mw->Frame()->pack(-side=>'top'); my ($var, $tvar); my $table; # <-- declare the variable here.. my $opt = $f->Optionmenu( -options => [[jan =>1], [feb =>2]], -command => sub { my @nums = @_; show_table_data($nums[0], $table); }, -variable => \$var, -textvariable => \$tvar, )->pack(-side => 'left', -anchor => 'n',); my $f2 = $mw->Frame()->pack(-side=>'bottom'); $table = $f2->Table( -columns => 2); foreach my $c (0 .. 1) { if ($c) { my $t = $table->Label(-text => 'product'); $table->put(0, $c, $t); } else { my $t = $table->Label(-text => 'id'); $table->put(0, $c, $t); } } $table->pack(); MainLoop; } sub show_table_data { my $num = shift; my $table = shift; return if !defined $table; say "Num = $num"; say "table = $table"; }
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" android:layout_height="match_parent" android:background="@drawable/app_background_01" tools:context=".FullscreenActivity"> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/topbar" android:layout_width="match_parent" android:layout_height="50dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <ImageView android:id="@+id/actionDrawer" android:layout_width="28dp" android:layout_height="28dp" android:layout_marginStart="16dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/ic_hamburger" /> <ImageView android:id="@+id/actionHome" android:layout_width="28dp" android:layout_height="28dp" android:layout_marginRight="16dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/ic_home" /> </androidx.constraintlayout.widget.ConstraintLayout> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/containerFragments" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/topbar"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:fontFamily="sans-serif-condensed" android:text="This is Home page" android:textAlignment="center" android:textColor="#FFFFFF" android:textSize="40sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> </TextView> </androidx.constraintlayout.widget.ConstraintLayout> <androidx.drawerlayout.widget.DrawerLayout android:id="@+id/drawer" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="50dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/topbar"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" android:background="@drawable/app_background_01" android:orientation="vertical" android:layout_gravity="left"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"> <ImageView android:id="@+id/imageView2" android:layout_width="50dp" android:layout_height="50dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="?android:attr/textSelectHandle" /> </androidx.constraintlayout.widget.ConstraintLayout> </LinearLayout> </androidx.drawerlayout.widget.DrawerLayout> </androidx.constraintlayout.widget.ConstraintLayout> kotlin code package com.example.testdrawer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Gravity import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.GravityCompat import com.example.testdrawer.databinding.ActivityFullscreenBinding class FullscreenActivity : AppCompatActivity() { private lateinit var binding: ActivityFullscreenBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityFullscreenBinding.inflate(layoutInflater) setContentView(binding.root) setListeners() } private fun setListeners() { binding.actionDrawer.setOnClickListener { if (binding.drawer.isDrawerOpen(GravityCompat.START)) { binding.drawer.closeDrawer(Gravity.LEFT) } else { binding.drawer.openDrawer(GravityCompat.START) } } } } Behaviour Required 1- Home screen comes in start 2- When click on hamburger icon the drawerlayout should come with full height and width also containing hamrbuger and home icons. 3- When click on hamburger icon the drawerlayout should close and the home screen should come. Issues 1- drawerlayout is not full width and required functionality is not achievable. The below is the homescreen Want the drawerlayout to fully occupy the screen as in the design its having full background and icons on top. When I tried Drawerlayout constraint in xml toptotopof parents I was not able to click on hamburger icon
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 is based on the default theme, replacing all the colors with k (for normal black) or K (for bold black). Save this in ~/.config/bpython/light.theme and then set color_scheme = light in ~/.config/bpython/config.
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, "")): foo bar (blah) foo bar (blah) blah (blah) I don't like to match: some (blah) data some date following (1920-1921). I have the following regex: \s*(.+?)\s*$. It tends to match too much: some data (..) match (match) some data (1920-1977)
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 before the end of line. Try it on regex101.com. The above regex will not match: parentheses with no content () years with more than 4 digits (1234-56789) or less than 4 (123-4567) nested ((brackets)) mismatched (brackets
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 Scrollbar is moved
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 600ft 600 38.5910000 481042727208 1685770037 500ft 500 38.6960000 481042727207 1685770037 400ft 400 38.6570000 481042727206 1685770037 300ft 300 38.9040000 481042727205 1685770037 200ft 200 39.3400000 481042727204 1685770037 150ft 150 39.5030000 481042727203 1685770037 100ft 100 40.2140000 481042727202 1685770037 80ft 80 41.3850000 481042727201 1685770037 60ft 60 44.1530000 481042727200 1685770037 50ft 50 46.2590000 481042727199 1685770037 40ft 40 47.2420000 481042727198 1685770037 30ft 30 49.7390000 481042727197 1685770037 20ft 20 55.3010000 481042727196 1685770037 10ft 10 61.8840000 481041534602 1685769380 600ft 600 38.5910000 481041534601 1685769380 500ft 500 38.6400000 481041534600 1685769380 400ft 400 38.7130000 481041534599 1685769380 300ft 300 38.9040000 481041534598 1685769380 200ft 200 39.2840000 481041534597 1685769380 150ft 150 39.5600000 481041534596 1685769380 100ft 100 40.2700000 481041534595 1685769380 80ft 80 41.4410000 481041534594 1685769380 60ft 60 44.3220000 481041534593 1685769380 50ft 50 46.3150000 481041534592 1685769380 40ft 40 47.3540000 481041534591 1685769380 30ft 30 49.9070000 481041534590 1685769380 20ft 20 56.1450000 481041534589 1685769380 10ft 10 62.5030000 Hoping to get output in this format: unixtimestamp depth10 depth20 depth30 ... 1685769380 62.5 56.14 49.91 ... 1685770037 61.8 55.3 49.74 ... ... ... ... ... ... I have inherited this table format. I have tried using distinct but can't find a way to have a distinct timestamp and depth. Thinking I may have to dump the data and use python to read and reorganize in a one row per timestamp. Is there a straightforward SQL query to get the data to list in one row per timestamp with each depth temperature as columns? I want to output the data in csv format where each row is one timestamp. Also 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. Thanks in advance.
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 having pivoted data make them more consumable for your needs, you should go for it. Just to give you an example, if you had to get depth values when the temperature went higher than 40, attempting to do it with the output you're requiring, would likely force you to go through unpivoting, while it would be straight simple if you used your original table. Conversely, if you need to do some kind of reporting, and observe only temperatures for specific depths (say depth 10 and depth 100), using the input table would require you a filtering, while using the output table can give you that instantly. What you're looking for is called "pivot", and allows you to change rows into columns. Since in the output there are 14 columns dedicated to depth (from the data I assume they're always 14 for each timestamp), you should expect to put 14 computed fields inside the SELECT statement, like: SELECT unixtimestamp, ... AS depth10, ... AS depth20, ... AS depth30, ... AS depth40, ... ... AS depth600 FROM water_temp Then you realize that you actually need to select your temperatures, but only when the depth corresponds to your selected depth. Something you can do with a CASE expression (or an IF, if we want): SELECT unixtimestamp, CASE WHEN depth = 10 THEN temperature END AS depth10, CASE WHEN depth = 20 THEN temperature END AS depth20, CASE WHEN depth = 30 THEN temperature END AS depth30, CASE WHEN depth = 40 THEN temperature END AS depth40, ... CASE WHEN depth = 600 THEN temperature END AS depth600 FROM water_temp And when you attempt to do that, you realize you will have a kind of squared matrix, for which unique timestamp has now 14 records, each of which with one non-null value (on the corresponding depth column). Since you wanted one record only, for each of your timestamps, one of the best options for reducing the size of tables is aggregation (as long as it "aggregates" data). You need to aggregate by grouping on your timestamps (because you want one record for each timestamp), and using an aggregate function that can compress one non-null value with other null values, and that's either MIN or MAX. Your code then becomes: SELECT unixtimestamp, MAX(CASE WHEN depth = 10 THEN temperature END) AS depth10, MAX(CASE WHEN depth = 20 THEN temperature END) AS depth20, MAX(CASE WHEN depth = 30 THEN temperature END) AS depth30, MAX(CASE WHEN depth = 40 THEN temperature END) AS depth40, ... MAX(CASE WHEN depth = 600 THEN temperature END) AS depth600 FROM water_temp GROUP BY unixtimestamp which gives you exactly what you were looking for.
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_count,media_count,name} But when I operate following code on Python file in Jupyter lab import requests import pandas as pd pd.set_option('display.max_rows', None) # information business_account_id = "same as IgUserId" token = "one that generated on Graph Api Explorer" fields = "followers_count,media_count,name" version = "v17.0" username = "bluebottle" def user_info(version, igUserId,token,username,fields): request_url = "https://graph.facebook.com/{version}/{igUserId}?fields={fields}&access_token={access-token}" response = requests.get(request_url) return response.json() print(user_info(business_account_id,token,username,fields,version)) I get following error {'error': {'message': 'Invalid OAuth access token - Cannot parse access token', 'type': 'OAuthException', 'code': 190, 'fbtrace_id': 'Just for case I'm deleteing this bit'}} To avoid my misunderstanding to confuse anybody, following is picture of Graph Api Explorer where I got Access Token which I just copy and pasted from top black shadowed bit.
"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) # information business_account_id = "YOUR_IG_USER_ID" access_token = "YOUR_ACCESS_TOKEN" fields = "followers_count,media_count,name" version = "v17.0" username = "bluebottle" def user_info(version, igUserId,access_token,username,fields): request_url = f"https://graph.facebook.com/{version}/{igUserId}?fields=business_discovery.username({username}){{{fields}}}&access_token={access_token}" print(request_url); response = requests.get(request_url) return response.json() print(user_info(version,business_account_id,access_token,username,fields)) Output:- {'business_discovery': {'followers_count': 442462, 'media_count': 2076, 'name': 'Blue Bottle Coffee', 'id': '17841401441775531'}, 'id': '17841448XXXXX'} I used Python 3.10.6 to test this script. Hope this helps.
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],'Percentage': [88, 92, 95, 70,55,47]} df = pd.DataFrame(data, columns=['Age', 'Stream', 'Percentage']) print("Given Dataframe :n", df) def modname(frame): frame=frame.rename(columns={'Age':'aa','Stream':'bb','Percentage':'cc'}) return frame df=df.apply(modname) print(df) ` I greatly appreciate your help i tried the same code without UDF and it works
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. Alternatively: Download and install Visual Assist: https://www.wholetomato.com/ Highlight code to be commented. Shift + 8 or * on the keypad. Profit.
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. Code: library(partykit) cf <- cforest(Species ~., data=iris) tr <- gettree(cf, tree=1) plot(tr) Errors in console: Error in Summary.factor(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, : ‘min’ not meaningful for factors I am expecting plots for individual trees in the cforest() result.
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: ..$ (fitted) : int [1:150] 2 2 2 2 2 2 2 2 2 2 ... ..$ (weights) : num [1:150] 1 1 1 1 1 1 1 1 1 1 ... ..$ (response): Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ... but for a tree from cforest() result, which cannot be plotted: $ fitted:'data.frame': 150 obs. of 4 variables: ..$ idx : int [1:150] 1 2 3 4 5 6 7 8 9 10 ... ..$ (response): Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ... ..$ (weights) : int [1:150] 0 1 1 1 1 1 1 1 0 0 ... ..$ (fitted) : int [1:150] 2 2 2 2 2 2 2 2 2 2 ... Please note that the variables (response), (weights) and (fitted) are in different columns in the data structure of "fitted" dataframe in these two trees. Therefore, I use the following manipulation to adjust the "fitted" dataframe structure in the cforest tree object, and plotting is successful: library(partykit) cf <- cforest(Species ~., data=iris) tr <- gettree(cf, tree=1) nfitted <- data.frame(tr$fitted$`(fitted)`,tr$fitted$`(weights)`,tr$fitted$`(response)`) colnames(nfitted) <- c('(fitted)', '(weights)', '(response)') tr$fitted <- nfitted plot(tr) Hope this will help those who encounter the same problem with the plotting of trees from cforest() in the partykit package.
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: id | name | next_id 1 | Test01 | 2 2 | Test02 | 3 3 | Test03 | 6 6 | Test06 | 4 4 | Test04 | 5 5 | Test05 | null 7 | Test07 | null It is necessary to read the next_id field for each record, find this record and display it after the existing one. After all, this field can change, so sorting in ascending order will not work and other tricks. So far, there are no ideas how to do it gracefully. Except for loops and temporary tables.
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', NULL)), cte AS ( SELECT t.id, t.name, t.next_id, t.id AS root_id, 1 AS depth FROM t WHERE NOT EXISTS (SELECT * FROM t t2 WHERE t.id = t2.next_id) UNION ALL SELECT t.id, t.name, t.next_id, cte.root_id, cte.depth + 1 AS depth FROM t JOIN cte ON (t.id = cte.next_id)) SELECT cte.id, cte.name, cte.next_id FROM cte ORDER BY cte.root_id, cte.depth, cte.id; This query assumes that there are no cycles in the path defined by next_id. The query first initializes the recursive CTE by identifying the rows that are not referenced by any next_id, memoizing the root id, and initializing depth. The recursive portion of the CTE finds the rows referenced by these root rows and incrementing depth. The recursive part repeats using the rows discovered by the prior iteration until no rows are found. The final step sorts by root_id, depth, and id. Including id in the sort is done to create a deterministic order for the case of ids with multiple next_ids (a tree structure instead of linear paths): it can be left out if only linear paths are allowed.
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 difference which gives the negative value. If I close the port range in parenthesis it fails because it requires number format. What is the appropriate way to create ingress rule for a large range of ports? resource "aws_security_group" "sg_nx" { name = "sg_nx" vpc_id = aws_vpc.vpc.id ingress { from_port = 4000 to_port = 4000 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } ingress { from_port = 4011-4999 to_port = 4011-4999 protocol = "udp" cidr_blocks = ["0.0.0.0/0"] } } Using list does not work either. I know Terraform allows dynamicly generated resources, how to implement it in this case?
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#from_port
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. However, I am using volk to load Vulkan symbols. This library loads global functions based on the extensions enabled for a Vulkan instance, and problems arise when attempting to create multiple instances, potentially with different layers/extensions enabled. For example, if I create an instance with debug utils enabled, the associated functions like vkCreateDebugUtilsMessengerEXT are loaded as expected. If I then create another instance without debug utils enabled, these functions seem to be unloaded, which sets their function pointers to NULL, causing a segfault when the instance that enabled them attempts to call them. At the end of the day, supporting multiple Vulkan instances seems to be introducing a lot of issues - is there perhaps a better way of abstracting this design, or should I just limit the user to creating one Vulkan renderer (and therefore one instance) per program?
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 other some_instance objects or those derived from them (like VkDevices). Note that Volk doesn't hand you function pointers; it initializes global function pointers. Therefore, if you call volkLoadInstance, all of the global functions it hands you are bound to that instance. You can call it again for a different instance, but you're just changing which global pointers you're talking about. That is, Volk is specifically designed to be used with a single instance. It has functionality for easily using it with multiple devices without dynamic dispatch logic (volkLoadDeviceTable returns a table of function pointers specific to a device), but it has no similar construct for instances. As such, trying to allow each "renderer" to have its own VkInstance object is going to run into problems. volkLoadInstance is not a fast function. The reason Volk is written this way is because creating multiple instances like this is generally... not useful. Vulkan instance extensions tend to be about the interaction between your code and the operating system. Consider VK_KHR_surface. This is an instance extension that acts as glue between your program and an OS window. If you want to render into a window, you need this instance extension. But the glue between the OS window (represented by a VkSurfaceKHR) and a Vulkan device is governed by VK_KHR_swapchain, which is a device extension. A device created from an instance doesn't have to use that extension. If it doesn't, then it won't be able to render into a surface. But it doesn't harm the device in any way to have been created from an instance that uses VK_KHR_surface. So you should get your "renderers" together and set down a list of instance extensions that they could rely on, and then require them for the one VkInstance that they all share. Broadly speaking, separate VkInstance objects exist primarily for DLLs, where there is a hard barrier between the global state of two pieces of code that happen to exist in the same program. One DLL can use a Vulkan instance, while the main program uses a separate one. The separate instances, and attendant global instance function pointers, make it easy for these two pieces of code to co-exist without stomping on each other.
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: ZeusPrefManager){ var fPCallback: ValueCallback<Array<Uri>>? by remember { mutableStateOf(null) } val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetMultipleContents() ) { fPCallback!!.onReceiveValue(it.toTypedArray()) } var backEnabled by remember { mutableStateOf(false) } var webView: WebView? = null var gameStat by remember { mutableStateOf("") } LaunchedEffect(key1 = "goStat"){ val destination = zeusPrefManager.zeusStatDataFlow.first() gameStat = destination } if (gameStat != ""){ AndroidView(factory = { context -> WebView(context).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) settings.javaScriptEnabled = true settings.domStorageEnabled = true settings.loadWithOverviewMode = true settings.userAgentString = ZeusConstan.converter007(settings.userAgentString) webViewClient = object: WebViewClient(){ override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) { backEnabled = view.canGoBack() } override fun onPageFinished(view: WebView?, url: String?) { super.onPageFinished(view, url) } } webChromeClient = object : WebChromeClient(){ override fun onShowFileChooser( webView: WebView?, filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: FileChooserParams? ): Boolean { if (fPCallback != null){ fPCallback!!.onReceiveValue(null) } fPCallback = filePathCallback launcher.launch("image/*") return true } } loadUrl(gameStat) } }, update = { webView = it }) BackHandler(enabled = backEnabled) { if (webView!!.canGoBack()){ webView?.goBack() } else { //Do nothing but webView!!.canGoBack() is always true, and close the app } } } } I didn't override onBackPressed() in Activity. I need to avoid closing application when I press button back
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 { onBackPressed() } } } In your activity, override the onBackPressed() method and pass it to the StatScreen composable function: override fun onBackPressed() { // Handle the back button press here }
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 solving that issue? Many thanks in advance function happendCSV() { const folder = DriveApp.getFolderById("ID_Folder"); const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet_Name"); const files = folder.getFiles(); while (files.hasNext()) { let file = files.next(); //let fn = file.getName(); let fileID = file.getId(); let fileType = file.getMimeType(); if (fileType === "text/csv") { let csvData = Utilities.parseCsv(file.getBlob().getDataAsString(), ","); sheet.getRange(sheet.getLastRow +1, 1, csvData.length, csvData[0].length).setValues(csvData); } } }
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 your situation, I thought that getFilesByType might be useful. When setValues is used outside of the loop, the process cost becomes low a little. When these points are reflected in your script, it becomes as follows. Modified script: function happendCSV() { const folder = DriveApp.getFolderById("ID_Folder"); const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet_Name"); const files = folder.getFilesByType(MimeType.CSV); let values = []; while (files.hasNext()) { let file = files.next(); let csvData = Utilities.parseCsv(file.getBlob().getDataAsString(), ","); values = [...values, ...csvData]; console.log(`Now: ${file.getName()}`); // For confirming the current processing file. } sheet.getRange(sheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values); } Note: If your CSV data is large, Sheets API might be suitable instead of Spreadsheet service (SpreadsheetApp). References: getFilesByType(mimeType) getLastRow()
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.IsRecurring and if true I can get some parameters from recurrencePattern. However it seems to work only for appointments that has been set in this specific month with recurring parameter. If appointment with recurrence has been set earlier, then current code does not seem to work. Is there some way to get just all the appointments from specific month? private void GetAllItems(DateTime startDate, DateTime endDate) { Outlook.Application outlookApp = new Outlook.Application(); Outlook.NameSpace outlookNamespace = outlookApp.GetNamespace("MAPI"); Outlook.MAPIFolder calendarFolder = outlookNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar); Outlook.Items calendarItems = calendarFolder.Items; string restriction = $"[Start] >= '{startDate.ToShortDateString()}' AND [Start] <= '{endDate.ToShortDateString()}'"; Outlook.Items filteredItems = calendarItems.Restrict(restriction); foreach (Outlook.AppointmentItem appointment in filteredItems) { DataModel dataModel = new DataModel { Subject = appointment.Subject, }; this.Data.Add(dataModel); if (appointment.IsRecurring) { Outlook.RecurrencePattern recurrencePattern = appointment.GetRecurrencePattern(); DataModel recurringDataModel = new DataModel { Subject = appointment.Subject, }; this.Data.Add(recurringDataModel); } } }
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 calendarItems = calendarFolder.Items; calendarItems.Sort("[Start]"); calendarItems.IncludeRecurrences = true; string restriction = $"[Start] >= '{startDate.ToShortDateString()}' AND [Start] <= '{endDate.ToShortDateString()}'"; Outlook.Items filteredItems = calendarItems.Restrict(restriction);
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: class Custom; class Program : public QMainWindow { Q_OBJECT friend class Custom; public: Program(QWidget *parent = nullptr); ~Program(); private: Ui::ProgramClass ui; } Program.cpp: #include "Program.h" #include "Custom.h" Program::Program(QWidget *parent) : QMainWindow(parent) { ui.setupUi Custom custom = Custom(this); } Custom.h: #include "Program.h" class Custom : public QObject { Q_OBJECT public: Custom(Program* program); ~Custom(); public slots: void foo(); private: Program* m_program; } and finally Custom.cpp: #include "Custom.h" #include "Program.h" Custom::Custom(Program* program) { m_program = program; /* Here's the main problem */ QObject::connect(m_program->ui.TestButton, &QPushButton::clicked, m_program, &Custom::foo); } /* Here just changing text of the button and set flat true or false every time button is clicked */ void Custom::foo() { QPushButton* button = m_program->ui.TestButton; button->setFlat(!button->isFlat()); button->setText(button->isFlat() ? "If you see the text changing when clicking the button, it means test is working correctly" : "Text changed"); } The main part is in the Custom constructor, where I typed connect function. Error: cannot convert argument 3 from 'Program *' to 'const Custom *. So, a pointer to receiver and to function foo must be the same classes. So I tried this: QObject::connect(m_program->ui.TestButton, &QPushButton::clicked, this, &Custom::foo); No error, but there is actually no connection to the main program and when I click the button - nothing changing. The only working variants are: make foo function as a method of Program class, BUT I don't want to make Program class have a lot of functions which are actually should be methods of separated classes. And if I want to modify some other fields of these separated classes, this variant won't work; type lambda-function inside QObject::connection, BUT I have some big functions, and I need to call some of them as a slot in QObject::connect oftently. So, how can I make a proper connection to the whole program but leave foo function as the method of Custom class?
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 you want access it later. The constructor of Custom must be: Custom::Custom(Program* program) : QObject(program) { QObject::connect( m_program->ui.TestButton, &QPushButton::clicked, this, &Custom::foo ); } This constructor passes pointer to constructor of QObject, which registers Custom as a "child" of provided object, a Program in our case. In Qt terms Program will be responsible for Custom instance's destruction. Is what you meant to do? To connect a button to an instance of Custom? Frankly, using m_program->ui.TestButton here invades Programs personal space and relies on implementation, but it's an offtopic here. But let's make a step aside and take a look why actually what you did, even if that was utterly wrong, didn't work? Let's put aside functions and slots. What you'd do if had to do this with "normal" classes and to call a method foo() of class B using a pointer of distinct class A? Right, class B should be derived from A and foo() should be a virtual method first declared in A. THis allows a kind of type erasure where a pointer or reference to B can be passed as pointer to A. Functions can be passed by pointer too, but not if they are members of a class. For that a special kind of pointer exist. #include <iostream> class A { public: virtual void foo() = 0; }; class B : public A { public: virtual void foo() { std::cout << "Hello from foo()!\n"; } }; // A registering\calling class class C { public: void connect(A* p) { cptr = p; f_ptr = &A::foo; } void call() { (cptr->*f_ptr)(); } private: A *cptr; void (A::*f_ptr)(); }; int main() { B b; C c; c.connect(&b); c.call(); } Now, you must understand what C::connect does there: it saves value of pointer to the object A* p and a pointer to the member. The expression &A::foo, a pointer to a member of A, is legal and correct for overridden &B::foo if we will use it with a pointer to B. The pointer-to-member could be made a parameter of C::connect like in Qt, but to make it work with any member function we need to create a template and another level of type erasure to save those values. I left it out for brevity. It's almost same what happens with Qt signal\slot system, at least if you use direct connection and new connect syntax. You need a class instance in order to call its member, that's why connect got such syntax. Even if you had succeed in performing connection, you would have invoked an Undefined Behavior by clicking connected button. Thankfully, Qt handles it gracefully by disconnecting destroyed objects, therefore nothing actually happens. That's why all classes that use signal\slot have to be descendants of QObject. Signals and slots are just functions. The difference between them is that meta object compiler generates an implementation for signals. For type erasure to work, you can do either of those: have to pass a pointer of type QObject* to an instance of Custom and cast it to class Custom in order for QObject::connect to work. The cast is unnecessary if signal or virtual slot is declared in QObject. Or you have to pass a pointer to some base class which already got the slot void foo() declared. You can declare a slot as virtual and you don't need to do so for signals. public slots: virtual void foo(); // can be pure in abstract class It appears to me that to have a QMainWindow as a base class is a bad idea, you'd needs some third class. In simplest cases it creates too verbose code and that's why another overload was introduced, which allows a lambda or functor object.
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, ...rest }) => ( <Route {...rest} render={(props) => <Component {...props} />} /> ); export default PublicRoute import { Route, Redirect } from 'react-router-dom'; const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => ( <Route {...rest} render={(props) => isAuthenticated ? ( <Component {...props} /> ) : ( <Redirect to="/" /> ) } /> ); export default PrivateRoute And my app.js import { Routes } from "react-router-dom" import PublicRoute from "./components/PublicRoute" const App = () => { return ( <> <Routes> <PublicRoute exact path="/" component={Com} /> </Routes> </> ) } export default App const Com=()=>( <> <h1>Hi</h1> </> ) And currently I am getting this error not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment> at invariant (history.ts:48 Given I am returning a Route Component I can't quite understand why this error pops up. Eventually I want a way to perform checks and keep code clean, If there's another efficient way please let me know!
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 "react-router-dom"; import PublicRoute from "./PublicRoute"; const App = () => { return ( <BrowserRouter> <Routes> <Route exact path="/" element={ <PublicRoute component={Com} msg={"there"} person={"sandy"} /> } /> </Routes> </BrowserRouter> ); }; export default App; const Com = ({ msg, person }) => ( <> <h1> Hi {msg} {person} </h1> </> );
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, datasets: [{ label: 'Dataset 1', data: datas.value, backgroundColor: datas.colour }], others: datas.others }, options: { hover: { mode:'index' }, legend: { display: true, position: "right", "labels": { "fontSize": 20, } }, tooltips: { "fontSize": 20, bodyFont:20, callbacks: { label: function (tooltipItem, data) { let label = data.labels[tooltipItem.index]; let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]; let otherdata = data.others[tooltipItem.index]; return ' ' + label + ': ' + value + '% ' + otherdata; } } }, hover: { mode: 'index', "label": { "fontSize": 20, } } } }) i tried hover: { mode: 'index', "label": { "fontSize": 20, } } but it didn't work this is how it looks right now
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, { type: 'pie', data: { labels: datas.labels, datasets: [{ label: 'Dataset 1', data: datas.value, backgroundColor: datas.colour }], others: datas.others }, options: { hover: { mode: 'index' }, legend: { display: true, position: "right", "labels": { "fontSize": 20, } }, tooltips: { // "fontSize": 20, bodyFont: 20, callbacks: { label: function (tooltipItem, data) { let label=data.labels[tooltipItem.index]; let value=data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]; let otherdata=data.others[tooltipItem.index]; return ' '+label+': '+value+'% '+otherdata; } } }, hover: { mode: 'index', "label": { "fontSize": 20, } }, plugins: { tooltip: { titleFont: { size: 20 }, bodyFont: { size: 20 } } } } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script> <canvas id="mychart"></canvas>
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 actually true when element is checked. } } return checked;//Is actually false when element is checked. }
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), Insert_date date ); INSERT INTO daily_account_data VALUES('A01R11', 'Gene Graham', 'PT12', 'TRUE', 'FALSE', '2023-06-01'); INSERT INTO daily_account_data VALUES('A01R16', 'Molly Ringwald', 'PT15', 'TRUE', 'TRUE', '2023-06-01'); INSERT INTO daily_account_data VALUES('A01R19', 'John Doe', 'PT24', 'FALSE','TRUE', '2023-06-01'); INSERT INTO daily_account_data VALUES('A01R34', 'Jane Doe', 'PT26', 'TRUE', 'FALSE', '2023-06-01'); INSERT INTO daily_account_data VALUES('A01R11', 'Gene Wilder', 'PT12', 'TRUE', 'FALSE', '2023-06-02'); INSERT INTO daily_account_data VALUES('A01R16', 'Molly Ringwald', 'PT15', 'TRUE', 'TRUE', '2023-06-02'); INSERT INTO daily_account_data VALUES('A01R19', 'John Doe', 'PT24', 'TRUE', 'TRUE', '2023-06-02'); INSERT INTO daily_account_data VALUES('A01R34', 'Jane Doe', 'PT26', 'TRUE', 'FALSE', '2023-06-02'); I have the query to find the difference in the data of the 2 days. SELECT id, name, DS_DW_Id, flag_1, flag_2 FROM daily_account_data WHERE Insert_date = '2023-06-02' EXCEPT SELECT id, name, DS_DW_Id, flag_1, flag_2 FROM daily_account_data WHERE Insert_date = '2023-06-01'; But I can't figure out to get the data in the pseudo column. The last column is changed data. On 1st June data the name of the id A01R11 is Gene Graham and on 2nd it is Gene Wilder. The pseudo column should display "Name change". Similarly for id A01R19 (John Doe) the value for flag_1 has changed to TRUE. The pseudo column should display "flag_1 change". The output should look like : id Name DS_DW_Id flag_1 flag_2 Data Change A01R11 Gene Wilder PT12 TRUE FALSE Name Change A01R19 John Doe PT24 TRUE TRUE flag_1 Change
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') +iif(a.DS_DW_Id=b.DS_DW_Id ,'',' DS_DW_Id Change') +iif(a.flag_1=b.flag_1 ,'',' flag_1 Change') +iif(a.flag_2=b.flag_2 ,'',' flag_2 Change') AS [Data Change] from daily_account_data a inner join( select * from daily_account_data b )b on a.id=b.id and DATEADD(day,-1, b.Insert_date)=a.Insert_date where a.Name<>b.Name or a.DS_DW_Id<>b.DS_DW_Id or a.flag_1<>b.flag_1 or a.flag_2<>b.flag_2
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 FileNAme <> "" Then FileNAme = Me.TextBox_5 With ws Set Img = .Pictures.Insert(FileNAme) With Img .Placement = xlMove .Width = 150 .LockAspectRatio = msoTrue .Left = ws.Cells(lr, "D").Left .Top = ws.Cells(lr, "D").Top End With End With End If
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 + ".") else answer == (no) print("Sorry to hear that\nPerhaps we could use other names?") I want to give to print() informations in my program, depending from user choice. I am very fresh so pls be forgiving.
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' #but since you only have two choices consider this a shortcut print("Sorry to hear that") print("Perhaps we could use other names?") ifelse() ps. you can format the print statement so that the user input 'entername' can be printed along side it [ you can also do this w/o using def fcns]
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 \0's): 5danny5000.00 4lena2500.50 one item is "4lena2500.50" for example. in my code, the while loop does not stops. what can I do to repair the problem? thanks! int count_items(FILE* file) { int count=0; int curr_name_len; while (!feof(file)) { fread(&curr_name_len, sizeof(int), 1, file); fseek(file, (curr_name_len * sizeof(char)) + sizeof(float), SEEK_CUR); count++; } rewind(file); return count; }
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 you intend to write things inbetween. Thus the eof-indicator is set after the fread-call, but is cleared after your fseek-call. So this should work: int count_items(FILE* file) { int count=0; int curr_name_len; for (fread(&curr_name_len, sizeof(int), 1, file); !feof(file); fread(&curr_name_len, sizeof(int), 1, file)) { fseek(file, (curr_name_len*sizeof(char))+sizeof(float), SEEK_CUR); count++; } rewind(file); return count; } or if you don't like that style: int count_items(FILE* file) { int count=0; int curr_name_len; fread(&curr_name_len, sizeof(int), 1, file); while (!feof(file)) { fseek(file, (curr_name_len*sizeof(char))+sizeof(float), SEEK_CUR); count++; fread(&curr_name_len, sizeof(int), 1, file); } rewind(file); return count; } or less structured, but more clearly: int count_items(FILE* file) { int count=0; int curr_name_len; while (true); { if (sizeof(int) != fread(&curr_name_len, sizeof(int), 1, file))) { break; } fseek(file, (curr_name_len*sizeof(char))+sizeof(float), SEEK_CUR); count++; } if (feof(file)) { rewind(file); return count; } if (ferror(file)) { /* error handling */ } else { /* fatal error handling */ } }
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 this issue. Here's my codepen with the problem <div id="all"> <div class="move txtbox"> <div class="topper">test test</div> <span id="test">test test etst test test test</span> </div> <div class="move txtbox"> <div class="topper">test test</div> <span id="test">test test etst test test test</span> </div> </div> <script src="move.js"></script> * { box-sizing: border-box; font-family: Arial, Helvetica, sans-serif; line-height: 1.1; margin: 0; } #all { position: relative; margin: 0 auto; width: 50%; height: 100vh; } .move { cursor: move; position: absolute; } .txtbox, .topper { background-color: lightgrey; } .txtbox { min-height: 70px; max-width: 250px; } .topper { font-size: .625em; border-bottom: 1px solid black; padding: 2px; } const els = document.querySelectorAll(".move"); els.forEach((name) => { dragElement(name); }); function dragElement(elmnt) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; elmnt.onmousedown = dragMouseDown; function dragMouseDown(e) { e = e || window.event; e.preventDefault(); // get the mouse cursor position at startup: pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = closeDragElement; // call a function whenever the cursor moves: document.onmousemove = elementDrag; } function elementDrag(e) { e = e || window.event; e.preventDefault(); // calculate the new cursor position: pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // set the element's new position: elmnt.style.top = elmnt.offsetTop - pos2 + "px"; elmnt.style.left = elmnt.offsetLeft - pos1 + "px"; } function closeDragElement() { /* stop moving when mouse button is released:*/ document.onmouseup = null; document.onmousemove = null; } }
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 < 1000, SETF(GETREF(User.Count), User.Count + 1), "Loop complete!") + DEPENDSON(User.Count) This executes to User.Count = 41 (these pulses of 41 are consistent). Is performing this type of loop possible?
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 through the context menu Go to 1000 limit.
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> fixed4 col = tex2D(_MainTex, i.uv); UNITY_APPLY_FOG(i.fogCoord, col); return fixed4(col.rgb * _Color.rgb, col.a * i.uv.y * _Intensity); <ERROR 2> } At line 58 (first error) there are only two arguments requested by the fixed2 call. It's only calling for two things, which I would expect would be fulfilled by i.uv.x and i.uv.y, and that the addition shouldn't affect the number of arguments.. At line 62 (second error), from what I can tell it's returning the arguments R,G,B (multiplied by user input in the _Color variable), and A (multiplied by the Intensity variable), so that should be working, too, right? I should note that the second error is only thrown in the absence of line 58, and that these errors are thrown even if I change them to fixed1, fixed2, fixed3, or fixed4, just as experiments. Seeing as I've reproduced his code exactly, I can't begin to know where to look that would be causing this error. The whole code is as follows (I've commented out the problem lines, and it works fine without them, just without the desired functionality): Shader "Unlit/Shader_PortalVortex" { Properties { _MainTex ("Texture", 2D) = "white" {} _Color ("Color", Color) = (1, 1, 1, 1) _Intensity ("Intensity", Range(0, 1)) = 1 _Speed ("Speed", Range(0, 1)) = 0.5 } SubShader { Tags { "RenderType"="Opaque" "Queue"="Transparent+2"} ZTest Greater Blend SrcAlpha OneMinusSrcAlpha Cull Front LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag // make fog work #pragma multi_compile_fog #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; }; struct v2f { float2 uv : TEXCOORD0; UNITY_FOG_COORDS(1) float4 vertex : SV_POSITION; }; sampler2D _MainTex; float4 _MainTex_ST; float4 _Color; float4 _Intensity; float4 _Speed; v2f vert (appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.uv = TRANSFORM_TEX(v.uv, _MainTex); UNITY_TRANSFER_FOG(o,o.vertex); return o; } fixed4 frag (v2f i) : SV_Target { //fixed2 uvs = fixed2(i.uv.x, i.uv.y + (_Time.y * _Speed)); fixed4 col = tex2D(_MainTex, i.uv); UNITY_APPLY_FOG(i.fogCoord, col); //return fixed4(col.rgb * _Color.rgb, col.a * i.uv.y * _Intensity); } ENDCG } } } Thanks in advance.
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 = fixed2(i.uv.x, i.uv.y + (_Time.y * _Speed)); Same thing for line 62 and Intensity Cast: Try casting to native HLSL types such as ‘float2’. They are more precise than ‘fixed’, which only usually takes 11 bits or make Speed and Intensity float Debugging: Try removing ’Time’ and ‘Speed’ variables one by one and running each time to see if one of them makes the error or both. HLSL in Unity reference
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? private static async Task<string> ReadOne() { return await readerOne.ReadAsync(); } private static async Task<string> ReadTwo() { return await readerTwo.ReadAsync(); } private static async Task<string> ReadThree() { return await readerOne.ReadAsync(); } private static async Task<string> ReadCombinedAsync(string one, string two, string three) { return await reader.CombineAsync(one, two, three); } private static Task<string> ReadCombinedTask(string one, string two, string three) { return reader.CombineAsync(one, two, three); } private static async Task<string> DoItAwait() { string one = await ReadOne(); string two = await ReadOne(); string three = await ReadOne(); return await ReadCombinedAsync(one, two, three); } private static Task<string> DoItTask() { string one = await ReadOne(); string two = await ReadOne(); string three = await ReadOne(); return ReadCombinedAsync(one, two, three); } ps - I initially asked this question with a very sloppy example. Apologies for that.
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(); string three = await ReadOne(); // OK, because method is not async return ReadCombinedAsync(one, two, three); } Asynchronous methods with the async Task signature create a state machine under the hood, which then executes the asynchronous operation without blocking the calling thread. The calling method gets suspended while any Task that is being executed hasn't finished yet. Inside of an asynchronous method, you can only await other asynchronous Tasks or start Tasks without returning them. This is different when you have a synchronous method. There, the Task can actually be returned directly: public Task GetSomeTaskAsync() { return SomethingElseAsync(); } public async Task AwaitTaskAsync() { await GetSomeTaskAsync(); } This only is useful when you really can just pass along a Task without doing anything else related to that operation, so that you can save some resources, because the state machines of async Task create some overhead. The downside is that you'll lose some stack trace information when exceptions occur. You can find more useful information here: Why use async and return await, when you can return Task directly? Coming back to your scenario, your only two options here are: private static async Task<string> DoItTask() { string one = await ReadOne(); string two = await ReadOne(); string three = await ReadOne(); return await ReadCombinedAsync(one, two, three); } or private static async Task<Task<string>> DoItTask() { string one = await ReadOne(); string two = await ReadOne(); string three = await ReadOne(); return ReadCombinedAsync(one, two, three); } The latter actually returns a Task<string> as the result of the async Task. Note: I don't recommend doing this, it will be very confusing for other developers as this is unexpected. Tasks should be awaited whenever possible. If you return a Task, you'll lose parts of the call stack in the stack trace when an exception occurs and it makes debugging quite nasty if you do this in many places, especially when wrapping Tasks in Tasks like this.
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': 0.0, 'lane-max-speed': 50.0, 'lane-typology': 'real', 'lane-access-points': 6, 'lane-travel-time': 292.159682258003, 'lane-capacity': 7200.0, 'lane-cost': 0.8407885973127324, 'other-attributes': None, 'linestring-wkt': 'LINESTRING (434757.15286960197 4524762.33387408, 434267.30180536775 4525511.90463009, 436180.7891782945 4526762.385413274)'}}}), (1, 4, {'weight': {'weight': 0.6659876355281887, 'attributes': {'orig_id': 131, 'direction': 1, 'flip': 0, 'lane-length': 2496.129360921626, 'lane-width': 3.6, 'lane-shoulder': 0.0, 'lane-max-speed': 50.0, 'lane-typology': 'real', 'lan... That list is used to add weight and attributes to a MultiDiGraph previous mentioned: graph = ntx.MultiDiGraph(weight=None) graph.add_weighted_edges_from(edge_list) Trying to read the properties of a single edge(graph.edges.data()) I see this: (0, 1, {'weight': {'weight': 0.8407885973127324, 'attributes': {'orig_id': 1, 'direction': 1, 'flip': 0, 'lane-length': 3181.294317920477, 'lane-width': 3.6, 'lane-shoulder': 0.0, 'lane-max-speed': 50.0, 'lane-typology': 'real', 'lane-access-points': 6, 'lane-travel-time': 292.159682258003, 'lane-capacity': 7200.0, 'lane-cost': 0.8407885973127324, 'other-attributes': None, 'linestring-wkt': 'LINESTRING (434757.15286960197 4524762.33387408, 434267.30180536775 4525511.90463009, 436180.7891782945 4526762.385413274)'}}}) Every edge is builded in that way: [node[0], node[1], {'weight': weight, 'attributes': attributes}]. If I use this way: [node[0], node[1], weight], I see the right use of the weight but I need to use also the attributes. [(0, 1, {'weight': 0.8407885973127324}), (1, 4, {'weight': 0.6659876355281887}), (1, 46, {'weight': None}), (4, 5, {'weight': 1.2046936800705539}), (4, 6, {'weight': 0.4469496439663275}).... What is the correct way to manage in the same time both weight and attributes?
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_weighted_edgees_from([...], attr1=..., attr2=...) but you will find the same attribute values for all edges in the bunch. Instead, you can directly use the add_edge method in a for loop: for u, v, attr in [...]: graph.add_edge(u, v, **attr) which will add your edges with individual attributes.
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 delivery price based on the category (i.e. the columns A, B, C, D) and the weight of your parcel (i.e. the first column Weight) and for weights larger than 30, we have prices specified only for 30, 40, 50 etc. I also have PySpark dataframe requests, one row for each request by a customer. It includes columns product_weight, Type (the category that is in dhl_price). I want to create a new column in requests delivery_fee based on dhl_price dataframe. In particular, for each row in dhl_price column, I want to get a cell value in dhl_price where column is the one specified in column Type and row is the one specified in column product_weight of requests dataframe. So far I could code it in pandas: def get_dhl_fee(weight, type): if weight <= 30: price = dhl_price.loc[dhl_price["Weight"] == weight][type].values[0] else: price = dhl_price.loc[dhl_price["Weight"] >= weight].reset_index(drop = True).iloc[0][type].values[0] return price new_requests["dhl_fee"] = new_requests.apply(lambda x: get_dhl_fee(x["product_weight_g"], x["Type"]), axis = 1) How can I do the same with PySpark? I tried to use PySpark's UDF: # Define the UDF (User-Defined Function) for calculating DHL fee @fn.udf(returnType=DoubleType()) def get_dhl_fee(product_weight_g, calculate_way): broadcast_dhl_price = fn.broadcast(dhl_price) if weight <= 30: price = broadcast_dhl_price.filter(dhl_price["Weight"] == weight).select(calculate_way).first()[0] else: price = broadcast_dhl_price.filter(dhl_price["Weight"] >= weight).select(calculate_way).first()[0] return price # Register the UDF sc.udf.register("get_dhl_fee", get_dhl_fee) # Apply the UDF to calculate dhl_fee column requests = requests.withColumn("dhl_fee", get_dhl_fee(fn.col("product_weight"), fn.col("Type"))) but it returns error SPARK-5063: "It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers."
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| +------+-----+-----+-----+-----+ requests.show() +--------------+----+ |product_weight|type| +--------------+----+ | 1| B| | 2| D| | 4| A| | 30| A| | 100| C| +--------------+----+ Code Create a column of map type which maps type to corresponding price for a given weight c = dhl_price.columns[1:] dhl_price_map = dhl_price.select('Weight', F.map_from_arrays(F.array(*map(F.lit, c)), F.array(*c)).alias('price')) dhl_price_map.show() +------+--------------------+ |Weight| price| +------+--------------------+ | 1|{A -> 16.78, B ->...| | 2|{A -> 16.78, B ->...| | 3|{A -> 18.43, B ->...| | 4|{A -> 20.08, B ->...| | 30|{A -> 20.08, B ->...| | 40|{A -> 21.08, B ->...| +------+--------------------+ Assign a unique identifier for each row in the requests dataframe df = requests.withColumn('id_', F.monotonically_increasing_id()) df.show() +--------------+----+-----------+ |product_weight|type| id_| +--------------+----+-----------+ | 1| B| 8589934592| | 2| D|25769803776| | 4| A|34359738368| | 30| A|51539607552| | 100| C|60129542144| +--------------+----+-----------+ Join the two dataframes on weight condition then use the indexing to yank the value of price corresponding to type for each row df = df.join(dhl_price_map, on=df['product_weight'] >= dhl_price_map['Weight'], how='left') df = df.withColumn('dhl_fee', F.expr("price[type]")) df.show() +--------------+----+-----------+------+--------------------+-------+ |product_weight|type| id_|Weight| price|dhl_fee| +--------------+----+-----------+------+--------------------+-------+ | 1| B| 8589934592| 1|{A -> 16.78, B ->...| 17.05| | 2| D|25769803776| 1|{A -> 16.78, B ->...| 40.1| | 2| D|25769803776| 2|{A -> 16.78, B ->...| 58.07| | 4| A|34359738368| 1|{A -> 16.78, B ->...| 16.78| | 4| A|34359738368| 2|{A -> 16.78, B ->...| 16.78| | 4| A|34359738368| 3|{A -> 18.43, B ->...| 18.43| | 4| A|34359738368| 4|{A -> 20.08, B ->...| 20.08| | 30| A|51539607552| 1|{A -> 16.78, B ->...| 16.78| | 30| A|51539607552| 2|{A -> 16.78, B ->...| 16.78| | 30| A|51539607552| 3|{A -> 18.43, B ->...| 18.43| | 30| A|51539607552| 4|{A -> 20.08, B ->...| 20.08| | 30| A|51539607552| 30|{A -> 20.08, B ->...| 20.08| | 100| C|60129542144| 1|{A -> 16.78, B ->...| 20.23| | 100| C|60129542144| 2|{A -> 16.78, B ->...| 20.23| | 100| C|60129542144| 3|{A -> 18.43, B ->...| 25.0| | 100| C|60129542144| 4|{A -> 20.08, B ->...| 29.77| | 100| C|60129542144| 30|{A -> 20.08, B ->...| 29.77| | 100| C|60129542144| 40|{A -> 21.08, B ->...| 30.77| +--------------+----+-----------+------+--------------------+-------+ Create a window specification to rank the Weight per unique row in the requests, and then filter the rows to retain only those corresponding to the maximum weight in dhl_price. W = Window.partitionBy('id_').orderBy(F.desc('Weight')) df = df.withColumn('rank', F.dense_rank().over(W)).filter('rank == 1') +--------------+----+-----------+------+--------------------+-------+----+ |product_weight|type| id_|Weight| price|dhl_fee|rank| +--------------+----+-----------+------+--------------------+-------+----+ | 1| B| 8589934592| 1|{A -> 16.78, B ->...| 17.05| 1| | 2| D|25769803776| 2|{A -> 16.78, B ->...| 58.07| 1| | 4| A|34359738368| 4|{A -> 20.08, B ->...| 20.08| 1| | 30| A|51539607552| 30|{A -> 20.08, B ->...| 20.08| 1| | 100| C|60129542144| 40|{A -> 21.08, B ->...| 30.77| 1| +--------------+----+-----------+------+--------------------+-------+----+ Drop the extra columns df = df.select(*requests.columns, 'dhl_fee') df.show() +--------------+----+-------+ |product_weight|type|dhl_fee| +--------------+----+-------+ | 1| B| 17.05| | 2| D| 58.07| | 4| A| 20.08| | 30| A| 20.08| | 100| C| 30.77| +--------------+----+-------+
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 D:\***\***\backweb\backweb-api\target\classes\application-test.properties failed with MalformedInputException: Input length = 1 -> [Help 1] Compile output application-test.properties Full trace mvn compile -3 -I reviewed the application-test.properties file and I think that it's ok. -I cleanned the target folders and re compiled maven project. [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.propert ies to D:\***\***\backweb\backweb-api\target\classes\application-test.properties failed with MalformedInputException: Input length = 1 -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: 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 D:\***\***\backweb\backweb-api\target\classes\application-test.properties failed with MalformedInputException: Input length = 1 at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute2 (MojoExecutor.java:347) at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute (MojoExecutor.java:330) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:175) at org.apache.maven.lifecycle.internal.MojoExecutor.access$000 (MojoExecutor.java:76) at org.apache.maven.lifecycle.internal.MojoExecutor$1.run (MojoExecutor.java:163) at org.apache.maven.plugin.DefaultMojosExecutionStrategy.execute (DefaultMojosExecutionStrategy.java:39) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:160) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:105) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:73) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:53) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:118) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:260) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:172) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:100) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:821) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:270) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:568) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347) Caused by: org.apache.maven.plugin.MojoExecutionException: filtering D:\***\***\backweb\backweb-api\src\main\resources\application-test.properties to D:\***\***\backweb\backweb-api\target\classes\application-test.p roperties failed with MalformedInputException: Input length = 1 at org.apache.maven.plugins.resources.ResourcesMojo.execute (ResourcesMojo.java:362) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:126) at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute2 (MojoExecutor.java:342) at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute (MojoExecutor.java:330) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:175) at org.apache.maven.lifecycle.internal.MojoExecutor.access$000 (MojoExecutor.java:76) at org.apache.maven.lifecycle.internal.MojoExecutor$1.run (MojoExecutor.java:163) at org.apache.maven.plugin.DefaultMojosExecutionStrategy.execute (DefaultMojosExecutionStrategy.java:39) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:160) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:105) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:73) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:53) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:118) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:260) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:172) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:100) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:821) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:270) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:568) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347) Caused by: org.apache.maven.shared.filtering.MavenFilteringException: filtering D:\***\***\backweb\backweb-api\src\main\resources\application-test.properties to D:\***\***\backweb\backweb-api\target\classes\applica tion-test.properties failed with MalformedInputException: Input length = 1 at org.apache.maven.shared.filtering.DefaultMavenFileFilter.copyFile (DefaultMavenFileFilter.java:118) at org.apache.maven.shared.filtering.DefaultMavenResourcesFiltering.filterResources (DefaultMavenResourcesFiltering.java:277) at org.apache.maven.plugins.resources.ResourcesMojo.execute (ResourcesMojo.java:356) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:126) at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute2 (MojoExecutor.java:342) at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute (MojoExecutor.java:330) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:175) at org.apache.maven.lifecycle.internal.MojoExecutor.access$000 (MojoExecutor.java:76) at org.apache.maven.lifecycle.internal.MojoExecutor$1.run (MojoExecutor.java:163) at org.apache.maven.plugin.DefaultMojosExecutionStrategy.execute (DefaultMojosExecutionStrategy.java:39) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:160) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:105) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:73) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:53) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:118) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:260) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:172) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:100) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:821) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:270) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:568) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347) Caused by: java.nio.charset.MalformedInputException: Input length = 1 at java.nio.charset.CoderResult.throwException (CoderResult.java:274) at sun.nio.cs.StreamDecoder.implRead (StreamDecoder.java:326) at sun.nio.cs.StreamDecoder.read (StreamDecoder.java:188) at java.io.InputStreamReader.read (InputStreamReader.java:177) at java.io.BufferedReader.read1 (BufferedReader.java:211) at java.io.BufferedReader.read (BufferedReader.java:287) at java.io.BufferedReader.fill (BufferedReader.java:162) at java.io.BufferedReader.read (BufferedReader.java:183) at org.apache.maven.shared.filtering.BoundedReader.read (BoundedReader.java:85) at org.apache.maven.shared.filtering.MultiDelimiterInterpolatorFilterReaderLineEnding.read (MultiDelimiterInterpolatorFilterReaderLineEnding.java:235) at org.apache.maven.shared.filtering.MultiDelimiterInterpolatorFilterReaderLineEnding.read (MultiDelimiterInterpolatorFilterReaderLineEnding.java:197) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:126) at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute2 (MojoExecutor.java:342) at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute (MojoExecutor.java:330) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:175) at org.apache.maven.lifecycle.internal.MojoExecutor.access$000 (MojoExecutor.java:76) at org.apache.maven.lifecycle.internal.MojoExecutor$1.run (MojoExecutor.java:163) at org.apache.maven.plugin.DefaultMojosExecutionStrategy.execute (DefaultMojosExecutionStrategy.java:39) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:160) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:105) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:73) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:53) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:118) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:260) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:172) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:100) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:821) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:270) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:568) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347) [ERROR] [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException [ERROR] [ERROR] After correcting the problems, you can resume the build with the command [ERROR] mvn <args> -rf :backweb-api
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='button' button.onclick = function() { var div = document.getElementById('tblContact'); if (div.style.display !== 'none') { div.style.display = 'none'; } else { div.style.display = 'block'; } }; <button id="BtnNextInsured" class="btn btn-md btn-primary">Next</button> Table to show: <table id="tblContact" class="table table-light table-borderless" style="display:none;"> <tr> <td class="cellContent"> <input id="txtEmail" class="txt" placeholder="Email" /> </td> <td class="cellContent"> <input id="txtCell" class="txt" placeholder="Cell Phone" /> </td> <td class="cellContent"> <input id="txtLandline" class="txt" placeholder="Landline" /> </td> </tr> <tr> <td colspan="3" style="text-align: right"> <button id="BtnNextContact" class="btn btn-md btn-primary">Next</button> </td> </tr> </table> I don't understand what's wrong with my code. I am a beginner to javascript.
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').addEventListener('click', evt => { evt.stopImmediatePropagation(); document.querySelector('#tblContact').classList.toggle('hide'); }); } window.addEventListener('load', tableAppear); .hide { display: none; } <button id="BtnNextInsured" class="btn btn-md btn-primary">Next</button> Table to show: <table id="tblContact" class="table table-light table-borderless hide"> <tr> <td class="cellContent"> <input id="txtEmail" class="txt" placeholder="Email" /> </td> <td class="cellContent"> <input id="txtCell" class="txt" placeholder="Cell Phone" /> </td> <td class="cellContent"> <input id="txtLandline" class="txt" placeholder="Landline" /> </td> </tr> <tr> <td colspan="3" style="text-align: right"> <button id="BtnNextContact" class="btn btn-md btn-primary">Next</button> </td> </tr> </table>
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: List element. You can see that it uses a list. I always saw on the Internet that in order to use a list, I need to add "using System.Collections.Generic;" at the beginning of my file. However, the program can run without this line, why?
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 later version. When the feature is enabled, the .NET SDK adds global using directives for a set of default namespaces based on the type of project SDK. Set this property to true or enable to enable implicit global using directives. To disable implicit global using directives, remove the property or set it to false or disable. Note that that means you don't need using System; either. Combined with top-level statements, your whole file could actually be: List<string> list = new List<string>(); list.Add("List element."); Console.WriteLine(list[0]); Or if the namespace is important to you: namespace testProgram; List<string> list = new List<string>(); list.Add("List element."); Console.WriteLine(list[0]);
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 for: scheduler, webserver, workers. I connected to these 3 individually via Session Manager. Once the terminal opened, I installed the library using pip install python-rapidjson I also verified the installation using pip list. Now, I import the library in my dag's code simply like this: import rapidjson However, when I open the Airflow UI, my DAG has an error that: No module named 'rapidjson' Are there additional steps that I am missing out on? Do I need to import it into my Airflow code base in any other way as well? Within my Airflow git repository, I also have a "requirements.txt" file. I tried to include python-rapidjson==1.5.5 this there as well but I do not know how to actually install this. I tried this: pip install requirements.txt within the session manager's terminal as well. However, the terminal is not able to locate this file. In fact, when I do "ls", I don't see anything. pwd /var/snap/amazon-ssm-agent/6522
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 = PythonVirtualenvOperator( task_id="my_task ", requirements="python-rapidjson==1.5.5", python_callable=my_callable, ) I still recommend updating your server environment for core libs, but this is a best practice when using special libs for a small minority of jobs.
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? For instance, I am hoping for something like the following. Public class ConsoleOutput { private var consoleBackground = ConsoleColor.White; private var consoleForeground = ConsoleColor.Black; Public ConsoleOutput { Console.BackgroundColor = consoleBackground Console.ForegroundColor = consoleForeground } } This, however, did not work.
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 Main(string[] args) { var coloredPrinter = new ColoredPrinter(ConsoleColor.White, ConsoleColor.Blue); coloredPrinter.WriteLine("This is white text on blue background"); coloredPrinter.ChangeColors(ConsoleColor.Yellow, ConsoleColor.Red); coloredPrinter.WriteLine("This is yellow text on red background"); Console.WriteLine("This is the default"); } } class ColoredPrinter { public ConsoleColor ForegroundColor { get; set; } public ConsoleColor BackgroundColor { get; set; } public ColoredPrinter(ConsoleColor foregroundColor, ConsoleColor backgroundColor) { ChangeColors(foregroundColor, backgroundColor); } public void ChangeColors(ConsoleColor foregroundColor, ConsoleColor backgroundColor) { ForegroundColor = foregroundColor; BackgroundColor = backgroundColor; } public void WriteLine(string text) { Console.ResetColor(); Console.BackgroundColor = BackgroundColor; Console.ForegroundColor = ForegroundColor; Console.WriteLine(text); Console.ResetColor(); } } This prints out the following:
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. // Instantiate bullet/projectile GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity); // Rotate bullet to shoot direction currentBullet.transform.forward = directionWithSpread.normalized; // Add forces to bullet currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse); currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse); EDIT Perhaps, is there anyway to assign a script to a prefab that will be instantiated?
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 script to it with something like this: GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity); currentBullet.AddComponent<YourScript>(); 3? Using RayCasting (this option in my opinion fits your needs) Usually the best way to handle bullets is using RayCast In this case the bullet does not need the code to handle its collision but it is just the visual representation of the bullet, the real collision detection and other actions linked to it are controlled by the raycasting, in this way you save some memory Hope this helps
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, "%s, %d %s %d", name, &age, priorityGroup, &priorityLevel) == 4) edit2:
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. Then to output the first two words in record you can use standard C function sscanf as shown in the demonstration program below. #include <stdio.h> int main( void ) { char record[] = "john smith 21 VETERAN 1\n"; int n = 0; for (size_t i = 0; i < 2; i++) { const char *p = record + n; int m; sscanf( p, "%*s%n", &m ); n += m; } printf( "\"%.*s\"\n", n, record ); } The program output is "john smith" Or you could make a string of the two words just writing record[n] = '\0'; printf( "\"%s\"\n", record ); Or if your compiler supports variable length arrays you could write #include <string.h> //... char name[n + 1]; memcpy( name, record, n ); name[n] = '\0'; printf( "\"%s\"\n", name ); If the compiler does not support variable length arrays then you will need to allocate an array dynamically like for example #include <string.h> #include <stdlib.h> //... char *name = malloc( n + 1 ); memcpy( name, record, n ); name[n] = '\0'; printf( "\"%s\"\n", name ); In this case do not forget to free the allocated memory when it will not be required any more free( name ); In the demonstration program the string literal used as an initializer of the array record is appended with the new line character '\n' because the function fgets itself can store this character in the destination array.
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 dumped all 10 logs when it finished ForEach loop. And I am just curious why does it work that way? Is it related to ForEach/Linq or maybe to the Console object?
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 fileStream = File.OpenWrite("./consoleOutput.txt"); using var streamWriter = new StreamWriter(fileStream); // redirect standard output Console.SetOut(streamWriter); Enumerable.Range(0, 10).ToList().ForEach(_ => { Thread.Sleep(500); Console.WriteLine($"Slept... {DateTime.UtcNow}"); }); Console.WriteLine("Done"); } } What this program does is, it redirects the standard output to write to a FileStream of a file called consoleOutput.txt. So when you run the program it creates the file and writes everything you would normally print to the console to the file. If you have a look at the file you can see that in fact it contains the whole output: consoleOutput.txt Slept... 6/3/2023 9:34:42 PM Slept... 6/3/2023 9:34:42 PM Slept... 6/3/2023 9:34:43 PM Slept... 6/3/2023 9:34:43 PM Slept... 6/3/2023 9:34:44 PM Slept... 6/3/2023 9:34:44 PM Slept... 6/3/2023 9:34:45 PM Slept... 6/3/2023 9:34:45 PM Slept... 6/3/2023 9:34:46 PM Slept... 6/3/2023 9:34:46 PM Done
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_split = np.linspace(0, 100, 4 + 1, dtype=int) x_start = x_split[:-1] - 5 x_start[0] = 0 x_end = x_split[1:] + 5 x_end[-1] = 100 y_split = np.linspace(0, 100, 4 + 1, dtype=int) y_start = y_split[:-1] - 5 y_start[0] = 0 y_end = y_split[1:] + 5 y_end[-1] = 100 x_inds = zip(x_start, x_end) y_inds = zip(y_start, y_end) i = 0 for start_x, end_x in x_inds: for start_y, end_y in y_inds: i += 1 print(f"i = {i}") print(f"x = {start_x} {end_x}") print(f"y = {start_y} {end_y}") print("") Current output: i = 1 x = 0 30 y = 0 30 i = 2 x = 0 30 y = 20 55 i = 3 x = 0 30 y = 45 80 i = 4 x = 0 30 y = 70 100 And then stops. I want to to continue... i = 5 x = 20 55 y = 0 30 i = 6 x = 20 55 y = 20 55 ...
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 square coordinates: coords = np.repeat(x_start,y_start.size)[:,None], \ np.repeat(x_end, y_start.size)[:,None], \ np.tile(y_start,x_start.size)[:,None], \ np.tile(y_end, x_start.size)[:,None] squares = np.concatenate(coords,axis=1) print(squares) [[ 0 30 0 30] [ 0 30 20 55] [ 0 30 45 80] [ 0 30 70 100] [ 20 55 0 30] [ 20 55 20 55] [ 20 55 45 80] [ 20 55 70 100] [ 45 80 0 30] [ 45 80 20 55] [ 45 80 45 80] [ 45 80 70 100] [ 70 100 0 30] [ 70 100 20 55] [ 70 100 45 80] [ 70 100 70 100]]
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 TestFlight. Using synced StoreKit.storekit.. in_app_purchase: ^3.1.7. Why this may be?
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(), ), }; println!("{:?}", j.record_stringified); ( StatusCode::CREATED, "created".to_string(), ) } gives error: error[E0308]: `match` arms have incompatible types --> src/main.rs:128:20 | 126 | let j = match serde_json::from_str::<CreationJSON>(&body) { | ------------------------------------------------- `match` arms have incompatible types 127 | Ok(j) => j, | - this is found to be of type `CreationJSON` 128 | Err (_) => ( | ____________________^ 129 | | StatusCode::UNPROCESSABLE_ENTITY, 130 | | "body is invalid".to_string(), 131 | | ), | |_________^ expected `CreationJSON`, found `(StatusCode, String)` | = note: expected struct `CreationJSON` found tuple `(axum::http::StatusCode, std::string::String)` However, if I add a "return" to the Err arm, then it works fine: async fn create(body: String) -> impl IntoResponse { let j = match serde_json::from_str::<CreationJSON>(&body) { Ok(j) => j, Err (_) => return ( StatusCode::UNPROCESSABLE_ENTITY, "body is invalid".to_string(), ), }; println!("{:?}", j.record_stringified); ( StatusCode::CREATED, "created".to_string(), ) } Why do I need to add the return in the Err arm? I thought a function with no semi-colon was supposed to automatically return in Rust?
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 dynamically, but I could be wrong. url = https://finance.yahoo.com/quote/AAPL/analysis?p=AAPL Is someone able to explain the issue and offer a solution? Thank you! import requests from bs4 import BeautifulSoup def get_growth_data(symbol): url = "https://finance.yahoo.com/quote/{symbol}/analysis?p={symbol}" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") # Find the table containing the growth data table = soup.find("table", class_="W(100%) M(0) BdB Bdc($seperatorColor) Mb(25px)") if table is None: print("Table not found.") return [] # Extract the growth values from the table growth_values = [] rows = table.find_all("tr") for row in rows: columns = row.find_all("td") if len(columns) >= 2: growth_values.append(columns[1].text) return growth_values symbol = 'AAPL' growth_data = get_growth_data(symbol) print(growth_data)
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'} soup = BeautifulSoup(requests.get(url, headers=headers).content, 'html.parser') table = soup.select_one('table:-soup-contains("Growth Estimates")') df = pd.read_html(str(table))[0] print(df) Prints: Growth Estimates AAPL Industry Sector(s) S&P 500 0 Current Qtr. -0.80% NaN NaN NaN 1 Next Qtr. 5.40% NaN NaN NaN 2 Current Year -2.30% NaN NaN NaN 3 Next Year 9.90% NaN NaN NaN 4 Next 5 Years (per annum) 8.02% NaN NaN NaN 5 Past 5 Years (per annum) 23.64% NaN NaN NaN
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 keyError with the help of Exception handling. If i got keyerror i added NAN value. As java have function like OptString whenever we get keyerror it add default value. I just want to get all data in list but via using optString type method. Can you give any example ? Thanks ,
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 setting acl as well as uniform permissions on the bucket, but it was the same result. I would be willing to change the bucket permissions to anything (other than making it public) that would allow me to get the file updater/owner information.
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 & storage logs
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 minimum height (as per implementation) which is apparently zero. You have couple of options for fixing this: Set a certain height to RecyclerView Set ScrollView.fillViewport to true Or keep RecyclerView outside of ScrollView. In my opinion, this is the best option by far. If RecyclerView height is not limited - which is the case when it's put into ScrollView - then all Adapter's views have enough place vertically and get created all at once. There is no view recycling anymore which kinda breaks the purpose of RecyclerView . (Can be followed for android.support.v4.widget.NestedScrollView as well)
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/balikci.png" genislik = 1000 yukseklik = 600 ekran = pygame.display.set_mode((genislik,yukseklik)) # ... class Balik(pygame.sprite.Sprite): def __init__(self,x,y,resim,tip): super().__init__() self.image = resim self.rect = self.image.get_rect() self.rect.topleft = (x,y) self.tip = tip self.hiz = random.randint(0,13) self.yonx= random.choice([1,-1]) self.yony= random.choice([1,-1]) def update(self): self.rect.x = self.hiz*self.yonx self.rect.y = self.hiz*self.yony if self.rect.left <=0 or self.rect.right >= genislik : self.yonx *=-1 if self.rect.top <=0 or self.rect.bottom >= yukseklik : self.yony *=-1 #Balık Grupları balik1 = pygame.image.load("E:/E/Python/Python-eski/Oyuncalismalari/balik_avlama_oyunu/textures/balik1.png") balik2 = pygame.image.load("E:/E/Python/Python-eski/Oyuncalismalari/balik_avlama_oyunu/textures/balik2.png") balik_grup = pygame.sprite.Group() balik = Balik(random.randint(0,genislik-32),random.randint(0,yukseklik-32),balik1,0) balik_grup.add(balik) balik = Balik(random.randint(0,genislik-32),random.randint(0,yukseklik-32),balik2,0) balik_grup.add(balik) # ... that is all of my code i tried relocating objects but still get_rect() function doesn't work
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) { // distribute object properties into "this" for (const prop in object) { this[prop] = object[prop] } return new Proxy(this, { construct:(target, args) => { console.log(`Creating a new ${target.name}`) // why is this not fired? return Reflect.construct(...args) }, set: (target, prop, val, receiver) => { console.log(`attempting to set ${prop}=${val} type ${typeof val}`); return Reflect.set(target, prop, val) } }) } } // create an instance of our BoundObject class, passing in an object and an HTML element const user = new BoundObject({name:'fred'},document.querySelector('#user-form')) // why is the 'construct' call not intercepted? user.name = 'mary' // set user name. The 'set' call is sucessfully intercepted The set trap works, but the construct trap fails to fire. I suspect this is to do with javascript deep magic around 'this' but cannot figure it out How can I intercept the construction of the proxy object my class returns?
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 where the construct trap could be called. function MyObj() {} const proxy = new Proxy(MyObj, { construct(target, args) { console.log(args); return new target(...args); } }); new proxy('something');
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 mirror:parallel-directories yes set mirror:include-regex $REGEX set log:enabled/xfer yes set log:file/xfer $LOG set xfer:use-temp-file yes set xfer:temp-file-name *.lftp mirror -c -v --loop --Remove-source-dirs "$REMOTEDIR" "$LOCALDIR" quit EOFF EOF )" I am capturing terminal output with the script(1) utility. The env TERM=dumb is just a random piece of code I found to disable ANSI escape codes. My problem is that the line breaks of the output log file get quiet mangled. It seems to be using CR and LF. I discovered more information here and it seems this is by design. Though I'm not sure how to fix it. These line endings cause issues when viewing the logs in lnav: The reason for this becomes quickly apparent upon inspecting the raw text: I have thought of some potential options, but not sure how to implement: Fix the output of the script(1) utility so that single CR are converted to LF. Maybe this can be achieved with piping or some arguement? A hack for lnav to treat CR as LF when displaying in the GUI. Anyone know how I can fix these line breaks so it shows correctly in lnav?
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 number of special ALL_UPPERCASE variables that are used in shell programming. See Correct Bash and shell script variable capitalization. The quotes on $LOGSTDOUT are necessary in general. Use Shellcheck to find common problems with shell code, including missing quotes.
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 properties parameter contains the user, password and driver ("org.postgresql.Driver") details in the form of a dictionary. Anybody know what I am missing? I get the error: IllegalArgumentException: requirement failed: the driver could not open a JDBC connection. Check the URL Added context: I am using Postgres 15, Spark 3.4.0 and Python 3.10 spark = SparkSession\ .builder\ .config('spark.jars','C:\Program Files\Spark\spark-3.4.0-bin-hadoop3\jars\postgresql-42.6.0.jar')\ .getOrCreate() spark.read.jdbc( url=f'jdbc:postgresql//localhost:5432/ag', table='customers', properties=props).load()
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 allows to search across all the fields of the items, including their tags. The problem(s) On the results view, the tagged items are showing up multiple times (one occurence per tag) The ranking is correct when I specify * only a single* tag in the search field, but when I specify multiple tag names, I will get unexpected ranking results. I suspect the SearchVector() does not resolve the tags relation as I expected it to do. The tags should be treated just like a list of words in this case. Example Code models.py from django.db import models from taggit.managers import TaggableManager class Item(models.Model): identifier = models.SlugField('ID', unique=True, editable=False) short_text = models.CharField('Short Text', max_length=100, blank=True) serial_number = models.CharField('Serial Number', max_length=30, blank=True) revision = models.CharField('Revision/Version', max_length=30, blank=True) part_number = models.CharField('Part Number', max_length=30, blank=True) manufacturer = models.CharField('Manufacturer', max_length=30, blank=True) description = models.TextField('Description', blank=True) tags = TaggableManager('Tags', blank=True) is_active = models.BooleanField('Active', default=True) forms.py from django import forms class SearchForm(forms.Form): search = forms.CharField(max_length=200, required=False) active_only = forms.BooleanField(initial=True, label='Show active items only', required=False) views.py from django.views.generic.list import ListView from django.contrib.postgres.search import SearchQuery, SearchVector, SearchRank from . import models from . import forms class ItemListView(ListView): form_class = forms.SearchForm model = models.Item fields = ['serial_number', 'part_number', 'manufacturer', 'tags', 'is_active'] template_name_suffix = '_list' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form_class(self.request.GET) return context def get_queryset(self): queryset = super().get_queryset() form = self.form_class(self.request.GET) if form.is_valid(): if form.cleaned_data['active_only']: queryset = queryset.filter(is_active=True) if not form.cleaned_data['search']: return super().get_queryset() search_vector = SearchVector('identifier', 'short_text', 'serial_number', 'revision', 'part_number', 'manufacturer', 'description', 'tags') search_query = SearchQuery(form.cleaned_data['search'], search_type='websearch') return ( queryset.annotate( search=search_vector, rank=SearchRank(search_vector, search_query) ) # .filter(search=search_query) .order_by("-rank").distinct() ) #.filter(search__icontains=form.cleaned_data['search'],) return super().get_queryset()
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 your get_queryset function def get_queryset(self): queryset = super().get_queryset() form = self.form_class(self.request.GET) if form.is_valid(): if form.cleaned_data['active_only']: queryset = queryset.filter(is_active=True) if not form.cleaned_data['search']: return queryset queryset = queryset.annotate(tags_str=StringAgg('tags__name', delimiter=' ')) search_vector = SearchVector('identifier', 'short_text', 'serial_number', 'revision', 'part_number', 'manufacturer', 'description', 'tags_str') search_query = SearchQuery(form.cleaned_data['search'], search_type='websearch') return ( queryset.annotate( search=search_vector, rank=SearchRank(search_vector, search_query) ) .order_by("-rank").distinct() ) return queryset
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 good understanding of a directive.
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. Both the pre-processing directives and the using directive are not something that the user gets to define. They have a fixed meaning in the language. They can be used with different arguments to achieve different results. Directives like #include can be used to direct what source code is used in the compilation. For example, #include <iostream> will cause the file iostream to be included. There are numerous other pre-processor directives, but for starting out, #include is by far the most important. A directive like using std::cout instructs the compiler to bring the std::cout symbol into the current namespace so it can be referenced as simply cout. I hope this helps clear up the 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 in the above list with related values (in this case report-1, report-2…) result_List = {ID001: [Report-1, Report-2, Report-5], ID002: [Report-3, Report-6, Report-23]} I thought of using for loop, but once the first dictionary is done looping through all the other dictionaries in list, it has to store unique ID’s in the result_List. The code itself contains lot of loops, which I believe too complex for a list of 200 dictionaries with data. I am looking for something with Pandas or Numpy with relatively less complex. Can anyone suggest the best way to do this kind of data crunch?
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: DOCTOR APHRA 32 CHRIS SPROUSE RETURN OF THE JEDI 40TH ANNIVERSARY VARIANT DEADPOOL 7 X-23: DEADLY REGENESIS 3 GERALD PAREL VARIANT SPIDER-MAN 2099: DARK GENESIS 5 THE GODFORSAKEN 99 OF KRONOS 2 KEN GRAGGINS VARIANT Teenage Mutant Ninja Turtles: Saturday Morning Adventures (2023-) #1 Variant RI (10) (Dooney) I'm using VBA and this is my current function: Function ExtractText(c As Range) As String Dim rgx As RegExp Dim match As match Dim mc As MatchCollection Dim sComicNo As String, sPattern As Variant Dim lPos As Long, x As Long sComicNo = "" sPattern = Array(" [0-9] ", " #[0-9] ", " [0-9][0-9] ", " #[0-9][0-9] ", " [0-9][0-9]", " #[0-9][0-9]", " [0-9]", " #[0-9]") lPos = 0 Set rgx = New RegExp On Error GoTo ErrHandler Do While sComicNo = "" With rgx .Pattern = sPattern(x) .Global = True If .Test(c.Value) Then Set mc = .Execute(c.Value) If mc.Count > 0 Then Set match = mc.Item(mc.Count - 1) Else ExtractText = "" End If lPos = match.FirstIndex sComicNo = WorksheetFunction.Trim(match.Value) & "|" & lPos Else sComicNo = "" End If x = x + 1 If x > 8 Then ExtractText = sComicNo Exit Function End If End With Loop ExtractText = sComicNo ErrHandler: Exit Function End Function This pattern matches all my examples except the Spider-Man 2099, but there are other possible variations I'm overlooking. It is also retrieving the position of the match for a separate purpose. I'm trying to be as restrictive as possible by using patterns in a sequence that will retrieve very specific cases and gradually work up from there.
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, you can use a lookbehind to skip the trimming part: (?<=\s)#?\d\d?\b ...in which (?<=\s) means "match something preceded by a whitespace". Try it on regex101.com.
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 shows: hello\n (which is indeed what the user typed in) const outputData = { password: value } console.log(outputData) // Console shows: { password: "hello\\n"} It would be fine if it were just a display issue, but that data is being sent to the server with the double backslash, so there is a mismatch between what the user types in and what gets sent to the server (which of course breaks things). It's also worth noting this doesn't happen (everything works as expected) when I send a request body via Postman Why is this happening? How can I avoid it?
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/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="myInput" value="hello\n"> I assume you're referring to this style of console output: That's just the difference between how the Chrome console (and some others) displays the output when you pass it a string vs. when you pass it an object. JavaScript is not adding anything to the string. When you pass a string to console.log, it just shows the characters of the string (which in your case are h, e, l, l, o, \, and n). But when you pass it an object, it shows you something that looks like an object literal, and since the object literal contains a string literal for password, the backslash in the string literal has to be shown escaped. (Otherwise, it would be an escape character.) But there is only one backslash in the string, not two, exactly like this: console.log("hello\\n"); // <== Notice the escaped backslash The backslash is escaped in the string literal, because otherwise it wouldn't be a backslash, it would be an escape character changing the meaning of the next character (in this case, putting a newline in the string rather than \ and n.) There is only one backslash in the string. It would be fine if it were just a display issue, but that data is being sent to the server with the double backslash... Two possibilities here: The extra backslash is being added by code you haven't shown, either the code preparing the string to send to your server, or the code on the server writing it to the database. For instance, another answer posted to this question suggested doing JSON.stringify(value), but that would add an extra backslash to it for the same reason we put on in a string literal: you have to escape backslashes in JSON strings. The extra one would be removed if the server code parsed the JSON, but it wouldn't be if the server code used the string as-is. I'm not saying you're doing that, just that it's the kind of thing you could be doing to see what you're describing. Or — with apologies! :-) — it's possible that you're misinterpreting what you're seeing for what's in the database in the same way you misinterpeting the object literal in the console and there is actually only one backslash in the database. Your best bet for finding out what's causing the problem is to carefully audit the code processing the string, in particular: Check the actual value of the string with a debugger just prior to sending it to the server. Check how you're encoding what you're sending the server. Check exactly what your code on the server is receiving. Check what that code is doing to the string when adding the value to the database. Somewhere along the line, you'll either determine there isn't actually a problem (#2 above), or you'll find out what's mistakenly adding the backslash (#1 above).
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.EditingElementStyle> <Style TargetType="TextBox"> <Setter Property="FlowDirection" Value="LeftToRight" /> </Style> </DataGridTextColumn.EditingElementStyle> </DataGridTextColumn>
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 private ComboBox<String> mealCB; @FXML void initialize() { // courseCB. ObservableList<String> courseList = FXCollections.observableArrayList(fileReader.getMealCourseArray()); courseCB.setItems(courseList); courseCB.setValue("main meal"); courseCB.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observableValue, String s, String t1) { switch (t1){ case "first meal": { ObservableList<String> mealByCourse = FXCollections.observableArrayList(fileReader.getMealsByCourse("first meal")); mealCB.setItems(mealByCourse); } case "main meal": { ObservableList<String> mealByCourse = FXCollections.observableArrayList(fileReader.getMealsByCourse("main meal")); mealCB.setItems(mealByCourse); } case "drink": { ObservableList<String> mealByCourse = FXCollections.observableArrayList(fileReader.getMealsByCourse("drink")); mealCB.setItems(mealByCourse); } break; } } }); } the code of getMealBycourse: public static String[] getMealsByCourse(String mealCourse){ ArrayList<String> mealsList = new ArrayList<>(); Meal[] meals ; fileReader filereader= new fileReader(); meals = filereader.getMealArray(); for (int i = 0; i < meals.length ; i++) { if ((meals[i].getMealCourse()).compareTo(mealCourse)==0) { mealsList.add(meals[i].getMealName()); } } String [] mealsByCourse = mealsList.toArray(new String[mealsList.size()]); return mealsByCourse; } fileReader.getMealCourseArray() will return an array of items of courseMeal and populate the courseCB (comboBox) with it. the problem is that that mealCB is getting values of drinks only. the method of get mealByCourse is working very well by testing it. so what is needed to change in the addListener to make it work.
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 only at the end of the switch. So the other conditions are "working" as in doing what they are asked to do, but the subsequent conditions run too and only the last one applies. You can fix your logic error with the following code: switch (t1) { case "first meal": { ObservableList<String> mealByCourse = FXCollections.observableArrayList(fileReader.getMealsByCourse("first meal")); mealCB.setItems(mealByCourse); } break; case "main meal": { ObservableList<String> mealByCourse = FXCollections.observableArrayList(fileReader.getMealsByCourse("main meal")); mealCB.setItems(mealByCourse); } break; case "drink": { ObservableList<String> mealByCourse = FXCollections.observableArrayList(fileReader.getMealsByCourse("drink")); mealCB.setItems(mealByCourse); } break; } Note that I added break statements in between each case statement. That way, only the block of a single case statement will be executed for each case. I advise you to go back and do some study on the Java language basics. Study how switch statements work. That article is for Java 8. There are improved switches in later Java versions, but you aren't using the improved switch syntax, so the old article still applies for the old syntax that you use. If you want to switch to using a more modern syntax (requires Java 14+), then you can write instead: switch (t1) { case "first meal" -> { ObservableList<String> mealByCourse = FXCollections.observableArrayList(fileReader.getMealsByCourse("first meal")); mealCB.setItems(mealByCourse); } case "main meal" -> { ObservableList<String> mealByCourse = FXCollections.observableArrayList(fileReader.getMealsByCourse("main meal")); mealCB.setItems(mealByCourse); } case "drink" -> { ObservableList<String> mealByCourse = FXCollections.observableArrayList(fileReader.getMealsByCourse("drink")); mealCB.setItems(mealByCourse); } } This will do the same as the previous example, but is IMO, less error prone. It uses the new -> syntax for cases in switches rather than the old : syntax. The new syntax does not fall through cases and does not require explicit break statements. The switch can be converted to an expression to allow a more functional style of programming, which I often prefer: String[] mealsByCourse = switch (t1) { case "first meal" -> fileReader.getMealsByCourse("first meal"); case "main meal" -> fileReader.getMealsByCourse("main meal"); case "drink" -> fileReader.getMealsByCourse("drink"); default -> new String[0]; ); mealCB.setItems( FXCollections.observableArrayList( mealsByCourse ) ); But then when you do that it becomes clear that you are just switching on a value and applying that value. So you can instead just eliminate the switch statement and use the simple solution proposed by Anon in comments: ObservableList<String> mealsByCourse = FXCollections.observableArrayList( fileReader.getMealsByCourse(t1) ); mealCB.setItems(mealsByCourse); This final approach is the same as one of those proposed solutions in this answer to a related question: combobox dependent on another combobox - JavaFX