Thursday, October 7, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


REACTJS.NET SSR - Object doesn't support property or method 'forwardRef'

Posted: 07 Oct 2021 08:06 AM PDT

I am trying to render my REACT components via SSR with REACTJS.NET in ASP.NET project.

In the JS file for SSR, I'm importing SimpleBar component from simplebar-react package. This is causing the error TypeError: Object doesn't support property or method 'forwardRef'.

I currently have 2 JS files, one for server and one for client. In the JS for server I am removing the adding of event listeners and similar. However, I can't get away from importing at least the npm in both JS files.

Any idea on how I can avoid such error?

I am using Webpack + REACTJS.NET version 3.2.0.

How to add multiple records for foreign key in a single request in DRF?

Posted: 07 Oct 2021 08:05 AM PDT

There is a model named as UserSkill. It contains User and Skills ForeignKeys I want to create multiple skills for one user in single post request and i want to store data like this [{'user': 1, 'skills': 1,2,3,4}]. The problem is how can i write create method for that? I do not want to use ManyToMany field for that

class UserSkill(models.Model):      user = ForeignKey(User, on_delete=models.CASCADE)      skills = ForeignKey(Skills, on_delete=models.CASCADE)    class UserSkillSerializer(ModelSerializer):      class Meta:          model = UserSkill          fields = "__all__"    class UserSkillList(ListCreateAPIView):      serializer_class = UserSkillSerializer      queryset = UserSkill.objects.all()        def create(self, validated_data):          ...  

How to make BokehJS work with QtWebEngine in an executable?

Posted: 07 Oct 2021 08:05 AM PDT

I essentially have a working program that creates interactive bokeh figures with CustomJS (widgets and tables) and it works fine in my IDE.

However, when I create an executable with PyInstaller of this code, I get the following error: console.log("Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing").

Since I'm saving the figures as HTML and opening them with QtWebEngine, i'm guessing the issue is there? Im guessing QtWebEngine doesnt have access to the BokehJS library? The HTML themselves work well when opened with chrome.

Here's a small code snippet that covers the problematic code if it helps:

from bokeh.resources import INLINE  from bokeh.embed import file_html  from PyQt5 import QtWidgets, QtWebEngineWidgets, QtCore, QtGui    self.m_output = QtWebEngineWidgets.QWebEngineView()    html_file = Bgf.plot_bokeh(all_my_variables) # this function deals with the figure generation and output a bokeh Document that includes a single plot and widgets with JS    html_file.validate()  with open("html_test.html", "w", encoding="utf-8") as f:      f.write(file_html(html_file, INLINE, "html_test_test"))  url = QtCore.QUrl.fromLocalFile(r"My_ABS_path")    self.ui.Vlayout_network.addWidget(self.m_output) # addind the WebEngine to a widget in the PyQT5 GUI  page = WebEnginePage(self.m_output)  # class webenginepage required for download signals  self.m_output.setPage(page)  self.m_output.load(url)  self.m_output.show()  

Any ideas how i could fix my issue? Thanks in advance

How to safely cancel all pending futures after timing out on allOf()

Posted: 07 Oct 2021 08:05 AM PDT

I am trying to refactor code that sequentially waits on multiple futures to complete, to instead jointly wait for completion.

So I try to wait on multiple futures with a single timeout by using

// Example outcomes  final CompletableFuture<String> completedFuture      = CompletableFuture.completedFuture("hello");  final CompletableFuture<String> failedFuture      = failedFuture(new RuntimeException("Test Stub Exception"));  final CompletableFuture<String> incompleteFuture      = new CompletableFuture<>();    final AtomicBoolean timeoutHandled = new AtomicBoolean(false);  final CompletableFuture<String> checkedFuture      = incompleteFuture.whenComplete(           (x, e) -> timeoutHandled.set(e instanceof TimeoutException));    // this example timeouts after 1ms  try {      CompletableFuture          .allOf(completedFuture, checkedFuture, failedFuture)          .get(1, TimeUnit.MILLISECONDS);  } catch (final InterruptedException e) {      Thread.currentThread().interrupt();  } catch (final TimeoutException e) {      // probably do something here?  }    // but the incomplete future is still pending  assertTrue(checkedFuture.isCompletedExceptionally());  assertTrue(timeoutHandled.get().isTrue());  

However the assert above fails because while the collective future timed out, the individual future did not time out yet. I would like to cancel such individual futures the same way as if they had run into timeouts individually, because they might have individual whenComplete() handlers handling TimeoutExceptions:

Expecting    <CompletableFuture[Incomplete]>  to be completed exceptionally.  

Is there a useful/safe pattern by which I can loop over all exceptions and invoke completeExceptionally() to simulate a timeout in each of the futures, and make sure all "exception handlers" have been invoked before moving on?

Create 2 classes named SavingsAccount (no class modifier) and runSavingsAccount (public)

Posted: 07 Oct 2021 08:05 AM PDT

//Hello guys can you help me to fix this public static setInterestRate(double newRate) becuase it keep getting error

class SavingsAccount {

private double balance;  public double interestRate = 0;    public SavingsAccount()  {      this.balance = balance;      balance = 0;  }     public static setInterestRate(double newRate)  {      interestRate = newRate;   }      public static double getInterestRate()      {          return interestRate;      }         public double getBalance()      {          return this.balance;      }      public void deposit(double amount)      {          balance += amount;      }      public double withdraw(double amount)      {          if (balance >= amount)          {              balance = balance - amount;      }             else {              System.out.println("Insufficient Funds.");          }                 }      public void addInterest(double interest)      {          balance += ((interestRate)*balance);      }      public static void showBalance(SavingsAccount account)      {          getBalance() = account;  }  

}

// main class

import java.util.*;

public class RunSavingsAccount {

public static void main(String[] args){              Scanner input = new Scanner(System.in);                  SavingsAccount savings = new SavingsAccount();                                                    System.out.print("Enter interest rate: ");  double userInterestRate = input.nextDouble();        System.out.print("Enter deposit amount: ");  double depositAmount = input.nextDouble();            System.out.println("Your balance is " + depositAmount);    System.out.print("Press D for another deposit or W for withdraw: ");  String Press = input.nextLine();    if (Press.equals("D")){            savings.setInterestRate(userInterestRate);                         System.out.print("Enter deposit amount: ");      double depositAmount = input.nextDouble();        savings.deposit(depositAmount);            if (savings > 1000){      System.out.println("Your new balance is " + savings.getBalance() + userInterestRate);         } else { System.out.println("Your new balance is " + savings.getBalance());      }                                   } else if (Press.equals("W")){                    System.out.print("Enter withdraw amount: ");      double withdrawAmount = input.nextDouble();        savings.withdraw(withdrawAmount);        System.out.println("Your new balance is " + savings.getBalance());        } else {      System.out.println("Wrong Input! Please try again.");  }        }  

}

error: invalid method declaration; return type required public static setInterestRate(double newRate) ^ 1 error

Stimulus.js private function returns undefined

Posted: 07 Oct 2021 08:05 AM PDT

I call a private function _checkCompletion() in a Stimulus.js controller. The private function sends an Ajax call and given its result, it should return true or false. However, the moduleSlug variable is undefined after the private function is called.

Here is my stimulus method:

nextQuestion() {      var container = this.containerTarget;        var moduleSlug = this.continueBtnTarget.getAttribute("data-course-module-slug");      var allValidated = this._checkCompletion(moduleSlug);      if(allValidated == true) {            container.classList.remove("active");            document.getElementById("quiz-result-container").style.display = "block";      }  }    

Here is the private function:

_checkCompletion(moduleSlug) {      $.ajax({          url: "/check_module_completion",          method: 'post',          beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},          data: {              course_module_slug: moduleSlug          },          success: function(data) {              console.log(data['value']);              if (data['value'] == 'true') {                  return true;              } else {                  return false;              }          },          error: function() {              console.log("Ajax error!");          },      })    }    

Any idea what I am doing wrong? I tried to change the private function into a normal function after the stimulus controller function _checkCompletion() { ... } but the moduleSlug variable is also undefined.

Thanks.

How do I fix infinite scrolling in React?

Posted: 07 Oct 2021 08:05 AM PDT

I have a table mapped with data from API. I want to implement an infinite scrolling such that on scroll to the end of the page, the API loads additional data. Here's my code below...

function Enrollment() {            const [enroll, setEnroll] = useState([]);          const getEnrollments = async () => {      try {         const fetch = await Axios.get(           "https://pshs3.herokuapp.com/enrollments?limit=20&skip=0"         );         setEnroll(fetch.data.data);               } catch (err) {         console.log(err);      }    };       useEffect(() => {       getEnrollments();       return () => {         setEnroll([])               };    }, []);         return (      <Wrapper>               <TableContainer component={Paper}>          <Table stickyHeader aria-label="sticky table">            <TableHead>              <TableRow>                <TableCell />                <TableCell >                  Enrollee Name                </TableCell>                <TableCell >                  Gender                </TableCell>                <TableCell >                  LGA                </TableCell>                             </TableRow>            </TableHead>            <TableBody>              {enroll?.map((enroll, id) => {                return (                  <>                    <TableRow                      key={id}                    >                                         <TableCell component="th" scope="row">                        {enroll.name}                      </TableCell>                      <TableCell align="left">{enroll.gender}</TableCell>                                         </TableRow>                                                         </>                );              })}            </TableBody>          </Table>        </TableContainer>      </Wrapper>    );  }    export default Enrollment;      

The limit and skip are the params and I want to be able to fetch on 20 records on first load. The when a user scrolls to the end of the page, another 20 records should batch with the prev records. How can I be able to do this? please

How to set a maximum number of files for imagePicker in flutter

Posted: 07 Oct 2021 08:05 AM PDT

let me explain How can I set a maximum number of files to pick for filepicker so that I can limit the pick of file so it does not overload the server.

expo IOS testflight crashes after splash screen

Posted: 07 Oct 2021 08:05 AM PDT

app.json : enter image description here

err 01 : https://iosapps-ssl.itunes.apple.com/itunes-assets/Purple125/v4/ba/e0/02/bae00265-fcb9-343c-a933-5dae70c72eed/attachment.crashlog-A85CB792-DDAB-4AAE-86EB-5C19C9497A67.txt?accessKey=1633878024_4869009577037455420_s4zRM2SEhH1m45CzIXi6Nb2gQGFl6sRYg0EO81486Yonfy5SouhywL32JmM9leosgLYKyKEuJTiJr%2FsheRdrc4pO%2FRSl8s85vMDeE8Z1TvHsgbiGm6vFvExofsFRvEWuxEY3Zt07K%2FKNdCrrgOJyFv3FtKZiMrZ%2FeIj5tVkD%2Bi%2FIVHk6A%2FnRB8wh8Dvykzhg0fz6KbhbVD7nrIgrcGJDe2YnHufAkB7PF3jgKZSZroA%3D

err 02 : https://iosapps-ssl.itunes.apple.com/itunes-assets/Purple115/v4/df/e1/33/dfe133e6-afd0-8aac-d499-2c091a6c5cf4/attachment.crashlog-B4FD2AC9-42DA-4E42-A5AD-A8617F6E552D.txt?accessKey=1633878024_2062451314580326046_iZHZ9fgljZvohmZ5QjUFKXr7D9VUQWNuxwqo9aG4LQE3m7%2FpNfAYf1PtvipXa0F7sOV2uJGIaDvNUntZHhGUKody7eqT%2BXZo9fBvOTjbtm9g88N0pe58yAdR6MNHpEN%2B7MYkop3xS0JxuUA9J7CjHRByCOwbXi3M0clGYreAFIKa%2BUhQ2WjLNhmeO1klP4AyKLaLdv0zOTKsYhh72l4vAkTR9oiCTxe4aNt3mQMhMU4%3D

pulumi - signing in to an organization unmarshalling response object: invalid character '<' looking for beginning of value

Posted: 07 Oct 2021 08:05 AM PDT

Does soemone knows why I am getting this error when doing pulumi login against a specific organization?

 pulumi login -c https://app.pulumi.com/myorg  Logging in using access token from PULUMI_ACCESS_TOKEN  error: problem logging in: getting user info from https://app.pulumi.com/myorg: unmarshalling response object: invalid character '<' looking for beginning of value  

I have configured as an environment variable in my shell the PULUMI_ACCESS_TOKEN variable, but it seems that the response I got has to do with this comment in this issue x

Can I make a file in the git repository read-only?

Posted: 07 Oct 2021 08:04 AM PDT

If I add a filename to gitignore, this will be ignored by git and will not go in the repository. What I would like to do is to have a specific file in the upstream repository, allow everybody to check it out and modify it according to their needs, but then exclude it from their commits.

Basically I would like the repository to provide a template configuration file that needs to be fine tuned depending on the development environment of each developer, but that must not be modified in the repository.

Copy venv to an offline pc

Posted: 07 Oct 2021 08:05 AM PDT

I need to migrate my python virtual environnement to an offline pc I didn't find in similar questions a solution that fix my problem. Thanks in advance

Calculate the S1 sum for variance of Moran's I

Posted: 07 Oct 2021 08:05 AM PDT

I would like to calculate the S1 term for the variance of Moran's I. The following is the formula to calculate the S1

S1 formula

where w_{ij} is an element in the spatial weights matrix.

My spatial weights matrix is as following:-

structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0.111111111111111, 0.1, 0.1, 0.166666666666667,  0, 0.1, 0.111111111111111, 0.125, 0.166666666666667, 0, 0, 0.1,  0.111111111111111, 0, 0, 0.166666666666667, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0.0909090909090909,  0, 0, 0.1, 0.1, 0.166666666666667, 0, 0.1, 0.111111111111111,  0.125, 0.166666666666667, 0, 0, 0.1, 0, 0, 0, 0, 0, 0, 0.0909090909090909,  0, 0.111111111111111, 0, 0.1, 0, 0, 0.1, 0.111111111111111, 0.125,  0.166666666666667, 0, 0, 0.1, 0.111111111111111, 0, 0, 0.166666666666667,  0, 0, 0.0909090909090909, 0, 0.111111111111111, 0.1, 0, 0, 0.333333333333333,  0.1, 0.111111111111111, 0.125, 0, 0, 0, 0.1, 0.111111111111111,  0, 0, 0.166666666666667, 0, 0, 0.0909090909090909, 0, 0.111111111111111,  0, 0, 0, 0, 0.1, 0.111111111111111, 0, 0.166666666666667, 0,  0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0.111111111111111, 0, 0, 0.166666666666667, 0, 0, 0.0909090909090909,  0, 0.111111111111111, 0.1, 0.1, 0.166666666666667, 0, 0, 0.111111111111111,  0.125, 0.166666666666667, 0, 0, 0.1, 0.111111111111111, 0, 0,  0, 0, 0, 0.0909090909090909, 0, 0.111111111111111, 0.1, 0.1,  0.166666666666667, 0, 0.1, 0, 0.125, 0, 0, 0, 0.1, 0.111111111111111,  0, 0, 0, 0, 0, 0.0909090909090909, 0, 0.111111111111111, 0.1,  0.1, 0, 0, 0.1, 0.111111111111111, 0, 0, 0, 0, 0.1, 0.111111111111111,  0, 0, 0, 0, 0, 0.0909090909090909, 0, 0.111111111111111, 0.1,  0, 0.166666666666667, 0, 0.1, 0, 0, 0, 0, 0, 0.1, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,  0.0909090909090909, 0, 0.111111111111111, 0.1, 0.1, 0, 0, 0.1,  0.111111111111111, 0.125, 0.166666666666667, 0, 0, 0, 0.111111111111111,  0, 0, 0.166666666666667, 0, 0, 0.0909090909090909, 0, 0, 0.1,  0.1, 0, 0.333333333333333, 0.1, 0.111111111111111, 0.125, 0,  0, 0, 0.1, 0, 0, 0, 0.166666666666667, 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.166666666666667,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0909090909090909,  0, 0, 0.1, 0.1, 0, 0.333333333333333, 0, 0, 0, 0, 0, 0, 0.1,  0.111111111111111, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(20L, 20L), .Dimnames = list(      c("AUS", "BEL", "CAN", "CHE", "DEU", "DNK", "ESP", "FIN",      "FRA", "GBR", "IRL", "ITA", "JPN", "KOR", "NLD", "NOR", "NZL",      "PRT", "SWE", "USA"), c("AUS", "BEL", "CAN", "CHE", "DEU",      "DNK", "ESP", "FIN", "FRA", "GBR", "IRL", "ITA", "JPN", "KOR",      "NLD", "NOR", "NZL", "PRT", "SWE", "USA")))  

I can do this by using a for loop within a for loop, but I am thinking that there might be a more efficient way to do this. Maybe using lapply or something else.

Thanks in advance.

"Cannot open database requested by the login. The login failed." When the database name is incorrect

Posted: 07 Oct 2021 08:06 AM PDT

I'm writing some code at work to test the connectivity to an SQL Server database. Here is the code I am working with:

public bool TestSQLServerConnectivity(              string serverAddress,              int? serverPort,              string databaseName,              string userName,              string password,              out Exception exception)          {              SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder() {                   InitialCatalog = databaseName              };                if (string.IsNullOrWhiteSpace(userName) &&                  string.IsNullOrWhiteSpace(password))                  connectionStringBuilder.IntegratedSecurity = true;                connectionStringBuilder.DataSource =                  serverPort.HasValue                  ? $"{serverAddress}, {serverPort.Value}"                  : serverAddress;                if (!string.IsNullOrWhiteSpace(userName))              {                  connectionStringBuilder.UserID = userName;              }                if (!string.IsNullOrWhiteSpace(password))              {                  connectionStringBuilder.Password = password;              }                exception = null;                using (var connection = new SqlConnection(connectionStringBuilder.ToString()))              {                  try                  {                      connection.Open();                        return true;                  }                  catch (SqlException ex)                  {                      exception = ex;                        if (ex.State != 0 && ex.InnerException == null)                      {                          return true;                      }                        return false;                  }              }          }  

I'm aware of the issue in the following snippet of code, and I will be checking for the authentication method instead of what I'm currently doing, but this works for testing and it is not the issue:

if (string.IsNullOrWhiteSpace(userName) &&                  string.IsNullOrWhiteSpace(password))                  connectionStringBuilder.IntegratedSecurity = true;  

The issue is that I'm trying to connect to the sql server by sending a WRONG database name. I'm expecting it to throw an exception saying that the database does not exist or something of the sort. I'm confused why it is instead throwing an exception saying "Cannot open database requested by the login. The login failed".

Things to note:

  1. I am not sending values in for username and password, so it's using Integrated Security (Windows Authentication).

  2. The database exists on a different machine in our lab, and this code is being called from another machine in our lab too (vhsm lab, but I don't think that matters).

  3. When I send the correct database name, the connection does not throw any exceptions.

Additionally, I'm also confused about the State property of the SqlException. In the aforementioned exception thrown, the State is 1. I looked this up, and apparently 1 stands for warning. How is this a warning?

I have a hunch that MAYBE it is trying to create the database since it doesn't exist and maybe it doesn't have the authority to do so? I may be completely wrong though.

Why is this error being thrown instead of a "database does not exist" error? And why is the State 1? Any guidance on this issue would be greatly appreciated.

Matching text from corrupted filenames with stringr

Posted: 07 Oct 2021 08:05 AM PDT

I have a dataframe where one column is waypoint names from GPS files. Some of the waypoints have been corrupted, and the names of these are in an odd format with symbols which (I think) are not alphanumeric.

I'm ultimately trying to remove these filenames from the data, but I'm not sure how to properly match non alphanumeric text. I've tried the below code, comparing matching text from the incorrect text format with the correctly formatted filenames.

With each one I'm getting unexpected behaviour, presumably due to incorrect syntax or possibly because some of the odd symbols are actually counted as alphanumeric characters?

How do I properly use stringr to match these corrupted filenames?

corrupt_names <- c("矸Хꦉ㠀", "絀Ш㥺㸞>Ä©","ç€Ð¥Ü㣗","羈Х㡃") # create example filenames  correct_names <- c("1050M", "1800L","Newwaypoint1") # create example of correct filenames    str_view(corrupt_names,"[^alnum]+") # seems to select correct non alphanumeric symbols  str_view(correct_names,"[^alnum]+") # but this also selects alphanumeric characters in the correct names vector?    str_view(corrupt_names,"[^[:alnum:]]+") # selects only some symbols  str_view(correct_names,"[^[:alnum:]]+") # seems to work ok, doesn't select anything  

Edit: after creating the example vectors in my r script, I receive a warning when trying to save the file: "Not all of the characters in C:/Myfile.R could be encoded using ISO8859-1. To save using a different encoding, choose "File | Save with Encoding..." from the main menu. I assume this is relevant to the issue.

Containerizing a Spring boot application with Docker error

Posted: 07 Oct 2021 08:05 AM PDT

I am trying to containerize my Spring application with Docker. However, Docker cannot find my jar file. My Dockerfile:

FROM adoptopenjdk:16-jre-hotspot  RUN mkdir -p /app  WORKDIR /app  ARG JAR_FILE=*.jar  COPY ${JAR_FILE} rtv-1.jar /app  ENTRYPOINT ["java", "-jar", "/rtv-1.jar"]  

My docker-compose.yml

version: '2'    services:    app:      image: 'docker-spring-boot-postgres:latest'      build:        context: .      container_name: app      depends_on:        - db      environment:        - SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/compose-postgres        - SPRING_DATASOURCE_USERNAME=compose-postgres        - SPRING_DATASOURCE_PASSWORD=compose-postgres        - SPRING_JPA_HIBERNATE_DDL_AUTO=update      volumes:        - absolutepathtothedircontaining "rtv-1":/app    db:      image: 'postgres:13.1-alpine'      container_name: db      environment:        - POSTGRES_USER=compose-postgres        - POSTGRES_PASSWORD=compose-postgres  

When I run docker-compose up I am still having the same error.

Any idea what is causing this issue?

Many thanks in advance

Using a gFortran dll with Excel 365 / VBA 7

Posted: 07 Oct 2021 08:06 AM PDT

For years I used a combination of dlls written in Fortran PowerStation and Excel 02/03, with VBA 6.

But progress marches on, and I got a new machine with Windows 64 bit, Excel 365 (64 bit), and no Fortran. So I downloaded gFortran as part of MinGW-w64-for 32 and 64 bit Windows from SourceForge. Now I have to get it working. Here is the Fortran source code, in a file called gTest.F90:

integer(2) function AddIt(iVal1,iVal2)  !MS$ATTRIBUTES dllexport, stdcall, alias:'AddIt' :: ADDIT  Integer(2) iVal1,iVal2          AddIt=iVal1+iVal2  end function AddIt  

(The second line specifies Microsoft attributes. More about this later.)

I compiled it as follows, from directory ., after adding the path to the MinGW bins added to %PATH%

gfortran -Wextra -Wall -pedantic -shared -fPIC -o .\Output\gTest.dll .\Source\gTest.F90  

This produced no output, but did write the file gTest.dll.

And so onto Excel / VBA. I set up a little spread sheet, gTest.xlsm, which tried to invoke AddIt. It declared AddIt as follows:

Declare PtrSafe Function AddIt Lib "C:\A\Projects\gTest\Output\gTest.dll"(iVal1 As Integer, iVal2 As Integer) As Integer  

No luck. So I entered the following VBA code and stepped through it:

Sub RunIt()  Dim Val1 As Integer, Val2 As Integer, Sum As Integer      Val1 = 1      Val2 = 10      Sum = AddIt(Val1, Val2)      Debug.Print Val1, Val2, Sum  End Sub  

As expected, it blew up on Sum =, with one of MS's more useless error messsages "Error in loading DLL (Error 48)". Now, I suspect that the problem is that I am not telling the dll what within it must be exported - the function of the MS attribute statement above. I see that in the C++ environment, you can export from a dll with either the keyword __declspec(dllexport), or with a module definition (.def) file. But I cannot see how you could utilise either of these with gFortran (and I have tried). Or, possibly, did I not compile and link for 64 bits?

Can someone please help me? It would be gratefully appreciated.

Thanks, Rogan.

Why is my new list outputting an empty one when I should be getting an answer

Posted: 07 Oct 2021 08:05 AM PDT

I'm having problems with my code where I'm trying to add to a new list all words that match a given list (in order at the end to have a basic sentiment analysis code). I have tried passing it through Python Tutor but have had no success. In short, I'm expecting an output of the word great but instead get an empty list.

def remove_punc_and_split (wordlist) :       punc = '.!?/:;,{}'  #the punctuation to be removed      no_punc = ""       for char in wordlist :          if char not in punc :              no_punc = no_punc + char.lower()      new_word_list = no_punc.split() #dividing the words into seperate strings in a list      return new_word_list    def sentiment1 (wordlist1):      positive_words = ["good","awesome","excellent","great"]      wordlist1 = remove_punc_and_split (comment_1)      pos_word_list = []                                                                     for postive_words in wordlist1 :          if wordlist1[0] == positive_words :              pos_word_list.append(wordlist1)              print(wordlist1)      return pos_word_list        comment_1 = 'Good for the price, but poor Bluetooth connections.'  sentiment1(comment_1)  

Why "not a function" error when using module.exports?

Posted: 07 Oct 2021 08:06 AM PDT

If I have this recursive function

function checkNested(obj, level, ...rest) {    if (obj === undefined) return false;    if (rest.length == 0 && obj.hasOwnProperty(level)) return true;    return checkNested(obj[level], ...rest);  }  

When I try to make it a module, I get this error

checkNested is not a function  

Can anyone see what I am doing wrong?

function checkNested(obj, level, ...rest) {    if (obj === undefined) return false;    if (rest.length == 0 && obj.hasOwnProperty(level)) return true;    return checkNested(obj[level], ...rest);  };    module.exports.checkNested = checkNested;  

Powershell string interpolation of date value is in incorrect locale [duplicate]

Posted: 07 Oct 2021 08:05 AM PDT

I have a powershell script that prints a date, it does this via:

"$([DateTime]::Now)"  

This produces a US format date of MM/DD/YYYY etc. I'm in the UK and would like this to come out as DD/MM/YYYY etc. I had thought that my server or shell was in the incorrect locale, so I added:

$culture = [system.globalization.cultureinfo]"en-GB"  [System.Threading.Thread]::CurrentThread.CurrentUICulture = $culture  [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture  

To the top of my script - no difference, indeed, checking the locale at startup or in the shell reports that my locale is "en-GB".

I have now tried the following:

"$([DateTime::Now.ToString())"  

Which gives me a UK format date. I have therefore acheived what I want to do, but this is now a mystery, why does Powershell's string interpolation of a DateTime return a different result than .ToString()? Is this a defined or controllable behaviour?

Cheers,

Mark

Select records without duplicate with specific logic

Posted: 07 Oct 2021 08:06 AM PDT

I have a tables A, B and C with a lot of columns (30+). Main columns for all are Id, RefNumber

Also I have table LinkedEntity where I can match records from different tables (A, B or C)

I need to select all records from table A and also display linked records from B and C

A

Id RefNumber OtherColumns
101 A101 ...
102 A102 ...

B

Id RefNumber OtherColumns
201 B101 ...
202 B102 ...

C

Id RefNumber OtherColumns
301 C101 ...
302 C102 ...

LinkedEntity

Id EntityId LinkedEntityId
1 101 202
2 102 301
3 102 201
4 102 202

Expected result:

Id RefNumber LinkedB LinkedBRefNumb LinkedC LinkedCRefNumb
101 A101 202 B102 NULL NULL
102 A102 201,202 B101,B102 301 C101

First idea to write something like

SELECT A.Id, A.RefNumber, L1.Id, L1.RefNumber, L2.Id, L2.RefNumber  FROM A  LEFT JOIN (SELECT B.Id, B.RefNumber, le.EntityId, le.LinkedEntityId FROM B JOIN LinkedEntity le ON le.EntityId = B.Id OR le.LinkedEntityId = B.Id) L1  ON A.Id = L1.EntityId OR A.Id = L1.LinkedEntityId   LEFT JOIN (SELECT C.Id, C.RefNumber, le.EntityId, le.LinkedEntityId FROM C JOIN LinkedEntity le ON le.EntityId = C.Id OR le.LinkedEntityId = C.Id) L2  ON A.Id = L2.EntityId OR A.Id = L2.LinkedEntityId  

But this query returns duplicates records of A table. Is there any way to remove duplicates and have joined values of linkedEntities? (Maybe using STRING_AGG) ?

ESP8266 loses last byte returned from Nextion

Posted: 07 Oct 2021 08:04 AM PDT

I am having problems with data coming back from a Nextion that I have connected to an esp8266 (Nodemcu v0.9). I am communicating with the Nextion at 9600 b/s.

I have code that parses commands entered via the serial console of the IDE and sends the appropriate command to the Nextion. The relevant command here is 'getn xxxx' which asks for a numeric value from the Nextion.

For example, 'getn 123' sends a 'get 123', expecting a numeric result. (There is a 'gets 123' which sends a 'get "123"' but it is not used here)

When I send a 'getn 123' followed by a 'getn 222', this is what I get

**ESP8266**    //1st getn command. Note only 7 bytes come back and missing 3rd 0xFF in returned data  Processing command: getn 123  Sending [get 123]  found 7 bytes  71 7b 00 00 00 ff ff    //2nd getn command. Note additional leading 0xFF and missing 3rd 0xFF in returned data  Processing command: getn 222  Sending [get 222]  found 8 bytes  ff 71 de 00 00 00 ff ff    If I connect an Arduino Nano instead of the esp8266, the same code works perfectly!    **nano** (I only execute one 'getn 123' since it works ok    Processing command: getn 123  Sending [get 123]  found 8 bytes  71 7b 00 00 00 ff ff ff     

Please see code listing below.

#include <SoftwareSerial.h>    #define SERIAL_TIMEOUT 3000    #ifdef ESP8266    // ESP8266    #define MY_RX 5  // NEXTION TX, esp8266 D1    #define MY_TX 4  // NEXTION RX, esp8266 D2  #else    // arduino, nano and similar    #define MY_RX 11  // NEXTION TX,    #define MY_TX 10  // NEXTION RX,  

No comments:

Post a Comment