Skip to main content

Posts

R join a table column from a vector

I would like to get the corresponding values of a vector in a table from a column in another column. (just look below) example: Vector: v = c('A', 'B', 'C') Table : # key Value 'C' 3 'A' 1 'B' 2 When I give the vector v ( A, B, C ) I want to get back the corresponding values in the good order 1, 2, 3 . In reality, the vector is the rownames of a dataset, and I need to replace it with the corresponding values. I was thinking about using the left_join function from Dplyr but I would need 2 tables for this. Thanks for your help by vinalti in StackOverflow on July 05, 2022 . Answer A possible solution in base R : df$Value[match(v, df$key)] #> [1] 1 2 3 Using dplyr : library(dplyr) df %>% mutate(x = Value[match(v, key)]) %>% pull(x) #> [1] 1 2 3 by PaulS on July 05, 2022 . Other helpful answers ...

Replace values based on ID's for determinate columns

I have this situation: ID n post date el a b c d 100_left 4 50 10/11/2020 y 190 5.41 4 300 100_right 4 50 10/11/2020 n 5.4 5 200 101_left 4 50 10/11/2020 y 180 5.49 6 360 101_right 4 50 10/11/2020 n 5.48 6 180 102_left 4 50 10/11/2020 y 190 5.5 3 300 102_right 4 50 10/11/2020 n 5.46 5 200 103_left 4 50 10/11/2020 y 190 5.39 3 170 103_right 4 50 10/11/2020 n 5.44 3 360 I would like to use the same values of n_left for n_right ( ID ), but just for columns from a to d . Like this: ID n post date el a b c d 100_left 4 50 10/11/2020 y 190 5.41 4 300 100_right 4 50 10/11/2020 n 190 5.41 4 300 101_left 4 50 10/11/2020 y 180 5.49 6 360 101_right 4 50 10/11/2020 n 180 5.49 6 360 102_left 4 50 10/11/2020 y 190 5.5 3 300 102_right 4 50 10/11/2020 n 190 5.5 3 300 103_left 4 50 10/11...

SQL: only return results, after a join, where columns with different words represent the same idea (col 1 'dog' col 2 'hound' = match)

SQL flavor is Mode's unique variation, that said SQL flavor doesn't really matter. If you can show me how to do it in one variety of SQL, I'll at least know what to Google to figure it out in this variation. I'm joining two tables and trying to identify columns where the status of an item is the same, however the statuses are written differently between the two tables. Table 1 columns: Name Number Status (available, unavailable, inactive) Table 2 columns: Number Status (unassigned, unavailable, retired) Available = unassigned, unavailable = unavailable, inactive = retired. I am trying to first compare available/unassigned line up, inactive/retired line up, etc. Then I'm trying to return only the results where both status columns do not match, but since they use different words for the same idea I just don't know how to do it. by Ryan Mercer in StackOverflow on July 05, 2022 . Answer I'd simply...

For each item, find COUNT of item with lower price

I have a table Items(ID, Name, Price). For every item in Items, I‘d like to receive an output of the form: (ID, Name, Count), where Count is the number of items in Items which are cheaper in price. I have tried running a subquery with the same table but found no solution. It seems so simple, but I‘m a bit stuck. by William Bomb in StackOverflow on July 05, 2022 . Answer SELECT t1.ID, t1.Name, t1.Price, COUNT(t2.id) FROM Items t1 LEFT JOIN Items t2 ON t1.price > t2.price GROUP BY t1.ID, t1.Name, t1.Price I add Price column to the output because you have not told that the presence of the same item name with different prices is not possible. by Akina on July 05, 2022 .

How to create a mysql query that checks if a row exists - if it does I want to insert a new record otherwise increment a value

I have a table which has an ID and an occurrences column. I want to create a single transaction to the db where if ID exists in DB: occurrences++ else: insert new row where occurrences = 1 I saw that it's possible to do an IF THEN statement so I was attempting to do something like this: IF ID = 123 IS NOT NULL THEN UPDATE occurrences = occurrences +1 ELSE INSERT INTO entity_table(123, 1) END IF; by DannyD in StackOverflow on July 05, 2022 . Answer INSERT INTO entity_table SET id=123, occurrences = 1 ON DUPLICATE KEY UPDATE occurrences = occurrences + 1 by Bill Karwin on July 05, 2022 .

SwiftUI animation: move up/down on press, spring on release - how to do the "move up" part

How can I get the blue circles to first move away from the green circle before getting back to it? The animation should be: press and hold: the green circle scales down the blue circles, while scaling down as well, first move "up" (away from their resting position, as if pushed away by the pressure applied) and then down (to touch the green circle again, as if they were pulled back by some gravitational force) release everything springs back into place (bonus) ideally, the blue circles are ejected as the green circle springs up, and they fall back down in their resting position (next to the surface) I got everything working except the blue circles moving up part. This is the current animation: And its playground. import SwiftUI import PlaygroundSupport struct DotsView: View { var diameter: CGFloat = 200 var size: CGFloat = 25 var isPressed: Bool = false var body: some View { ZStack { ForEach(0...5, id: \.self) { i in ...

How to make button visible in scrollview if it's related textfield has been focused

I have a ScrollView which contains VStack which contains a large amount of entries. The amount is not important it is just that you have to scroll to get to a TextField at the end of the list. Below the text field is a "submit"- Button . If the user taps on the text field, the scrollview will adjust its scrolling position to make the textfield visible. But I need, that the button below the input becomes visible, too. Does someone have any idea how I could achieve this behavior? Thanks! Abstract code ScrollView { VStack { // ... content // Button aera VStack { Text("Text") Button("Action Text") { onSubmitRequested() } } } } by Tobonaut in StackOverflow on July 05, 2022 . Answer Here is a possible solution - based on scrollTo , focused state, and animation alignment, latter is important, becaus...

How to create a flowchart in CSS

I am trying to put together a diagram in CSS of a flow chart. I have attached below a picture. Is there a simple way to do this? I've been Googling around quite a bit looking for examples, but I don't know what to call this. Can you please let me know how to do this? Or if this is something common, what I can Google to find more information. by Collin Cunningham in StackOverflow on July 04, 2022 . Answer By using CSS Flex you could achieve something like: body {font: 16px/1.4 sans-serif;} .chart-row, .chart-col { display: flex; gap: 1em; } .chart-row { flex-direction: row; } .chart-col { flex-direction: column; } .chart-pill, .chart-rect{ padding: 1em; text-align: center; border: 2px solid #999; } .chart-pill { flex: 1; border-radius: 1em; border-style: dashed; } .chart-rect{ flex: 0; margin: auto 0; background: #eee; } .chart-line-h { height: 2px; min-width: 3em; background: #99...

OpenGL clear sprite

I created 10 sprites on the window and now I want to clear only one sprite out of 10 sprites. Now the function glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) clears the entire window of sprites, but I don't want to clear the entire window of drawn sprites. What function should I use to clear just one sprite and not clear the whole window and redraw 9 sprites in the window? by Evil JuniorCplusplus in StackOverflow on July 05, 2022 . Answer There is no such feature. Clear the screen, and redraw 9 sprites. Most computer games with moving objects clear the screen every single frame. by user253751 on July 05, 2022 .

Calling a common method of tuple elements

Say I have a tuple of types T1,...,TN that implement some method, apply() . How do I define a function that takes this tuple and some initial element, and returns the chained call of apply() on this element? For example: template <typename... Args, typename Input> auto apply(std::tuple<Args...> const &tpl, Input x) { // return ??? } // simple example struct Sqr { static int apply(int x) { return x * x; } }; enum class Choice { One, Two, }; struct Choose { static int apply(Choice choice) { switch (choice) { case Choice::One: return 1; case Choice::Two: return 2; } } }; void test() { auto tpl = std::tuple(Sqr{}, Choose{}); assert(apply(tpl, Choice::One) == 1); assert(apply(tpl, Choice::Two) == 4); } I tried to use fold expressions , and variations of answers from: Template tuple - calling a function on each element but couldn't get anything to compile. The main difference is that I need each invocation...

Convert jquery ajax to fetch

Does someone knows jquery and can help me convert this ajax to js fetch ? Unfortunately, I don't know jquery and I need to convert this into js fetch. function ajaxLogoutDetailsApi() { $.ajax({ type: "GET", url: "OIDCGetLogoutDetails", async: false, cache: false, data: "json", success: function (data, status, xhr) { data = data.replace('\/\*', ''); data = data.replace('\*\/', ''); var dataJson = JSON.parse(data); if (dataJson.logoutUrl != null) { document.location.href = dataJson.logoutUrl; } }, error: function (xhr, status, err) { console.log("error in ajaxLogoutDetailsApi"); } }); } Appreciate every hint. by Christian10 in StackOverflow on July 04, 2022 . Answer I was going to use async/await but since there's that odd replacing before the JSON gets parsed I've reve...

How do I multiply values within id and display answer?

How do multiply each value in the div with class="crtTotal" and have a div output that displays the answer: for example 1.75 x 3.65 x 2.10 = 13.41 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="box" class="boxlit"> <div class="box" data-id="75">Weston Bears - Cooks Hill United <br>Home <div class="crtTotal">1.75</div> </div> <div class="box" data-id="79">Logan Lightning - Brisbane City <br>Draw <div class="crtTotal">3.65</div> </div>...

svg clipPath using absolute points instead of percentages

I want to use clipPath for an image I'm trying to display on my webpage, and I want to be able to use percentages instead of absolute points with polygon . I've tried adding the viewBox attribute to my svg element to do so (suggested here SVG polygon points with percentage units support ), but when the image renders, it looks like absolute points are still being used. I have my html setup like this: <img class="clip-svg" src="{% static 'myApp/images/random.png' %}"> <div id="svg-container" style="width:100%; height:100%;"> <svg width='100%' height='100%' viewBox="0 0 100 100"> <defs> <clipPath id="myClip"> <polygon points="89,0 100,50 89,100 71,100 83,50 69,0"/> <polygon points="53,0 75,50 59,100 48,100 64,50 41,0" /> </clipPath> </defs> </svg> </div> With the CSS being: ...

Remove specific tag with its contents using sed

I would like to remove following tag from HTML including its constantly varying contents: <span class="the_class_name">li4tuq734g23r74r7Whatever</span> A following BASH script .... | sed -e :a -re 's/<span class="the_class_name"/>.*</span>//g' > "$NewFile" ends with error sed: -e expression #2, char XX: unknown option to `s' I tried to escape quotes, slashes and "less than" symbols in various combinations and still get this error. by Paul in StackOverflow on July 05, 2022 . Answer I suggest using a different sed separator than / when / is contained within the thing you want to match on. Also, prefer -E instead of -r for extended regex to be Posix compatible. Also note that you have a / in your first span in your regex that doesn't belong there. Also, .* will make it overly greedy and eat up any </span> that follows the first </...

Incorrect RectF On Canvas Created From Composable

I'm trying to highlight a view by grabbing the layoutCoordinate from a Box using .onGloballyPositioned . I receive the following coordinates: val viewLeft = layoutCoordinates.boundsInWindow().left val viewTop = layoutCoordinates.boundsInWindow().top val viewRight = layoutCoordinates.boundsInWindow().right val viewBottom = layoutCoordinates.boundsInWindow().bottom When I try to create a highlight with this code, it is always off by a bit: canvas.drawRoundRect( viewLeft, viewTop, viewRight, viewBottom, cornerRadius, cornerRadius, paint) This is the result that I am getting: Any idea what I may be doing incorrect? Thanks! by Ilyas Saleem Khurshid in StackOverflow on July 05, 2022 . Answer layoutCoordinates.boundsInWindow() adds status bar height to coordinate. You should use layoutCoordinates.boundsInParent() to get a Composable coordinates relative to its parent's top left corner. For instance this example Column(mod...

Callback function can be changed in Compose?

As I am doing this codelab (Step 4) from Android Developer website, I noticed it is said that the callback function can be changed even after it is passed to the Composable, and the code needs to protect it against changes. As below: Some side-effect APIs like LaunchedEffect take a variable number of keys as a parameter that are used to restart the effect whenever one of those keys changes. Have you spotted the error? We don't want to restart the effect if onTimeout changes! To trigger the side-effect only once during the lifecycle of this composable, use a constant as a key, for example LaunchedEffect(true) { ... }. However, we're not protecting against changes to onTimeout now! If onTimeout changes while the side-effect is in progress, there's no guarantee that the last onTimeout is called when the effect finishes. To guarantee this by capturing and updating to the new value, use the rememberUpdatedState API: The code: import androidx.compose.runtime.get...

How to show/fetch amount of posts, comments etc a user has made

I want to show the users the amount of posts, comments etc they have created in their profile section, just like any other forums that exist. I am doing this with php and MYSQLI. Post table: 1 post_id Primary int(11) AUTO_INCREMENT 2 title varchar(255) 3 users_id int(11) 4 content varchar(500) 5 type int(11) 6 imagepath varchar(50) 7 date_created datetime I have tried to add another column to the post table and increment its value by 1 each time the user makes a post in php by an INSERT statement but it's value only stays at 1, even though the user continues to create more posts. Here is what I tried: function createPost($conn, $content, $title, $users_id, $date_created, $type, $total_post){ $sql = "INSERT INTO post (title, users_id, content, date_created, type, total_post) VALUES (?,?,?,?,?,?);"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($...

How to order by a column if it exists for a table or order by another column if it doesn't

I have a generic function (php) that retrieves multiple records of a table by matching a column value and orders them by a datetime field. In some instances the datetime is the same for multiple records, inserted at nearly the same time, and on these tables there is another column that is a record number, an automatically incrementing number. I would like to check if the table has this record number column present, and if so, sort by it. Otherwise if the record number column does not exist in the table I want to sort by the datetime field. I could write a separate function, sorting for record numbers, but prefer this to be handled by a single function using a mysql solution. I just want to know if this can be done? Using IF, Exist, or orderby? by callison in StackOverflow on July 05, 2022 . Answer As a very broad description, you can think of SQL query execution as consisting of separate stages: Parsing the query: checking the sy...

C# Specify generic type parameter once and use it throughout class

Let's say I have a class ClassWhichDoesThings which makes various calls to methods such as DoSomething<TheTypeIWantToSpecifyOnce>(); DoAnotherThing<TheTypeIWantToSpecifyOnce>(); AndAnother<TheTypeIWantToSpecifyOnce>(); throughout the class. Is it possible to specify the generic type in one place (like a variable but not determined at runtime) without anything outside of the class having to also pass a generic type (avoiding ClassWhichDoesThings<T> ) such that the method calls become something like: Type WriteTypeOnce = typeof(TheTypeIWantToSpecifyOnce); DoSomething<WriteTypeOnce>(); DoAnotherThing<WriteTypeOnce>(); AndAnother<WriteTypeOnce>(); The objective here being that if I want to change the Type, I don't have to do a find and replace on 20 different method calls for example. Essentially I want a generic class which specifies its own generic type privately. Edit: In other words, I'm trying to better organise code w...

C# Regex replace all occurrences of 3 numbers together with a different one from a list

I have a list of numbers that have in the left the new number and in the right the old number I want to change, each separated by a Tab character: 000 256 007 002 056 078 And I have filenames with the following composition: aaaa_bbb_01_cccc_000_a aaaa_bbb_01_cccc_000_b aaaa_bbb_01_cccc_000_c aaaa_bbb_01_cccc_007_a aaaa_bbb_01_cccc_056_a I want to change the 3 digits that are together into it's corresponding new number, but the fact that some of the numbers in the filenames repeat have me a little stuck since I'm just trying to learn regex. The output I want would look like this (keeping the same order as above): aaaa_bbb_01_cccc_256_a aaaa_bbb_01_cccc_256_b aaaa_bbb_01_cccc_256_c aaaa_bbb_01_cccc_002_a aaaa_bbb_01_cccc_078_a How can I change these filenames using regex? If it's not possible using regex what other alternative could I use? by Claudia Provoste in StackOverflow on July 05, 2022 . Answer Extra...