C # program that reads characters and replaces characters

A C # program that reads a line of characters and prints it on the console in such a way that the vowels are replaced by the character that is repeated most on the line.

Multiple Threading: Is my server's design safe with respect to multiple threads and concurrent database reads / writes?

I am creating a chat server using sockets and a MySQL database, and after it works, I want to expand it to make it a more complex game server.

I want to know if my design is missing something.

Specifically, I am concerned about accessing the database from different threads, or if I may be creating too many threads and if there is likely to be a bottleneck somewhere.

I have 3 functions:

principal function start a second thread for the ServerHandler function that repeats and accepts new customer connections. That ServerHandler function then opens a new thread for each client connection for a ClientHandler function.

The code / pseudocode (so far incomplete while I am still considering the architecture) is below. I am writing it in Scala.

My main questions are about the ClientHandler function and if I am doing something in the wrong order. Will I be at risk of separate client threads performing database writes and reads in an unexpected order that cause irreproducible problems?

I wonder if I need a separate thread with a list of commands to execute, so I can be sure that 1 client writes and then reads, then another client writes and then reads, etc. Do I need to maintain a read / write list of the database? Or does the database server handle it in some way?

Mainly, I would like to be aware of my lack of understanding of database readings / writes in different threads, and if there is something obvious that I am doing wrong here. Does the design of the program structure look good?

With regard to threads, will I have to test the server with many client connections (1k, 10k, 100k?) And then set some client connection limit to what I think is safe?

// ** ClientHandler **
// This is run in a new thread for each client that connects to the ServerHandler
// This does:
// 1. Set up input and output streams to communicate with 1 client
// 2. Set up connection to database (MySQL server running on the same machine), including:
//    a. Establish connection
//    b. Read some data from the database (latest version #, # of clients connected, etc)
// 3. Send welcome message to client (latest version #, # of clients connected, etc)
// 4. Set "startTime" variable to current system time in milliseconds to detect client timeout
// 5. Loop and do this (nothing is blocking, so irrelevant steps will be skipped):
//    1. Handle client message (if there is a new one), including:
//       a. Parse client message, including:
//          i. If we have not verified the client yet, we only accept one command: "connect"
//          ii. On "connect", we verify the ID and update the database (most recent log in time)
//       b. Database reads/writes/updates as necessary, depending on the command
//       c. Send a response message back to the client with the results
//    Even if there is no client message received, we do this:
//    2. Check for server-side updates that should be notified to the client, including:
//       a. Database reads
//       b. Timestamp comparisons, checking when we last notified the client of the server state
//    3. Notify client of any server-side state changes (if necessary)
// 6. If the client times out (~5000ms), update the database that the client has disconnected
// 7. Close database connection
// 8. Close socket
ClientHandler(socket){
    // Set up input and output streams to communicate with 1 client
    val inputstream = new BufferedReader(new InputStreamReader(socket.getInputStream()))
    val outputstream = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))

    // Set up connection to database (MySQL server running on the same machine)
    val db = Database.forConfig("mydb")
    // Read some data from the database (latest version #, # of clients connected, etc)
    ...

    // Send welcome message to client (latest version #, # of clients connected, etc)
    outputstream.write(...).newLine().flush()

    // Set "startTime" variable to current system time in milliseconds to detect client timeout
    var startTime = System.currentTimeMillis()

    //
    ...
}

// ** ServerHandler **
// This runs once in its own thread (because it contains a blocking call)
// This creates a new thread to run ClientHandler for each client that connects
ServerHandler(server_socket){
    while(true){
        val socket = server_socket.accept() // this is a blocking call
        val client_handler = new ClientHandler(socket)
        val thread = new Thread(client_handler)
        thread.start() // when a client connects, start a new thread to handle that client
    }
}

// ** main **
// This does 3 things:
// 1. Start a new thread for ServerHandler which sits and waits for clients to connect
// 2. Loop and accept commands from admin via console
// 3. Process server-side logic in real-time
main{
    // Start a new thread for ServerHandler
    val server_socket = new ServerSocket(port 10000)
    val server_handler = new ServerHandler(server_socket)
    val thread = new Thread(server_handler)
    thread.start() // start a thread for the server handler

    // Loop and accept commands from admin via console
    while(true){
        input match{
            case "stats" =>
                // print stats (# of clients logged in etc)
            case "quit" =>
                // close server_socket etc and stop program
            case _ =>
                // unrecognized command
        }
    }
}

python: a program that reads 8763×2 values ​​from a CSV file and initializes an array and some other variables

Relatively new in Python. Have some experience in C ++.

I have written a small program that reads a CSV file (SAMPLE) and initializes two matrices and few values. There are 2 values ​​in each line, and there are 8763 of those lines. The first value of each line is placed in a matrix and the second value is placed in the second matrix. The last three values ​​of each matrix (total 6) are given to another variable.

I want more calculations as accurate as possible, therefore, I tried the decimal. Decimal approach to floating point arithmetic, but for some reason, it is not as accurate. I think I am using it badly. It is still in acceptable tolerance.

Also, I would like to know if there is a better / efficient way to initialize the matrix and / or the variables.

Code:

rf = 100
counter = 0
with open('CSVData.csv', 'r') as csv_file_in:
    csv_reader = csv.reader(csv_file_in)
    for line in csv_reader:
        alpha(counter) = (float(decimal.Decimal(line(0))))  # Alpha Angle Initialized
        gamma(counter) = (float(decimal.Decimal(line(1))))  # Gamma Angle Initialized
        if counter == 8762:
            break
        counter = counter + 1
csv_file_in.close()

# Initializing last 6 parameters
C_NSX = rf * alpha(8760)
C_NSY = rf * gamma(8760)
C_EWX = rf * alpha(8761)
C_EWY = rf * gamma(8761)
NSC = int(alpha(8762))
EWC = int(gamma(8762))

Here the value of C_NSX must be 2790 but it is 2789.9999185. (Debug image)

seo: what elements Googlebot reads on this AngularJS website

I have this page and I want to know what elements are readable / illegible by the Google web crawler.

I understand that Googlebot has trouble understanding some advanced angular features.

I tried to inspect the page and saw many gaps

Tags

Thanks for any suggestions and answers.

sql server: improving a code that reads an SQL query and fills a DataGrid, C #

I have this template to run my query, but sometimes it takes too long to load and I wonder if it is a problem with the query or the code itself

private DataTable NewSelect()
{
SqlDataReader read;
string query = @"SELECT Client_id, RSocial, NFantasia, Endereço, num_end, Complemento, Bairro,
                Cidade, Estado, CEP, CPFJ, C.EMail, Tel_Emp, Ativo, Tipo, Concorrente1, DT_criacao, Ult_update,
                Notas_1, Indicacao from Clientes C
                inner join Login_user L on L.User_id = C.User_id

 WHERE Client_id NOT IN(select Client_id from Sched) and L.User_id = @p1 ";

using (SqlConnection con = DbConnection.db())
            {
                con.Open();

                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    cmd.Parameters.AddWithValue("@p1", ID);
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        read = cmd.ExecuteReader();

                        DataTable dt = new DataTable();

                        dt.Load(read);
                        return dt;
                    }
                }
            }
}
```

debian: "A valid partition table was not found on this device." + "Error: You can't have a partition off the disk!" + fdisk reads the size "7.3T"; How can i fix this?

Distro: Netrunner Blackbird (Debian)

I / O: Sata to USB cable

KDE partition editor: "A valid partition table was not found on this device."

me@computer:~$ sudo parted -l
Model: ATA LITEONIT LCT-128 (scsi)
Disk /dev/sda: 128GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags: 

Number  Start   End     Size    Type     File system  Flags
 1      1049kB  269MB   268MB   primary  ext4         boot
 2      269MB   32.5GB  32.2GB  primary  ext4
 3      32.5GB  54.0GB  21.5GB  primary  ext4
 4      54.0GB  128GB   74.1GB  primary  ext4


Model: ATA ST1000LM049-2GH1 (scsi)
Disk /dev/sdb: 1000GB
Sector size (logical/physical): 512B/4096B
Partition Table: msdos
Disk Flags: 

Number  Start   End     Size    Type     File system     Flags
 1      1049kB  8591MB  8590MB  primary  linux-swap(v1)
 2      8591MB  17.2GB  8590MB  primary  ext4
 3      17.2GB  1000GB  983GB   primary  ext4


Error: Can't have a partition outside the disk!
Ignore/Cancel? i
Model: WDC WD10 02F9YZ-09H1JL1 (scsi)
Disk /dev/sdc: 1000GB
Sector size (logical/physical): 4096B/4096B
Partition Table: msdos
Disk Flags: 

Number  Start   End     Size    Type     File system  Flags
 1      8389kB  8002GB  8002GB  primary

me@computer:~$ sudo fdisk -l -u /dev/sdc
Disk /dev/sdc: 931.5 GiB, 1000204886016 bytes, 244190646 sectors
Disk model: 02F9YZ-09H1JL1  
Units: sectors of 1 * 4096 = 4096 bytes
Sector size (logical/physical): 4096 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: dos
Disk identifier: 0x45b0734a

Device     Boot Start        End    Sectors  Size Id Type
/dev/sdc1        2048 1953523711 1953521664  7.3T 83 Linux

Is:

me@computer:~$ sudo sfdisk -d /dev/sdc > sdc-backup.txt

He gave me this as a text file in my home folder:

label: dos
label-id: 0x45b0734a
device: /dev/sdc
unit: sectors

/dev/sdc1 : start=        2048, size=  1953521664, type=83

So, I'm not sure exactly what is happening here or how to fix it … I looked at the sudo parted error and I found this:

https://gparted.org/h2-fix-msdos-pt.php

It seems to be the same problem (and it seems that finding this with gparted, instead of the KDE Partition Editor is irrelevant), but before making changes to a partition table, I want to be as careful as possible, because I CAN & # 39 ; Do not lose data on the HDD.

Any suggestions or know any specific solution that someone can point to?

I really appreciate all the help and let me know if you want me to run some other command to post here.

Thank you all.

FYI: I installed testdisk and I'm running it now, if you need the results of that somewhere, let me know.

beginner: I want some comments on the Rust code that reads data from the .txt file

I am writing a code to read data from the text file in Rust. The destination files have two columns and rows of non-fixed length, for example,

example.txt

1  1
2  4
3  9
4  16

To achieve this, I wrote the following code.

use std::fs::read_to_string;

pub fn open_file(filename: &str) -> (Vec, Vec){
    let data = read_to_string(filename);
    let xy = match data {
        Ok(content) => content,
        Err(error) => {panic!("Could not open or find file: {}", error);}
    };

    let xy_pairs: Vec<&str> = xy.trim().split("n").collect();
    let mut x: Vec = Vec::new();
    let mut y: Vec = Vec::new();

    for pair in xy_pairs {
        let p: Vec<&str> = pair.trim().split(" ").collect();

        x.push(p(0).parse().unwrap());
        y.push(p(1).parse().unwrap());
    }

    (x, y)
}

I am a beginner of Rust, so I don't know if I follow best practices in Rust and this is the most efficient code.

I want some advice on this function.

c – This program reads from the serial port, saves it in a text file, increases the name of the file each time it is run

I want to condense it and get rid of any newbie programming error.

The code works fine, but I know it's not as elegant as it could be and I really want to improve. Your advice would be great!

I have spoken with other engineers and received basic help, but not much.

int main(){
//OPENING SERIAL PORT

int res = 0;        //variables to be passed to functinos
int logNum = 0;
HANDLE hComm;
hComm = CreateFile( "\\.\COM4",                //port name
                    GENERIC_READ | GENERIC_WRITE, //Read/Write
                    0,                            // No Sharing
                    NULL,                         // No Security
                    OPEN_EXISTING,// Open existing port only
                    0,            // Non Overlapped I/O
                    NULL);        // Null for Comm Devices

  if (hComm == INVALID_HANDLE_VALUE){ //print if COM port wont open
      printf("Error opening port");
      exit(42);
  }
  else {
      printf("Opening of port successfuln");   //Print to know serial port is open
  }

//Calling necessary functions
serialPort(hComm);
res = fileExist();
logNum = readPort(hComm, res);
parseFile(logNum);
CloseHandle(hComm);//Closing the Serial Port
return 0;   //main returns 0
}



void serialPort(HANDLE Comms){
//CONFIGURING SERIAL PORT
    BOOL Status;
    DCB dcbSerialParams = { 0 }; // Initializing DCB structure
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);

    dcbSerialParams.BaudRate = CBR_57600;  // Setting BaudRate = 9600
    dcbSerialParams.ByteSize = 8;         // Setting ByteSize = 8
    dcbSerialParams.StopBits = ONESTOPBIT;// Setting StopBits = 1
    dcbSerialParams.Parity   = NOPARITY;  // Setting Parity = None

    SetCommState(Comms, &dcbSerialParams); //Assignin serial settings to comm handle
    Status = EscapeCommFunction(Comms, SETRTS); //RTS Request to Send Signal to esentially reset Serial port (arduino)
    Status = EscapeCommFunction(Comms, SETDTR); //DTR data terminal ready, PC side terminal ready to recieve data

}


int fileExist(void){
//DOES FILENAME ALREADY EXIST

int result = 0;
char testNum(10);    
char fp(80);
char file(80) = "C:/Users/jgrayjt/Documents/Logs/TestLog_";
char fileEnd(5) = ".txt";

for (int i = 1; i < 1000; i++){

    sprintf(testNum, "%d", i); //converting testNum as int to string
    //adding test num to file dir
    strcpy(fp, file);       //adding strings to make file name
    strcat(fp, testNum);
    strcat(fp, fileEnd);
    printf("%s", fp);

        /* Check for existence */
        if((_access(fp, 0 )) != -1 ){           //Function to check if file exists
            printf( "nFile logs existsn" );
        }
         else { //if file doesnt exists 
          printf("nFile doesnt existn");
          result = i; //set result to equal current value for i
          break;
         }
    }
return result;  //send file num to next function
}


int readPort(HANDLE Comms, int testNum){
//READING DATA FROM SERIAL PORT
//time_t rawtime;
//struct tm * timeinfo;
//time (&rawtime);
//timeinfo = localtime (&rawtime);
char word(14) = "Test Finished";  //Text to look for
char SerialBuffer(256);//Buffer for storing Rxed Data
DWORD NoBytesRead;  //set type for NoBytesRead
char Num(10);
sprintf(Num, "%d", testNum);    //convert test num to string
char str(80);
//char buf(100);
char *file = "C:/Users/jgrayjt/Documents/Logs/TestLog_";
//char tandd(8) = "_%x_%X";
char fileEnd(5) = ".txt";
//strftime(buf,64, "_%x_%X", timeinfo);
strcpy(str, file);      //adding strings to make file name
strcat(str, Num);
//strcat(str, buf);
strcat(str, fileEnd);
printf("%s", str);

FILE *fp;    //create file pointer

fp = fopen(str, "w");   //create file to write serial data to

    do { //start do while loop
        ReadFile(Comms,           //Handle of the Serial port
                 SerialBuffer,       //
                 sizeof(SerialBuffer) -1,//Size of Buffer
                 &NoBytesRead,    //Number of bytes read
                 NULL);

        SerialBuffer(NoBytesRead) = ''; //Specify null terminator to stop data rxing strangly

        printf("%s", SerialBuffer); //Print rx'd data to CMD
        fprintf(fp, "%s", SerialBuffer); //Save rx'd data to txt file


        char *fin = strstr(SerialBuffer, word); //Find 'search' in SerialBuffer and assign to 'fin'

        //if fin has data then close Serial and close/save file
        if (fin != NULL){
            printf("Results Successfully logged n r n r");
            fclose(fp);         //close file
            fp = NULL;          //set file pointer to equal null to break from the loop
        }
    } while (fp != NULL);  //while, from do while loop
return testNum; //return testNum for use in another function
}



void parseFile(int fileNum){
//FUNCTION TO PARSE DATA FROM LOG FILE TO FIND FAILED TESTS

char Num(10);   //set Num as char and give extra memory
sprintf(Num, "%d", fileNum); //Convert filenNum to string
char dir(80);   //set dir as char and give extra memory
char *file = "C:/Users/jgrayjt/Documents/Logs/TestLog_";
char fileEnd(5) = ".txt";
strcpy(dir, file);      //adding strings to make file name
strcat(dir, Num);
strcat(dir, fileEnd);
printf("%s", dir);
FILE *fp1;      //create file pointer
char str(512);  //string to store data read from log file
const char fail(5) = "FAIL";    //text to look for
const char testnum(23) = "Test Iteration";     //text to look for
char *ret;  //create char variables
char *num;

fp1 = fopen(dir , "r");  //Open file to read

    if (fp1 == NULL){ //if you cant open file, print 
        printf("File open fail");
    }

    //Loop to find test number and fail strings  
    while( fgets (str, 512, fp1)!=NULL ) { 
        num = strstr(str, testnum); //find test num in string and assign to num
        ret = strstr(str, fail);    //find 'fail' in string and assign to ret

    if (ret != NULL && num != NULL){    //if both variables have data then print num
        printf("n r %snr", num);  //num has been given enough mem to include the fail that comes after it
    }
    }

fclose(fp1);    //close/save fil
getchar();
getchar();
}

application: application that reads all articles on the web and in pdf format

You want to know what it means to make an application that can read aloud text from web pages or PDF files, etc., how does the application develop? What all components of the computer field are involved? I saw a similar application from Google, it's called Google go. I tried to find out more about how they built it, but they didn't get much information, only that they used natural language processing and artificial intelligence. But I wanted to see some example or code on how they made use of these concepts.
It would be really nice, if someone here could shed some light.

How can I see what data application reads and writes when the application is running?

Battery exchange network

The Stack Exchange network consists of 175 question and answer communities, including Stack Overflow, the largest and most reliable online community for developers to learn, share their knowledge and develop their careers.

Visit Stack Exchange