Let's assume that the node's actual load is sensitive information that cannot be exposed outside the node itself, but the average is not sensitive.
With your approach, some external code or eavesdropper could always determine the value of the node's load exactly just by multiplying by 2. However there are ways to compute the average without disclosing the exact value of a single node. Basically, you want to construct two mathematical functions, f & g, such that
g(f(load1), f(load2)) = (load1 + load2)/2
AND
f^-1(x), the function inverse, is difficult or impossible to compute.
I'm about to be late for a meeting, so I don't have time to explain this step by step, but basically you can keep a synchronized random number generator inside the node class, and use it to introduce a random element into f() that will not be known by the outside.
If you can't figure out a mathematical function to use, then make two different f() functions, and have one be e1 = (load1 + random) and the other be e2 = (load2 - random), then your average is (e1 + e2)/2, but the outside world can't figure out load1 or load2 without knowing the value of 'random'.
It sounds to me like the instructor wants you to access the load indirectly, to demonstrate encapsulation.
What course/course level is this in if you don't mind me asking?
It's a Python/Perl class. (A "3000" level course, if that means anything -- generally taken by Sophomores or Juniors.) It's been a pretty easy class, since I think the purpose has mainly been to introduce CS students here to dynamically typed scripting languages, since most of the other courses focus on C++ or Java.
This question surprised me a bit, because it's been the only one the entire semester that wasn't trivially easy. At first it did just seem like encapsulation to me (and to show a bit of how Python uses name mangling rather than actually allowing private class members, given the __load name). But the wording really makes me think I should be leaning more towards tokkun's suggestion.
private void Main()
{
var records = ReadAllRecords();
foreach (var record in records)
{
SaveRecord(record);
}
}
private IEnumerable<string> ReadAllRecords()
{
return Infinity<int>().Select(x => ReadNextRecord()).TakeWhile(x => x != null);
}
private IEnumerable<T> Infinity<T>()
{
return new[] { default(T) }.Cycle();
}
public static class Extensions
{
public static IEnumerable<T> Cycle<T>(this IEnumerable<T> source)
{
while (true)
foreach (var i in source)
yield return i;
}
}
public static void main(String[] args)
{
Code
}
public static void main(String[] args) {
Code
}
I've seen a lot of people write code like yours with the curly braces under the declaration instead of immediately after.
Code:public static void main(String[] args) { Code }
Instead of
Code:public static void main(String[] args) { Code }
What's the reason for that?
I've seen a lot of people write code like yours with the curly braces under the declaration instead of immediately after.
Code:public static void main(String[] args) { Code }
Instead of
Code:public static void main(String[] args) { Code }
What's the reason for that?
Am I going to be tarred and feathered if I admit to preferring the in-line bracket?
Spaces, in-line brackets and parentheses  directly following the statement. That's how code is supposed to look!Nah. I was (somewhat) joking. Just make sure to keep it consistent if you're working with other people.
#!/usr/bin/python
from PySide.QtCore import *
from PySide.QtGui import *
import sys
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.setWindowTitle("Test Widget Mapper")
self.model = QStandardItemModel(self)
self.rootitem = self.model.invisibleRootItem()
self.treeview = QTreeView()
self.treeview.setModel(self.model)
self.mapper = QDataWidgetMapper(self)
self.mapper.setSubmitPolicy(QDataWidgetMapper.AutoSubmit)
self.mapper.setModel(self.model)
self.mapper.setOrientation(Qt.Vertical)
self.mapper.setRootIndex(self.rootitem.index())
# create widgets
self.line_edit1 = QLineEdit()
self.line_edit2 = QLineEdit()
self.line_editsub = QLineEdit()
# create and set layout
layoutw = QHBoxLayout()
layout = QVBoxLayout()
layout.addWidget(QLabel("Item 1:"))
layout.addWidget(self.line_edit1)
layout.addWidget(QLabel("Subitem 1:"))
layout.addWidget(self.line_editsub)
layout.addWidget(QLabel("Item 2:"))
layout.addWidget(self.line_edit2)
layoutw.addWidget(self.treeview)
layoutw.addLayout(layout)
self.setLayout(layoutw)
# create and map items
self.item1 = QStandardItem("Item 1")
self.item2 = QStandardItem("Item 2")
self.subitem1 = QStandardItem("Sub item 1")
self.rootitem.appendRow(self.item1)
self.item1.appendRow(self.subitem1)
self.rootitem.appendRow(self.item2)
self.mapper.addMapping(self.line_edit1, 0)
self.mapper.addMapping(self.line_edit2, 1)
self.mapper.toFirst()
self.treeview.expandAll()
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
You should try to be efficient in your use of vertical space. It allows more actual code to fit on the screen at once, and this can be beneficial to someone trying to read and understand your code.
Putting the opening brace in-line reduces vertical waste at little cost to readability.
Well, that gets into a different discussion, because I want less code on screen, not more. Less code to understand at any given time. I don't want vertical length of code to be a consideration, not if I can help it. Small functions, small classes.
I was taught that the reason for using new line braces was their use as 'bookends' to more easily recognize scope, so yeah, I agree with the "where" there iapetus.
You are also right that the right formatting to use is whatever convention is expected/required either by the project you are on, or the employer you are with, personal preference in those domains doesn't really come into it![]()
Well, that gets into a different discussion, because I want less code on screen, not more. Less code to understand at any given time. I don't want vertical length of code to be a consideration, not if I can help it. Small functions, small classes.
So shrink your editor window. If you shrink it enough you can even get to have to scroll to read a single line. Ultimate efficiency!
Having an issue comparing strings from fgets. I read that it includes the newline character so I've tried putting that into my comparison but it doesn't seem to work. I'm doing something along the lines of...
if(fgets(buff, size, stdin) = NULL)
exit(1);
else if (buff == "quit\n")
exit(1);
else {
do stuff
}
How would I go about this?
hah thanks. I'm too used to c++.You can't compare strings like that in C, gotta use strcmp(str1, str2). I believe it returns 0 on a match.
On second thought, I'll wait until I can take a closer look over your code before responding.Slavik/any other Qt users: is it possible to use QDataWidgetMapper() to map widgets to a tree-based model? Since widgets are mapped by integer (column or row, rather than two-dimensional index) based "sections", and the QStandardItemModel resets the row value for child items, without any additional tweaks there will be ruinous overlap between the sections of child and parent widgets. The only tweak I can think of is subclassing QStandardItemModel to entirely change the implementation of index values. Beyond that, I can only think to do updates to the model from widgets manually, but it would be nice if it were possible to utilize the mapper. Below is a full dialog window demonstrating my problem. (You can run if you have either PySide or PyQt installed; if the latter, I think you'll only need to replace PySide with PyQt in the from statements.)
Code:#!/usr/bin/python from PySide.QtCore import * from PySide.QtGui import * import sys class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.setWindowTitle("Test Widget Mapper") self.model = QStandardItemModel(self) self.rootitem = self.model.invisibleRootItem() self.treeview = QTreeView() self.treeview.setModel(self.model) self.mapper = QDataWidgetMapper(self) self.mapper.setSubmitPolicy(QDataWidgetMapper.AutoSubmit) self.mapper.setModel(self.model) self.mapper.setOrientation(Qt.Vertical) self.mapper.setRootIndex(self.rootitem.index()) # create widgets self.line_edit1 = QLineEdit() self.line_edit2 = QLineEdit() self.line_editsub = QLineEdit() # create and set layout layoutw = QHBoxLayout() layout = QVBoxLayout() layout.addWidget(QLabel("Item 1:")) layout.addWidget(self.line_edit1) layout.addWidget(QLabel("Subitem 1:")) layout.addWidget(self.line_editsub) layout.addWidget(QLabel("Item 2:")) layout.addWidget(self.line_edit2) layoutw.addWidget(self.treeview) layoutw.addLayout(layout) self.setLayout(layoutw) # create and map items self.item1 = QStandardItem("Item 1") self.item2 = QStandardItem("Item 2") self.subitem1 = QStandardItem("Sub item 1") self.rootitem.appendRow(self.item1) self.item1.appendRow(self.subitem1) self.rootitem.appendRow(self.item2) self.mapper.addMapping(self.line_edit1, 0) self.mapper.addMapping(self.line_edit2, 1) self.mapper.toFirst() self.treeview.expandAll() app = QApplication(sys.argv) form = Form() form.show() app.exec_()
You don't spam ~100 lines, you paste into Pastebin and post the link.I would appreciate some guidance without outright solving this problem for me, and if you would like me to post code I can. (I avoided it at first since I didn't want to spam ~100 lines.)
You don't spam ~100 lines, you paste into Pastebin and post the link.
Anyone familiar with building a shell(unix)? I'm making a basic one and right now and a little stuck at figuring out how to implement redirection like >, < and whatnot. Right now my command gets parsed into a linked list and I'll(haven't implemented yet, still thinking about it) search for redirection characters like the ones above and pass the values of the list before said char into an array and run exec. This should "work" but I'm having trouble understanding how to redirect from there or if this is how I should go about running a command in the first place.
I'm also having trouble figuring out how to put a process into the background. Any tips/links for either/both of these topics would be great.
I was able to solve the problem by creating a static String variable to store the information.
Then I modified the variable from the outside class by pulling the information from textfields and add it to the string.
I'm sure it's not the most efficient way to go about this problem, but here's the modified code
Often with floats it makes a lot more sense to check a difference rather than equality. Have some very small epsilon value which you consider to be "close enough to the same", then subtract your floats and see if the difference is within the epsilon from zero.Working on some basic 2d collision detection for an assignment and I guess I was a little lazy with floats but I was running into this weird bug when adjusting the x,y coordinates. I wasn't being precise enough so when I was checking the bounding box it would bug out because the number was something like X.00000001 for some reason and I was checking for X.00. *sigh* ThankfullyI didn't spend too much time on that..
That's not inefficient. That's horribly, horribly, horribly, horribly wrong.
Every time you *create* a Dog using this it's setting that value. After that the dogs are useless. This really isn't what you're supposed to be doing. Try rethinking things so that you actually use a Dog instance to provide the data to the UI. Stay away from static variables for this, and stay away from directly modifying fields of the UI classes from your data classes.
If I get time later I'll take a look at the history of this and see if I can point you in the right direction.
Working on some basic 2d collision detection for an assignment and I guess I was a little lazy with floats but I was running into this weird bug when adjusting the x,y coordinates. I wasn't being precise enough so when I was checking the bounding box it would bug out because the number was something like X.00000001 for some reason and I was checking for X.00. *sigh* ThankfullyI didn't spend too much time on that..
What you're doing now with the Dog class is pretty useless since it really just changes the frame's display value. You're not really doing anything with the dog, in other words.Well I look forward to learning what the correct way to do this is if you have the time.
The assignment was asking for the textarea to be changed by utilizing the Dog class, but I think I misunderstood what he meant. My next assignment will be using the same concept, except adding data into a 2D array before displaying it, so I'd like to learn the correct way for object communications.
Osiris, I'm going to look into the Observer pattern you mentioned. Thank you.
class Dog
{
String name;
String breed;
String age; // Maybe use an int instead
Dog(String name, String breed, String age)
{
this.name = name;
// etc
}
}
// later you can use it to create a Dog
myDog = new Dog("Doggy", "Doggy breed", "1");
System.out.println(myDog.name) // "Doggy"
System.out.println(myDog.breed) // "Doggy breed"
System.out.println(myDog.age) // 1
public void displayDog(Dog dog)
{
this.display = " Name: " + dog.name; //eg
}
Often with floats it makes a lot more sense to check a difference rather than equality. Have some very small epsilon value which you consider to be "close enough to the same", then subtract your floats and see if the difference is within the epsilon from zero.
Yep, floating point equality is hard. Here is a good article on that subject. There's a whole series on floating point numbers on that blog as well.
I'm currently building a project in C where the objective is to allocate memory for an array of nodes that is created from words read from a text file. Nodes contain text (a word read from the text file) and a pointer to another node. In a sense, each element in the array acts as its own linked list. The program is supposed to add new words with no anagrams to the next spot in the array (ex: list[0], list[1], etc.), but if that word is an anagram with any existing elements in the array, then it should be added to its counterparts linked list via "next". (ex: an anagram for list[0] would be list[0]->next)
However, the program keeps generating segmentation faults when building the list and tracking it down has been a giant pain. The current program for building is:
snipity snip
Code:list = (Node **) calloc(*arySize, sizeof(Node *)); //allocates memory for list while(fgets(text, MAX_WORD_SIZE, fp) != NULL){ //reads word from text file text[strlen(text)-1] = '\0'; int i; for(i = 0; i < *arySize; i++){ if(areAnagrams(list[i]->text,text)){
I don't think you're allocating space for the individual lists inside the array. You only allocate the space for the array but each index outside of 0 is not allocated.
You are filling list with a bunch of null pointers with your calloc statement.
Then you try to dereference list, which causes a segmentation fault.
Probably your for loop should terminate when list == NULL.
for (int i = 0; i < heroes.size(); i++) {
h = heroes.get(i);
String filename = "C:/Users/Matt/Documents/GitHub/Dota2DraftingGameDesktop/src/Assets/" + h.getImage();
[B]BufferedImage buttonIcon = ImageIO.read(new File(filename));[/B]
JButton button = new JButton(new ImageIcon(buttonIcon));
//Other stuff
} //End of for loop
for (int i = 0; i < heroes.size(); i++) {
h = heroes.get(i);
String filename = "C:/Users/Matt/Documents/GitHub/Dota2DraftingGameDesktop/src/Assets/axe.png";
BufferedImage buttonIcon = ImageIO.read(new File(filename));
JButton button = new JButton(new ImageIcon(buttonIcon));
//Other stuff
} //End of for loop