Quantcast
Channel: Programming Forums
Viewing all 51036 articles
Browse latest View live

Asio (standalone) C++ socket progamming on Linux

$
0
0
Hello to all,

I aim at learning C++ socket programming by Asio standalone (non-Boost) library on Linux and have a couple of questions:

1- How to start learning Asio C++ as a beginner, please?
I have searched the Web but almost every tutorial about Asio is its Boost version. The Asio Docs esxit but I think they are hard for a starter to begin learning.
There are also some tuts but I even don't know how to install Asio-1.12.2 that I have downloaded on the Ubuntu machine. :(
So, how to really start learning that, please? I need some guide book to teach it from the first place.

2- What do you think of C++ socket programming or generally C++ programming on Linux? Do you prefer that to Windows? And why please?

How do computers print integers from binary?

$
0
0
Tried searching but only got results for conversion and etc.

I want to know how computers change binary representation of integers into a string of characters representing an integer. How's that done?

Extract numbers, Pattern/Matcher

$
0
0
Hi guys,
there is a little something that I don't understand regarding the whole pattern/ matcher thing in Java. I recently started to learn it and so far it was good, but that just doesn't work somehow and I do not know why.

My input: I get a sentence with names and age, for example "Bert 24, Hannah 12, Mary 35." I want to extract the names and the age of this String and put it in a different Array. This example it would be:
First Array: Bert Hannah Mary
Second Array: 24 12 35
I can't seem to get it to work, though. Here is what I have so far:

Pattern pAge = Pattern.compile("[0-9]+");
Matcher mAge = pAge.matcher(debits);

int[] age = new int[mAge.groupCount()];
int tmp = 0;

while(mAge.find()) 
{
	age[tmp] = Integer.parseInt(mAge.group());
        b++;
		
}



Why does this not work? Why does groupCount() not give me the number of ages? I just need this String to be sorted into two arrays but it appears to be impossible.

C program to replace all occurrences of a character in a string

$
0
0
Hi everyone,

I want to write a C program to search all occurrences of a word in given string and
to write all occurrences of a word in capital letters.

Example

Input

Input string: good morning. have a good day.

Output
The word 'good' was found at location 1
The word 'good' was found at location 22

GOOD morning. have a GOOD day.

I wrote the following code
#include<stdio.h>
#include<string.h>

void main()
{
char str[1000] , pat[20]="good" ;
int i=0,j,mal=0,flag=0 ;
printf("Enter the string :");
gets(str);

while(str[i]!='\0')
{
if(str[i]==pat[0])
  {
    j=1;
   //if next character of string and pat same
   while(pat[j]!='\0' && str[j+i]!='\0' && pat[j]== str[j+i])
    {
     j++;
     flag = 1;
    }

   if(pat[j]=='\0')
    {
        mal+=1;
        printf("\n The word was found at location %d.\n" , i+1);
    }

  }
  i++;
  if(flag==0)
 {
    if(str[j+i]=='\0')
    printf(" The word was not found ") ;
 }

}
  printf("The word was found a total of %d times", mal);

}
 



my question is
How can I convert the word 'good' into uppercase letters?

When i use the the functions toupper from the C library ctype.h, the entire text is converted into uppercase letters.
can you help me pleas?

Thanks

How can I get this to compile?

$
0
0
Hi, I have an assignment due tomorrow and on paper I'm pretty sure this is coded correctly but it won't compile. Here is the problem
https://gyazo.com/ac56f3262f034438337f9fad8961e4fe and here is what I have:

#include <stdio.h>

#define GRAVITY_CONST 9.8f
#define FT_TO_KM 0.0003048

int main()
{
  float v0, H;
  printf(“Enter initial velocity, in ft/s: ”);
  scanf_s(“%f”, &v0);
  v0 *= FT_TO_KM;
  H = (v0 * v0) / (2 * GRAVITY_CONST);
  printf(“Maximum height: %f km”, H);
  return 0;
}

How to get blog posts by label in blogger api

$
0
0
I using blogger api in my android app to integrate blogger content with it by using the REST APIs, as a json's objects.

I need to retrieve/filter posts by label. In most blogs the link of blog's label it usually is

https://abtallaldigital.blogspot.com/search/label/Food
https://abtallaldigital.blogspot.com/search/label/Technology


I read all api documentation and I see it's deal with Blogs, Posts, Comments, Pages, Users but there's no thing handle labels/categories in it.

There's a class BloggerAPI in the app that's used to retrieve blogs


package abtallaldigital.blogspot.com.dummyapp;

import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Url;

public class BloggerAPI {

    public static final String BASE_URL =
            "https://www.googleapis.com/blogger/v3/blogs/2399953/posts/";
    public static final String KEY = "THE-KEY";

    public static PostService postService = null;

    public static PostService getService() {

        if (postService == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            postService = retrofit.create(PostService.class);
        }

        return postService;
    }

    public interface PostService {
        @GET
        Call<PostList> getPostList(@Url String url);
    }
}


It is used thus

private void getData(){

    String url = BloggerAPI.BASE_URL + "?key=" + BloggerAPI.KEY;

    if(token != ""){
        url = url+ "&pageToken="+token;
    }
    if(token == null){
        return;
    }

   final Call<PostList> postList = BloggerAPI.getService().getPostList(url);
    postList.enqueue(new Callback<PostList>() {
        @Override
        public void onResponse(Call<PostList> call, Response<PostList> response) {
            PostList list = response.body();
            token = list.getNextPageToken();
            items.addAll(list.getItems());
            adapter.notifyDataSetChanged();
            Toast.makeText(MainActivity.this, "Sucess", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(Call<PostList> call, Throwable t) {
            Toast.makeText(MainActivity.this,"Error occured",Toast.LENGTH_LONG).show();
            Log.i(TAG, "onFailure: "+t.toString());
        }
    });

}


I googling for how to get link of rss XML for any label and I found this result

https://example.blogspot.com/feeds/posts/default/-/label/?alt=rss


this will gets the blog posts of any label with replace the word "label" in the link

Stuff after the for loops performing before it's done

$
0
0
#include "Engine.h"

#include <atomic>
#include <condition_variable>
#include <mutex>
#include <iostream>
#include <thread>

Engine::Engine()
{
    active = true;
    cThread = std::thread(&run, this);
    curScreen.resize(1297000);
    std::cout << curScreen.size() << std::endl;
    std::cout << "Initialized" << std::endl;
}


void Engine::run() {
    std::unique_lock<std::mutex> lock(mtx);
    while (active) {
        std::cout << "Active" << std::endl;
        //if(animation) { } else {
        perform.wait(lock);
        //int i = 0;
        //int b = 0;
        int g = 0;
        //try {
        std::cout << "Start " + sizeof(curScreenTile) << std::endl;
        for(int i = 0; i < 1430; i++) {
            for(int b = 0; b < 890; b++) {
                std::cout << "Start2" << std::endl;
                //std::cout << "at: " + g << std::endl;
                curScreen.at(g).setActive(true, curScreen.at(g));
                curScreen.at(g).setColor(0,240,0, curScreen.at(g));
                curScreen.at(g).setPos((short) i, (short) b, 1, curScreen.at(g));
                g++;
            }
        }
        std::cout << "End" << std::endl;
        //} catch(...) {
           // std::cout << "failed" << std::endl;
        //}
        update = true;
        //}
        std::cout << "Tasks Performed" << std::endl;
    }
}

int Engine::getSize() {
    return curScreen.size();
}

bool Engine::getIsActive(int position3) {
    return curScreen.at(position3).active(curScreen.at(position3));
}

RECT Engine::getRectOf(int position) {
    return curScreen.at(position).getR(curScreen.at(position));
}

unsigned long Engine::getColorOf(int position2) {
    return curScreen.at(position2).getColor(curScreen.at(position2));
}

bool Engine::processing() {
    return inProcess;
}

void Engine::setProcess(bool var) {
    inProcess = var;
}

bool Engine::getUpdate() {
    return update;
}

void Engine::done() {
    update = false;
    inProcess = false;
}

void Engine::notify() {
    perform.notify_one();
}


Engine::~Engine()
{
    active = false;
    //dtor
}




#include <atomic>
#include <condition_variable>
#include <mutex>
#include <iostream>
#include <thread>
#include <vector>
#include <windows.h>

#ifndef ENGINE_H
#define ENGINE_H


struct curScreenTile {
        RECT r;
        unsigned long rgb;
        bool activeTile = false;

        static void setColor(int b, int g, int r, curScreenTile tile) {
            tile.rgb = ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff);
        }

        static void setPos(short x, short y, short pixelSize, curScreenTile tile) {
                tile.r.left = x;
                tile.r.top = y;
                tile.r.right = y+pixelSize;
                tile.r.bottom = x+pixelSize;
        }

        static void setActive(bool toSet, curScreenTile tile) {
            tile.activeTile = toSet;
        }

        static RECT getR(curScreenTile tile) {
            return tile.r;
        }

        static unsigned long getColor(curScreenTile tile) {
            return tile.rgb;
        }

        static bool active(curScreenTile tile) {
            return tile.activeTile;
        }
};



class Engine
{
    public:
        Engine();
        void run();
        void notify();
        int getSize();
        bool getIsActive(int position3);
        RECT getRectOf(int position);
        unsigned long getColorOf(int position2);
        bool getUpdate();
        bool processing();
        void setProcess(bool var);
        void done();
        virtual ~Engine();

    protected:

    private:
        std::mutex(mtx);
        std::condition_variable perform;
        std::thread cThread;
        std::vector<curScreenTile> curScreen;
        bool active = false;
        bool update = false;
        bool inProcess = false;
};

#endif // ENGINE_H




Everything seems to be working except the std::out << "End" and update = true is happening before it is done

Also is that the correct way to find out the data size of the Struct, It's not recreating the static variables like it doesn't in java?

What's the difference?

$
0
0
What is the difference between these 2 lines of code?

boolean exists = groceryList.contains(searchItem);


int position = groceryList.indexOf(searchItem);







^groceryList is a class... using an arrayList:
private ArrayList<String> groceryList = new ArrayList<String>();

TypeError: __init__() missing 3 required positional arguments

$
0
0
OO Newbie here!

Hi Guys,

I am studying a mark scheme answer from a previous exam question and when following the mark scheme on Python , I am presented with an error: TypeError: __init__() missing 3 required positional arguments: 'MemberName', 'MemberID', and 'SubscriptionPaid'

The focus is on practicing Methods:
methods
• SetMemberName
• SetMemberID
• SetSubscriptionPaid

I have played around with the code and used various methods to pass the arguments, unfortunately, still presented with this error.

Any help appreciated.


class Member() :
    def __init__(self, MemberName, MemberID, SubscriptionPaid):
        self.__MemberName = ""
        self.__MemberID = ""
        self.__SubscriptionPaid = False
    def SetMemberName(self, Name):
        self.MemberName = Name
    def SetMemberID(self, ID):
        self.MemberID = ID
    def SetSubscriptionPaid(self, Paid):
        self.SubscriptioPaid = Paid
 
 
 
class JuniorMember (Member):
    def __init__(self):
        super().__init__()
        self.DateOfBirth=""
 
    def SetDateOfBirth(self, Date):
        self.DateOfBirth = Date
 
 
NewMember=JuniorMember()
NewMember.SetMemberName("Ali")
NewMember.SetMemberID("12345")
NewMember.SetSubscriptionPaid(True)
NewMember.SetDateOfBirth("12/11/2001")


Error: "The path is not of a legal form" in C#

$
0
0
Hello, I'm currently working on a PictureViewer assignment, when I recieved this error message:
Additional information: The path is not of a legal form.



 private void browseFolderButton_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderDialog = new FolderBrowserDialog();

            {
                //Clear lists
                fileList.Clear();   //Empty file list before refilling
                filelistbox.Items.Clear();  //Empty the list box display before refilling it

                [b]string[] file = Directory.GetFiles(folderDialog.SelectedPath);[/b]


                foreach (string fileItem in file)
                {
                    if ((fileItem.EndsWith("jpg")) || (fileItem.EndsWith(".jpeg"))
                       || (fileItem.EndsWith(".png"))) // Filter file items for image files. || means or.

                    {
                        fileList.Add(fileItem);
                        filelistbox.Items.Add(Path.GetFileName(fileItem));
                    }

                    currentIndex = 0;                //Set the current index to the first item in the list
                    updateViewer();                  //update picturebox interface
                }
            }
        }


I bolded the part where my error message was taking place.

I am new to python and can not get this change calculattor to function

$
0
0
#!/usr/bin/evn python3
#
# Change Calculator Program
# The program will display minimun number of coins
#
print ("Change Calclator")
print ()

quarters = 25
dimes = 10
nickels = 5
pennies = 1
 
# get choice from the user
choice = "y"
while choice.lower() == "y":
    
    # get input from the user
    # times 100 to convert dollard to pennies
    dollar_amount = (input("Enter dollar amount( for example, .65, 3.95):")*100)
    print()

    quarters = (dollar_amount //25)
    dimes   =  dollar_amount % 25 // 10
    nickels =  dollar_amount % 25% 10//5
    pennies =  dollar_amount % 25% 10 % 5 // 1

    # Display the results
    print("Quarters:", quarters)
    print("Dimes:", dimes)
    print("Nickels:", nickels)
    print("Pennies:", pennies)
    print()

    # see if the user wants to continue
    choice = input("Continue (y/n)?: ")
    print ()

print ("Bye!")

Any thoughts, suggestions on small fun project of mine?

$
0
0
Hello people!

I'm posting here because I'm "working" on something which is more of a leisure project than anything, and I'd like to know what you think about it, if you have any ideas, criticism etc..

I was basically done with having so many gadgets on my desktop (windows 7), I was using sticky notes, a clock, calendar, and I felt it was using too much memory for what it was (since I have a crappy laptop as of now, I try to use things that are as efficient as possible memory-wise).

So I made a program which works with username - password and which can do a few things thanks to commands that you type in which access different menus:
*Add and remove user
*Log on and off with users that are already registered in the program

for each user you can
*reset your password
*display a list of all commands and what they do
*set reminders, similar to sticky notes really, like a few words, a line at most
*set calendar events, with the date (year, month, day) and time, and you can also write a description of the event to go with that
*store personal information such as email account credentials, any type of credentials really, which you can only access for a certain user, having logged on with a password. You can either display all data, search with key word and display one specific one or delete some of course
*set an alarm (at the moment only one at a time) to go off within the next 24h (currently working on having it attached to date and time so that you can have multiple stored at the same time), sort of a reminder

And to make the info above accessible easily, I made a sleep screen, which toggles if you don't enter a command after 30 seconds. This sleep screen shows in real time and in order:
*date and time
*if an alarm is set, it displays the time and description of the alarm
*all reminders if there are any
*next event on calendar, with date, time, description
*and a small ascii art of a cat sleeping

As I said, it's really something I'm doing for fun, si I'd love to hear some suggestions as to what more could be added, or thoughts, criticism or anything really!

Have a good day/evening/night!

Regards,

Hugo.

How do I use a function in the main?

$
0
0
How do I use this signature to call in the main method? I have been doing this for ages and cannot get it to work. The below code should read a file and store the data in an array.

void SaveData(const char* inFile, int arr[], int maxSizeofArr) {

		short loop = 0;
		int num;
		std::string line;
		inFile = "in.txt";
		std::ifstream InputFile(inFile);
		if (InputFile.is_open) {
			do {
				while (std::getline(InputFile, line)) {
					std::stringstream sst(line);
					sst >> num;
					arr[loop] = num;
					std::cout << arr[loop] << std::endl;
					loop++;
				}
			} while (loop << maxSizeofArr);
		}

		else {
		std::cout << "Error Loading file";
		}

		InputFile.close();
	}



Above is my code and I am supposed to use the same signature and cannot change it. Please help me.

Below is my main method:
#include "Header.h"

#include<iostream>
int main() {
	int date[7];
	header::LoadMeasurements("inputFile.txt", date, 7);
	std::cin.get();
}

Exporting Data From Table from 000webhost's phpmyadmin

$
0
0
Hey there! I was wondering if anyone could give a few hints on what i could search for or use for my code. my teacher is having us make a website on 000webhost and have it connected to our vb database which is mssql. When we asked about he mentioned something about needing some kind of API? He told us to export our table data or something in our php code there so that whenever we're online, both our vb program and website would have the same table in that database. I've tried looking around google and youtube but i guess since i dont have any specific idea on what exactly i need to look for, I can't come up with anything helpful for me. so any hints or sources would be greatly appreciated!

Stop working after a certain date or after a week

$
0
0
Hello All,


I want my code to stop working after a certain date, I mean after my client pays my invoice full amount.
I use a certain checkbox in the application window and disable it but still visible. I name it Trial.

How do I write this in my code at the best way? I appreciate your help so much. Thank you


Regards,
Steve

How to create counter

$
0
0
Need to create time (in hours) counter. For example count 20 hours and save intermediate values to file, so will be enough to check time each hour (not each second). Is it possible?

Help implementing a paper

$
0
0
https://drive.google.com/open?id=1eCavkPMAI3LsDjMOa0w-qquLzTbXahd5

Hallo , i am trying to implement the above concept in python.

In planning it i have decided that i will do something of the sort of looping through thye dataset images with the following code

for i in dataset
backpropagate(image[i], label[i])



then in the backpropagation method

y=forward(weights(image)


where weights returns the matrices for GreenB values, GreenA, BlueB, BlueA, RedB and RedA matrices

Then forward propagation receives this and forward propagates by multiplying them appropriately.

I am very new to coding so i don't have the experience to know what code to use for the weights method that takes in an image and creates all the matrices. help would be appreciated.

Help implementing a paper

$
0
0
https://drive.google.com/open?id=1eCavkPMAI3LsDjMOa0w-qquLzTbXahd5

Hallo , i am trying to implement the above concept in python.

In planning it i have decided that i will do something of the sort of looping through thye dataset images with the following code

for i in dataset
backpropagate(image[i], label[i])



then in the backpropagation method

y=forward(weights(image)


where weights returns the matrices for GreenB values, GreenA, BlueB, BlueA, RedB and RedA matrices

Then forward propagation receives this and forward propagates by multiplying them appropriately.

I am very new to coding so i don't have the experience to know what code to use for the weights method that takes in an image and creates all the matrices. help would be appreciated.

using arrays

$
0
0
im creating the game hammurabi and im stuck ive got the base game all running with the codes for inputs and everything working but im at the stage where i now need to create the results after 10 years and im having trouble storing data after each year for example i need to store the the amount of people starved for every year and then work out the average and display, my code so far is as follows

// variables
       int year = 1;
       int arrivals = 0;
       int population = 100;
       int acres = 1000;
       int harvested = 0;
       int rats = 5;
       int trading = 18;
       int ratsAte = 0;
       int bushels = 2800;
       int bushelsHarvested = 0;
       int bushelsTrading = 0;
       int plague = 0;
       int starved = 0;

       

       


       private void btnAllocate_Click(object sender, EventArgs e)

       {
           

          
           


           // moves the game forward a year every time the allocate button is clicked
           year = year + 1;


           // random amount of people come to the city
           Random random = new Random();
           arrivals = random.Next(1, 16);

           // plague that halfs the population
           Random random4 = new Random();
           plague = random.Next(1, 21);
           if (plague == 1)
           {
               population = population / 2;
               MessageBox.Show("You were hit by a plague, half your population died");
           }
           else
           {
               plague = 0;
               
           }


           

           // working out the amount of people starved
           if (int.Parse(txtFeeding.Text) < (22 * population / 2))
           {
               MessageBox.Show("You starved " + population);
               
           }
           if (int.Parse(txtFeeding.Text) >= (22 * population / 2) && int.Parse(txtFeeding.Text) < 20 * population)
           {
               starved = ((20 * population) - (int.Parse(txtFeeding.Text))) / 20;
              
           }

           // possibilty of rats
           Random random2 = new Random();
           rats = random.Next(1, 11);

           if (rats == 5)
           {
               ratsAte = bushels * 10 / 100;
               lblRats.Text = "Rats ate " + ratsAte + " bushels.";
               
           }
           else
           {
               ratsAte = 0;
               lblRats.Text = "Rats ate 0 bushels";
               
           }

           // new population total
           population = population + arrivals - plague - starved;

           // randomised number for trading
           Random random3 = new Random();
           trading = random.Next(17, 27);

           // calculating the amount of acres that are left
           acres = acres + int.Parse(txtBuySell.Text);

           //randomised number of bushels harvested per acre
           Random random1 = new Random();
           harvested = random.Next(1, 6);


           // calculates the amount of bushels harvested and stores it in a variable

           bushelsHarvested = harvested * int.Parse(txtSeed.Text);

           bushels = bushels + bushelsHarvested  - ratsAte - int.Parse(txtFeeding.Text) - int.Parse(txtSeed.Text);

           


           // resets the textboxes
           txtBuySell.Text = ""; 
           txtFeeding.Text = "";
           txtSeed.Text = "";

           // changing the lables to show the new information remaining labels
           lblBushels.Text = "You now have " + bushels;
           lblNewPeople.Text = arrivals + " people came to the city.";
           lblHarvest.Text = "You harvested " + harvested + " bushels per acre.";
           lblPopulation.Text = "The city population is now " + population;
           lblTrading.Text = "land is trading at" + trading + " bushels per acre.";
           lblYear.Text = "In Year " + year + ", " + starved + " people starved.";
           lblRemaining.Text = bushels + " Remaining";



       }

       private void txtBuySell_Leave(object sender, EventArgs e)
       {
           // buy/sell calculation
           if (int.Parse(txtBuySell.Text) < 0)
           {
               bushelsTrading = Math.Abs(int.Parse(txtBuySell.Text) * trading);
           }
           else if (int.Parse(txtBuySell.Text) >= 0)
           {
               bushelsTrading = -int.Parse(txtBuySell.Text) * trading;
           }

           bushels = bushels + bushelsTrading;

           // calculating the amount of acres that are left
           acres = acres + int.Parse(txtBuySell.Text);

           lblAcres.Text = "The city now owns " + acres + " acres.";

           lblRemaining.Text = bushels + " Bushels Remaining";
       }

       private void txtFeeding_Leave(object sender, EventArgs e)
       {
           // warning user they dont have enough bushels
           if (int.Parse(txtFeeding.Text) > bushels)
           {
               MessageBox.Show("You do not have enough bushels in store");
               return;
           }

           lblRemaining.Text = (bushels - int.Parse(txtFeeding.Text)) + " Bushels Remaining";
       }

       private void txtSeed_Leave(object sender, EventArgs e)
       {
           // tells user that they can not seed more than 10 seed per person
           if (int.Parse(txtSeed.Text) > (10 * population))
           {
               MessageBox.Show("You can only Plant a max of 10 seeds per person");
               return;
           }
           if (int.Parse(txtSeed.Text) > acres)
           {
               MessageBox.Show("you can only plant a max of 1 bushel per acre");
               return;
           }
           

           lblRemaining.Text = (bushels - int.Parse(txtFeeding.Text)) + " Bushels Remaining";

How do I validate user input?

$
0
0
If output >= 0 AndAlso output <= 1000 Then
UnitsTextbox.AppendText(Environment.NewLine & InputTextbox.Text)
Else
MessageBox.Show("ERROR! Number must be between 0 and 1000!")
End If

So above is the code I have been working on. Now I'm trying to validate the user input and I need the numbers to be from 0 to 1000 and display an error message if they are not. I have no problem doing that it works fine but I have all output displayed in a textbox and even if its wrong its still putting that number in my output textbox how do i fix that?
Viewing all 51036 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>