Issue with pointers in expression tree Posted: 26 Apr 2021 08:34 AM PDT I want to implement an expression tree from the prefix form, but i had an issue with pointers. I created ny own array with an element containing int as num or char as var -- variable(a, b, c, etc) or an operaton (+, -, *, etc). One element contains not null char and 0 or '\0' and int (not zero) or '\0' and 0 at the end of the array. typedef struct numNchar { char var; int num; }nc; typedef struct tree { nc value; struct tree *left; struct tree *right; } tree; bool isOp(char ch) { return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^' || ch == '(' || ch == ')'); } tree *createNode(nc value) { tree* result = (tree*)malloc(sizeof(tree)); if (result != NULL) { result->left = NULL; result->right = NULL; result->value = value; } return result; } bool ncNull(nc value) { if (value.num == 0 && value.var =='\0') return false; else return true; } nc RnullNC() { nc out; out.num = 0; out.var = '\0'; return out; } bool add(tree **root, nc a[], int i) { if (ncNull(a[i])) { if (!isOp(a[i].var)) { (*root)->value = a[i]; return true; }else { (*root)->value = a[i]; add(&((*root)->right), a, i+1); add(&((*root)->left), a, i+1); return true; } } } I supposed that function bool add(tree **root, nc a[], int i) would give me output for an array containing not null operations like this {*, -, 12, B, +, 11, A } I would get this tree * / \ / \ - + / \ / \ B 12 A 11 Using function like this. add(&root,tmpOut, 0); Unfortunately I got Segmentation fault (core dumped) I wathced videos and read articles about pointers and uderstand sumple usage of them but I have an issue with recursive functions with it |
Dealing with nested variables in R linear regression Posted: 26 Apr 2021 08:34 AM PDT I have a dataset which includes some nested variables. For example, I have the following variables: the speed of a car, the existence of another car following it other_car and, if there is another car, the distance between the two cars distance . Dummy dataset: speed <- c(30,50,60,30,33,54,65,33,33,54,65,34,45,32) other_car <- c(0,1,0,0,0,1,1,1,1,0,1,0,1,0) distance <- c(NA,20,NA,NA,NA,21,5,15,17,NA,34,NA,13,NA) dft <- data.frame(speed,other_car,distance) I would like to include the variables other_car and distance in a model with the form of nested variables, i.e. if the car is present consider also the distance. Following an approach mentioned here: https://stats.stackexchange.com/questions/372257/how-do-you-deal-with-nested-variables-in-a-regression-model , I tried the following: lm_speed <- lm(speed ~ other_car:distance) summary(lm_speed) Which gives the following result: Call: lm(formula = speed ~ other_car:distance) Residuals: 2 6 7 8 9 11 13 0.03776 3.72205 19.77341 -15.38369 -16.01511 10.61782 -2.75227 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 43.6480 12.9010 3.383 0.0196 * other_car:distance 0.3157 0.6563 0.481 0.6508 --- Signif. codes: 0 '' 0.001 '' 0.01 '' 0.05 '.' 0.1 ' ' 1 Residual standard error: 14.27 on 5 degrees of freedom (7 observations deleted due to missingness) Multiple R-squared: 0.04424, Adjusted R-squared: -0.1469 F-statistic: 0.2314 on 1 and 5 DF, p-value: 0.6508 Based on this, 7 observations were not considered due to missingness, which probably means that the ones with no other car present were not included in the regression. However, what I had in mind was to include it as a categorical variable (existence/no existence) and then add the additional variable when other_car=1. Any ideas? |
Numpy array in form (5,1) vs numpy array in form (5,) Posted: 26 Apr 2021 08:34 AM PDT What's the difference here? I can't call a method I wrote with the first numpy array variant but with the second it works. How do I convert my first array to match the second one? |
How to make reverse foregnkey/1to1/MtoM connections explicit in django models? Posted: 26 Apr 2021 08:33 AM PDT Say there are two models like these: class Post(models.Model): ... class User(models.Model): posts = ManyToManyField(post, ...) ... I know that Post.user is still available in the django querysets and I know about relatedname but there are cases where I also need to add field users to Post model, to which, if I remember correcly, django issues a warning. In my case, I need to write a serializer (project uses DRF) for such implicit field, which is not possible (because "model Post doesn't have field users" to continue the example). And even if it's ok to ignore warning and just make fields explicit, situation is still hard since MtoM is an reverse of MtoM and 1to1 is a reverse of 1to1 but there is no reverse to foreignKey. |
How can I create a function to reindex top X worst postgres indexes Posted: 26 Apr 2021 08:33 AM PDT I'm trying to take the output of the following query and pass the indexes to another query that will perform a reindex. The end goal is to schedule a nightly job that will reindex the top 5 or 10 "most fragmented" indexes. Our application is highly transactional and can be rather large so we can't afford to do a nightly reindex of all tables. Also, we're running postgres 11 (so CONCURRENTLY) isn't an option. ... SELECT i.indexrelid::regclass --,s.leaf_fragmentation FROM pg_index AS i JOIN pg_class AS t ON i.indexrelid = t.oid JOIN pg_opclass AS opc ON i.indclass[0] = opc.oid JOIN pg_am ON opc.opcmethod = pg_am.oid CROSS JOIN LATERAL pgstatindex(i.indexrelid) AS s WHERE t.relkind = 'i' AND pg_am.amname = 'btree' AND s.leaf_fragmentation > 30 AND s.leaf_fragmentation != 'NaN' AND left(relname,3) !='pg_' ORDER BY leaf_fragmentation desc LIMIT 10 ... |
How do you assign variables in python exec? Posted: 26 Apr 2021 08:33 AM PDT Given the following code a = 100 snip = ''' b = 2 c = a+b print(c) ''' exec(snip) how can get the value of c from exec? |
How to destruct an object and update MySQL with keys and values? Posted: 26 Apr 2021 08:34 AM PDT I am passing data from a react frontend to an express backend: axios.post('http://localhost/api', {foo: true, bar: false}); In the backend I am updating a MySQL database like app.post("/user", (req, res) => { const {foo, bar} = req.body; const sql = `UPDATE users SET foo = ?, bar = ?`; connection.query(sql, [foo, bar], (err) => { if (err) { res.send({err: err}); } else { res.send({updated: true}); } }) }); What if I don't know the keys of the data I'm passing? Like foo and bar could be whatever. I need to know the keys that I am currently destructuring in const {foo, bar} = req.body . Additionally I need to have them in the column part of the UPDATE string in foo = ? and bar = ? . I want to do this, to be able to update different values in a database with the same function. |
Pandas How to replace values based on Conditions for Several Values Posted: 26 Apr 2021 08:33 AM PDT I have a Dataframe with several column and below is first 3 columns in that dataframe: data_df = pd.DataFrame({'id':['era','bb','cs','jd','ek','gtf','okg','huf','mji','loj','djjf','wloe','rfm','cok'], 'doc':[1050 ,580,170,8, 7, 220, 45155,305,458,201,48,78,256,358], 'dif':[1,1,1,3,3,2,2,3,4,5,8,7,9,10]}) data_df id doc dif 0 era 1050 1 1 bb 580 1 2 cs 170 1 3 jd 8 3 4 ek 7 3 5 gtf 220 2 6 okg 45155 2 7 huf 305 3 8 mji 458 4 9 loj 201 5 10 djjf 48 8 11 wloe 78 7 12 rfm 256 9 13 cok 358 10 I want to change the values in "dif" column like the reverse. I mean I want to change 1 to 10, 2 to 9, 3 to 8,.... 10 to 1. How can I do that? I was trying to do that like below but then I couldn't figure which values to correct next time. data_df.loc[(data_df.dif == 1),'dif']= 10 data_df['dif'].mask(data_df['dif'] == 2, 9, inplace=True) Any help would be appriciate. Thanks in advance |
Take input from a dropdown form and put it into a database PHP Posted: 26 Apr 2021 08:33 AM PDT I am trying to send the input from a user on a form to my database and I am not sure why it isn't going. I have the sql going to my database and all the correct IDs are met so I think it should be working but I am missing something. It may be something in the if(isset part of the code but most likely something in the dropdown portion. Any help would be appreciated. <?php session_start(); if(!isset($_SESSION["sess_user"])){ header("location:login.php"); } else { ?> <!doctype html> <html> <head> <link rel="stylesheet" href="siteCSS.css"> <meta charset="UTF-8"> <title>Recommendations</title> </head> <body> <div id="wrapper"> <header> <h2>Welcome <?=$_SESSION['sess_user'];?>! <a href="logout.php">Click to Logout</a></h2> <nav> <ul> <li><a href="member.php">Home</a></li> <li><a href="committees.php">Committees</a></li> <li><a href="recommendations.php">Recommendations</a></li> <li><a href="voting.php">Voting</a></li> </ul> </nav> </header> <h1>Recommendations Main Page</h1> <form action = "recommendations.php" method="POST"> <br> <br> <label>Recommendation ID: </label> <select name="recommended" required> <?php $conn = new mysqli('localhost', 'root', 'root', 'mydb'); if ($conn->connect_error) { die("Failed: " . $conn->connect_error); } $UserID = $_SESSION['sess_userID']; $selectsql = "select * from user"; echo '<option value="" disabled selected>Choose option</option>'; $result = $conn->query($selectsql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo '<option value=\"'.$row["UserID"].'">'.$row["UserName"].'</option>'; } } ?> </select> <br> <br> <label>Committee ID: </label> <select name="committee" required> <?php $conn = new mysqli('localhost', 'root', 'root', 'mydb'); if ($conn->connect_error) { die("Failed: " . $conn->connect_error); } $selectsql = "select * from committee"; echo '<option value="" disabled selected>Choose option</option>'; $result = $conn->query($selectsql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo '<option value=\"'.$row["CommitteeID"].'">'.$row["CommitteeName"].'</option>'; } } ?> </select> <br> <br> <label>Description (Why they should be recommended):</label> <input type="text" size = 25 class="textbox" id="RecommendationDescription" name="RecommendationDescription" required> <br> <br> <button type="submit" name="submit">Submit</button> <?php if(isset($_POST["submit"])){ if(!empty($_POST['RecommendationDescription'])) { $recomuser=$_POST['RecommendationID']; $recommddesc=$_POST['RecommendationDescription']; $recomcommittee=$_POST['CommitteeID']; $conn = new mysqli('localhost', 'root', 'root', 'mydb'); if ($conn->connect_error) { die("Failed: " . $conn->connect_error); } $userID = $_SESSION['sess_userID']; $sql="INSERT INTO mydb.recommendation(RecommendatedID, RecommendationDescription, RecommendationSubmissionDate, UserID, CommitteeID) VALUES('$recomuser', '$recommddesc', CURRENT_TIMESTAMP, '$userID', '$recomcommittee')"; $result = $conn->query($sql); if($result){ echo "Recommendation Successfully Created"; } else { echo "Failure!"; } } } ?> </form> <main> </main> </div> </body> </html> <?php $variable=$_POST['RecommendationName']; echo $variable; } ?> |
SAPGui Script VBA, Grab Performance Assistant Text Posted: 26 Apr 2021 08:33 AM PDT As I want to long texts from ALV Grids, I came across a problem. I was able to move throughout lines from an ALV-Grid and bring up the performance assistant window (see attachment). As next step, I want to grab the text shown within the dialog. Is there any possibility to do this via GuiScript? Thank you for your help in advance. Best regards, House [Attachment 1][1] [1]: https://i.stack.imgur.com/qYfid.png |
NAudio - List input device GUIDs properly Posted: 26 Apr 2021 08:33 AM PDT I am trying to list input device from NAudio to later record on them. I believe that the best way to do this would be from their Guids. Below is code that I wrote to list their name, guid and other information. try { int waveInDevices = WaveIn.DeviceCount; for (int waveInDevice = 0; waveInDevice < waveInDevices; waveInDevice++) { WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice); string message = $"{deviceInfo.ProductName} {deviceInfo.NameGuid} {deviceInfo.ProductGuid} {deviceInfo.Channels}"; //MessageBox.Show(message); richTextBox1.Text += message + "\n"; } } catch (Exception ex) { MessageBox.Show(ex.Message); } This is the output Microphone (2- GENERAL WEBCAM) fc576b87-4e0a-463b-a72f-a5bf64c86eba abcc7a60-c263-463b-a72f-a5bf64c86eba 2 1 - ASI5740 /02 WDM In (AudioSc 00000000-0000-0000-0000-000000000000 e36dc311-6d9a-11d1-a21a-00a0c9223196 2 1 - ASI5740 /03 WDM In (AudioSc 00000000-0000-0000-0000-000000000000 e36dc311-6d9a-11d1-a21a-00a0c9223196 2 1 - ASI5740 /01 WDM In (AudioSc 00000000-0000-0000-0000-000000000000 e36dc311-6d9a-11d1-a21a-00a0c9223196 2 Microphone (2- Fast Track) fc5757ab-4e18-463b-a72f-a5bf64c86eba abcc7a6e-c263-463b-a72f-a5bf64c86eba 2 Line In (Blackmagic DeckLink St 00000000-0000-0000-0000-000000000000 e36dc311-6d9a-11d1-a21a-00a0c9223196 2 1 - ASI5740 /04 WDM In (AudioSc 00000000-0000-0000-0000-000000000000 e36dc311-6d9a-11d1-a21a-00a0c9223196 2 Microphone (Fast Track) fc5757ab-4e18-463b-a72f-a5bf64c86eba abcc7a6e-c263-463b-a72f-a5bf64c86eba 2 The NameGuid is not unique and sometimes all zeros for PCIe devices. Here is all of my audio devices that can be found within device manager Is this not a good way of getting each input device uniquely? I would use the name, but the name can change when new devices are added or swapped. This is for a broadcast related program, so devices could be swapped frequently. |
Aggregate pandas using multiple column Posted: 26 Apr 2021 08:33 AM PDT Say I have the following dataframe: import pandas as pd df = pd.DataFrame({'user': ['00001C05', '00001C05', '00001C05', '00007142'], 'mois_couverture': ['01-2018', '01-2018', '02-2018', '01-2018'], 'categorie_A': ['x', 'x', 'x', 'y'], 'categorie_B': ['v', 'v', 'v', 'w'], 'revenue': [40, 50, 40, 100]}) user mois_couverture categorie_A categorie_B revenue 0 00001C05 01-2018 x v 40 1 00001C05 01-2018 x v 50 2 00001C05 02-2018 x v 40 3 00007142 01-2018 y w 100 Now I would like to aggregate the column revenue using all the other columns as id-columns. For this toy example here, just: df.groupby(['user', 'mois_couverture', 'categorie_A', 'categorie_B'])['revenue'].sum() user mois_couverture categorie_A categorie_B 00001C05 01-2018 x v 90 02-2018 x v 40 00007142 01-2018 y w 100 However, in my case, this is not feasible, because the dataframe is very large and there are many many more columns such as categorie_A and categorie_B . The good news: the values in these columns usually do not change for individual user. df.groupby still tries to create the cartesian product of all these columns which makes it impossible to calculate. What is the best way to do this efficiently? |
Mocking top-level constructor call in Python Posted: 26 Apr 2021 08:33 AM PDT I'm trying to unit test a Python Google Cloud Function that writes JSON (extracted from a HTTP request body) into BigQuery. I'm having a problem mocking out the bigquery.Client() call. main.py: from google.cloud import bigquery BQ_CLIENT = bigquery.Client() def http_to_bq(request): payload = request.get_json() BQ_CLIENT.insert_rows_json('mytable', payload) My current (failing) test class: from unittest.mock import Mock, patch import main class TestMain(): @patch('main.BQ_CLIENT') def test_happy_path(self): data = {'trigger': 'testval'} req = Mock(get_json=Mock(return_value=data), args=data) assert 200 == main.http_to_bq(req) The problem is that bigquery.Client() is called before the patch is created, due to import main being above the test class. How can I work around this? |
XOR operation in C Posted: 26 Apr 2021 08:33 AM PDT I've been facing a problem for a few hours with my XOR operation in C. I'm trying to XOR the content of two char * between each other. char* toto = malloc(sizeof(char)*5); char* bob = malloc(sizeof(char)*5); They both contain only 0 and 1 with 5 slots each. The printf for toto returns 00011 and bob returns 11111 . printf("%s", toto) => 11111 printf("%s", bob) => 00011 These are the two values that I'm trying to XOR in the end. First I proceed by steps : 1- Translate each of them into an int value int val_toto = atoi(toto); int val_bob = atoi(bob); // printf("%d", val_toto) => 11111 // printf("%d", val_bob) => 11 As you can see the 0 in bob disapeared, no problem. 2- Use the XOR operator ^ between their respective same bits int result = val_toto ^ val_bob; And here comes the problem : printf("%d", result) => 11116 The result of the XOR operation should be 11111 ^ 00011 // the 0 are taken care of even if not showed in printf ------- 11100 // but I get 1116 ??? The real deal is that the problem occurs only when I use that combination for toto and bob . The XOR operations works fine for all of them, example : toto => 00101 // as char* bob => 000001 //then I use atoi() with each of them toto => 101 // as int bob => 1 And as a result I get what's expect : 101 XOR 1 => 100 //as int Do you have any idea why it works fine in the combination above for instance but never when I have a 11111 ? Thank you |
I always get Index out of bounds in my program Minesweeper java Posted: 26 Apr 2021 08:33 AM PDT This is my program, a minesweeper where it should determine the number of adjacent. The input should be : Enter number of test case(s): 2 Enter row and column: 4 4 And the third input is . * . . . . . . . . . * . . . . The output should be: 1 * 1 0 1 1 2 1 0 0 1 * 0 0 1 1 I am getting the error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.base/java.lang.StringLatin1.charAt(Unknown Source) at java.base/java.lang.String.charAt(Unknown Source) at Minesweeper.print_adjacent(Minesweeper.java:23) at Minesweeper.main(Minesweeper.java:78) [Program finished] Recommendations and changes are welcome, I know my code is not so good Here is the full code of my program: static Scanner sc = new Scanner(System.in); static void print_adjacent (int input1, int input2) { char [][] mine = new char [input1][input2]; String line = " "; for(int i = 0; i < input1; i++ ) { line = sc.nextLine(); for(int j = 0; j < input2; j++) mine[i][j] = line.charAt(j); } // initialize counter int [][] counter = new int [input1][input2]; for(int k= 0; k < input1; k++){ for(int l = 0; l < input2; l++){ counter [k][l] = 0; } } for (int row = 0; row < input1; row++) { for (int col = 0; col < input2; col++) { if (mine[row][col] == '*') { counter [row - 1][col - 1]++; counter [row - 1][col]++; counter [row - 1][col + 1]++; counter [row][col - 1]++; counter [row][col + 1]++; counter [row + 1][col - 1]++; counter [row + 1][col]++; counter [row + 1][col + 1]++; } } } for (int m = 0; m < input1; m++) { for (int n = 0; n < input2; n++) { if (mine[m][n] == '*') System.out.print("*"); else System.out.print(counter[m][n]); } System.out.println(); } System.out.println(); } public static void main(String args []) { int test_no, input1, input2; System.out.printf("%20s\n", "Minesweeper"); System.out.print("Enter number of test case(s): "); test_no = sc.nextInt(); sc.nextLine(); System.out.print("Enter row and column: "); for(int i = 0; i < test_no ; i++) { input1 = sc.nextInt(); input2 = sc.nextInt(); print_adjacent(input1, input2); } } } |
How to change the value of first row to its row number in R? Posted: 26 Apr 2021 08:33 AM PDT I have multiple excel sheets to be imported into R. I used the following code files <- list.files(path = "D:/xxx/Daily Report/", pattern = "*.xlsx", full.names = T) tbl <- sapply(files, read_xlsx, simplify=FALSE) %>% bind_rows(.id = "S No") In the S No column, the values that are filled is the file path. I want to convert them into the row number. Getting the following output when I try to change the value of S No tbl <- tbl %>% mutate(.$`S No` = row_number()) Error: unexpected '=' in "tbl <- tbl %>% mutate(.$`S No` =" |
How to change the innerHTML of the char js Posted: 26 Apr 2021 08:33 AM PDT I want to make a Hangman game so I can learn JavaScript, I don't know how to change the innerHTML of the char I made in js. So when I know if the string includes the guess then i want to make the line which represents the correct guess to transform into a charater and make it apear but when i run the code it turns the last of the lines into the correct guess and makes it disapear when there's a new guess and transforms the line into second correct guess. And doesn't reconizez 'o'(the last character that is in the string) I would like to apologize if I made grammer mistakes. //defineing the word var a = 'hello'; // makes the lines for ( var i=0; i<a.length; i++){ var letter = document.createElement("h3"); letter.className = 'letter'+i; var j = 2*i+23; letter.style ="position: absolute;"+"top: 14%;"+"left: "+j+"%;"; letter.innerHTML = "_"; document.body.appendChild(letter); } //submit btn gets the input and if it's correct shows it, if it isn't correct than puts into a wrong words function submt(a,letter){ var inpt = document.getElementById('input'); if (a.includes(inpt.value)){ letter.innerHTML = a[a.indexOf(inpt.value)]; }else { console.log('wrong') } } <!DOCTYPE html> <html lang="en"> <head> <title>Hangman</title> <link rel="stylesheet" href="style.css"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Yanone+Kaffeesatz:wght@500&display=swap" rel="stylesheet"> </head> <body> <p class='letter'>Write the letter in here:</p> <p class='bad'> the wrong letters:</p> <p class='word'>the word:</p> <input type="text" class="input" id="input"> <button class="sub" id='submit' onclick="submt(a,letter)">submit</button> <script src="script.js"></script> </body> </html> |
Memory will not release in C# singleton mode Posted: 26 Apr 2021 08:34 AM PDT I have a puzzle about singleton mode freeing object memory in C# between in C++; Here C++ Code: #include<iostream> using namespace std; class Rocket { private: Rocket() { speed = 100; } ~Rocket() {} static Rocket* ms_rocket; public: int speed; static Rocket*ShareRocket() { if (ms_rocket == NULL) ms_rocket = new Rocket(); return ms_rocket; } static void Close() { if (ms_rocket != NULL) delete ms_rocket; } }; Rocket *Rocket::ms_rocket = NULL; int main() { Rocket* p = Rocket::ShareRocket(); p->speed = 100; cout << p->speed << endl; Rocket::Close(); cout << p->speed << endl; getchar(); } When I use Rocket::Close(), the memory space which ms_rocket pointed to will be freed, ms_rocket become a wild pointer, and the second "cout<age<<endl" show is not 100, but when I use C# , I also use Dispose(), but still show 100. here the C# code: class A : IDisposable { public int age; public A() { } public void Run() { Console.WriteLine("Run"); } #region IDisposable Support private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { Console.WriteLine("A is release"); } disposedValue = true; } } public void Dispose() { Dispose(true); }
|
No comments:
Post a Comment