Friday, August 13, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Copy from byte[] buffer to a IBuffer in C# Creating an "Value does not fall within the expected range." Exception

Posted: 13 Aug 2021 08:42 AM PDT

I am starting to develop a C# application using the Bluetooth stack library. Each block must have a length of 128 bytes (Header (6 bytes) + payload (122 bytes)).

To read the file I am using the StorageFile class.

Before sending a block of data I copy the header into my buffer then I add the payload from the file ... I do the same operation for each block until I reach the end of the file.

Once my buffer is filled with the HEADER + PAYLOAD,

I am using an interface IBuffer to send the buffer via Bluetooth(BT) ...

The issue is at each loop I am trying to send my buffer and I am facing the following exception:

"Exception thrown: 'System.ArgumentException' in System.Private.CoreLib.ni.dll Exception raised ! to be handled Value does not fall within the expected range.:"

Please below a piece of the code used, please feel free to comment: I tried to add as many as possible comments.

/* Before to send the chunk of data, send the command FWWRITE and the length of the file */                   ' /* Buffer to send CMD + FileSize */                  header[0] = 0x00; /* MSB  Config CMD */                  header[1] = 0xF1; /* LSB Config CMD */                  header[4] = 0x00; /* MSB CRC */                  header[5] = 0x00;  /* LSB CRC */                    /* fileBuffer.Length is 5760  == fileSize */                  /* Header CMD + packetSize + Payload */                  while (offset < fileBuffer.Length)                  {                      /* Compute length data to send */                      if (fileBytesAvailable < CustomConstants.chunk_size)                          /* Compute last chunck of data available */                          fileBytesWritten = (int)fileBytesAvailable;                      else                          fileBytesWritten = CustomConstants.chunk_size;                        /* Compute each header with a new len of data from the file */                                              header[2] = ((byte)((byte)fileBytesWritten >>8)); /* MSB LEN Size */                      header[3] = ((byte)((byte)fileBytesWritten & 0xFF)); /* LSB LEN Size */                        /* Dynamically set the size of the bytes array with the real size of data */                      /* header.Length already added */ /* 122 + 6 = 128 elements */                      byte[] buffer = new byte[header.Length + fileBytesWritten];                        /* Copy header */                      System.Buffer.BlockCopy(header, (int)0, buffer, 0, (int)header.Length);                        /* Copy 122 bytes from the file, and store it after each header, 6 + 122 = 128 bytes are inside my buffer */                      System.Buffer.BlockCopy((Array)readingFileBuffer, (int)offset, (Array)buffer, header.Length, (int)fileBytesWritten);                                                                  /* I am supposed to use the range of 128 bytes stored into my buffer */                      IBuffer streamBuffer = buffer.AsBuffer(0 , buffer.Length, buffer.Length);                        /* Compute next packet offset */                      offset += fileBytesWritten;                      /* Compute the data  size still available in the file */                      fileBytesAvailable -= fileBytesWritten;                          /* Now the data will be given to the specific method to send the streanbuffer via BT stack, the exception is raised from here */                      try                      {                          Debug.WriteLine(String.Format("streamBuffer.Capacity {0}  streamBuffer.Length {1} buffer.Length {2}", streamBuffer.Capacity, streamBuffer.Length, buffer.Length));                                                    if (streamBuffer.Capacity == buffer.Length                              && streamBuffer.Length != 0)                          {                              Debug.WriteLine(String.Format("OK  to write ..."));                              writeSuccessful = await WriteBufferToSelectedCharacteristicAsync(fwUpdateCharacteristic, streamBuffer);                                                        if (writeSuccessful != true)                              {                                  rootPage.NotifyUser("Error write chunck of data !", NotifyType.ErrorMessage);                              }                          }                      }                      catch (Exception ex)                      {                          Debug.WriteLine(String.Format("Exception raised ! to be handled  {0}:", ex.Message));                      }                                          }                  fileBytesAvailable = 0;              }  

Please feel free to help,

Thank you for your advises,

Regards

js: difference between using + and += to add a space to each element in a 'for' loop?

Posted: 13 Aug 2021 08:41 AM PDT

 let sentence = ["Hello", "my", "name", "is", "Per"]                     for (i=0; i<sentence.length; i++){          sentence[i] + " "          console.log(sentence)      }  

if i use + " " to add a space, no space is added to each element in the array and console prints out 5["Hello", "my", "name", "is", "Per"]

however, if i use += " ", a space is added to each element and console prints out 1["Hello ", "my", "name", "is", "Per"] 2["Hello ", "my ", "name" "is", "Per"] 3["Hello ", "my ", "name ", "is", "Per"] 4["Hello ", "my ", "name ", "is ", "Per"] 5["Hello ", "my ", "name ", "is ", "Per "]

could someone explain the logic behind why using + " " doesn't add a space to each element?

How to configure required navigation properties in EF Core

Posted: 13 Aug 2021 08:41 AM PDT

I would like to use EF core with nullable reference types configured by fluent annotations.

I want to model a one-to-one relationship where SomeEntity has an OtherEntity called Relation, and OtherEntity optionally has a SomeEntity.

Because I don't want to always load the relation, I define OtherEntity as nullable, since it will be null if it's not loaded:

public class SomeEntity {    public virtual OtherEntity? Relation {get;}  }  

However, when I use this definition to build a model, OtherEntity becomes nullable in the database definition. That's not my intention: it should be required, in the database, just not necessarily loaded in the code.

How do I model this in such a way that it's clear the value could be null at runtime, but has a database backing store with a column that's not null?

I prefer not to adjust the code of the entity for this purpose, but if there is no other way, that will have to do.

How to make database design for multiple information included table?

Posted: 13 Aug 2021 08:41 AM PDT

How to design one to one database table?

I have a report that gets data from users. But report includes multiple type of resords.

Report includes following informations

  • CustomerInformations (name, age, city, ...)
  • CompanyInformations (name, address, coutry, year, ...)
  • DeviceInformations (devname, code, serialnumber,...)
  • ApproveInformation (who_approved, date, ..)

and more informations.

So I have a report table. But should create only one report table and add all columns in this table? Or should I create a Reports table and CustomerInformations,CompanyInformations,DeviceInformations,ApproveInformation and one to one relationships?

Transfer data from one page to another

Posted: 13 Aug 2021 08:41 AM PDT

I created a site in NextJs, on which you can connect with your Discord account and I was then able (in the oauth file) to retrieve the user's guilds.

And I would like to send these guilds (json file) to my dashboard page.

oauth.tsx :

export default async (req: NextApiRequest, res: NextApiResponse) => {  ...    const guildsuser = await fetch("http://discord.com/api/users/@me/guilds", {      headers: { Authorization: `${token_type} ${access_token}` },    });    const guilds = guildsuser.json();  }  

here is the guilds constant that I would like to send to the dashboard page to display it

works in tutorial,but not when doing. c++

Posted: 13 Aug 2021 08:41 AM PDT

#include <iostream>  using namespace std;    class Classroom{  public:     string Name;     string Class;     int Age;       void IntroduceY() {       cout << "name: " << Name << endl;       cout << "class: " << Class << endl;       cout << "age: " << Age;    }     Classroom(string name, string class, int age){       Name = name;       Class = class;       Age = age;    }  };    int main(){       Classroom child1 = Classroom("Toby","5th grade", 12);     child1.IntroduceY();  }  

For some reason this doesn't work.Many errors pop up: expected identifierenter code here before ',' token two or more data types in declaration of 'parameter' expected ')' before ',' token expected unqualified-id before 'int'

using Atom ide.

How can I find a SKU match across two spreadsheets, and update the pricing column in the master table according to the matching sheet?

Posted: 13 Aug 2021 08:41 AM PDT

I have two identically structured spreadsheets in Excel, both have a 'Product Code/SKU' column and a 'Price' column. One of the spreadsheets is a master table of all products in the database, while the other is a pricing update sheet.

I'd like to find a way to automate the process of updating the master sheet based on the updated pricing sheet. For each row in the master sheet, the updated sheet should be checked for a matching SKU, and if they match the pricing in the updated sheet should be copied to the master sheet.

I've made some progress looping through both datasets with Pandas, but I'm sure I'm overcomplicating this for myself and testing is taking a while as each dataset is around 4000 rows.

How do I initialize an empty array inside a java script object?

Posted: 13 Aug 2021 08:43 AM PDT

const cart = {    // I am initializing an empty array    contents: "[]",    addItem(item) {      // I am adding an element to the array      contents.push(item);    }  };    cart.addItem("laptop");  console.log("The cart contains:", cart.contents);

How to match regex between 2 strings JavaScript

Posted: 13 Aug 2021 08:41 AM PDT

I keep getting this error when trying to use this Regex in JavaScript.

SyntaxError: Invalid regular expression: unrecognized character after (?

var matches = navigator.userAgent.match(/(?<=Version\/)(.*?)(?= Safari)/);

Trying to figure out how to group tabs in Chrome's API, but my code is causing the browser to lockup

Posted: 13 Aug 2021 08:41 AM PDT

Here's my code:

for (i = 0; i < c; i++) {  if ((i = 0)) {    chrome.tabs.create({ url: String(urls[i] + String(OC)) }, function (t) {      first = t.id;    });    chrome.tabs.group({ tabIds: first }, function (g) {      g_id = g.groupId;    });  } else {    chrome.tabs.create({ url: String(urls[i] + String(OC)) }, function (u) {      chrome.tabs.group({ groupId: g_id, tabIds: u.id });    });  }  

Basically, I am wanting to create a new tab group and pull the ID when the new group gets created. A "new" group should only be created on the first element of the array. Every subsequent Tab I make should just use the group ID that gets assigned to "g_id" when the first tab is used to make a group.

However, running this code is causing Chrome to completely lock up and I'm not sure why.

How to refresh a materialized view in mongoDB by passing a parameter into it

Posted: 13 Aug 2021 08:41 AM PDT

I am working on creating a materialized view in mongoDB which is capable of refreshing itself, I am using mongoDB compass and inside that I am using the mongo shell to create the function which will create a materialized view. The MV should be able to refresh in 4 hours of interval and while refreshing it should update itself with any new row added to the table it is pointing to. I am using mongoDB compass only , I have seen many example where people are using mongoDB Atlas which is creating a cron which is firing the function to update the MV, but my limitation is I can not use the Atlas. So instead I have planned to create a MV and there should be some functionality to update it manually so that I can create java job which will call the MV at certain interval.

I have tried to create a MV which will take a date and from that date it will take the month, and will refresh the MV for the dates which are greater than the date

updateSampleMVItems =     function(startDate){    db.a-custom-db.aggregate([    {$match:dates_of_valid_items:{$gte:"startDate"}}},    {$group:{_id:{du_code:"$du_code",    itg_name:"$itg_name",    viewSample:"$viewSample",    hoc:"$hoc"}}},    {$merge:{into:"HourlyUpdateItems", whenMatched:"replace"}}    ]);    };  

I can see the function is created , but when i am trying to call the function using

 updateSampleMVItems("2021-06-30")  

I am getting error

NOW is not defined  

I am not able to find the issue why it is not working

Oracle SQL: Using LAG when the current row is missing

Posted: 13 Aug 2021 08:41 AM PDT

I have a table from which I'm trying to extract information using a LAG function.

Type Date Value
A 01 1
A 02 2
B 01 3

I'm trying to get lines by Type with the Value from this month and the month before that, so ideally:

Type Date Value M Value M-1
A 02 2 1
B 02 0 3
SELECT  Type,  Date,  Value as Value M,  LAG (Value,1,0) over(PARTITION BY Type ORDER BY Date) as Value M-1  FROM Table  

Except that, of course, because there is no line for Type B and Month 02, I don't get a line for Type B.

Do you have any suggestions?

The Angular Material version (12.1.4) does not match the Angular CDK version (12.2.1). Please ensure the versions of these two packages exactly match

Posted: 13 Aug 2021 08:40 AM PDT

After installing FlexLayout using this command

npm i -s @angular/flex-layout @angular/cdk  

Which obviously install Angular CDK as well, i'm getting the following warning

The Angular Material version (12.1.4) does not match the Angular CDK version (12.2.1).  Please ensure the versions of these two packages exactly match.  

I used ng update command in order to update packages, also tried ng add @angular/material, but i'm still with the same versions.

How do i solve this?

Convert JavaScript string format into another

Posted: 13 Aug 2021 08:41 AM PDT

I have a mobile no like (408) 931-4377 and need to create a format like (000) 000-0000 for validating other mobile nos

Please suggest how this can be achieved?

When use ObservableCollection and when ObservableHashSet

Posted: 13 Aug 2021 08:41 AM PDT

For me as a beginner, I don't see any difference between these two lists. They both update the UI when you add something. The data is not filtered or sorted.

What is the use case of these two lists?

Selenium explicit waits not working by time.sleep working

Posted: 13 Aug 2021 08:41 AM PDT

I am a newbie for selenium. I am trying to refresh the page when the list has loaded. The HTML is like below.

<span class="" title="Refresh">    <button class="MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-textPrimary" tabindex="0" type="button">      <span class="MuiButton-label">Refresh</span>      <span class="MuiTouchRipple-root"></span>    </button>  </span>  

Based on this html, I decided to like below in selenium part.

WebDriverWait(driver, 100).until(EC.element_to_be_clickable((By.XPATH, "//span[@title='Refresh']"))).click()  

If I use it like this, I am getting the below error

  File "workspaces.py", line 47, in <module>      WebDriverWait(driver, 100).until(EC.element_to_be_clickable((By.XPATH, "//span[@title='Refresh']"))).click()    File "/home/assistanz/Projects/Python/selenium/venv/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 80, in click      self._execute(Command.CLICK_ELEMENT)    File "/home/assistanz/Projects/Python/selenium/venv/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute      return self._parent.execute(command, params)    File "/home/assistanz/Projects/Python/selenium/venv/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute      self.error_handler.check_response(response)    File "/home/assistanz/Projects/Python/selenium/venv/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response      raise exception_class(message, screen, stacktrace)  selenium.common.exceptions.ElementClickInterceptedException: Message: Element <span class=""> is not clickable at point (1123,116) because another element <div class="MuiBackdrop-root jss29"> obscures it  

But If I use like below the code is working fine

time.sleep(5)  driver.find_element_by_xpath("//span[@title='Refresh']").click()  

I am not able to identify the differences. Based on my understanding, we should explicit wait concept not time.sleep

Could anyone help to resolve this problem?

Thanks in advance

table1.date1 = get prior 12 months data from date1 in table2.monthyear in Athena? how to get 12 months prior data in year month?

Posted: 13 Aug 2021 08:41 AM PDT

select table1.date1 - 12 months from table2.month_year1. The query should get 12 months prior date1 from table2 month_year1 field....I am still learning and not sure how to write this query. if anyone can help?

Approximate a curve given n 2d points and calculate angle/derivate at those n locations

Posted: 13 Aug 2021 08:41 AM PDT

I am looking to calculate a curve that contains n x,y points such as x=[0,2,3,5,8] and y=[8,3,-1,0,-2]. I am looking to use n-1 degree polynom. Then I would like to compute the angle/first derivative at each of the x locations.

So far I have tried a mix of numpy.polifit and scipy curve fitting without much success. I have also checked splines but not so interested in further splitting the interval as I know the points where I will be wanting to calculate the angle already.

Any ideas?

How to replace multiple rows in a dataframe with rows from another dataframe based on column value/string?

Posted: 13 Aug 2021 08:41 AM PDT

I have 2 country lists and a year array as follows:

regions1 = ["Brazil", "Canada", "China", "Mexico", "USA"]  regions2 = ["Brazil", "China", "USA"]  years    = np.arange(1990,2031)  

And 2 dataframes that look as follows, df1:

Index   Country   Source   1990   1991   ...   2030  0       Brazil    A        300    350          550  1       Canada    A        200    300          400  2       China     B        1000   1100         1300  3       Mexico    B        500    450          500  4       USA       C        650    800          1000  

And df2:

Index   Country   Source   1990   1991   ...   2030  0       Canada    A        300    350          600  1       Mexico    B        550    670          800  2       USA       C        850    900          1500  

I want to replace the values in the df1 columns 1990-2030 with the values in the df2 columns for the same countries. I have tried the .replace, .combine_first and.update methods but none of them work. I then tried with:

df1.loc[df1.Country=='Canada',[str(z)for z in years]] = df2.loc[df2.Country=='Canada',[str(z)for z in years]]  

which for some reason does not work. The only thing that has worked so far is:

df1.loc[1,[str(z)for z in years]] = df2.loc[0,[str(z)for z in years]]  

This replaces all the values for Canada correctly while keeping everything else the same, which is what I want, however I need to do it manually for each country/index, which is not very elegant and not possible if the dataframes are large.

What would be a 'pythonic' way to replace all values for the common countries in df1 with the values from df2? I have looked for 2 days where I could but none of the proposed solutions work for all cases for me, only one at a time like the above.

Thank you!

Azure Batch and use cases for JobManagerTask

Posted: 13 Aug 2021 08:42 AM PDT

I am currently digging into the Azure Batch service, and I am confused about the proper use of a JobManagerTask...

...and maybe what the overall architecture of an Azure Batch application should look like. I have built the below architecture based on code samples from Microsoft found on Github .

These are my current application components.

App1 - ClusterHead

  • Creates a job (including an auto pool)
  • Defines the JobManagerTask
  • Runs on a workstation

App2 - JobManagerTask

  • Splits input data into chunks
  • Pushes chunks (unit of work) onto an input queue
  • Creates tasks (CloudTask)

App3 - WorkloadRunner

  • Pulls from the input queue
  • Executes the task
  • Pushes to the output queue

Azure Storage Account

  • Linked to Azure Batch account
  • Provides input & output queues
  • Provides a result table

Azure Durable Function

  • Implements the aggregator pattern by using DurableEntities so that I can access incoming results prematurely.
  • Gets triggered by messages in the output queue
  • Aggregates results and writes the entity to Azure Storage table

Questions

  • Is that proper use of the JobManagerTask?
  • Why do I want/need the extra binary/application package, that encapsulates the JobManagerTask?
  • Could someone please give an example of when I should prefer to use a JobManagerTask over creating the Jobs manually?

Thanks in advance!

Is it possible to use Diagrams / Graphviz in AWS Lambda?

Posted: 13 Aug 2021 08:41 AM PDT

I'm building a python application to generate some AWS Diagrams using Diagrams library ( https://diagrams.mingrammer.com/docs/getting-started/installation )

But in order to use Diagrams, I need to install Graphviz. But as we know, it is not possible to operate in Lambda machines. So is there a way to access Graphviz packges throught Lambda to use Diagram lib?

Thanks in advance

[EDIT] I got source from graphviz and compiled with make. I put the generated dot executable in my code but now dot tries to generate the libs in lambda and lambda does not allow because it is not /tmp folder

[EDIT2] I was able to compile the libs but now I stucked at this error:

  Format: "png" not recognized. Use one of: canon cmap cmapx cmapx_np dot eps fig gv imap imap_np ismap pic plain plain-ext pov ps ps2 svg svgz tk vml vmlz xdot  

I tried to add manually gd libs. It worked on EC2 machine but in lambda don't. If I run the same dot executable in EC2, appears png format. I think png lib are dynamically loaded anyway. So it makes impossible to do this at lambda.

Gradle 4.2.+ Could not resolve navigation-ui-ktx:2.3.5

Posted: 13 Aug 2021 08:41 AM PDT

After upgrading Android Studio to Fox version, Gradle from 4.1.3 to 7.0.0 or even 4.2.+, and distributionUrl to gradle-7.0.1-bin.zip, I couldn't build my app anymore.

This is the error log:

* What went wrong:  Execution failed for task ':onboarding:dataBindingMergeDependencyArtifactsDebugMobDebug'.  > Could not resolve all files for configuration ':onboarding:debugMobDebugCompileClasspath'.     > Could not resolve android.arch.navigation:navigation-ui-ktx:2.3.5.       Required by:           project :onboarding        > Skipped due to earlier error  

It seems Gradle couldn't download NavigationKTX version 2.3.5. The solution is downgrading but How to fix the issue without downgrading to Gradle version 4.1.+

I wanna use jetpack compose in my application so I need to update gradle to 4.2.+.

How can I use Chinese letters for locals lua

Posted: 13 Aug 2021 08:41 AM PDT

im trying to make locals with Chinese letters

local 屁 = p   or   屁 = p  

none of those work any ways to do it?

How to restart docker for windows process in powershell?

Posted: 13 Aug 2021 08:41 AM PDT

I want to restart docker for windows (now known as Docker Desktop) in powershell.

I would like to do it with one command in PowerShell.

enter image description here

May I implement it?

When using Restart-Service *docker*:

enter image description here

Python: How can you ignore an argument in a function?

Posted: 13 Aug 2021 08:42 AM PDT

I am wondering if there is a way to define a function with arguments, but ignore some arguments within the function if they are not applicable.

For instance, in this code, I am trying to find contacts under a unique umbrella from a reference table to send an email to, but the table may have rows where contacts may be limited to maybe just one or two people vs five. If so, the argument for all other contacts following the first/second one should be ignored.

reference = [      {'Code': '10', "Group": "There", "Contact": "Me@there.com",   "Contact2": him@there.com", Contact3": "you@there.com"},      {'Code': '11', "Group": "Here", "Contact": "she@here.com", "Contact2": "her@here.com"},      {'Code': '20', "Group": "Everywhere", "Contact": "them@everywhere.com"}  ]    import win32com.client    def send_email(contact, contact2, contact3, contact4, contact5):      olMailItem = 0x0      obj = win32com.client.Dispatch("Outlook.Application")      newMail = obj.CreateItem(olMailItem)      newMail.Subject = "Email for %s" %group      newMail.Body = "Message"      newMail.To = contact      newMail.CC = contact2, contact3, contact 4, contact5      #newMail.BCC = "address"      attachment1 = file      newMail.Attachments.Add(attachment1)      #newMail.display()      newMail.Send()    count = 0  for Contact in reference:      send_email(reference['Contact'][count])      count = count + 1  

How to get dirent to ignore current directory?

Posted: 13 Aug 2021 08:41 AM PDT

I am working on a C++ program on Ubunutu 16.04 linux

It is to read a directory path and group width from shell. It should then navigate through the directory and keep track of files, if it finds a directory go in it and track those files as well. And print a histogram at the end

I have an odd bug that causes a seemingly infinite loop due to the recursive function I have that handles sub folders. If I run the comparison ((J -> d_type) == DT_DIR ) where struct dirent*J. It always returns true once all the files are read because it calls itself over and over again.

Is there any way to prevent that? I feel like an extra check should be all that I need but I don't know what to check. I implemented it via a struct linked list the code for the struct is below:

struct node{      node* next, *prev;      int count, name, min, max;      node(){          prev = NULL;          next = NULL;          count = 0;          name = nodecount;          min = 0;          max = 0;      }  }  

;

And the source code is as follows:

int main(int argc,char *argv[]){      // Ensures that a valid directory is provided by the cmd line argument      if (argc != 3){          fprintf (stderr, "%d is not the valid directory name \n", argc);          return 1;      }      DIR * cwd; // current working directory pointer      struct dirent *J; // pointer to dirent struct      int binWidth; // variable for the width of the grouping in the histogram      binWidth = atoi(argv[2]);      node *first = new node;      nodecount++;      first->max = binWidth - 1;      node * current;      current = first;      bool isadirectory = false;      if((cwd = opendir(argv[1]))== NULL){          perror("Can't open directory");          return 2;      }        while ((J = readdir(cwd)) != NULL){          isadirectory = false;          if((J -> d_type) == DT_UNKNOWN ){              struct stat stbuf;              stat(J->d_name, &stbuf);              isadirectory = S_ISDIR(stbuf.st_mode);          }          else if((J -> d_type) == DT_DIR ){              isadirectory = true;          }          else{              if((J-> d_reclen <= current->max)&&(J->d_reclen >=current->min)){                      current->count = current->count+1;              }              else if(J->d_reclen < current->min){                  node*temp = current->prev;                  while(temp->prev != NULL){                      if((J-> d_reclen <= current->max)&&(J->d_reclen >=current->min)){                              current->count = current->count+1;                              break;                      }                      else if(J->d_reclen < current->min){                          temp = current->prev;                  }              }          }              else{                  nodecount++;                  current -> next = nextNode(current);                  current = current -> next;              }          }          if(isadirectory){              traverseNewDirectory(current,J->d_name);          }      }      while ( ( closedir (cwd) == -1) && ( errno == EINTR) );      printHistogram(first);      return 0;  }  

How to ignore certain letters and spaces in character arrays

Posted: 13 Aug 2021 08:41 AM PDT

Trying to make an else statement that get rid of all other letter and spaces then the ones i want. This function is to change user inputted letters into other letters

using namespace std;      void dna_to_rna(char rna[])       {          for (int i = 0; i < 100; i++)          {              if (rna[i] == 'a' || rna[i] == 'A')                  rna[i] = 'U';              else if (rna[i] == 'c' || rna[i] == 'C')                  rna[i] = 'G';              else if (rna[i] == 'g' || rna[i] == 'G')                  rna[i] = 'C';              else if (rna[i] == 't' || rna[i] == 'T')                  rna[i] = 'A';  }  

What should the else statement look like in order to drop all other chars?

MySQL multiple insert: How to write a query to insert the new rows and ignore inserting duplicate rows?

Posted: 13 Aug 2021 08:41 AM PDT

I want to insert multiple rows in a MySQL table at once. One of the columns, column c, of that table is unique indexed. How to write a query to insert the new rows(rows where value of column c is not equal to the column c value of any previously inserted row) only and ignore inserting duplicate rows?

Best solution to maxLength being ignored

Posted: 13 Aug 2021 08:41 AM PDT

<input type="TEXT" name="smth" maxLength="19 "id="smthid">  

Works fine. But I came across situation where user could input more than 19 characters. (mobile browser on xperia, while some other phones work fine...)
what is the best solution to tackle this problem

good way to clone JSONObject on Android

Posted: 13 Aug 2021 08:41 AM PDT

I have to clone a JSONObject on Android. I am aware of the easy way:

JSONObject clone = new JSONObject(original.toString());  

but somehow it feels wrong/slow to do it this way. I found this: https://stackoverflow.com/a/12809884/322642 , but on Android I do not have JSONObject.getNames - anyone has a good pointer on how to do this?

No comments:

Post a Comment