Sunday, March 28, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


WooCommerce Analytics - Add meta data to query

Posted: 28 Mar 2021 07:59 AM PDT

Does anybody know if there is a hook to change/adapt the query under the WooCommerce Analytics tab?

I'm setting up a basic vendor marketplace, which creates sub-orders split out by the author (vendor).

These sub-orders have a parent_id set in wp_posts to distinguish them from the parent order and also an extra meta value _marketplace_vendor_id set in wp_postmeta to be used within any loop that requires it.

Having these "extra" sub-orders results in skewed sales data.

I would like to amend the query under the WooCommerce Analytics tab to only return data for orders if parent_id is empty and in the case of a vendor user, only return order data specific to their _marketplace_vendor_id.

SwiftUI. ScrollView on watchOS and message "AttributeGraph: cycle detected through attribute"

Posted: 28 Mar 2021 07:59 AM PDT

I try to run code like this on Apple Watch (simplified version of code with the same problem from a large project):

import SwiftUI    struct ContentView: View {      @State var fields = ["1", "2", "3"]         var body: some View {          TabView() {              ForEach(fields.indices, id: \.self) { index in                  VStack {                      ScrollView {                          Text(fields[index])                      }                      Button("Pop", action: { let _ = fields.popLast() })                  }              }          }      }  }  

But get output message like this when press "Pop" button:

...  === AttributeGraph: cycle detected through attribute 14356 ===  === AttributeGraph: cycle detected through attribute 14356 ===  === AttributeGraph: cycle detected through attribute 14728 ===  === AttributeGraph: cycle detected through attribute 14728 ===  === AttributeGraph: cycle detected through attribute 14356 ===  === AttributeGraph: cycle detected through attribute 14356 ===  ...  

How to fix these warnings?

Note:
When ScrollView removed all work properly.

Undo-Last-Action in php: Storing hashed queries in MySQL?

Posted: 28 Mar 2021 07:59 AM PDT

Good day. I am about to go ahead and implement an undo-last-action system on my website. Addressing those experts out there, would you say that I should not do it my method for whatever reason? I'll explain the procedure below.

Client side, the user can use their keyboard to press Ctrl + Z to undo the last action. I use jQuery for this:

document.addEventListener('keydown', function(event) {    if (event.ctrlKey && event.key === 'z') {      var UndoLastAction = confirm('Undo last action?');      if (UndoLastAction === false) {        return; //don't do anything.      } else {        //use ajax to fetch the latest row in the DB in table called "undo_actions"        //unhash the query, then execute it.      }    }  });  

I created a table in my database that is structured as such:

CREATE TABLE undo_actions (  id INT(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,  undo_code TEXT not null, /*Hashed sql query to undo the last action. Once this code is used up (i.e. when ctrl Z is confirmed) then delete this row so as to avoid double-undoing and other errors. Since this will be sql code, stringyfy it well, and stripslashes when executing it. An example of this code would be: "UPDATE users SET username = my_old_username WHERE user_id = 1" and hashed before it's been inserted into the DB */  date_of_action DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP  );  

The above table will be populated each time I do anything (that I would like to later edit/delete) on my website, such as, change my username, change my password, change my customer order number, and so on. Whenever I make such a change, I also log a "reverse" query into the undo_code column, saving the old values into that query, hashing the query, and inserting it into the database.

The reason I came up with this system is for the sake of simplicity. If you think this is a major security hazard which I should stay away from, kindly share your input :-)

material ui drawer + react-router-dom

Posted: 28 Mar 2021 07:59 AM PDT

I put all routes as children of Material UI drawer and use as props. Since the login page cant have the drawer, how can I structure the login route so that it doesnt include the drawer? What im trying now joins everything together

function App(props) {    const { history } = props;    return (      <BrowserRouter>        <Route path="/" exact component={Login} />        <Drawer history={history}>          <Switch>            <Route path="/kids" component={Listing} />            <Route path="/register" component={Register} />          </Switch>        </Drawer>      </BrowserRouter>    );  }    export default App;    

How to compare two dates (not time) in django-python project?

Posted: 28 Mar 2021 07:58 AM PDT

Here It is my function to print the previous(oldTickets) and upcoming(newTickets) bookings.
journeyDate is database attribute(column name) which is of type date and ticketDetail is model name.
Here It is showing error in comparing date attributes.

def booking(request):      if request.user.is_authenticated:          user_name = request.user.username          today = date.today()          oldTickets = ticketDetail.objects.all()          oldTickets = ticketDetail.objects.filter(userName=user_name).filter(ticketDetail.journeyDate<today)          newTickets = ticketDetail.objects.all()          newTickets = ticketDetail.objects.filter(userName=user_name).filter(ticketDetail.journeyDate>today)          context = {'oldticket':oldTickets, 'newticket':newticket}          return render(request, 'bookticket/myBookings.html', context)      else:          return redirect('/login')  

Can anyone guide me, how to solve this error?
Thank You :)

How can I use JavaScript to create subtotals by group and a grand total?

Posted: 28 Mar 2021 07:58 AM PDT

I am just starting to learn JavaScript and am fumbling my way through it while attempting to do some less than straightforward script writing.

I have a Django website that handles registration. I have a multi-step registration form, and the first step is to identify eligible, open-for-registration activities for children in a family. The list of children and activities is built dynamically so I don't know ahead of time how many sets of child/activities there will be.

There are two parts to the first step of the registration process for each child: selecting an activity/activities and determining whether a participant needs a uniform for a selected activity. I would like to create fee subtotals by child, and then a total registration fee. The math/logic for the latter seems to be working. I am currently experiencing two problems which I cannot figure out how to resolve:

1: how do I create and display subtotals for each child's combination of activities/uniforms? 2: how do I structure the JavaScript/HTML to pair the radio buttons for uniforms so that only one of "need a uniform/have a uniform" buttons is on, without unchecking previously checked radio buttons?

Here's a rudimentary fiddle with the relevant section of the form:Ittps://jsfiddle.net/3wos7zrf/

Thanks for any advice/direction you can provide

Why can't I use the variable Password here? What is the scope? PHP

Posted: 28 Mar 2021 07:58 AM PDT

I'm building a password recovery system but somehow it doesn't work the way i wanted. When I try to access the password variable, it just is an empty string even though in the top scope (under the declaration of the var it prints out the password.

I'm very confused I mean if i declare a var there why can't i use it in the other if else statemens? Anyway here is the code:

<?php     if (isset($_POST["submit"])) {      $selector = $_POST["selector"];      $validator = $_POST["validator"];      $password = $_POST["password"];      var_dump($password);      /* Here it prints out the password */            // Empty Check      if (empty($selector) || empty($validator) || empty($password)) {          $_SESSION["errorMessage"] = "Something went wrong :(";          header("Location: http://localhost/m/forgot_password.php");          exit();      }        // Password Check      $matches = null;      preg_match('/^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{10,35}$/', $password, $matches);      if (empty($matches)) {          $_SESSION["errorMessage"] = "Password does not match the criteria. (Minimum of 10 character, 3 lowercase letters, 2 uppercase letters, 2 numerials and at least 1 special character (!@#$&*) | Maximum of 40 character)";          header("Location: ../reset_password.php?selector=". $selector ."&validator=". bin2hex($token));          exit();      }        $currentDate = date("U");        require_once "Database.php";        $sql = "SELECT * FROM password_reset WHERE selector=? AND expires >= ?";      $stmt = mysqli_stmt_init($db);        if (!mysqli_stmt_prepare($stmt, $sql)) {          $_SESSION["errorMessage"] = "Something went wrong :(";          header("Location: http://localhost/m/forgot_password.php");          exit();      } else {          mysqli_stmt_bind_param($stmt, 'ss', $selector, $currentDate);          mysqli_stmt_execute($stmt);            $result = mysqli_stmt_get_result($stmt);          if (!$row = mysqli_fetch_assoc($result)) {              $_SESSION["errorMessage"] = "Something went wrong :(";              header("Location: http://localhost/m/forgot_password.php");              exit();            } else {              $tokenBin = hex2bin($validator);              $tokenCheck = password_verify($tokenBin, $row["token"]);                if ($tokenCheck == false) {                  $_SESSION["errorMessage"] = "Something went wrong :(";                  header("Location: http://localhost/m/forgot_password.php");                  exit();                } elseif ($tokenCheck == true) {                  $tokenEmail = $row["email"];                    $sql = "SELECT * FROM users WHERE email=?";                  $stmt = mysqli_stmt_init($db);                    if (!mysqli_stmt_prepare($stmt, $sql)) {                      $_SESSION["errorMessage"] = "Something went wrong :(";                      header("Location: http://localhost/m/forgot_password.php");                      exit();                    } else {                      mysqli_stmt_bind_param($stmt, "s", $tokenEmail);                      mysqli_stmt_execute($stmt);                                            $result = mysqli_stmt_get_result($stmt);                      if (!$row = mysqli_fetch_assoc($result)) {                          $_SESSION["errorMessage"] = "Something went wrong :(";                          header("Location: http://localhost/m/forgot_password.php");                          exit();                        } else {                          $sql = "UPDATE users SET password=? WHERE email=?";                          $stmt = mysqli_stmt_init($db);                            if (!mysqli_stmt_prepare($stmt, $sql)) {                              $_SESSION["errorMessage"] = "Something went wrong :(";                              header("Location: http://localhost/m/forgot_password.php");                              exit();                                    } else {                              var_dump($password);                              /* Why doesnt it work here? It prints a empty string */                                die();                                $passwordHash = password_hash($password, PASSWORD_DEFAULT);                                mysqli_stmt_bind_param($stmt, "ss", $passwordHash, $tokenEmail);                              mysqli_stmt_execute($stmt);                                $sql = "DELETE FROM password_reset WHERE email=?;";                              $stmt = mysqli_stmt_init($db);                                if (!mysqli_stmt_prepare($stmt, $sql)) {                                  $_SESSION["errorMessage"] = "Something went wrong :(";                                  header("Location: http://localhost/m/forgot_password.php");                                  exit();                              } else {                                  mysqli_stmt_bind_param($stmt, 's', $tokenEmail);                                  mysqli_stmt_execute($stmt);                                    $_SESSION["errorMessage"] = "Your password was updated!";                                  header("Location: ../login.php");                                  exit();                              }                          }                      }                  }              }          }      }    } else {      $_SESSION["errorMessage"] = "Something went wrong :(";      header("Location: http://localhost/m/forgot_password.php");      exit();  }  

Is there anything i oversaw? What can i do to make it work again? Thanks very much.

PS: I use PHP 8

How to assert expected HTTPExceptions in FastAPI Pytest?

Posted: 28 Mar 2021 07:58 AM PDT

I have a simple router designed to throw an HTTPException:

@router.get('/404test')  async def test():      raise HTTPException(HTTP_404_NOT_FOUND, "404 test!")  

I want to assert that the exception was thrown, as per FastaAPI docs:

def test_test():      response = client.get("/404test")      assert response.status_code == 404  

The exception is thrown before the assertion gets evaluated, marking test as failed:

>       raise HTTPException(HTTP_404_NOT_FOUND, "404 test!")  E       fastapi.exceptions.HTTPException: (404, '404 test!')  

What am I missing to properly anticipate HTTPExceptions in my test?

Unity3d OnTriggerEnter, animation

Posted: 28 Mar 2021 07:58 AM PDT

I want my character to play an animation when pressing a key when it enters the trigger, but I couldn't figure it out. Can you help? Here the my code

public Text text;  public Animator anim;    public void Start()  {      text.enabled = false;      anim = GetComponent<Animator>();  }    public void OnTriggerEnter()  {      text.enabled = true;  }     public void Update()  {     if (Input.GetKeyDown("e"))     {      anim.Play("DoorOpen");     }   }  

}

Is this the correct way to process results through the Spring Integration Flow?

Posted: 28 Mar 2021 07:58 AM PDT

I am currently working on a personal project - in which I need my Spring application to take queries from an EMQX (MQTT Server) and query its data for corresponding results, and then push the results to a topic with the query UUID.

This is working - after many hours understanding how the Spring Integration framework works. But I think the way in which the handler is using "block" is incorrect - and not in keeping with the manner in which the Integration Flow should operate. Whilst this works I do want to make sure it is being done properly - out of respect for the work - and to avoid future issues.

The code snippet below should be enough to understand what it is that I'm trying to achieve - and where the potential issue lies.

    @Bean  fun mqttInFlow() : Publisher<Message<String>> {      return IntegrationFlows.from(inbound())          .handle<String> { payload, headers ->              val emotionalOutput: EmotionalOutput = gson.fromJson(payload, EmotionalOutput::class.java)              emotionalPrintService.populateEmotionalOutput(emotionalOutput).map {                  MessageBuilder.withPayload(gson.toJson(it))                      .copyHeaders(headers)                      .setHeader(MqttHeaders.TOPIC, "query/" + it.query_uuid).build()              }.block()          }          .channel(outgoingChannel())          .toReactivePublisher()  }  

run Tensorflow exemple in Google Cloud api

Posted: 28 Mar 2021 07:58 AM PDT

I follow this tutorial example of pet detection, and I have encountered some problem when I run this second command :

bash object_detection/dataset_tools/create_pycocotools_package.sh /tmp/pycocotools  python setup.py sdist  (cd slim && python setup.py sdist)  

but I continue without her and when I start the training of the model:

gcloud ml-engine jobs submit training `whoami`_object_detection_eval_validation_`date +%s` \  --job-dir=gs://${YOUR_GCS_BUCKET}/train \  --packages dist/object_detection-0.1.tar.gz,slim/dist/slim-0.1.tar.gz,/tmp/pycocotools/pycocotools-2.0.tar.gz \  --module-name object_detection.model_main \  --runtime-version 1.15 \  --python-version 3.7 \  --scale-tier BASIC_GPU \  --region us-central1 \  -- \  --model_dir=gs://${YOUR_GCS_BUCKET}/train \  --pipeline_config_path=gs://${YOUR_GCS_BUCKET}/data/pipeline.config \  --checkpoint_dir=gs://${YOUR_GCS_BUCKET}/train   

I have this error in google cloud task :

The replica master 0 exited with a non-zero status of 1.   Traceback (most recent call last):    File "<string>", line 1, in <module>    File "/usr/lib/python3.7/tokenize.py", line 447, in open      buffer = _builtin_open(filename, 'rb')  FileNotFoundError: [Errno 2] No such file or directory: '/tmp/pip-req-build-o2xrywvb/setup.py'    

Discord sends message more than expected

Posted: 28 Mar 2021 07:58 AM PDT

import requests  from bs4 import BeautifulSoup  from random import choice  import re, json  import discord  Bot = discord.Client()    def names():      asd = []      n = open("1", "wb")      url = 'aurl.com'      r = requests.get(url).text      a = json.loads(r)      for i in a.items():          asd.append(i[1]["baslik"])      return asd  @Bot.event  async def on_ready():      print(1)      list = names()      channel = Bot.get_channel(825744124485173298)      for i in list:          await channel.send(i)  Bot.run(key)  

I want this bot to get dicts from 'aurl.com' site and send it. But following script send same dict more than one time. Where am i making mistake ?

I tried to import an excel file to Rstudio & the data on the original file don't match the data displayed on the r window, r creates new name for row

Posted: 28 Mar 2021 07:59 AM PDT

View Image here Take a look at the image and help me to solve it. Thank you

Parameters after function call?

Posted: 28 Mar 2021 07:58 AM PDT

I came across this code in PassportJS examples:

app.get('/auth/reddit', function(req, res, next){    req.session.state = crypto.randomBytes(32).toString('hex');    passport.authenticate('reddit', {      state: req.session.state,      duration: 'permanent',    })(req, res, next);  });  

I am interested in this statement:

passport.authenticate('reddit', {      state: req.session.state,      duration: 'permanent',    })(req, res, next);  

What does (req, res, next) mean/do in this statement?

Unable to access Google Sheets data with Apps Script and Advanced Protection

Posted: 28 Mar 2021 07:59 AM PDT

I'm trying to write a script to process data from a Google Sheets spreadsheet. I have Google Advanced Protection enabled and it seems to be blocking my script even though I wrote it for my own data.

The FAQ says:

If you're enrolled in Advanced Protection, Apps Script can be used. If scripts request access to certain data in your account, like emails, documents, or photos, they may be blocked.

However, I can't find any details about which functions are actually blocked or if there's any acceptable way to read my sheets data. Right now it seems like any function that tries to actually read data such as SpreadsheetApp.getCurrentCell or getActiveSpreadsheet prompts me for authorization (which is then blocked by advanced protection).

Is there a way around this without disabling advanced protection or will I just have to export my data and process it elsewhere?

I have python 2.7 and 3.8 both in my system, how can I use python 3.8 or remove 2.7?

Posted: 28 Mar 2021 07:58 AM PDT

I have python3 and python commands, like this:

screen image of terminal with python3 and python commands

Nevron line chart with vb.net

Posted: 28 Mar 2021 07:59 AM PDT

I'm trying to use Nevron to display data in line(curve) charts. Can anyone please help with a tutorial. The stuff on Nevron help aren't helpful. Many thanks in advance.

How can I search file1.txt and file2.txt for matching characters and print output to a new file

Posted: 28 Mar 2021 07:59 AM PDT

I've ran into a problem! I simply do not have enough knowledge to solve this on my own so if anyone is able to help me that'd be appreciated.

I have two text files... File1.txt and File2.txt they have similar formatting but not exact. Names are on separate line numbers and the files have different line counts. Doing this manually wouldn't be viable due to the amount of data in the files.

Example of file formats:

File1.txt

NAME:FLAT  Jerome:Flat 6  Jimmy:Flat 4  

File2.txt

0:NAME:JOB:MONEY:FLAT  1:Bob:Developer:$500:Flat 7  2:Jerome:Gardener:$50:Flat 6  3:Cindy:Graphics:$100:Flat 5  4:Jimmy:Mod:$150:Flat 4  

I'm trying to search through file1.txt to see which NAME matches with file2's NAME and print out the full line of file2.txt into a new text document.

Here's an example of what I would like to do:

Checks matching NAME in file1.txt and file2.txt  Ignores "1:Bob:Developer:$500:Flat 7" because Bob only exists in file2.txt  Pastes "2:Jerome:Gardener:$50:Flat 6" into file3.txt because Jerome exists in file1.txt and file2.txt  Ignores "3:Cindy:Graphics:$100:Flat 5" because Cindy only exists in file2.txt  Pastes "4:Jimmy:Mod:$150:Flat 4" into file3.txt because Jimmy exists in file1.txt and file2.txt  

How file3 would look File3.txt

2:Jerome:Gardener:$50:Flat 6  4:Jimmy:Mod:$150:Flat 4  

Thanks for reading! If anyone could let me know if this is possible that'd be great.

EDIT: This is similar to what i'd like but it does by line.

awk 'FNR==NR{a[$1];next}($1 in a){print}' file2.txt file1.txt > file3.txt  

open a position at the same time everyday with a daily stop loss (pinesript - tradingview)

Posted: 28 Mar 2021 07:58 AM PDT

So, I would like to open a trade at the same time everyday and close it only if it hits my daily adjusted 5% stop loss. If it has closed the previous day then open a new trade with a new stop loss. It's that simple but for some reason I can't build it correctly. I want to build the stop loss function manually and not use the strategy.order built in loss function. Thanks in advance.

// Detect a new day  newDay = change(dayofweek)    // Get Previous close of the opening bar.   lastClose = valuewhen(new_day, close, 1)    // Detect whether in a trade  notInTrade = strategy.position_size < 0    // Stop Level  sl_inp = input(5.0, title='Stop Loss %', type=input.float) / 100  stopLevel = lastClose * (1 - sl_inp)    // Orders  strategy.order("Long", true, when=newDay and notInTrade)  strategy.close("Long", true, when=stopLevel > close)  

Eliminate all non latins words from a list of strings [duplicate]

Posted: 28 Mar 2021 07:58 AM PDT

Jupyter Notebook Snippet

can someone please tell me why is my list not empty?

#Function that verify if a word is a latin word (delivers true) or not (delivers false)  # -*- coding: utf-8 -*-    def is_latin(word):  try:      word.encode(encoding='utf-8').decode('ascii')  except UnicodeDecodeError :      print(word) # for debugging purposes      return False  else:      return True    # Function to eliminate a latin word from a given List of Strings    def eliminate_non_latin(initial_list):  for element in initial_list:      if not is_latin(element):          initial_list.remove(element)  return initial_list    #Testing the two functions    Test=['幸福','المغرب']  print(eliminate_non_latin(Test))  

Output:

  • 幸福 ====> is_latin function works fine (Debugging)
  • ['المغرب'] ====> here's my problem this list should be empty!

Am i missing something?

Sqlite3 - UPDATE Column by Lookup

Posted: 28 Mar 2021 07:59 AM PDT

I am trying to lookup and update Market_Sector column in Accounts from MarketSector in Clients. The key columns are Client in Accounts Table and Id in Clients in Table. I have written the below code, but the look up only returns None! Please help!

import sqlite3  con = sqlite3.connect('''C:\\Users\\Bank DB1.db''')  cur  = con.cursor()  cur.execute('''ALTER TABLE Accounts ADD Market_Sector''')  cur.execute('''UPDATE Accounts              SET Market_Sector = (SELECT MarketSector FROM Clients              WHERE Client = (SELECT Id FROM Clients))''')  con.commit()  con = sqlite3.connect('''C:\\Users\\Bank DB1.db''')  cur.execute('''SELECT * FROM Accounts''')  results = cur.fetchall()  print(results)  con.close()  

.Net 5 change DbContext in controller

Posted: 28 Mar 2021 07:59 AM PDT

I have a design where I have one "master" database and multiple "client" databases. When I get a request I lookup in the master database and setup the connection to the right client database.

I'm now trying to design the same in .net 5, where I setup the masterDB in StartUps ConfigureServices():

services.AddDbContext<Models.DataContext.MasterContext>(options =>   options.UseSqlServer("Name=MasterDB"));  

I then on the request lookup in the MasterDB as the first thing in every controllers methods and find the connectionString for the clientDB.

But how do I then set it up at that point in time? While also not having to think about disposal of the connection, like when it's passed in using dependency injection, it's handled.

Any advice to do things slightly different are also encouraged.

Match values by string containing another string

Posted: 28 Mar 2021 07:58 AM PDT

I have two dataframes. The first looks like this:

month     Joanne K. Rowling   Samuel L. Jackson  2000/01   1                   0  2000/02   1                   1  2000/03   0                   1  2000/04   0                   0  2000/05   0                   1  2000/06   1                   0  

test_1<-data.frame("Month"=c("2000/01","2000/02","2000/03","2000/04","2000/05","2000/06"),"Joanne K. Rowling"=c(1,1,0,0,0,1),"Samuel L. Jackson"=c(0,1,1,0,1,0))

The other looks like this

Name            Score  Joanne Rowling  67  Samuel Jackson  52  

test_2<-data.frame("Name"=c("Samuel Jackson","Joanne Rowling"),"Score"=c(67,52))

I'd like to combine them in order to obtain the following data frame

month     Joanne K. Rowling   Samuel L. Jackson  2000/01   52                   0  2000/02   52                   67  2000/03   0                    67  2000/04   0                    0  2000/05   0                    67  2000/06   52                   0  

Where the value 1 is replaced by the score in test_2. The colnames from test_1 may differ slightly from the values in table_2, so the match should not be fixed. I found a way to do this:

for(i in 1:nrow(test_2)) {    for(k in 1:ncol(test_1){      for(l in 1:nrow(test_1)){        if(grepl(test_2[i,6],as.data.frame(colnames(test_1))[k,1])) {          if(test_1[l,k]==1){            test_1[l,k]<-test_2[i,5]          }        }      }    }  }  

But it is very inefficient, as I have to apply this to a list of dataframes. Please, try to write an efficient way with less loops as possible

How to return pointer to array of struct in C

Posted: 28 Mar 2021 07:58 AM PDT

I created a struct of student inside the function using malloc and populated it with data. I want to return the address of the array of struct back to main and print it line by line, but with my implementation, it is not printing. I debugged my code and indeed, it is able to return the address of my array to main. I don't know why it's not printing though. Any thoughts?

#include<stdio.h>  #include<stdlib.h>  #include<string.h>    typedef struct student Student;    struct student{      char name[100];      int age;      char sex;  };    Student** getstudents(int);  void free_students(Student**, int);    int main(){      Student **students;      int n;      scanf("%d\n", &n);      students = getstudents(n);      for(int i=0; i<n; i++){          printf("Name: %s, Sex: %s, Age: %d\n", students[i]->name, students[i]->sex, students[i]->age);      }      free_students(students, n);      getch();      return 0;  }    Student **getstudents(int n){      Student **t = malloc(sizeof *t * n); // memory for the array of pointers        for(int i = 0; i < n; i++){ // memory for each individual pointer          t[i] = malloc(sizeof **t);      }        for(int i = 0; i < n; i++){          char entry[100];          fgets(entry,100,stdin);;            char newString[3][25];            int k,j,ctr;          j=0; ctr=0;          for(k=0;k<=(strlen(entry));k++)          {              if(entry[k]==' '||entry[k]=='\0')              {                  newString[ctr][j]='\0';                  ctr++;                  j=0;              }              else              {                  newString[ctr][j]=entry[k];                  j++;              }          }            strncpy(t[i]->name, newString[0], strlen(newString[0]) + 1);          t[i]->sex = newString[1];          t[i]->age = atoi(newString[2]);      }        return t;  }        void free_students(Student **students, int n){      for(int i=0; i<n; i++){          free(students[i]);      }      free(students);  }  

I am only allowed to modify the code in Student **getstudents(int n).

Applying formula to a variable range that is transposed

Posted: 28 Mar 2021 07:59 AM PDT

Sorry if I am not able to phrase the question properly as this is my first VBA project. I am facing this problem:

  1. I would like to apply a formula to a given range.
  2. However, the number of columns are not fixed and will vary.

Hopefully the following screenshots will make it easier to visualise what I'm doing. Screenshot 1: I would like for the code to auto select from column C onwards, and apply the formula in the next image. The number of columns will vary as more students attempt the quiz.

Screenshot 2: This is the formula I wish to apply to the selected range. After that, I would be able to loop through the list of teachers from B31 and below one by one, copy the range of answers for each teacher's students and paste them onto Sheets 3-6 which contain the first set of results I mentioned earlier.

Thanks alot for your help in advance!


Sub obtainsecond()      Sheets("Question_answers").Select      Range("C31").Select      ActiveCell.Formula2R1C1 = _          "=FILTER(R[-29]C:R[-4]C[3],ISNUMBER(SEARCH(R[-1]C,R[-30]C:R[-30]C[3])))"        End Sub  

How to instantiate a list of types for compile-time/static polymorphism

Posted: 28 Mar 2021 07:58 AM PDT

I'm implementing a compile time dispatcher which makes use of static polymorphism and metaprogramming.

I have a list of types which I would like to instantiate into a runtime std::array.

struct Test  {       typedef std::integral_constant<int,0> nop;       typedef std::integral_constant<int,1> A;       typedef std::integral_constant<int,2> B;       typedef std::integral_constant<int,3> C;         using list = mp_list<A, B, C>; // mp_list expands to: template<A, B, C> struct {};         struct Things{           int (Test::*process)(int foo, float bar);           const std::string key;           int something;           float other;       };         typedef std::array<Things, mp_size<list>::value> Thing_list;       Thing_list thing_list;         template<typename T=nop> int process(int foo, float bar);         // stuff...         Test();  }  

In the above code, mp_list is simply a variadic template which 'expands' to struct<A, B, C> mp_list. And likewise, mp_size gives an mp implementation of the sizeof.

As can be inferred, the Thing_list is an array with a compile-time known size.

I can then specialize a template function like so:

template<> int process<Test::B>(int foo, float bar){ /* do stuff */ };  

to achieve compile-time polymorphism.

The above code works well, except that to initialize it, I am stuck at doing this in the constructor:

Test::Test() thing_list({{{&Test::process<A>, "A"}, // this all should be achieved through meta-programming                            {&Test::process<B>, "B"},                            {&Test::process<C>, "C"}}}} )  {     // stuff  }  

There are two things I'm unable to get right:

  1. I would like to have a MP based initialization of the list. As I update the list definition in the declaration, I would like my initialization to automatically reflect that list type.
  2. I would also like to avoid having to duplicate the name of the type as a string literal. I have tried to use something like integral_constant but the use of const char* as a template parameter seems to be forbidden. I am left to having to duplicate declaration (triplicate, really).

This answer is almost the solution: it takes a list of types and instantiates them like so:

static std::tuple<int*, float*, foo*, bar*> CreateList() {  return { Create<int>(), Create<float>(), Create<foo>(), Create<bar>() };  }  

However, I'm stuck on converting from std::tuple to std::array.

The main question is #1. Bonus for #2 without using #define based trickery.

If anyone cares: this code is destined for embedded software. There are dozens of different types, and importantly, each type (e.g. A, B, C) will have an identically structured configuration to be loaded from memory (e.g. under a configuration key for "A") - hence the reason of wanting to have access to the string name of the type at runtime.

Django how to remove default string " Currently: avatar/default.png " from template

Posted: 28 Mar 2021 07:59 AM PDT

I'm using Django to upload user avatar,my question is ,how to remove the default string " urrently: avatar/default.png Clear " from template

Model:

class User(AbstractUser):      nickname1 = models.CharField(max_length=30, blank=True, null=True, verbose_name='昵称')      url = models.URLField('个人网址', blank=True, help_text='提示:网址必须填写以http开头的完整形式')      avatar = ProcessedImageField(upload_to='avatar', default='avatar/default.png', verbose_name='头像',                                   processors=[ResizeToFill(100, 100)],  # 处理后的图像大小                                   format='JPEG',  # 处理后的图片格式                                   options={'quality': 95}  # 处理后的图片质量                                   , blank=True                                   )      identifier = models.CharField(max_length=40, unique=True,blank=True, null=True)      ...      USERNAME_FIELD = 'identifier'        def save(self, *args, **kwargs):          if len(self.avatar.name.split('/')) == 1:              self.avatar.name = self.username + '/' + self.avatar.name          super(User, self).save()          class Meta:          verbose_name = '用户信息'          verbose_name_plural = verbose_name           ordering = ['-id']      def __str__(self):          return self.username  

url:

path('<str:username>/', views.account_profile,name = 'process'),  

view.py:

@login_required  def account_profile(request, username):      profile_user = get_object_or_404(User, username=username)      messages = []            if request.method == 'POST':                   form = UserDetailForm(request.POST, request.FILES, instance=request.user)          if form.is_valid():              form.save()              messages.append('资料修改成功!')      form = UserDetailForm(instance=request.user)      return render(request, 'user/user_detail.html', context={'form': form,                                                               'messages': messages,                                                              'profile_user': profile_user,})  

form:

class UserDetailForm(ModelForm):      class Meta:          model = User          fields = ['avatar',]  

template:

<form class="profile" method="post" enctype="multipart/form-data"           action="/<str:username>/">          {% csrf_token %}          {{ form|crispy }}          <div class="avatar">              <img class="img-rounded" src="{{ request.user.avatar.url }}">          </div>          <button class="primaryAction" type="submit">更新资料</button>      </form>  

In the form I only set filed avatar there,but there is always a string " Currently: avatar/default.png Clear "

Any friend know how to remove this string?

Child-EBP vs Child-SP

Posted: 28 Mar 2021 07:58 AM PDT

While following up on some windbg tutorials I have noticed that some callstacks using k command are in this format, specially mine

Child-SP          RetAddr           Call Site  

While other online resources like CodeProject have the k command spit out info in this format

Child-EBP          RetAddr           Call Site  

I am confused to why there is a difference between my output and theirs and to what that truly means.

How to upgrade my global vue-cli install to the latest version?

Posted: 28 Mar 2021 07:58 AM PDT

I already have vue-cli 3.5.5 installed. When I run vue create myapp, it shows message Update available 3.6.2.

Vue CLI v3.5.5  ┌───────────────────────────┐  │  Update available: 3.6.2  │  └───────────────────────────┘  

How to upgrade vue-cli to the latest version?

When I run npm i -g vue-cli it installs vue-cli version 2.9.6 instead of upgrading the existing vue cli version.

OS: Ubuntu 18.04.1.

node version: 10.15.3.

nvm version: 0.34.0.

Switch statement in C++

Posted: 28 Mar 2021 07:59 AM PDT

Consider:

#include <iostream>    using namespace std;    int main()  {      int score;      char grade;      cout << "Enter your score: " << endl;      cin >> score;      if (score >= 90)          grade = 'a';      if (score >= 80)          grade = 'b';      if (score >= 70)          grade = 'c';      if (score >= 60)          grade = 'd';      else          grade = 'f';        cout << grade << endl;        switch (grade) {          case 'a':              cout << "Good job" << endl;              break;          case 'c':              cout << "Fair job" << endl;              break;          case 'f':              cout << "Failure" << endl;              break;          default:              cout << "invalid" << endl;      }        cin.get();      return 0;  }  

Why is it giving my default switch case when I enter 95 when I should be getting case 'a'?

No comments:

Post a Comment