Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would like to add one piece of advice on the topic of tutorials.

There are many, many tutorials on Python programming, either as web pages or as YouTube videos; some are great, some are only okay, but most are pretty bad. It can be hard to judge which are which until you've already learned the language, unfortunately.

The important thing to know is that even an excellent tutorial should only be treated as a supplement to a good book and personal guidance, not as a primary method of learning. They are invariably too focused on a specific task to give you a broad view of the language and its possible uses.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I haven't had the chance to look through this code in detail, but two things immediately strike me:

  • The use of <conio.h>. This is a non-standard library which is specific to certain ancient MS-DOS and Windows compilers, and won't be supported by any modern compiler library.
  • The declaration of main() as a void function. This is entirely non-standard, and should be avoided - while older compilers sometimes allowed it, and the older versions of the standard permitted it, modern compilers will invariably catch it as an error.

In addition, the indentation is seriously messed up, though that could be the result of pasting the code into the post.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

A forum is just a central meeting place, or (in this case) a place where you can talk with others about some topic. More specifically, it is a synonym for "message board".

In other words, you are already using the forum.

The link Dani gave should help you with this specific forum (Daniweb).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would recommend moving away from the older C-style srand()/rand() combination, and use the C++ <random> library, which is both more flexible and gives finer control. While it requires more effort to set up, it would be well worth that effort.

#include <iostream>
#include <limits>
#include <ctime>
#include <iomanip>
#include <random>


struct Sanity {

    unsigned int turns = std::numeric_limits<int>::max();
    unsigned int sanity = std::numeric_limits<int>::max();
    std::default_random_engine generator;
    std::uniform_int_distribution<int> distribution(1,6);
    int randNum = 0;
    int choice = 0;
    int low = 0;
    int high = 0;

};

void game_greeting();
int roll_dice(Sanity& s1);
int even_odd(Sanity& s1);

int main()
{
    Sanity s1;

    game_greeting();
    roll_dice(s1);
    even_odd(s1);


}

int roll_dice(Sanity &s1)
{
    s1.randNum = distribution(generator) + distribution(generator);

    return s1.randNum;
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I've been working on the GUI portion of my C++ Connect-N game project, and have gotten it to would could charitably be called a working state. However, the game AI, not to put it to finely, stinks.

I was wondering if anyone here has more experience in implementing a minmax algorithm, and can offer any advice on how to get it to play a suitably challenging game.

The minmax code is:

#ifndef __CONNECTN_AI_H__
#define __CONNECTN_AI_H__ 1

#include <vector>
#include "connectnboard.h"

namespace ConnectN
{

    typedef intmax_t Weight;
    typedef uint8_t Depth;
    const Weight infinity = INTMAX_MAX, neg_infinity = INTMAX_MIN;

    struct Node
    {
        Board board;
        Grid_Size column;
        Weight weight;
        Depth depth;
        Node(const Board& b, Grid_Size c, Weight w, Depth d): board(b), column(c), weight(w), depth(d) {};
        Node(const Node& n);
        void operator=(const Node& n);
    }; 


    class Solver
    {
    private:
        Board& board;
        Depth search_depth;
        Node negamax(Node node, Depth depth, Weight alpha, Weight beta, Weight color);
        std::vector<Node> enumerate_moves(Node node);
        void order_moves(std::vector<Node>& children);
        Weight evaluate_move(Node& node);
        Weight evaluate_node(Node& node);
        Weight weight_column(Grid_Size c);

    public:
        Solver(Board& b, Depth d);
        Grid_Size move();

        friend class Board;
    };
}

#endif

and

#include <algorithm>
#include <chrono>
#include <cmath>
#include <random>
#include "connectnboard.h"
#include "connectn_AI.h"

namespace ConnectN
{

    /**
     * 
     *
     */
    Node::Node(const Node& n)
    {
        this->board = n.board;
        this->column = n.column;
        this->weight = n.weight;
        this->depth = n.depth;
    }


    /**
     * 
     *
     */
    void Node::operator=(const Node& n)
    {
        this->board = n.board;
        this->column = n.column;
        this->weight = n.weight;
        this->depth = n.depth;
    }


    /**
     * 
     *
     */
    Solver::Solver(Board& b, Depth d = 3): board(b), search_depth(d)
    { …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ranged Numeric Types in C++

I've started writing a simple template class for automating range checking in specialized numeric types, inspired by the ranged types in languages such as Pascal and Ada. At the moment it is mainly meant for integer types, though I've made it flexible enough that it should work with floating-point types (I may need to revisit this later).

It is just a stub at this point, but it should make it easier to define numeric types which don't fit the usual 8/16/32/64 bit signed and unsigned sizes. It allow the client-programmer to select a base type define both a lower and an upper bound, and define how it should behave on either underflow or overflow (with the choices at the moment being to wrap around; to saturate at the boundary; or to throw an exception). The usual arithmetic operators will all be supported.

The question I have is this: is this really a useful class to write, and will others find it useful enough that it is worth providing publicly? Can you think of use cases where this would make things easier for someone working on a real-world project?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Itself, since PHP is in fact a programming language. One for a specific set of uses, but a programming language nonetheless.

As for which other language it most resembles, that's a bit of a judgement call, really. I would say... well, no, that would be giving you the answer, which I suspect is for a homework question. Given the tags you put, I will say that my personal answer is 'none of those three'.

Mind you, this question doesn't makes much sense as homework, but it doesn't make sense in any other context, either, so I am puzzled as to why either you or your professor would think this is relevant.

Dani commented: Not useful: Yes, it's a judgement call, but you just poke fun at the legitimacy of the question and then refuse to give your opinion -8
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

We would need a lot more information than that to be able to help you with it, starting with the code in question and the error you are getting.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

@Toneewa: please stop answering questions which don't show the OP's own code - DaniWeb is not a free homework solving service. And yes, I know I'd made the same mistake in the past myself, but when this was pointed out to me I stopped doing so.

Also, please pay more attention to the dates of original posts. After more than a month, it is safe to say that the assignment has passed.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you don't mind me asking, how is it that you are writing new VB 6.0 code in 2022? I would strongly advise against trying to beat that dead horse any further, if you have any choice in the matter.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic ethics on your part, and actually doing so would be an even bigger breach on ours (not that this …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Several of us have VB6 experience, but for most of us it would be several years since we've used it - VB6 was released in 1998 and support for it was mostly discontinued by 2008. It is extremely inadvisable to write any new code using VB6 in 2022.

Also, while you appear to have tried to format your code, you need to know that the inline code formatting using the backtick doesn't span multiple lines of code. For multiline code snippets, you need to indent the code by four spaces. The Cod Block tool ("</>") on the window toolbar will do this automatically for you.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

With a little further testing by a process of elimination, I have found that the critical sections are the definitions of login_load_button and captcha_input, both of which are the only user input widgets on the window. I've also found that with those two commented out (along with their relevant .place() method invocations), the CAPTCHA image appears, but after a few seconds vanishes. Just what this indicates isn't clear to me. Some issue with how it refreshes, perhaps?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As a proof-of-concept, minimal reproducible example, I stripped out all of the code except that which is necessary for displaying the Captcha image:

from PIL import Image, ImageTk  
import os,re,requests,time,customtkinter
import customtkinter as ctk
from tempfile import gettempdir, mkdtemp
from captcha.image import ImageCaptcha

app = customtkinter.CTk()  # create CTk window like you do with the Tk window (you can also use normal tkinter.Tk window)
app.geometry("500x400")
app.title("Image Test")
PATH = os.path.dirname(os.path.realpath(__file__))

captcha_width = 280
captcha_height = 90

image = ImageCaptcha(width = captcha_width, height = captcha_height)
captcha_text = 'Test Image'
captcha = image.generate(captcha_text)
dir = mkdtemp()

image.write(captcha_text, f"{dir}/CAPTCHA-{captcha_text}.png")
render = ImageTk.PhotoImage(Image.open(f"{dir}/CAPTCHA-{captcha_text}.png").resize((captcha_width, captcha_height), Image.Resampling.LANCZOS))

img = ctk.CTkLabel(app, image=render)

img.place(relx=0.5, rely=0.35, anchor='center')
app.mainloop()

This example version does in fact display the CAPTCHA image, which leads me to think that the fault is in some interaction with the rest of the display code.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In the future, please post the code into your message (using the Code Block button, </>, in the editor window menubar), rather than as a link to a copy on another site.

Also, please tell us what is failing, in detail. We need to know what you expected the code to do, what it is actually doing, and what error messages you are getting, if any. We are not mind readers, nor are we likely to try running your code for you.

That having been said, I did try running the code, and got the following results:

$ python my_captcha.py 
lM9sZE
Traceback (most recent call last):
  File "/home/schol-r-lea/Documents/Programming/Projects/Quick Tests/my_captcha.py", line 99, in <module>
    captcha("B")
  File "/home/schol-r-lea/Documents/Programming/Projects/Quick Tests/my_captcha.py", line 73, in captcha
    render = ImageTk.PhotoImage(Image.open(dir + f"/CAPTCHA-{captcha_text}.png").resize((280, 90), Image.Resampling.LANCZOS))
  File "/usr/lib/python3.10/site-packages/PIL/Image.py", line 3092, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpkuasr8qv/CAPTCHA-lM9sZE.png'

Subsequent runs make it clear that you are trying to randomly generate a temporary directory path and image file name, but you do not seem to be actually creating file in question. Is it safe to assume that this is the error you are getting, or is it something different?

EDIT: I think I've found the problem I was getting. In the line

  image.write(captcha_text, dir + f"\\CAPTCHA-{captcha_text}.png")

You are trying to insert a Windows-style backslash path. Regardless of the OS, paths in Python should always follow the Unix format:

  image.write(captcha_text, f"{dir}/CAPTCHA-{captcha_text}.png")

I suspect that this is not the problem you …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

i have posted the code.its a bit bulky because i had to repeat one function four times. i know there is a shorter way to do this but i have not figured out how.

One thing you can do is, rather than having separate final_searchn and newest_listn variables, use a list of lists for each of those. For example:

final_search = []
for i in range(3):
    final_search[i] = []
    for item in my_new_list[:index_list[0]]:
        final_search[i].append(item)
    final_search[i] = final_search[i][::-1]

As for the function search_engine(), I would parameterize new_input:

def search_engine(my_new_list, new_input):
    # ...


def update_list():
    f = open("list_file.txt", "r")
    print(f"Last Updated Liist: {f.read()}")
    enter_input = float(input("Please enter your input: "))
    my_list.insert(0, enter_input)
    my_list.remove(my_list[-1])
    my_new_list = my_list
    print(f"Updated List: {my_new_list}")
    for ni in ['3', '4', '5', '6']:
        search_engine(my_new_list, ni)

    f = open("list_file.txt", "w")
    f.write(str(my_new_list))
    f.close()
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The reason you need to change Score() rather than FinalScore() is because Score() is where you are updating the totals.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There are two approaches you can take: you can either make scP1 and scP2 globals by moving their declarations to the top level outside of the main() function or - preferably - pass them as references to Score() so that they could be updated.

Note that similar issues exist for the readCards() function; you need some way to return the values read in from the file to the main() function. This is where that damnable requirement for parallel arrays (as opposed to packing all values into an single vector<> of a data structure as any sane coder would do) becomes a serious headache - with the parallel arrays, not only do you need to synchronize them manually, but you have to pass each of them individually to each function that uses them. The fact that it uses primitive arrays rather than vector<>s doesn't help, either. Parallel arrays is simply a very bad design for this sort of data structure, and I frankly would complain to the instructor that the textbook is teaching poor techniques.

Anyway, here is what I recommend (warning, not tested):

int Score(int&, int&, int ,int ,int [],int []);

//scores for each round
int Score(int& scP1, int& scP2, int IDcardP1,int IDcardP2,int sctype[],int scsystem[]){
    cout << "The winner for this round is " <<endl<<endl;
    if (sctype[IDcardP1]>sctype[IDcardP2])
    {
        cout << "  PLAYER 1  " <<endl;
        scP1+=10;
        cout<<endl;
    }
    else
    {
        if (scsystem[IDcardP1]>scsystem[IDcardP2])
        {
            cout << "  PLAYER 1  " <<endl;
            scP1+=10;
            cout<<endl;
        }
        else
        {
            cout << "  PLAYER 2 …
isyae commented: i already done with the function scores, but for the function finalscore i still didnt get the total score based on function scores +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Fortunately, the assignment gives a good deal of detail as to how to go about it, and seems focused on how well you understand basic OOP development. From the assignment, you know that:

  • You'll have a class called Account
  • Account objects will have member (instance) variables for the account number; the account type; the account balance; the account holder's name; an optional joint account holder's name; and the account transfer status.
  • The Account class has member functions to act as getters and setters for each of the member variables.
  • Account will have two sub-classes, which could be called something like SavingsAccount and PersonalLoanAccount, both of which extend Account in specified ways.

This seems to me to be the place to start.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If I might recommend a bit of an improvement:

void ShowCardP1(int cardP1, string cardName[], string p_code[], string type[], string plusMode, string system[]) {
    cout<< "Product code: " << p_code[cardP1] << "  " << endl;
    cout<< cardName[cardP1] << "  " << endl ;
    cout<< "Type: " << type[cardP1] << "  " << endl;
    cout<< "PlusMode:" << plusMode[cardP1] << endl;
    cout<< "System: " << system[cardP1] << endl;
}

Mind you, if it weren't for the (rather absurd) instructions to use parallel arrays, I would instead declare a struct type to hold this information:

struct CardDetails {
    string name, code, type, mode, system;
} cards[SIZE] = {{"Abyss Devolos", "F0647", "Balance", "NA", "SpeedStorm"},
                 {"Ace Dragon", "E7609", "Attack", "NA", "HyperSphere"},
                 // ... etc. 
                };

// ...

void ShowCardP1(int cardP1, string cards[]) {
    cout<< "Product code: " << cards.code[cardP1] << endl;
    cout<< cards.name[cardP1] << endl ;
    cout<< "Type: " << cards.type[cardP1] << endl;
    cout<< "PlusMode:" << cards.mode[cardP1] << endl;
    cout<< "System: " << cards.system[cardP1] << endl;
}

This is probably a bit ahead of where your course is right now, however.

isyae commented: aaaa thankyouuu sooo muschhhh +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I spent far too much time on this, but I worked out a usable password sign-in process that you may want to look into. It uses a third party library, passlib, which can be installed using pip install passlib.

import getpass
from passlib.context import CryptContext

# some of the code taken from the web page
# https://blog.teclado.com/learn-python-encrypting-passwords-python-flask-and-passlib/

def init_pwd_context():
    return CryptContext(
        schemes=["pbkdf2_sha256"],
        default="pbkdf2_sha256",
        pbkdf2_sha256__default_rounds=30000
    )

def encrypt_password(pwd_context, password):
    return pwd_context.hash(password)


def check_encrypted_password(pwd_context, password, hashed):
    return pwd_context.verify(password, hashed)


def add_account(fname, pwd_context, username, password):
    """ Adds an account to a file of 'username, password' pairs.
        Simply appends the new information to the end of the file, if a username already
        exists the new one shadows the old information."""
    file = open(fname, "a")
    file.write(f"{username}: {encrypt_password(pwd_context, password)}\n")


def collect_accounts(fname):
    """ Reads a file with 'username,password' pairs and returns a dictionary with the pairs."""

    accounts = dict()
    try:
        file = open(fname,"r")
    except FileNotFoundError as e:
        return accounts
    account_strings = file.readlines()
    for acct in account_strings:
        username, password = acct.split(': ')
        accounts[username.strip()] = password.strip()
    return accounts


def get_user_pwd(): 
    """ Reads in a username and password."""
    username = input("Username: ")
    password = getpass.getpass()
    return username.strip(), password.strip()


def login(accounts, pwd_context):
    """ Log user in, returning the user name."""
    while True:
        username, password = get_user_pwd()

        if (username in accounts):
            if check_encrypted_password(pwd_context, password, accounts[username]):
                return username
        print("Username or password incorrect.")



if __name__ == "__main__":
    pwd_context = init_pwd_context()
    accounts = collect_accounts("Accounts.txt")
    a_or_l = input("A)dd or L)ogin? ").upper()
    if a_or_l == 'A':
        username, password = get_user_pwd()
        add_account("Accounts.txt", pwd_context, username, password)
    elif a_or_l == …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Unfortunately, there's really no way to read Python code when the indentation has been lost. I'll try to puzzle out your intentions here, but it isn't straightforward. As it is, I can't even tell if this is all supposed to be one function, or the function followed by some top-level code. As best as I can determine, you intended the code to read like so:

def login(): 
    username = input("Enter username: ")
    password = input("Enter password: ")
    file = open("Account.txt","r")
    account = file.readlines()

    access = False
    while access == False:
        for user in account:
            if username in user and password in user:
                login = user.strip("\n")
                login = login.split(",")
                if username == login[0] and password == login[1]:
                    access = True
                    print("Welcome", username)
                else:
                    print("Username or Password is incorrect, try again.")

            else:
                print("Username or Password is incorrect, try again.")
                username = input("Enter username: ")
                password = input("Enter password: ")

        if access == True:
            break

This forum uses Markdown, so in order to preserve the formatting of your code, you would indent teach line by four spaces. The Code Block button (</>) will open a separate sub-window to make this easier to paste the code into the message while preserving formatting.

As an aside, you generally don't want to have the text of a password to echo to the console, to prevent people from shoulder-surfing. There is a standard password library, getpass as part of the Python standard library, for precisely this purpose.

On a related note, you seem to be using …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While it is an extra step, I would recommend converting the date text value to a System.DateTime value and perform the operations on that before converting back to text.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

We'd be happy to help if you had some code to show us, so we could give pointers for it. Solving your homework for you isn't helping.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I can see a number of issues with the code as given.

  • You define a class Shapes but then declare Circle as a subclass of Shape. The names need to match in order to be valid.
  • You never #include the header Shapes.h in the Circle.h header.
  • You define Circle middle as an instance variable of Circle itself, which leads to a recursive definition. While one can have a recursive definition using a pointer (e.g., Circle* middle;), having an object of the type inside the class definition isn't valid.
  • Point::getX(), Point::getY(), and Point::Print() are all instance methods rather than class methods. There would need to be a Point object for them to be applied to. Applying an instance method is in the form myPoint.getX().

Presumably, what you want to do is have middle as a Point instead, and apply those methods to middle.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Uhm, 'struggle'? I have no idea what that refers to in this context. OTOH, void just means a function doesn't return a value, or conversely, that a pointer doesn't have a type.

Mind you, I don't think this code would even compile under most compilers today, or at least would give few warnings about it. The main() function must - I repeat, must - be declared as int in C++, and return some sort of value, no ifs, ands, or buts. Furthermore, <string.h> was renamed to just <string> in 1998, and most modern compilers won't allow that header - or if they do, they assume you want the C string library (renamed to <cstring> in modern C++, but still sometimes used in older code) rather than the C++ string class library. If you don't mind me asking, what compiler are you using?

Getting to the problem at hand, I would suggest that you have separate wincount variables for each of the teams; as it is, you are just counting how many games were played (except in the cases of ties). The simplest way to do this would be to declare two variables, wincount1 and wincount2, and use those to count the wins for the individual teams, rather than the aggregate of both.

    cout << "\tTeam " << team2 << " Points: ";
    cin >> p2;
    cout << "================================\n";

        if (p1 > p2)
            {
                cout << "Winner: Team " << team1 << endl;
                wincount1 += 1;
            }
        else if (p1 …
rproffitt commented: +1 for the win. +16
Jash_1 commented: It worked! I've derived some codes and it finally run. Thank you very much +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Definitely homework, apparently from University of Technology of Jamaica (which fits with the reference to Norman Manley Airport, a real airport in Kingston). If that link is anything to go by, the project is meant to be solved in Java.

If so, I guess my first question to the OP is, why tag it as C++ if it needs to be done in Java?

My second question is, what have you tried doing on the project so far? Please post your code in your messages, or at least give us a link to an offsite repo which we could view (and yes, I recommend having all programs placed into version control and stored on an offsite repository on a host such as GitHub, even homework problems).

We cannot and will not provide code for you, but we can help you by giving advice on how to fix the code you have written.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you want it to run in a browser, then yes, you almost certainly want to use JavaScript. While there are other languages which can be used, such as TypeScript or ClojureScript, they all get translated into JavaScript anyway.

There are many video tutorials on this topic, and many web pages as well. I would go over a few of them to see what you can get out of them, then apply that to your own game.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic ethics on your part, and actually doing so would be an even bigger breach on ours (not that this …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There is a developer on the OSDev forum, David Cooper, who managed to do something like this for his OS project, though I am pretty sure he started off cross-developing his toolkit. He created what he describes as a sophisticated suite for editing code in hex, though presumably if you really wanted to you could do it in binary.

He's a bit of a crank, but that's true of everyone on that forum, myself included.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While I do not know if this is quite what you have in mind, I do think the code can be improved upon substantially. For a start, roulette wheels generally have slots with both a color and a number, and you have to get both right to pay off.

import random

money = 0
finturns = 0
print("""
1
2
3
4
5
6
7
8
9
10

red
black 

every guess = - 1$
every colour = - 5$
every correct = + 10
The goal is to get to 100$
""")

while money < 100:
    print(f"Your current bank is ${money}.")
    col = input("what colour are you betting on: ")
    num = int(input("what number are you betting on: "))

    finturns += 1
    gamble = random.randint(1,10)
    redblack = "red" if random.randint(0,1) == 0 else "black"
    print(f"{redblack}-{gamble}, ", end='')    

    if redblack == col and gamble == num:
        print("Player wins!")
        print("you gained 10 dollars!")
        money += 10
        print(f"it took you {finturns} attempts to win.")
        finturns = 0

    else:
        print(f"House wins.")
        money -= 1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The fact that the code given is incomplete, with no main() function, makes it hard for us to judge whether it works at all.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

From what I've read, MIPSMARK is intended for checking and grading MIPS assembly language programs. Are you compiling the C code to MIPS assembly, and if you are, with what compiler and compiler invocation?

Where is MIPSMARK available from? Do you know of a download site for it, or a documentation page? Also, could you tell us which book the assignment is from?

rproffitt commented: OP supplied C style code and then as you note something about assembler check app but left out the story and more. +16
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Honestly, it is so ubiquitous as a sub-set of modern programming techniques that it isn't really even a debate any more. Pretty much all modern programming is 'structured' in the sense it was originally meant, it is just that more elaborate design approaches have subsumed it.

Or to put it another way: outside of assembly programming and certain specialized C code, when was the last time you saw a general unconditional jump (i.e., goto)? How many modern languages even have a goto statement? Even the unconditional jumps that are still common (exceptions, break, continue, etc.) are for specialized cases, and are still 'structured' in how they are used.

As for structured programming as a specific paradigm, it is still practiced in C programming in exactly the sense Dijkstra meant. C doesn't explicitly support either OOP or FP, and does have a goto, and yet it is exceedingly rare to see it used.

rproffitt commented: Do I have a break for you? Goto Park Place, get of jail card. +16
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The structure tag is optional because there are instances where you want a one-off structure;

struct {
    int foo;
    char bar[4];
} my_unique_data_structure;  // only struct of this form

The tag is for when you want to name the structure template or type.

struct quux {
    int baz, bang, zing;
};

struct quux whoopie;

You can also declare instances of a named structure following the structure definition, for cases where you know ahead of time that you need at least one structure of that type:

struct quux {
    int baz, bang, zing;
} whoopie;

// later ...
struct quux flarp;

I hope this makes it a bit clearer.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

According to this post, the solution is to operate on playlist directly rather than extracting the "items" sub-dictionary.

razstec commented: Excellent as always +3
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Is there a specific reason you need to ensure that the values are positive?

As per RProffitt's suggestion, here is how you would loop on the input to require that the input value is positive.

#include <iostream>

using namespace std;

int main()
{
   int X = -1;
   int Y = -1;
   while (X < 0)
   {
       cout<<"please enter a positive value for X";
       cin>>X;
   }
   while (Y < 0)
   {
       cout<<"please enter a positive value for Y";
       cin>>Y;
   }
   float result;
   result=4*X^3+Y^3-4;
   cout<<"the result of Z="<<result;
   return 0;
}

A simpler alternative is to use abs() (which requires you to #include <cmath>) to force the value positive regardless of whether it was negative or not. However, looping on the input is advisable in any case, to hand the instance where the input is a string.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There are already functions for saving games and loading saves in the code, so I assume that there is some problem with those functions. Could you please explain what is actually happening?

Does the program fail to compile, or compile with warnings? Is the program crashing when you try to save and/or load? Does it save, but incorrectly? Does loading fail restart the game at the saved point? Are there any error messages?

BTW, <conio.h> is not a standard C library, it is specific to a few older Windows compilers such as Turbo C. I would recommend avoiding it, even if your intention is to run purely on Windows. Similarly, you are using the ANSI character set for extended and control characters, which will only work properly with certain settings even under Windows. I would recommend the windows port of NCurses instead, as that should work in all circumstances; or conversely, moving out of the console entirely and writing the program as a Windows application. Finally, using system() presents a number of security holes, and is best avoided as well.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you want to learn how to program in PHP (which I think is what you really mean), then you would want to find a good book or tutorial on the topic. It isn't really something you can just pick up, even if you are familiar with other programming languages.

I am by no means an expert in PHP, but I would recommend as a starting point the book Learning PHP, MySQL & JavaScript: A Step-by-Step Guide to Creating Dynamic Websites by Robin Nixon. There are also several free online tutorials on the topic, but I don't know personally which ones are worth your trouble.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic ethics on your part, and actually doing so would be an even bigger breach on ours (not that this …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Having taken a closer look at it, I can see that there are serious problems with how the code is edited and structured. Aside from the fact that it is completely un-formatted, I found that a section of code which appears to have been meant to be part of the main() function somehow got misplaced at the end of the code. I have managed to edit the code to at least the point where it compiles; whether it works correctly is up to you to determine.

For the record, I compiled the code in GCC with the shell invocation:

g++ -Wall -Wextra -Werror simple-sci-calc.cpp -o simple-sci-calc

The updated code is:

#include <iostream>
#include <cstring>
#include <cmath>

void Power(float,float);
void Sine(float);
void Square(float);
void Cos(float);
void Tan(float);
void Log(float);
void Baselog(float);

int main()
{
    int input;
    std::cout << "CHOOSE BETWEEN SCIENTIFIC AND SIMPLE CALCULATOR:" << std::endl;
    std::cout << "[1] Scientific" << std::endl << "[2] Simple" <<std::endl;
    std::cin >> input;

    switch(input) 
    {
    case '1':
 //       float a,b;
        int z;

        std::cout<<"WHAT YOU WANT TO FIND: "<<std::endl;
        std::cout<<"Press '1' for Power: "<<std::endl;
        std::cout<<"Press '2' for Sin: "<<std::endl; 
        std::cout<<"Press '3' for Square: "<<std::endl; 
        std::cout<<"Press '4' for Cos: "<<std::endl; 
        std::cout<<"Press '5' for Tan: "<<std::endl;
        std::cout<<"Press '6' for Log: "<<std::endl;
        std::cout<<"Press '7' for Base Log: "<<std::endl;

        std::cin>>z;
        switch(z)
        {
        case 1:
            std::cout<<"Enter the Number for Calculating its Power: "<<std::endl;
            int a;
            std::cin>>a;
            std::cout<<"Enter the Power for a Number: "<<std::endl;
            int b;
            std::cin>>b;
            Power(a,b);
            break;

        case 2:
            std::cout<<"Enter the Number for Calculating SIN: "<<std::endl;
            std::cin>>a;
            Sine(a);
            break; …
Husnain_6 commented: Thanks Sir it helped alot +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you please elaborate on what you mean when you say "it is not running"? Is it failing to compile? Does it compile, but crash? Please give details about the failure mode.

Also, the header <conio.h> isn't valid in any modern compiler, being specific to the now-ancient Turbo C++ compiler suite. If you are still using Turbo C++, STOP. You are doing yourself a disservice by learning an pre-standard version of C++.

Similarly, the C headers <math.h> and <string.h> are renamed <cmath> and <cstring> in modern C++.

rproffitt commented: I said similar to someone and the reply was "But Turbo C++ is free." +16
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic ethics on your part, and actually doing so would be an even bigger breach on ours (not that this …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oops, I dropped a dollar sign in there. Sorry about that.

    $stmt = $conn->query("INSERT INTO ronin(phrase, password)VALUES(?, ?)");
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The procedure mysqli_query() has the following signature:

mysqli_query(mysqli $mysql, string $query, int $result_mode = MYSQLI_STORE_RESULT)

It takes either two or three arguments, with the first argument being the database connection handle. Thus, you probably want the call to be:

    $stmt = mysqli_query($conn, "INSERT INTO ronin(phrase, password)VALUES(?, ?)");

Alternately, you could instead use the OOP model to call the method query() like so:

    $stmt = conn->query("INSERT INTO ronin(phrase, password)VALUES(?, ?)");

I suspect that this was what you intended to do in the first place.

On an unrelated note, please do not post images of code snippets to the forum, but instead cut and paste the code into a code block using the Code Block button ("</>" in the editing window icons). This makes it far easier for respondents to read, and to make code changes.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Can you show us what you have done so far, please? We would need to see your current progress in order to give assistance; we cannot provide a solution directly.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

My first comment is more of an aside, but I was puzzled by the mixing of C stdio and C++ iostreams. I would pick one or the other, not both. Similarly, why use CStrings rather than C++ string objects? It isn't particularly relevant, but it gives the impression that the original coder (you, presumably) was more comfortable with C than C++.

Also, the usual caveats about using globals apply.

Finally, I think there are issues with the entire design of this, starting with why you aren't using a dedicated logging library in the first place. I assume that this is a class assignment, however, meaning that this option is closed to you.

Getting back to the problem at hand, lets look at the first place the segfault is occurring:

static bool write_to_outputfile(char* outputfile,char* content)
{
    bool write = false;
    for(const struct Fileoutput fo : vect_fileoutputs)
    {
        if(strcmp(fo.filetag.c_str(),outputfile) == 0)
        {
            printf("Writing [%s] to [%s]\n",content,outputfile);
            std::fstream* fs_write;
            fs_write = fo.filepointer;
            *fo.filepointer << content; 
            write = true;
            break;
        }
    }

    return write;
}

Here, the problem is that you are attempting to dereference a struct as a pointer. the correct form should be

            fo.*filepointer << content; 

With the indirection operator on the fstream pointer (EDIT: I originally dropped the indirection pointer outright, then noticed that it was still needed on the fstream pointer). I would assume that you've tried that, but sometimes it is the most obvious errors which are hardest to spot - I once spent two weeks chasing …

rproffitt commented: Thanks for this. It does seem to be a curious mix of c and c++. +0
sankar2000 commented: good explination, i want something simple that is why i dont use a log library, and indeed, is a mixing of c and c++, i should rewrite +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

We would need to see the code in order to determine anything about it. Please post your code (in the message directly, using the Code Block '</>' button), or at least post a link to your public repository, if you have one (which is highly recommended, even if it a small personal project). Please do not use pastebin or anything similar, nor should you post a screenshot - we would need to see all of the code, in an editable form.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Not to be overly pedantic, but: .NET Framework is the library and runtime support system used by a number of different Microsoft languages. Visual Basic.NET is one language, C# is another, F# is yet another. The same .NET libraries work for all of them.

There may not be examples of how to use NAudio in VB.NET in the documentation, but it should be possible to do so with minimal effort. It is simply a matter of figuring out how to use the library classes and functions from VB.NET.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would definitely try putting the "Days" constant string into a Label next to the ComboBox in question. As it is, you'd need to parse the string into the part with the numerical value, and the part with the "Days" substring, and you would need to do it any time you want the numeric value. It can be done, but it isn't really worth the effort, and in any case the Label would probably be clearer for the user.

Not to be too much of a nuisance about it, but it might help if we knew more about the program as a whole, in case there might be a better solution which isn't obvious just from this one small piece of the puzzle.