Humor, you say? Okay, I'll keep looking then... :)
Husoski 60 Newbie Poster
Yes, you can do that. The normal way to do that is to create a source file with the variable definitions that you then import into other source files that want to use them. A simple example:
# This is "my_app_globals.py"
MY_APP_NAME = "My Application"
MY_APP_VERSION = "1.02"
MY_APP_NVERSION = (1, 2)
Then you can ues that file in another Python source file with something like:
# This is "main.py"
import my_app_globals
print("App Name:", my_app_globals.MY_APP_NAME)
print("Version: ", my_app_globals.MY_APP_VERSION)
The longer story is that import
reads and compiles all of a single Python source file and puts of of the definitions into a module
with a name that is (by default) the source file name without the .py suffix. (The compilation part will be skipped if an up-to-date precompiled file is found, but that's a run-time optimization. The principle is the same.) Any top-level code (not in a class or function definition) will be run once at import time to "initialize the module". All global names in that source file are stored in the module, available to other modules import it.
Those names are pretty long. You can shorten them in a couple of ways. One way that's pretty safe is to simply rename the module on import:
import my_app_globals as gbls
print("App Name:", gbls.MY_APP_NAME)
That makes "gbls" a name your program can use to access the "my_app_globals" module. The original module is only imported once per execution of your program. Another way is to use another form of the import …
Husoski 60 Newbie Poster
Dart has no standard array types, but it does have a built-in list data type that is much like a one-dimensional array in other languages. The usual way to represent a matrix in a language that only has lists and/or 1-D arrays is as a list of lists. There's an example in the accepted answer to this StackOverflow question. .
Husoski 60 Newbie Poster
The usual way to avoid duplicate entries is to search for a matching entry before inserting. It will be helpful to have a find_by_id(char *id)
function that you can code and test separately before worrying about insertions. It should search the list for an entry with the given ID number and return a pointer to the first or only matching entry, or NULL if that ID wasn't found in the list. Once that's coded and tested, you can use it in your insert()
function with something like:
if (find_by_id(data) != NULL)
{
// report attempt to insert a duplicate ID
}
You can reuse that function in any other code that might need to search for a student with a given ID number. I don't know what your application needs to do when an attempt to add a duplicate ID is detected. There's no return value from insert()
that you can use to inform the caller that the duplicate entry couldn't be added.
By the way, it looks like you have missing {} braces in the last if statement in your display
function. That's kind of an illustration that it's usually not worth trying to code a function before you're ready to write code to test it. By the time you finish testing the insert logic (needed to get data into the list), you may have forgotten some details of why you wrote the display()
code the way you did.
By the way, using '\t'
tab characters for …
Husoski 60 Newbie Poster
Your comments on lines 41-43 say why you get an error on line 46. The data
variable is a list, so data['hours']
is invalid. The error message says what you should already know...lists are indexed with numbers, not strings.
I don't have an authorization key to use for that API, so I can't look at any real data. If you wanted to sort a list of dictionaries, based on the 'hours' field in each dictionary, you don't need an index at all. Use sorted(data, key=lambda i:i['hours'])
without the index.
Looking closer, it looks like you are using the variable data
for two different purposes. You read the previously cached data into it on line 16, and then replace that with the API response data. That discards the cache file data before you even get a chance to use it. Think about using two different variable names here, like cached_data
and response_data
or something. Even if you meant to append the response data to the cached file data, it's probably a good idea to first read the response into a separate variable. That gives you an opportunity to check the response data for validity, non-duplication, etc. before adding it to the cached data.
If you know that the the response is going to be a list of dictionaries that's compatible with the list of dictionaries from the cache file, then you can simply append the response data with: data += response.json()
. You could try that as a quick-fix, but I still …
Xioto commented: Thank You! It works now, I am embarrassed that I didn't notice that sooner... +0
Husoski 60 Newbie Poster
Neither C nor C++ defines specifics sizes for those data types. There are certain minimum requirements. A char is required to have at least 8 bits. Short integers require at least 16 bits, normal and long ints must be at least 32 bits and a long long integer must be at least 64 bits. There are no maximum sizes for any of those.
The sizeof
operator returns the size of an object in "bytes", but the language specifications don't specify how big a byte is. The C11 standard, for example, describes "byte" as, "A byte is composed of a contiguous sequence of bits, the number of which is implementation defined." It's also described as "an addressable unit of data storage", meaning that each byte has it's own unique memory address. Whatever the "byte" size is, the sizeof operator returns the number of those units needed to store an object or an instance of a given type. And since a char is defined to be one "byte", that means that sizeof (char)
is guaranteed to be 1.
It is required that the different integral type sizes be ordered. 1 == sizeof (char) <= sizeof (short) <= sizeof (int) <= sizeof (long) <= sizeof (long long)
is guaranteed, and the sizes of the unsigned types are the same as the corrsponding signed types. But some implementations today have 64 bit long ints even though most 32 and 64-bit implemementations have used 32 bits for both int an long for decades. Also, …
rproffitt commented: You should get credit for doing this homework for them. +15
Husoski 60 Newbie Poster
Your sample code doesn't say what "add" is, but I'll guess it's the full sized ArrayList with 150 elements.
Do you really need to create 30 more ArrayLists to hold them in groups of 5? You can get a view of 5 consecutive elements from that list, starting at any given index with:
List<Double> five = add.subList(i, Math.min(i+5, add.size());
The syntax is similar to .substring() on a String object. Calling .sublist(i,j) returns all element from index i (inclusive) to index j (exclusive). If you need that to specifically be an ArrayList, you can pass that to ArrayList's Constructor:
ArrayList<Double> five = new ArrayList<>(add.subList(i, Math.min(i+5, add.size())));
The business with Math.min() simply insures that j is never more than the size of the original list. You can leave that out and just write .sublist(i,i+5) if both i and the length of the large list are always multiples of 5.
Husoski 60 Newbie Poster
First things first, if you want to get that working on a modern Python installation, change all occurrences of "Tkinter" to "tkinter". All standard module and package names are lowercase in Python 3. I don't see any other 2-vs-3 problems; and after that change the code runs in my Python 3.8 installation with no obvious errors.
I don't know if this particular widget is going to be exactly what you need, but I can try to explain the __init__
stuff. It's really simple OOP inheritance. The Accordion class inherits from Frame. That makes any Accordion object a specialized version of a Frame object. When an Accordion object is created, the __init__
function in Accordion is called to intialize it. That method needs to ensure that any base classes get initialized with whatever information they need. That's what base class (aka "superclass") constructor calls do.
The Frame.__init__(self, parent)
call you're looking at is old-style Python syntax for initializing a base class (aka "superclass"). It's more common to write that as super().__init__(parent)
in the usual case there's only one base class. Both ways work in this code and the idea is to tell the Frame object what its parent object is. The super
function actually takes two arguments. Both are using default values in that second call, but you may also see that second form written with explicit values: super(self, Frame).__init__(parent)
. All three versions do the same thing: Call the superclass's __init__
function to see that it gets the values it …
Liam_12 commented: Thank you for this response. Am still working to understand it. Trying to figure out how to capture the data in each part of the accordion, as it is. +0
Husoski 60 Newbie Poster
In a weird way, C++ makes this harder than plain C, provided that you know the maximum line length in advance. (The strtok() function from <string.h> will help split up a C string into comma-separated tokens.) That idea probably won't get a good grade on your C++ assignment, even though it's technically legal & standard to include <cstring> and use the C-style string library.
What I'd suggest is to use std::getline() (the function from <string>, not the getline method of std::cin) to read whole lines into C++ string object, then use the string's .find() member function. In a string named "line", line.find(',') will return the index of the first comma and line.find(',', cpos+1) will find the index of the next comma after some previous comma position "cpos".
Use the .substr() member function to extract the individual values. There are a bunch of options, but the most common use you'll have is to use line.substr(start, stop-start) to extract characters starting at line[start] up to but not including line[stop]. In your program, (start) will be the index of the first character of a comma-separated value, and (stop) will be the index of the comma that end the value.
See docs at: http://www.cplusplus.com/reference/string/string/
or more authoritative (but a bit less readable) docs at: https://en.cppreference.com/w/cpp/string/basic_string
Husoski 60 Newbie Poster
Try changing line 1 to:
#include <graphics.h>
In C, it's conventional to use ".h" as a suffix for a C header file; and that is the name of the Borland Graphics Interface header that defines functions named initgraph()
, circle()
and closegraph()
.
It's not a Standard C header, though, so unless you have an old copy of Turbo C or compatible, or have installed a compatible library on a modern compiler, that won't help. If you're in a class that gave you a setup procedure to install C on your computer for classwork, then fixing the include directective should get you started.
You may need other headers at some point. I include both <stdio.h> and <stdlib.h> in practically every C program I write. Also, programs that use <graphics.h> will also often use low-level console functions defined in <conio.h>, which is another common nonstandard header from last century. If you see something telling you to use getch() or kbhit(), then you probably need <conio.h> included.
rproffitt commented: The OP commented " i use Code Blocks IDE Windows 10 Pro" but they appear to have removed this information. +15
Husoski 60 Newbie Poster
You need to include header files to define the standard library features you plan to use. These should appear before anything else It looks like adding:
#include <iostream>
...is all you need for this program so far. If you add code that uses stream manipulators that take arguments, like setw() or setprecision(), then you'll also need to include <iomanip>
.
I hope your class is going to teach you about constructors soon, since those are the normal (and usually best) way to initialize instances of a class or struct type.
NotAceGG commented: Thx Your Answer Helpful me very much +0
Husoski 60 Newbie Poster
The reason you get 0 for an answer is in the constant expression 1/4. That's division of two int values and the fractional quotient is truncated to the next integer closer to zero. In this case, that is zero. And 0 times what follows is zero.
Another problem is attempting to use ^ as a "raised to the power" operator. There is no such operator in C++. Many will tell you to use pow() from the <cmath> library, but that's not really very sensible for small postive integer powers, and overkill for computing a square. The pow operator computes pow(x,y) = exp(y*log(x), doing two trancendental function calculations and a multiply, when all that's needed to square a number is a single multiplication.
One minor bit: The float type is often a poor choice. For individual variables, you don't save much memory and on most processors with hardware floating point support you don't save much time. Using float can be a great choice for large arrays, but I suggest you develop the habit of using double as your default floating point type and use float only when you have a specific reason to.
Using those ideas, plus a couple of more, gets to something like:
#include <iostream>
using namespace std;
const double PI = 3.14; // should be more digits, but maybe the assignment said to use 3.14
int main()
{
double diameter,height,volume;
cout << "Enter Diameter of Cylinder : ";
cin >> diameter;
cout << "Enter Height of Cylinder :"; …
Husoski 60 Newbie Poster
The first problem is that you aren't storing the password anywhere. You can't just compare characters as they come in. The user is allowed to backspace and correct mistakes. You don't compare the password to anything until the user presses enter (13). So you'll need an area large enough to hold the longest password you allow, and a length field. I haven't done 8086 assembly in years, but something like:
MAX_LENGTH equ 16
password_length dw 0
password_data db MAX_LENGTH dup (?)
db ? ; guard byte, leave room for terminating 0x00
In the input routine, I'd separate the control characters (01Fh and below, plus the 07Fh DEL control) from printable ASCII (020h..07Eh).
For each printable ASCII character, test to see that the password_length is less than the maximum. If so, store the byte, and increase the length:
mov bx,password_length
cmp bx,MAX_LENGTH
jae ERROR ; too big, go beep or something
mov password_data[bx],al ; store pw char
inc bx ; and increment length
mov password_length,bx
mov al,'*' ; and finally, echo the *
_PutCh al
Something like that. The backspace code will test the length for being greater than 0, jumping to ERROR if not, and simply decrement password_length
by 1 before displaying the 08h, ' ', 08h sequence.
When the Enter key (0Dh) is detected, compare the length of the entered password to the length of the actual password (unless you're using a C-style string comparison where each string has a terminating 00h byte) and then compare the first …
Husoski 60 Newbie Poster
The one that I stumble over, even decades after getting it "corrected", is URL. Learning networking concepts from books rather than a classroom, I still tend to read that as one syllable ("earl") instead of the accepted pronunciation as letters spelled out ("you are ell") . Occasonally I still have that lapse in converstion. (...along with "earn" and "Yuri" instead of "you are in" and "you are I".)
rproffitt commented: Where is Earl? +0
Husoski 60 Newbie Poster
I'm new around here, so I don't know how well your question fits the "show some effort" rule on assignments.
I don't see any harm in helping you with the syntax (regulars...help me out if this is wrong). You'll need a name for the derived Interface (or "ADT") and that will look something like:
public interface IndexiblePositionalList<E> extends PositionalList<E> {
default int indexOf(E item) {
int index;
// insert code to search the list, using
// only methods from PositionalList<E> and Position<E>.
return index; // and return the resulting index
}
}
The language in the assignment seems to be a little bit off. I don't see a way to express the answer in terms of PositionalList<E>
alone. You need to use some method from Position<E>
to compare the value you're searching for to the value stored at the list position.
When you want to test your code, you can use any methods you like to get test data into a LinkedPositionalList object, and then:
LinkedPositionalList<String> theList = new LinkedPositionalList<>();
// add strings to theList
IndexiblePositionalList<String> indexTest = theList;
// add code to test indexTest.indexOf() calls
rproffitt commented: Good formatting. +1 +15
Husoski 60 Newbie Poster
Sappie asked a question in a comment to my earlier answer and I can't figure out how to respond directly to a comment so here's my answer.
The question asks the difference betwee int main()
and int main(void)
.
The short answer is that both declare a function returning an int, but int main(void)
explicity says that the function takes no arguments, while int main()
says noththing at all about arguments.
tl;dr: This odd usage is due to the fact that in Dennis Ritchie's original C language there was no way to declare parameter types. Every function definition looked like some_type function_name();
, and functions returning an int usually weren't declared at all. The compiler would assume that any function not previously defined or declared, was a function returning an int; and if no such function were defined later in the source code, then it was defined as an external int-returning function, to be found by the linker.
By the time the first C standard (ANSI C, 1989) was being developed, the original syntax had been in wide use for about a decade, so the old syntax couldn't be made illegal. Too many programs were using it. The void
keyword was added to provide an explicit way to say "nothing is expected" as the return type or argument list of a function. (The void
keyword was also used as a placeholder for an unknown type in pointer declarations.)
That same standard (C89) also made the int
the standard return type from main
, …
rproffitt commented: Good explanation. Let hope they do this from now on. +15
Husoski 60 Newbie Poster
Using "void main()" for the main function has been deprecated for, oh, over 30 years. Standard C requires a return type of int from the main function. People keep using it because compilers let it slide, and vice versa.
You seem to have left out #include <stdio.h>
at the top. You'll also need #include <string.h>
to fix the logic problem.
The logic problems I see are:
-
You are using a pointer for opinions when an array is needed. Declare opinions as "char opinions[256];" instead. That will get you farther along.
-
The = operator is assignment, not comparison for equality. You can compare numbers with the == operator, but not strings. Use strcmp() from for comparing strings.
strcmp(string1, string2)
returns 0 if the two strings are the same, a positive number if the first string is greater than the second, or a negative number if the first string is less than the second. -
A
scanf()
for a string should specify a maximim length in the format (one less than the array size) and you do not use & with an array argument. Make thatscanf("%255s", opinions);
. -
If you fix the main line to read "int main(void)" as it should, then you'll need a "return 0;" line at the end of main.
Here's how I updated your source:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char opinions[256];
printf("What do you think of me?");
scanf("%255s", opinions);
if (0 == strcmp(opinions, …
Sappie commented: Could you please explain to me how "int main()" and "int main(void)" differ? +0