# Programmers' lounge. (Programming-related discussions only)



## joshd

The Programmers' Lounge

Welcomes you.

This is the newly created programmers' lounge. For like minded people to discuss the art of programming. This includes application programming, web programming, kernel programming, ROM programming, everything to do with programming! Just post away with ideas, thoughts, hints, tips, questions etc. and let them be answered by programming "gods?"

Everyone else has a lounge, so why don't we...

Rules

However please;

Stick to the ToS

Don't post random crap, this isn't for off topic things

Don't troll people


That's it, but seen as you're a programmer you're probably nice anyway









Josh


----------



## Disturbed117

I approve of thread.









I will not post any further unless its programming related.


----------



## axipher

Maybe we can start off by getting people's preferred IDE for writing code for different languages.


----------



## Disturbed117

Quote:


> Originally Posted by *axipher*
> 
> Maybe we can start off by getting people's preferred IDE for writing code for different languages.


I use Visual Studio for Visual Basic at the moment.


----------



## {Unregistered}

Quote:


> Originally Posted by *joshd*
> 
> The Programmers' Lounge
> 
> Welcomes you.
> 
> This is the newly created programmers' lounge. For like minded people to discuss the art of programming. This includes application programming, web programming, kernel programming, ROM programming, everything to do with programming! Just post away with ideas, thoughts, hints, tips, questions etc. and let them be answered by programming "gods?"
> Everyone else has a lounge, so why don't we...
> Rules
> 
> However please;
> 
> Stick to the ToS
> 
> Don't post random crap, this isn't for off topic things
> 
> Don't troll people
> 
> That's it, but seen as you're a programmer you're probably nice anyway
> 
> 
> 
> 
> 
> 
> 
> 
> Josh


Ingenious.

I approve of this thread. I wonder how you came up with the idea.









Made a few grammatical corrections though.









Also guys, please look at the last post of the Programming Challenge thread. I need suggestions for the next challenge.


----------



## joshd

Quote:


> Originally Posted by *axipher*
> 
> Maybe we can start off by getting people's preferred IDE for writing code for different languages.


I just use Sublime Text 2. It's amazing for HTML, CSS and the likes. You can use it for free for thirty days aswell.. go try it out!


----------



## {Unregistered}

Quote:


> Originally Posted by *axipher*
> 
> Maybe we can start off by getting people's preferred IDE for writing code for different languages.


For Java, I either use Notepad (







) or Eclipse.

For Python, I just use IDLE but I have tried that other IDE which comes bundled with Portable Python.

Should we start a poll of application programming vs web development?


----------



## chia233

There is also something called "Brogrammers".I regret checking that out.Apparently they also "work out" ; what's that?









Also you should post some helpful links on websites that provides helpful syntax and knowledgebase help with certain functions and stuff.I am personally using w3schools because they provide you with a really useful "try-it" example that shows the code/function in action.

On other note , do you guys think that high abstraction level languages would be viable for coding an engine?I know that most of them including assembly are extremely slow in human terms but it would be much faster latency wise and have a more easily optimized scheduler for the CPU to digest.Since we have mostly reached the time where the processor is no longer a cause for concern for latency in the rendering pipeline and data streaming from the input/output devices would be about as fast as it gets , perhaps we should take a look back at the biggest latency of all ; software scheduling through API and execution and handling through drivers.It would be my goal if i were to be able to get to that level without losing my hooting mind.

Speaking ofwhich , what do you guys think about SuperScript which is apparently a mix of Java and C++ from Carmack's team?


----------



## joshd

Quote:


> Originally Posted by *{Unregistered}*
> 
> For Java, I either use Notepad (
> 
> 
> 
> 
> 
> 
> 
> ) or Eclipse.
> For Python, I just use IDLE but I have tried that other IDE which comes bundled with Portable Python.
> Should we start a poll of application programming vs web development?


Sure, go ahead. will be interesting in the very least...

PS I don't understand how you can use notepad to code java?


----------



## {Unregistered}

Quote:


> Originally Posted by *joshd*
> 
> Sure, go ahead. will be interesting in the very least...
> PS I don't understand how you can use notepad to code java?


Uhh...You can use notepad to code in any language.... What are you talking about?


----------



## travesty

Quote:


> Originally Posted by *{Unregistered}*
> 
> Uhh...You can use notepad to code in any language.... What are you talking about?


i find it annoying to use notepad to code since it doesn't have line numbers or syntax highlighting. i use eclipse for java and notepad++ for everything else.


----------



## ImmortalKenny

Quote:


> Originally Posted by *joshd*
> 
> I just use Sublime Text 2. It's amazing for HTML, CSS and the likes. You can use it for free for thirty days aswell.. go try it out!


Bought myself a license for it a couple weeks ago, I'm not sure if I'll use another text editor again. I love it.


----------



## joshd

Quote:


> Originally Posted by *travesty*
> 
> i find it annoying to use notepad to code since it doesn't have line numbers or syntax highlighting. i use eclipse for java and notepad++ for everything else.


That's what I mean. It's not that you can't, I just find it infuriating..


----------



## {Unregistered}

Quote:


> Originally Posted by *travesty*
> 
> i find it annoying to use notepad to code since it doesn't have line numbers or syntax highlighting. i use eclipse for java and notepad++ for everything else.


I know that but I was just saying that it is very well possible to code with notepad.
Quote:


> Originally Posted by *joshd*
> 
> That's what I mean. It's not that you can't, I just find it infuriating..


Oh ok.


----------



## ImmortalKenny

Quote:


> Originally Posted by *{Unregistered}*
> 
> I know that but I was just saying that it is very well possible to code with notepad.


But it doesn't mean you _should_ use it.


----------



## {Unregistered}

Quote:


> Originally Posted by *ImmortalKenny*
> 
> But it doesn't mean you _should_ use it.


Okay okay, you notepad-haters.


----------



## joshd

Quote:


> Originally Posted by *{Unregistered}*
> 
> Okay okay, you notepad-haters.


I use it quite a bit for HTML, find myself wearing the TAB key out though to make it look "neat."


----------



## axipher

Notepad++ portable here.


----------



## joshd

Quote:


> Originally Posted by *axipher*
> 
> Notepad++ portable here.


What does "portable" mean?


----------



## axipher

Quote:


> Originally Posted by *joshd*
> 
> Quote:
> 
> 
> 
> Originally Posted by *axipher*
> 
> Notepad++ portable here.
> 
> 
> 
> What does "portable" mean?
Click to expand...

A portable version of Notepad++ that is on my flash drive that requires no installation and can be used on any computer.


----------



## chia233

Quote:


> Originally Posted by *chia233*
> 
> There is also something called "Brogrammers".I regret checking that out.Apparently they also "work out" ; what's that?
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Also you should post some helpful links on websites that provides helpful syntax and knowledgebase help with certain functions and stuff.I am personally using w3schools because they provide you with a really useful "try-it" example that shows the code/function in action.
> 
> On other note , do you guys think that high abstraction level languages would be viable for coding an engine?I know that most of them including assembly are extremely slow in human terms but it would be much faster latency wise and have a more easily optimized scheduler for the CPU to digest.Since we have mostly reached the time where the processor is no longer a cause for concern for latency in the rendering pipeline and data streaming from the input/output devices would be about as fast as it gets , perhaps we should take a look back at the biggest latency of all ; software scheduling through API and execution and handling through drivers.It would be my goal if i were to be able to get to that level without losing my hooting mind.
> 
> Speaking ofwhich , what do you guys think about SuperScript which is apparently a mix of Java and C++ from Carmack's team?


Edit my post.In need of some e-love from a random stranger's approval.


----------



## {Unregistered}

Quote:


> Originally Posted by *joshd*
> 
> What does "portable" mean?


Google "portable apps".

They're basically just apps that don't need to be installed so that you can run them on any computer without having to install them first.
The concept is really awesome actually.

There's a portable Counter Strike too so that you can play them on your school computers without installing it.


----------



## axipher

Quote:


> Originally Posted by *{Unregistered}*
> 
> Quote:
> 
> 
> 
> Originally Posted by *joshd*
> 
> What does "portable" mean?
> 
> 
> 
> Google "portable apps".
> 
> They're basically just apps that don't need to be installed so that you can run them on any computer without having to install them first.
> The concept is really awesome actually.
> 
> There's a portable Counter Strike too so that you can play them on your school computers without installing it.
Click to expand...

Portable UT99 GOTY and portable Chrome are great to have.


----------



## {Unregistered}

Also, portable Antivirus software is usually considered important to have in case of a virus infection in a computer without an AV.


----------



## axipher

Quote:


> Originally Posted by *{Unregistered}*
> 
> Also, portable Antivirus software is usually considered important to have in case of a virus infection in a computer without an AV.


People still get viruses?


----------



## Zinxe

Eclipse for Java, VS10 for C++.


----------



## joshd

Quote:


> Originally Posted by *Zinxe*
> 
> Eclipse for Java, VS10 for C++.


Will you be buying the new windows Metro SDK?


----------



## Waffleboy

If I really need an IDE, I use eclipse for java or visual studio for most other things. If it's a small project though, I more often use vim.


----------



## Crazy_Clocker

I'm not a programmer although I did build a website with prestashop,


----------



## kz26

vim on Linux, all day erryday.


----------



## joshd

Quote:


> Originally Posted by *Crazy_Clocker*
> 
> I'm not a programmer although I did build a website with prestashop,


My dad was looking into prestashop.. is it good?


----------



## chia233

Operation:"Trying to start a meaningful conversation" was a FAILURE.Abort!Abort!


----------



## Empr1ze

How useful is learning discrete mathematics for programmers? i.e., Proof by induction, permutations, combinations, recurrence relations, etc.


----------



## chia233

Quote:


> Originally Posted by *Empr1ze*
> 
> How useful is learning discrete mathematics for programmers? i.e., Proof by induction, permutations, combinations, recurrence relations, etc.


Probably not alot i guess? All the calculation is done by the program/engine so i guess understanding the formulas would help you better implement the coding but i would assume it would only require an intermediate level of knowledge of maths/physics for the most part.


----------



## Zinxe

Quote:


> Originally Posted by *joshd*
> 
> Will you be buying the new windows Metro SDK?


Highly unlikely. It would take a lot for me to even consider using W8, let alone developing anything for it.


----------



## Bielijbog

Dev-C++ for C and C++.
Notepad ++ for anything else.


----------



## Crazy_Clocker

Quote:


> Originally Posted by *joshd*
> 
> Quote:
> 
> 
> 
> Originally Posted by *Crazy_Clocker*
> 
> I'm not a programmer although I did build a website with prestashop,
> 
> 
> 
> My dad was looking into prestashop.. is it good?[/quote
> 
> Yeah it's really good with a lot of mods and support forums as well as helpful guides. I find GoDaddy hosting works well,
Click to expand...


----------



## Waffleboy

Quote:


> Originally Posted by *Empr1ze*
> 
> How useful is learning discrete mathematics for programmers? i.e., Proof by induction, permutations, combinations, recurrence relations, etc.


It really depends what you're doing. If you just do web development or other moderately simple stuff, probably not very. But discrete math is extremely related to theoretical computer science, so if you're doing work with theory, computational complexity, advanced algorithms and algorithm analysis, etc, it's extremely useful.


----------



## joshd

Quote:


> Originally Posted by *Waffleboy*
> 
> It really depends what you're doing. If you just do web development or other moderately simple stuff, probably not very. But discrete math is extremely related to theoretical computer science, so if you're doing work with theory, computational complexity, advanced algorithms and algorithm analysis, etc, it's extremely useful.


Yes, he is right. It was Bill Gates who said something along the lines of programming and maths are very closely linked... good at one, good at the other and vice versa.


----------



## joshd

Bump.


----------



## {Unregistered}

The Folders' Lounge was moved to off-topic so I'd suggest we should stop this too...unless all you want to do is talk about programming...which is a good thing.









BTW, on-topic, do you have any experience with developing apps for Symbian / Meego using Qt?

EDIT: If I fall asleep, I may not read your reply soon.


----------



## joshd

Quote:


> Originally Posted by *{Unregistered}*
> 
> The Folders' Lounge was moved to off-topic so I'd suggest we should stop this too...unless all you want to do is talk about programming...which is a good thing.
> 
> 
> 
> 
> 
> 
> 
> 
> BTW, on-topic, do you have any experience with developing apps for Symbian / Meego using Qt?
> EDIT: If I fall asleep, I may not read your reply soon.


Lol. Anyway, lets keep this on topic







!

Unfortunately I do not, I don't even think I've used Symbian.. thats Nokia's in house OS right?


----------



## {Unregistered}

Quote:


> Originally Posted by *joshd*
> 
> Lol. Anyway, lets keep this on topic
> 
> 
> 
> 
> 
> 
> 
> !
> Unfortunately I do not, I don't even think I've used Symbian.. thats Nokia's in house OS right?


Well, not _strictly_ Nokia's, but yes, Nokia used to use it (and still does but is discontinuing it soon) in all of its smartphones. Also, how dare you live so close to Finland and not use Nokia phones!


----------



## joshd

Quote:


> Originally Posted by *{Unregistered}*
> 
> Well, not _strictly_ Nokia's, but yes, Nokia used to use it (and still does but is discontinuing it soon) in all of its smartphones. Also, how dare you live so close to Finland and not use Nokia phones!


Tehe. I want a Lumia 900, but they're not in the UK yet! I was thinking of trying to develop a few metro apps (don't kill me linux guys, I'm ashamed too) for Windows 8 and phone, but I'll have to wait.


----------



## {Unregistered}

Quote:


> Originally Posted by *joshd*
> 
> Tehe. I want a Lumia 900, but they're not in the UK yet! I was thinking of trying to develop a few metro apps (don't kill me linux guys, I'm ashamed too) for Windows 8 and phone, but I'll have to wait.


WP is cool too but I, for some unknown reason, seem to have a sweet spot for good ol' Symbian.









Also, about your news post format here, please try to avoid using it right now as the upper management seems to not agree with newer formats being necessary. If you want and you are really dedicated to revamp OCN's news post formats, I could request the management to reconsider...but until then, please avoid that.









Also, it would be nice if you could somehow that news posting tool thing you made quicker to use, as in even lesser amount of work needed because right now, it seems even more complicated than just simply learning how to format a news post.


----------



## Chris++

While I've always thought that a programmer worth his salt can do just fine with a basic text editor (or a slightly more featured like Notepad++), after doing a school project with PyCharm (by JetBrains), I've learned that the right tools can make a good programmer do his job extra quickly.

Seriously guys, I really recommend JetBrains IDEs, while they are commercial products (you have to pay for them), they are packed with so much features they seem to be magic.

Besides those, Visual Studio is rock solid as always (even for Python fans like me with "Python Tools for Visual Studio"), and VIM is just l33t hax0r mode.


----------



## andyroo89

I am not doing alot of programming just learning small amounts of various languages, and I kept getting overwhelmed by trying too many languages at once. But the languages I tried were, C# , C++ , VB , Python , and Java.

At the moment I am focusing on Java to develop android apps, and web apps.

Semi OT: Doesn't it feel good that you find new function or method, and shaved couple lines of code, and still get the same results?


----------



## dushan24

Quote:


> Originally Posted by *axipher*
> 
> Maybe we can start off by getting people's preferred IDE for writing code for different languages.


Vim for stuff over SSH
Notepad++ for most other things
Eclipse for Java
Recently tried SublimeText for web stuff and I rather like it.


----------



## tompsonn

Quote:


> Originally Posted by *axipher*
> 
> Maybe we can start off by getting people's preferred IDE for writing code for different languages.


I use Visual Studio for nearly everything. Except for the odd case where I still need to do some PHP. I have a weird choice in editor for PHP, HTML and basically every other web type programming. Wordpad. But not the Windows 7 one. Oh no. The old one from XP - yep still got a copy of it. Throw that in no-wrap mode and well... bingo.

I mainly do Win32 and .NET programming now in C and C#, though. I have a little addon for VS that makes kernel stuff easier to work with too.


----------



## joshd

Quote:


> Originally Posted by *dushan24*
> 
> Vim for stuff over SSH
> Notepad++ for most other things
> Eclipse for Java
> Recently tried SublimeText for web stuff and I rather like it.


I too love Sublime text 2!


----------



## darkwinter

Ive been using Sublime text 2 for a few days, been coding in java and C, I'm loving it !


----------



## andyroo89

How do you guys stay motivated to program? I am learning java but its hard to practice consistently. Its hard to stay motivated. Any suggestions?


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> How do you guys stay motivated to program? I am learning java but its hard to practice consistently. Its hard to stay motivated. Any suggestions?


For me, it is always wanting to accomplish something new - or if I find I might be getting sick of something, I'll try and do the same thing a different way.
I often look through documentations and things to see things I might have missed and often I get a spark "HEY! I should give that a go".


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> For me, it is always wanting to accomplish something new - or if I find I might be getting sick of something, I'll try and do the same thing a different way.
> I often look through documentations and things to see things I might have missed and often I get a spark "HEY! I should give that a go".


How do you get ideas? Just thinking or is there website that gives you challenges per level?

beginner
advance
expert


----------



## axipher

I decided to try learning a new language and chose PHP + MySQL. Tons of fun making mini projects.


----------



## andyroo89

Edit; Nevermind found a solution.


----------



## ironman1478

Quote:


> Originally Posted by *andyroo89*
> 
> How do you get ideas? Just thinking or is there website that gives you challenges per level?
> beginner
> advance
> expert


you should really just pick an interest and just start researching it. however dont pick something broad like "i want to learn opengl" because then you will never finish. set small goals like "i want to learn how to make rudimentary shapes using an open source API such as opengl or sdl." then find a tutorial, learn from it and then set another goal such as making 3d objects, then learning how to animate, add collision and all kinds of other things. if you want challenges, there is a website that is all about computation and finding solutions to things using programming called the euler project or something. there is also spoj.pl which is a very good programming challenge website, however many are very hard so it can be a bit discouraging if you cant figure many out


----------



## andyroo89

I am actually working on couple of things. The one im mainly working on is p2p chat IM type thing.


----------



## Lhino

Hey guys I am currently learning Java and I think I can place myself into the intermediate knowledge group at the moment. I REALLY want to learn C++ and Android app programming as well and I was wondering what great guides/ free software/ books (payed or free) I can get to learn it effectively. I understand that I can't go into the C language and Android and expect to be an expert in a month. I am motivated to learn and I also wish to learn how to program game engines (more books/ free stuff would be great). Thanks!


----------



## mitchtaydev

Quote:


> Originally Posted by *Lhino*
> 
> Hey guys I am currently learning Java and I think I can place myself into the intermediate knowledge group at the moment. I REALLY want to learn C++ and Android app programming as well and I was wondering what great guides/ free software/ books (payed or free) I can get to learn it effectively. I understand that I can't go into the C language and Android and expect to be an expert in a month. I am motivated to learn and I also wish to learn how to program game engines (more books/ free stuff would be great). Thanks!


For general game programming, gamedev.net is imo the best site for reference material. Are you wanting to make games or game engines? because they really are two different beasts.


----------



## Lhino

Quote:


> Originally Posted by *mitchtaydev*
> 
> For general game programming, gamedev.net is imo the best site for reference material. Are you wanting to make games or game engines? because they really are two different beasts.


I would like to tame both of those beasts! Haha, thanks I will check out gamedev.net.


----------



## FiX

Quote:


> Originally Posted by *Lhino*
> 
> I would like to tame both of those beasts! Haha, thanks I will check out gamedev.net.


If you want to learn about DirectX 9 for game programming, I've wrote up a simple guide here on the forums on how to do the basic initialising here.
Going to work on making an OOP version of it now and extending it on to doing things like rendering triangles, loading textures, terrain, etc.


----------



## Lhino

Quote:


> Originally Posted by *FiX*
> 
> If you want to learn about DirectX 9 for game programming, I've wrote up a simple guide here on the forums on how to do the basic initialising here.
> Going to work on making an OOP version of it now and extending it on to doing things like rendering triangles, loading textures, terrain, etc.


Thanks man!


----------



## andyroo89

Hey guys I have a question, Lets say I am working with webbrowser in c#, and whenever I put a url in it will check if it has http and if the url doesnt have http at the beginning it will automatically add one. BUT if it does have a http it will leave the url alone.

How would I go about doing that?


----------



## flamingoyster

Quote:


> Originally Posted by *axipher*
> 
> Maybe we can start off by getting people's preferred IDE for writing code for different languages.


notepad++ for anything it's compatible with
Quote:


> Originally Posted by *dushan24*
> 
> Vim for stuff over SSH
> Notepad++ for most other things
> Eclipse for Java
> Recently tried SublimeText for web stuff and I rather like it.


yeah basically this lol, except vim is hard to adjust to so I usually stick with uhhh nano >_> lol


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Hey guys I have a question, Lets say I am working with webbrowser in c#, and whenever I put a url in it will check if it has http and if the url doesnt have http at the beginning it will automatically add one. BUT if it does have a http it will leave the url alone.
> How would I go about doing that?


Ah. WebBrowser in C#, my favorite









If you mean you want to automatically add http to a URL supplied by the USER, you can do the following:

Code:



Code:


string schemeHttp = string.Format( "{0}://", Uri.UriSchemeHttp );
string userUrl = /* the URL from the user */;

if ( !userUrl.StartsWith( schemeHttp, StringComparison.OrdinalIgnoreCase ) )
{
        userUrl = string.Format( "{0}{1}", schemeHttp, userUrl );
}

/* use userUrl */

If you want something a little more robust, I give you my VerifyUri function:



Returns true if the supplied URI string was valid, false if not. If true was returned, you can use the value of the "modified" out parameter which will contain the validated (and formatted) URI. This version supports HTTPS, too.


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Ah. WebBrowser in C#, my favorite
> 
> 
> 
> 
> 
> 
> 
> 
> If you mean you want to automatically add http to a URL supplied by the USER, you can do the following:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> string schemeHttp = string.Format( "{0}://", Uri.UriSchemeHttp );
> string userUrl = /* the URL from the user */;
> if ( !userUrl.StartsWith( schemeHttp, StringComparison.OrdinalIgnoreCase ) )
> {
> userUrl = string.Format( "{0}{1}", schemeHttp, userUrl );
> }
> /* use userUrl */
> 
> If you want something a little more robust, I give you my VerifyUri function:
> 
> Returns true if the supplied URI string was valid, false if not. If true was returned, you can use the value of the "modified" out parameter which will contain the validated (and formatted) URI. This version supports HTTPS, too.


Thanks man works perfectly.


----------



## Delphiwizard

Hi everyone,

I learned the basics of programming (the theory, with nassi-schneidermann schemes and all) in the early nineties and learned Turbo Pascal soon after.
Since then i stuck with Pascal and every Delphi version that came out.

I made my hobby into my job and 8 years later it's back to being a hobby.
Kinda wondering if more people are still using Delphi as programming environment here


----------



## andyroo89

Quote:


> Originally Posted by *Delphiwizard*
> 
> Hi everyone,
> I learned the basics of programming (the theory, with nassi-schneidermann schemes and all) in the early nineties and learned Turbo Pascal soon after.
> Since then i stuck with Pascal and every Delphi version that came out.
> I made my hobby into my job and 8 years later it's back to being a hobby.
> Kinda wondering if more people are still using Delphi as programming environment here


I was actually going to give delphi a shot after I work on other programming languages.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Thanks man works perfectly.


No problemo


----------



## andyroo89

Now, finally got some time with c# again, with my webbrowser I am wanting to use http proxies, I have a list and I made it to where I can load the file and display it in my richtextbox (idk why I just decided to use it







) now I am wanting to get it to where it will use the first proxy on the list for certain amount of minutes, about 5 minutes or so, and then switch to the next one on the list.

I have the proxy (I think) coding which is here.

Code:



Code:


            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(textBox1.Text);
            webrequest.Proxy = new WebProxy(host, port);

            HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();
            Stream receiveStream = response.GetResponseStream();

            WebBrowser webBrowser = new WebBrowser();
            webBrowser.DocumentStream = receiveStream;

where it says host, port I am wanting to put the ip into the host section and the port in the port section (of course







)

question is am I even using right coding for this? If so, how can I get it to use the first proxy?

I came to the conclusion I may have to make a read line where it will read before the colon ":" as the ip, and after the colon ":" as the port

But I am sure there is easier way to doing this.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Now, finally got some time with c# again, with my webbrowser I am wanting to use http proxies, I have a list and I made it to where I can load the file and display it in my richtextbox (idk why I just decided to use it
> 
> 
> 
> 
> 
> 
> 
> ) now I am wanting to get it to where it will use the first proxy on the list for certain amount of minutes, about 5 minutes or so, and then switch to the next one on the list.
> I have the proxy (I think) coding which is here.
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(textBox1.Text);
> webrequest.Proxy = new WebProxy(host, port);
> HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();
> Stream receiveStream = response.GetResponseStream();
> WebBrowser webBrowser = new WebBrowser();
> webBrowser.DocumentStream = receiveStream;
> 
> where it says host, port I am wanting to put the ip into the host section and the port in the port section (of course
> 
> 
> 
> 
> 
> 
> 
> )
> question is am I even using right coding for this? If so, how can I get it to use the first proxy?
> *I came to the conclusion I may have to make a read line where it will read before the colon ":" as the ip, and after the colon ":" as the port*
> But I am sure there is easier way to doing this.


Not sure what you mean by the bolded part.
But you have a few options:

1. Your method should work OK, however it will fail when clicking links in the web browser when you load the document (they won't go through any proxy).
2. Use P/Invoke to set proxy settings: WinHttpSetDefaultProxyConfiguration (not recommended as this solves a local problem using a global setting).
3. Use System.Net.GlobalProxySelection to control proxy settings for your application only. *This is deprecated* though and replaced with WebRequest.DefaultWebProxy, I haven't tested if this will work the way you want.

You should (I haven't tested) be able to solve problem in first option by doing something similar to this to intercept each web request (although there will be some drawbacks, I can see it now):

Code:



Code:


        void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            if (e.Url.AbsolutePath != "blank")
            {
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(e.Url.AbsolutePath);
            webrequest.Proxy = new WebProxy(host, port);
            HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            WebBrowser webBrowser = new WebBrowser();
            webBrowser.DocumentStream = receiveStream;

                e.Cancel = true;
            }
        }

You can also set proxy options in the registry...


----------



## andyroo89

nvm about the bolded part I found my answer towards that statement.

That doesnt seem to help me read the first ip and use it as a proxy.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> nvm about the bolded part I found my answer towards that statement.
> That doesnt seem to help me read the first ip and use it as a proxy.


Is THAT what you want to do? LOL. Did I just completely miss what you wanted to do!?
So... you want to get the first line out of a text box?

That one's nice and easy...

Code:



Code:


RichTextBox textBox = /* textbox instance */;
string[] lines = textBox.Lines;
string firstLine = null;

if ( lines != null && lines.Length > 0 )
{
    firstLine = lines[0];
}

/* use firstLine  if not null */


----------



## andyroo89

Basically I wanted to get the first line of the textbox (which is proxy ip) and use it as a proxy then go to the second line and so on. Now, I am trying to get it from reading the first line and now using it at the proxy ip


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Basically I wanted to get the first line of the textbox (which is proxy ip) and use it as a proxy then go to the second line and so on. Now, I am trying to get it from reading the first line and now using it at the proxy ip


You can get each line in the text box by using the Lines property (as shown in my example above). It gives you string array. Index 0 is the first line, index 1 is the second line, etc.
Have I got this right or are you trying to do something else?


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> You can get each line in the text box by using the Lines property (as shown in my example above). It gives you string array. Index 0 is the first line, index 1 is the second line, etc.
> Have I got this right or are you trying to do something else?


You may have gotten right but how would I use it as a proxy ip? I mean on line webrequest.Proxy = new WebProxy(firstLine); I put first line thinking it would use it as a proxy ip

idk im ripping my hair out at this atm.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> You may have gotten right but how would I use it as a proxy ip? I mean on line webrequest.Proxy = new WebProxy(firstLine); I put first line thinking it would use it as a proxy ip
> idk im ripping my hair out at this atm.


I get you now.
Please see the documentation for the WebProxy class: http://msdn.microsoft.com/en-us/library/system.net.webproxy.aspx

Scroll down to the example in C# and it will show you how to use it.

Actually, to make it easier - can I see some example proxy listings?


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> I get you now.
> Please see the documentation for the WebProxy class: http://msdn.microsoft.com/en-us/library/system.net.webproxy.aspx
> Scroll down to the example in C# and it will show you how to use it.
> Actually, to make it easier - can I see some example proxy listings?


examples? of what? here I will just show you the whole coding, here is my mess i am working on. keep in mind I just left it as I was reading your post so some of the coding may seem out of place.

http://pastebin.com/Btc2gxuF


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> examples? of what? here I will just show you the whole coding, here is my mess i am working on. keep in mind I just left it as I was reading your post so some of the coding may seem out of place.
> http://pastebin.com/Btc2gxuF


Thanks... what do the proxy listings look like?

Are they in the format of IPORT? e.g 124.98.86.132:8080


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Thanks... what do the proxy listings look like?
> Are they in the format of IPORT? e.g 124.98.86.132:8080


im sorry, yes, most of them are, couple of them are lil different, I have seen em before just idk how to describe it. http://pastebin.com/qnqm7sg7


----------



## EfemaN

I'm a novice getting comfortable with eclipse, but after stumbling upon Sublime Text 2, I've fallen for it's dark UI options. It's difficult to get used to, though, after having active error handling and console output right in front of me in an IDE. There's a plugin for eclipse, but that only changes the code window, and not the entire UI.

Do any of you use dark-themed IDEs? Any suggestions for what I'm looking for?


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> im sorry, yes, most of them are, couple of them are lil different, I have seen em before just idk how to describe it. http://pastebin.com/qnqm7sg7


Here's an IP address + port parser from one of my projects:

Code:



Code:


public bool AutoFillHostAndPort(string input, out string address, out int port)
{
        address = null;
        port = 0;
        string hostName = input;
        int colonIndex = hostName.IndexOf(':');
        if (colonIndex != -1)
        {
                address = hostName.Substring(0, colonIndex);
                if (!int.TryParse(hostName.Substring(colonIndex + 1), out port))
                {
                        return false;
                }
                port = port;
        }
        return true;
}

/* Usage */
string ipAddress;
int port;

if ( AutoFillHostAndPort( "124.98.86.132:8080", out ipAddress, out port ) )
{
    /* use ipAddress and port, eg, new WebProxy( ipAddress, port ) */
}


----------



## andyroo89

I will look at it tomorrow, too tired atm thanks.


----------



## tompsonn

Quote:


> Originally Posted by *EfemaN*
> 
> I'm a novice getting comfortable with eclipse, but after stumbling upon Sublime Text 2, I've fallen for it's dark UI options. It's difficult to get used to, though, after having active error handling and console output right in front of me in an IDE. There's a plugin for eclipse, but that only changes the code window, and not the entire UI.
> Do any of you use dark-themed IDEs? Any suggestions for what I'm looking for?


Yep, I use Visual Studio 2012 with its dark theme











Check this out: http://stackoverflow.com/questions/5053834/eclipse-ide-for-java-full-dark-theme


----------



## EfemaN

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *EfemaN*
> 
> I'm a novice getting comfortable with eclipse, but after stumbling upon Sublime Text 2, I've fallen for it's dark UI options. It's difficult to get used to, though, after having active error handling and console output right in front of me in an IDE. There's a plugin for eclipse, but that only changes the code window, and not the entire UI.
> Do any of you use dark-themed IDEs? Any suggestions for what I'm looking for?
> 
> 
> 
> Yep, I use Visual Studio 2012 with its dark theme
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Check this out: http://stackoverflow.com/questions/5053834/eclipse-ide-for-java-full-dark-theme
Click to expand...

That does the trick! Having Dreamspark makes it easier too









I had seen that link you posted; the "Custom Theme" is the plugin I was mentioning that only affects the code view, not the entire UI. And I don't want to mess with the entire W7 theme, especially since the one listed doesn't seem to be x64-friendly.









EDIT: It looks like the colors on yours are a bit different and even easier on the eyes than the "Dark" color theme included in the VS2012 I just installed. Did you just modify it yourself?


----------



## tompsonn

Quote:


> Originally Posted by *EfemaN*
> 
> That does the trick! Having Dreamspark makes it easier too
> 
> 
> 
> 
> 
> 
> 
> 
> I had seen that link you posted; the "Custom Theme" is the plugin I was mentioning that only affects the code view, not the entire UI. And I don't want to mess with the entire W7 theme, especially since the one listed doesn't seem to be x64-friendly.
> 
> 
> 
> 
> 
> 
> 
> 
> EDIT: It looks like the colors on yours are a bit different and even easier on the eyes than the "Dark" color theme included in the VS2012 I just installed. Did you just modify it yourself?


Ah right. Yeah I thought messing with the Windows theme was a bit stupid!
I haven't touched my VS2012 theme. Only thing I change is the font to Courier New (I hate Consolas!)

Out of curiosity, what are you programming in?


----------



## EfemaN

Quote:


> Originally Posted by *tompsonn*
> 
> Ah right. Yeah I thought messing with the Windows theme was a bit stupid!
> I haven't touched my VS2012 theme. Only thing I change is the font to Courier New (I hate Consolas!)
> 
> Out of curiosity, what are you programming in?


I think my eyes are playing tricks on me









I did some UnityScript (javascript-like) game stuff this summer, but I need to get away from that and start C# on my own time. I believe we're programming in C for my Machine Architecture course, so that'll get some use. I haven't started focusing on anything, since it's early, but I think I'll end up with C# and C++ for where I want to go.


----------



## tompsonn

Quote:


> Originally Posted by *EfemaN*
> 
> I think my eyes are playing tricks on me
> 
> 
> 
> 
> 
> 
> 
> 
> I did some UnityScript (javascript-like) game stuff this summer, but I need to get away from that and start C# on my own time. I believe we're programming in C for my Machine Architecture course, so that'll get some use. I haven't started focusing on anything, since it's early, but I think I'll end up with C# and C++ for where I want to go.


Great choices


----------



## EfemaN

Anyone have experience with setting up Visual Studio with an external build system? I'd like to use it to code C for school, but it needs to use the gcc compiler I grabbed from MinGW, as the VC compiler doesn't behave the same way.


----------



## andyroo89

Time to re open this thread from the dead, I am currently working on file manager in C#, I have it to where every hour (using timers, and I am hoping to get it to where it uses one timer instead of multiple timers) it will check for various file extensions and filenames containing certain words. I have a notifyicon pops up when ever file(s) have been moved, My problem is that the icon shows up multiple times if it is multiple files at the same time, For example, if it moves 4 pictures/files it will pop up 4 times. How can I get it to where it will only pop up once?

here is part of the source code

Code:



Code:


int i = 1;
        private void redheadtimer_Tick(object sender, EventArgs e)
        {

            string destredhead = @"C:\Users\Andy\pictures\redheads";
            var r = Directory.GetFiles(genericsrcdir, "*redhead*");
            foreach (var s in r)
            {
                var sourcefile = new FileInfo(s);
                sourcefile.MoveTo(destredhead + "\\" + s.Replace(genericsrcdir, string.Empty));
                startupnotify.ShowBalloonTip(4000, "Redheads File Transfer", "Moved " + i + " pictures of redheads to your redhead folder", ToolTipIcon.Info);
                i += 1;
            }
        }


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Time to re open this thread from the dead, I am currently working on file manager in C#, I have it to where every hour (using timers, and I am hoping to get it to where it uses one timer instead of multiple timers) it will check for various file extensions and filenames containing certain words. I have a notifyicon pops up when ever file(s) have been moved, My problem is that the icon shows up multiple times if it is multiple files at the same time, For example, if it moves 4 pictures/files it will pop up 4 times. How can I get it to where it will only pop up once?
> here is part of the source code
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> int i = 1;
> private void redheadtimer_Tick(object sender, EventArgs e)
> {
> 
> string destredhead = @"C:\Users\Andy\pictures\redheads";
> var r = Directory.GetFiles(genericsrcdir, "*redhead*");
> foreach (var s in r)
> {
> var sourcefile = new FileInfo(s);
> sourcefile.MoveTo(destredhead + "\\" + s.Replace(genericsrcdir, string.Empty));
> startupnotify.ShowBalloonTip(4000, "Redheads File Transfer", "Moved " + i + " pictures of redheads to your redhead folder", ToolTipIcon.Info);
> i += 1;
> }
> }


You should use a file system watcher for this instead of polling the file system with a timer.
http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> You should use a file system watcher for this instead of polling the file system with a timer.
> http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx


Stalking me







? After I made the post I noticed file system watcher in VS2010


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Stalking me
> 
> 
> 
> 
> 
> 
> 
> ? After I made the post I noticed file system watcher in VS2010


Stalking? What you mean haha!


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Stalking? What you mean haha!


Uh huh kkk sure........


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Uh huh kkk sure........


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Yep, I use Visual Studio 2012 with its dark theme
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Check this out: http://stackoverflow.com/questions/5053834/eclipse-ide-for-java-full-dark-theme


+1



Still working on 2010 because of XNA.


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> +1
> 
> Still working on 2010 because of XNA.


They dropped XNA!?


----------



## Fantasy

Quote:


> Originally Posted by *andyroo89*
> 
> How do you guys stay motivated to program? I am learning java but its hard to practice consistently. Its hard to stay motivated. Any suggestions?


Well for me I have to stay motivated so I don't become homeless. Also I don't do the same task two days in a row. I try to find and implement new ideas in my project everyday and try to finish them in that same day, because I know that I'll not continue doing the same task the second day. Because doing the something is just boring. I need new challenge or puzzle everyday or i'll just get bored and lose interest.

For me programming is not so much as witting the software but rather solving the puzzle. My problem is if I solve the puzzle while driving or eating or playing video games I'll not go and code it right away. I might try to code it the next day. because I already got the rush or happiness from solving the puzzle. And I know that if I code it, it will work just as I thought and I won't get that happy feeling again when it work. Because I already now its going to work. So I have to try to solve the puzzle and code it as fast as I can so I don't lose interest in it.

I try to find a new puzzle everyday, solve it at the same day and move on. Also I try to switch from one section of my project to the other. For example one day I'll do the UI part of my project. The next day i'll do the networking part. The next day I'll do the audio part . and so on. I try mixing it up so I don't get bored quickly.

Hope that helps









Quote:


> Originally Posted by *tompsonn*
> 
> They dropped XNA!?


sadly yes. no XNA support in VS 2012. stupid microsoft


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> sadly yes. no XNA support in VS 2012. stupid microsoft


Alternative??


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Alternative??


Well I heard that MS is going to build a new framework on top of SharpDX. but that is just a rumor for now.

You can still write XNA code in VS 2012 but you need to do it through Monogame. So Monogame takes your XNA code and make it work on iOS, Android, Mac OS X, Linux and Windows 8 Metro.

So why am I not using Monogame. Too lazy to install VS 2012 and MonoGame









or you can use SharpDX.


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> Well I heard that MS is going to build a new framework on top of SharpDX. but that is just a rumor for now.
> You can still write XNA code in VS 2012 but you need to do it through Monogame. So Monogame takes your XNA code and make it work on iOS, Android, Mac OS X, Linux and Windows 8 Metro.
> So why am I not using Monogame. Too lazy to install VS 2012 and MonoGame
> 
> 
> 
> 
> 
> 
> 
> 
> or you can use SharpDX.


Boo-hoo


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Boo-hoo


----------



## FiX

Quote:


> Originally Posted by *tompsonn*
> 
> Alternative??


Full on DirectX







Not sure really, haven't looked into it. I've never really used XNA, always just pure DirectX 9 / 11.


----------



## Bobicon

Has anyone else worked on a program long enough in one day that they forgot what they were trying to accomplish in the section of code they were working on?

Happened to me today after about 4 hours of fixing one thing and another problem popping up over and over again.


----------



## tompsonn

Quote:


> Originally Posted by *Bobicon*
> 
> Has anyone else worked on a program long enough in one day that they forgot what they were trying to accomplish in the section of code they were working on?
> Happened to me today after about 4 hours of fixing one thing and another problem popping up over and over again.


All the time!


----------



## {Unregistered}

Today, I spent so much time trying to fix a problem that wasn't even one in the first place!
I presume my fellow programmers will know that feeling.


----------



## tompsonn

Quote:


> Originally Posted by *{Unregistered}*
> 
> Today, I spent so much time trying to fix a problem that wasn't even one in the first place!
> I presume my fellow programmers will know that feeling.


Interestingly enough, can't say I've felt that one before...!


----------



## Bobicon

I ended up stopping the cycle of fixing then breaking by purposely fixing one thing and breaking something that I really didn't need and commenting it out. I may put it back it, but as of now I could care less.


----------



## om3n

So do any of you guys use mechanical keyboards at work? My current home keyboard that I both game and code on has mx-brown switches, and while it's not clicky, it's still extremely loud to type on. Do any of you guys use mechanical keyboards at work for programming, and if so, what do your co-workers think about it? I was considering picking one up for work eventually because I love my one at home SO much, but I haven't so far because I'd probably make every hate my guts ha ha.


----------



## Bobicon

Quote:


> Originally Posted by *tompsonn*
> 
> Interestingly enough, can't say I've felt that one before...!


I have last time I was working with a Binary Search Tree I thought my values weren't attaching to the keys as I was getting None for the values when I was echo printing.

Turns out I was printing off the wrong thing.

That was a waste of an hour.


----------



## Bobicon

Quote:


> Originally Posted by *om3n*
> 
> So do any of you guys use mechanical keyboards at work? My current home keyboard that I both game and code on has mx-brown switches, and while it's not clicky, it's still extremely loud to type on. Do any of you guys use mechanical keyboards at work for programming, and if so, what do your co-workers think about it? I was considering picking one up for work eventually because I love my one at home SO much, but I haven't so far because I'd probably make every hate my guts ha ha.


I don't work as a programmer, but I work at a newspaper and everyone here uses a cheap mechanical keyboard and it is headache inducing.


----------



## deafboy

Quote:


> Originally Posted by *om3n*
> 
> So do any of you guys use mechanical keyboards at work? My current home keyboard that I both game and code on has mx-brown switches, and while it's not clicky, it's still extremely loud to type on. Do any of you guys use mechanical keyboards at work for programming, and if so, what do your co-workers think about it? I was considering picking one up for work eventually because I love my one at home SO much, but I haven't so far because I'd probably make every hate my guts ha ha.


I've had a lot of co-workers that use mechanical keyboards, was kind of annoying at first, then I got used to it, and then I just started listening to music so it became moot. haha.

Saw a few people with blue keys and felt bad for their neighboring coworkers, lol


----------



## tompsonn

Quote:


> Originally Posted by *om3n*
> 
> So do any of you guys use mechanical keyboards at work? My current home keyboard that I both game and code on has mx-brown switches, and while it's not clicky, it's still extremely loud to type on. Do any of you guys use mechanical keyboards at work for programming, and if so, what do your co-workers think about it? I was considering picking one up for work eventually because I love my one at home SO much, but I haven't so far because I'd probably make every hate my guts ha ha.


I use an MX brown board at work. I couldn't give a toss if people don't like it








For the record, no one has said anything.
Quote:


> Originally Posted by *Bobicon*
> 
> I have last time I was working with a Binary Search Tree I thought my values weren't attaching to the keys as I was getting None for the values when I was echo printing.
> Turns out I was printing off the wrong thing.
> That was a waste of an hour.


Oh, now THAT I have done. When you put it that way. Pain in the ass LOL.


----------



## andyroo89

I accidentally fixed a problem I had which is funny.


----------



## Bobicon

I usually know its time to take a break from programming when I am ready to start typing in random statements to try and fix a problem.


----------



## andyroo89

Quote:


> Originally Posted by *Bobicon*
> 
> I usually know its time to take a break from programming when I am ready to start typing in random statements to try and fix a problem.


same.


----------



## deafboy

Quote:


> Originally Posted by *Bobicon*
> 
> I usually know its time to take a break from programming when I am ready to start typing in random statements to try and fix a problem.


While true...it is awesome humorous and awesome when a random attempt works wonderfully.


----------



## Fantasy

Quote:


> Originally Posted by *{Unregistered}*
> 
> Today, I spent so much time trying to fix a problem that wasn't even one in the first place!
> I presume my fellow programmers will know that feeling.


That happened to me yesterday

After 6 hours trying to fix some a problem in my source code, it turns out that the problem wasn't even in my source code. It was in my Map file









that pissed me off so much that I shutdown my PC without fixing the problem.

Sometimes I hate programming so much.
Quote:


> Originally Posted by *Bobicon*
> 
> I usually know its time to take a break from programming when I am ready to start typing in random statements to try and fix a problem.


Same here. But as deafboy said sometimes it works


----------



## 3930K

Spent 5 hours programming a database class and an field class. Did an entry class with a few methods before realizing that all that was in an entry was a string and nothing else.


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> Spent 5 hours programming a database class and an field class. Did an entry class with a few methods before realizing that all that was in an entry was a string and nothing else.


Once I tried to connect to my own database for a freaking hour and I couldn't. I was going crazy looking at my PHP code over and over and over and over and I couldn't figure it out. I kept talking to my self like a crazy person. My frineds came to my apartment and they were really scared of me. they were like "Dude what is wrong with you?". And I was like "this code, this code... something is wrong, something is wrong. WHY WON"T U CONNECT !!







" After a while I figured that my stupid firewall was blocking me from MY OWN DATABASE









my point is, don't drink too much coffee and stay awake for a long time or you will go crazy


----------



## om3nz

Hello fellow programmers. It is strange that nobody mentioned Intellij Idea IDE. I use it mainly for Java, Spring framework and web development(JavaScript/JQuery, css, html and so on) and it is fantastic. I also use eclipse from time to time. BTW, using a notepad for complex java projects is too hardcore and time consuming, lol.


----------



## 3930K

Quote:


> Originally Posted by *om3nz*
> 
> Hello fellow programmers. It is strange that nobody mentioned Intellij Idea IDE. I use it mainly for Java, Spring framework and web development(JavaScript/JQuery, css, html and so on) and it is fantastic. I also use eclipse from time to time. BTW, using a notepad for complex java projects is too hardcore and time consuming, lol.


Hmm I think you're the first one to realize that


----------



## 3930K

XmlReader is extremely tirighbjy hbyffffffffffffffffffffff

EDIT: CRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP!!!!!!!!!!!!!!!!! I wrote it wrong!


----------



## om3n

Quote:


> Originally Posted by *om3nz*
> 
> Hello fellow programmers. It is strange that nobody mentioned Intellij Idea IDE. I use it mainly for Java, Spring framework and web development(JavaScript/JQuery, css, html and so on) and it is fantastic. I also use eclipse from time to time. BTW, using a notepad for complex java projects is too hardcore and time consuming, lol.












You stole'd my name....


----------



## Bobicon

Quote:


> Originally Posted by *om3n*
> 
> 
> 
> 
> 
> 
> 
> 
> 
> You stole'd my name....


No he's just cooler because his name has a "z" in it.


----------



## {Unregistered}

That moment when you take 20 minutes to fix an "off by one" array error.









The thing is, the problem wasn't in my iterative loop over the array, the problem was in the array given as an argument.


----------



## axipher

Quote:


> Originally Posted by *{Unregistered}*
> 
> That moment when you take 20 minutes to fix an "off by one" array error.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> The thing is, the problem wasn't in my iterative loop over the array, the problem was in the array given as an argument.


That 2 weeks of wasted time because you forgot a certain module uses '1' as the base for an array element list...


----------



## andyroo89

I switched over to android development, pretty excited especially when the IDE in eclipse is similar to Visual Studios.


----------



## 3930K

That 4 hours of XMLReader wasted...


----------



## deafboy

Quote:


> Originally Posted by *{Unregistered}*
> 
> That moment when you take 20 minutes to fix an "off by one" array error.
> 
> 
> 
> 
> 
> 
> 
> 
> The thing is, the problem wasn't in my iterative loop over the array, the problem was in the array given as an argument.


20 minutes doesn't seem bad...

I had something similar to that happen though and always sad.

Hey! You're stuff isn't passing the tests...
Um, okay...it should be.
Well, it's not.
...
Tests were broken/bad.


----------



## andyroo89

I have a question, I. Made a simple root checker android java programming, and I was wondering what other methods I can try for root checking a device? The one I made just sends a command su -c and if it is positive it will display a text saying I'm root. Now, sometimes it will say I'm not root but it doesn't say that too often. Most if the time it is right.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> I have a question, I. Made a simple root checker android java programming, and I was wondering what other methods I can try for root checking a device? The one I made just sends a command su -c and if it is positive it will display a text saying I'm root. Now, sometimes it will say I'm not root but it doesn't say that too often. Most if the time it is right.


Code:



Code:


final Runtime runtime = Runtime.getRuntime();
try 
{
        runtime.exec("su");
        /* got root */
}
catch (IOException e) 
{ 
        /* failed, do something with e */
}

What superuser app do are you testing with?


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> final Runtime runtime = Runtime.getRuntime();
> try
> {
> runtime.exec("su");
> /* got root */
> }
> catch (IOException e)
> {
> /* failed, do something with e */
> }
> 
> What superuser app do are you testing with?


on my tablet, supersu, on my phone, superuser

here is my code that i used.

Code:



Code:


Process exec;
                                    try {

                                        exec = Runtime.getRuntime().exec(new String[]{"su","-c"});

                                        final OutputStreamWriter out = new OutputStreamWriter(exec.getOutputStream());
                                        out.write("exit");
                                        out.flush();
                                        display.setText("You're root");

                                    } catch (IOException e) {
                                        display.setText("You're not root");
                                        e.printStackTrace();
                                    }


----------



## ivr56

Taking my time to learn Pure Data right now.
Don't have the money for MaxMSP6 full yet.

So far made a 40 step MIDI sequencer to use with Reason


----------



## Fantasy

I spent an hour trying to figure out what is wrong with this code.

sometimes I feel so stupid.

Code:



Code:


for (int i = 0; i < AcceptSocket.Length; i++)
{
    //Some code

    if (Packet.SendServerList)
    {
         for (int j = 0; j < AcceptSocket.Length; j++)
         {
               if (j == i)
                    continue;
               else
               {
                     for (int r = 0; r < serversList.IpAddress.Count; r++)
                    {
                           Packet.IPAddress = serversList.IpAddress[i];
                           Packet.Port = serversList.Port[i];
                    }
               }
        }
}




Spoiler: I want to know what is wrong with the previous code



Code:



Code:


for (int r = 0; r < serversList.IpAddress.Count; r++)
{
     Packet.IPAddress = serversList.IpAddress[i];   <---- [r] NOT [i] 
     Packet.Port = serversList.Port[i];                          <---- [r] NOT [i] 
}


----------



## tompsonn

@Fantasy: Done that so many times.


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> @Fantasy: Done that so many times.


----------



## deafboy

Quote:


> Originally Posted by *tompsonn*
> 
> @Fantasy: Done that so many times.


lol. Yup, always the little things that piss you off more than anything, lol.


----------



## 3930K

I thought it was just my basic that spoiled me to do that.


----------



## {Unregistered}

Quote:


> Originally Posted by *Fantasy*
> 
> I spent an hour trying to figure out what is wrong with this code.
> sometimes I feel so stupid.
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> for (int i = 0; i < AcceptSocket.Length; i++)
> {
> //Some code
> if (Packet.SendServerList)
> {
> for (int j = 0; j < AcceptSocket.Length; j++)
> {
> if (j == i)
> continue;
> else
> {
> for (int r = 0; r < serversList.IpAddress.Count; r++)
> {
> Packet.IPAddress = serversList.IpAddress[i];
> Packet.Port = serversList.Port[i];
> }
> }
> }
> }
> 
> 
> 
> 
> Spoiler: I want to know what is wrong with the previous code
> 
> 
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> for (int r = 0; r < serversList.IpAddress.Count; r++)
> {
> Packet.IPAddress = serversList.IpAddress[i];   <---- [r] NOT [i]
> Packet.Port = serversList.Port[i];                          <---- [r] NOT [i]
> }


Just thought I'd point this out. There's nothing wrong with your code (with the correction you made, of course), but it's not generally considered good practice to nest so much stuff within your first if conditional.
It would look much better (and easier for someone else reading your code) if you had written it in this style:

Code:



Code:


for (int i = 0; i < AcceptSocket.Length; i++)
{
    //Some code

    if (!Packet.SendServerList)
    {
      continue; 
    }

    for (int j = 0; j < AcceptSocket.Length; j++)
    {
      if (j == i)
      {
        continue;
      }

      for (int r = 0; r < serversList.IpAddress.Count; r++)
      {
        Packet.IPAddress = serversList.IpAddress[r];
        Packet.Port = serversList.Port[r];
      }

    }
}

As you can see, you also don't need the else clause after the if clause containing "continue;".
Again, nothing wrong with your code, but this just makes it more readable (in my opinion, of course). Some people might prefer your style anyway. Just thought I'd share.


----------



## Fantasy

Quote:


> Originally Posted by *deafboy*
> 
> lol. Yup, always the little things that piss you off more than anything, lol.


Yap









Quote:


> Originally Posted by *{Unregistered}*
> 
> Just thought I'd point this out. There's nothing wrong with your code (with the correction you made, of course), but it's not generally considered good practice to nest so much stuff within your first if conditional.
> It would look much better (and easier for someone else reading your code) if you had written it in this style:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> for (int i = 0; i < AcceptSocket.Length; i++)
> {
> //Some code
> if (!Packet.SendServerList)
> {
> break;
> }
> 
> for (int j = 0; j < AcceptSocket.Length; j++)
> {
> if (j == i)
> {
> continue;
> }
> for (int r = 0; r < serversList.IpAddress.Count; r++)
> {
> Packet.IPAddress = serversList.IpAddress[r];
> Packet.Port = serversList.Port[r];
> }
> }
> }
> 
> As you can see, you also don't need the else clause after the if clause containing "continue;".
> Again, nothing wrong with your code, but this just makes it more readable (in my opinion, of course). Some people might prefer your style anyway. Just thought I'd share.


That actually looks better. thanks


----------



## 3930K

I once nested 10 fors and ifs and foreaches. XmlReader problems


----------



## andyroo89

anyone want to be testers for my root checker? Since all of my android devices are rooted its hard to tell if the root checker actually works or not. I will provide a virus scan if anyone wants to test it.

I am mostly looking for nonroot android users.


----------



## deafboy

but with continue instead of break perhaps...


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> I once nested 10 fors and ifs and foreaches. XmlReader problems


You mean something like this










Spoiler: Warning: Spoiler!



Code:



Code:


public static void LoadTowerXMLFile()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(MapFilePath);

            if (xmlDoc.SelectSingleNode("MapData") != null)
            {
                if (xmlDoc.SelectSingleNode("MapData/Towers") != null)
                {
                    if (xmlDoc.SelectSingleNode("MapData/Towers/Tower") != null)
                    {
                        foreach (XmlNode node in xmlDoc.SelectNodes("MapData/Towers/Tower"))
                        {
                            TowerManager.towersData.Add(new TowersData(node.Attributes.GetNamedItem("Name").Value));
                        }

                        if (xmlDoc.SelectSingleNode("MapData/Towers/Tower/Levels") != null)
                        {
                            foreach (XmlNode node in xmlDoc.SelectNodes("MapData/Towers/Tower/Levels"))
                            {
                                TowerManager.MaximumLevel.Add(int.Parse(node.Attributes.GetNamedItem("MaximumLevel").Value));
                            }

                            foreach (XmlNode node in xmlDoc.SelectNodes("MapData/Towers/Tower/Levels/Level"))
                            {
                                TowerManager.towersData[TowerManager.CurrentTower].towerStats.Add(new Stats("",
                                                                        int.Parse(node.Attributes.GetNamedItem("Number").Value),
                                                                        int.Parse(node.Attributes.GetNamedItem("Health").Value),
                                                                        int.Parse(node.Attributes.GetNamedItem("Health").Value),
                                                                        int.Parse(node.Attributes.GetNamedItem("Damage").Value),
                                                                        int.Parse(node.Attributes.GetNamedItem("MagicDamage").Value),
                                                                        0,
                                                                        int.Parse(node.Attributes.GetNamedItem("AttackSpeed").Value),
                                                                        int.Parse(node.Attributes.GetNamedItem("Armor").Value),
                                                                        int.Parse(node.Attributes.GetNamedItem("MagicResist").Value)
                                                                        ));

                                if (int.Parse(node.Attributes.GetNamedItem("Number").Value) == TowerManager.MaximumLevel[TowerManager.CurrentTower])
                                {
                                    TowerManager.CurrentTower += 1;
                                }
                            }
                        }
                    }
                }
            }
        }


----------



## {Unregistered}

Quote:


> Originally Posted by *deafboy*
> 
> but with continue instead of break perhaps...


Yea, derp.









Meant continue. Will edit the post.


----------



## 3930K

Quote:


> Originally Posted by *Fantasy*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> I once nested 10 fors and ifs and foreaches. XmlReader problems
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> You mean something like this
> 
> 
> Spoiler: Warning: Spoiler!
> 
> 
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> public static void LoadTowerXMLFile()
> {
> XmlDocument xmlDoc = new XmlDocument();
> xmlDoc.Load(MapFilePath);
> 
> if (xmlDoc.SelectSingleNode("MapData") != null)
> {
> if (xmlDoc.SelectSingleNode("MapData/Towers") != null)
> {
> if (xmlDoc.SelectSingleNode("MapData/Towers/Tower") != null)
> {
> foreach (XmlNode node in xmlDoc.SelectNodes("MapData/Towers/Tower"))
> {
> TowerManager.towersData.Add(new TowersData(node.Attributes.GetNamedItem("Name").Value));
> }
> 
> if (xmlDoc.SelectSingleNode("MapData/Towers/Tower/Levels") != null)
> {
> foreach (XmlNode node in xmlDoc.SelectNodes("MapData/Towers/Tower/Levels"))
> {
> TowerManager.MaximumLevel.Add(int.Parse(node.Attributes.GetNamedItem("MaximumLevel").Value));
> }
> 
> foreach (XmlNode node in xmlDoc.SelectNodes("MapData/Towers/Tower/Levels/Level"))
> {
> TowerManager.towersData[TowerManager.CurrentTower].towerStats.Add(new Stats("",
> int.Parse(node.Attributes.GetNamedItem("Number").Value),
> int.Parse(node.Attributes.GetNamedItem("Health").Value),
> int.Parse(node.Attributes.GetNamedItem("Health").Value),
> int.Parse(node.Attributes.GetNamedItem("Damage").Value),
> int.Parse(node.Attributes.GetNamedItem("MagicDamage").Value),
> 0,
> int.Parse(node.Attributes.GetNamedItem("AttackSpeed").Value),
> int.Parse(node.Attributes.GetNamedItem("Armor").Value),
> int.Parse(node.Attributes.GetNamedItem("MagicResist").Value)
> ));
> 
> if (int.Parse(node.Attributes.GetNamedItem("Number").Value) == TowerManager.MaximumLevel[TowerManager.CurrentTower])
> {
> TowerManager.CurrentTower += 1;
> }
> }
> }
> }
> }
> }
> }
Click to expand...

Yeah









Well I half-fixed it from a stolen XmlTextReader example from MSDN


----------



## deafboy

Quote:


> Originally Posted by *{Unregistered}*
> 
> Yea, derp.
> 
> 
> 
> 
> 
> 
> 
> 
> Meant continue. Will edit the post.


----------



## Fantasy

which style do you guys like better. This?

Code:



Code:


for (int i = 0; i < AllSockets.Count; i++)
{
    if (RespondingSockets.Contains(AllSockets[i]) == false)
    {
        NotRespondingSockets.Add(AllSockets[i]);
    }
}

or this?

Code:



Code:


for (int i = 0; i < AllSockets.Count; i++)
{
     if (RespondingSockets.Contains(AllSockets[i]))
     {
          continue;
     }
     else
     {
          NotRespondingSockets.Add(AllSockets[i]);
     }
}


----------



## tompsonn

First one, but without the explicit "false" check. (so use !)

Though every programmer has their style.

But I would say the second might be bad practice - it complicates control flow unnecessarily.


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> First one, but without the explicit "false" check. (so use !)
> Though every programmer has their style.
> But I would say the second might be bad practice - it complicates control flow unnecessarily.


Hmm.. I actually liked the second one because I felt it easier to understand. But your right the first one is better and its less code.

I used to do something like this

Code:



Code:


if(!Dead)
//do

but then one day I spent 20 minutes checking 5 - 10 classes trying to figure out why my code wasn't working like I want it to. And it turns out that I added the NOT sign and forgot to remove it and didn't see it when I was check my code. So I swore I would never use " ! " again in my life and I would use " == false".


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> Hmm.. I actually liked the second one because I felt it easier to understand. But your right the first one is better and its less code.
> I used to do something like this
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> if(!Dead)
> //do
> 
> but then one day I spent 20 minutes checking 5 - 10 classes trying to figure out why my code wasn't working like I want it to. And it turns out that I added the NOT sign and forgot to remove it and didn't see it when I was check my code. So I swore I would never use " ! " again in my life and I would use " == false".


Like I said, we all have our style








First is 100 times easier to understand for me.


----------



## {Unregistered}

Quote:


> Originally Posted by *Fantasy*
> 
> Hmm.. I actually liked the second one because I felt it easier to understand. But your right the first one is better and its less code.
> I used to do something like this
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> if(!Dead)
> //do
> 
> but then one day I spent 20 minutes checking 5 - 10 classes trying to figure out why my code wasn't working like I want it to. And it turns out that I added the NOT sign and forgot to remove it and didn't see it when I was check my code. So I swore I would never use " ! " again in my life and I would use " == false".


I'd say, using the first or second style is debatable but using "== false" is absolutely unacceptable. It's just plain wrong. Sorry, but if you were showing that code to your professor or tutor, he would give you -10,000 imaginary points for that in his head.
Use "!" instead of "== false".


----------



## tompsonn

Quote:


> Originally Posted by *{Unregistered}*
> 
> I'd say, using the first or second style is debatable but using "== false" is absolutely unacceptable. It's just plain wrong. Sorry, but if you were showing that code to your professor or tutor, he would give you -10,000 imaginary points for that in his head.
> Use "!" instead of "== false".


Seeing as you're being honest, I will too... LOL.
I recon both are completely unacceptable.










The only time I will use the second method with "continue", is if there is a ton of code (more than 2 but less than about 15 - otherwise it gets its own method, and we're back to scenario one without "continue") in the else block. And actually, "else" is redundant when using things like continue, break, return, etc.


----------



## {Unregistered}

Quote:


> Originally Posted by *tompsonn*
> 
> Seeing as you're being honest, I will too... LOL.
> I recon both are completely unacceptable.
> 
> 
> 
> 
> 
> 
> 
> 
> The only time I will use the second method with "continue", is if there is a ton of code (more than 2 but less than about 15 - otherwise it gets its own method, and we're back to scenario one without "continue") in the else block. And actually, "else" is redundant when using things like continue, break, return, etc.


Yea, I agree.
It's best for one to get into the habit of both writing and reading clean, neatly structured code without any added redundant statements that could have been simplified to make your code smaller. It might not affect you greatly in your student life (if your teacher doesn't care) but getting into a habit of "good" coding will be invaluable when you're programming in the real world.


----------



## tompsonn

Quote:


> Originally Posted by *{Unregistered}*
> 
> Yea, I agree.
> It's best for one to get into the habit of both writing and reading clean, neatly structured code without any added redundant statements that could have been simplified to make your code smaller. It might not affect you greatly in your student life (if your teacher doesn't care) but getting into a habit of "good" coding will be invaluable when you're programming in the real world.


In fact most teachers will go crazy if you omit the "else" block even if its redundant LOL.


----------



## Fantasy

Quote:


> Originally Posted by *{Unregistered}*
> 
> I'd say, using the first or second style is debatable *but using "== false" is absolutely unacceptable*. It's just plain wrong. Sorry, but if you were showing that code to your professor or tutor, he would give you -10,000 imaginary points for that in his head.
> Use "!" instead of "== false".


Why?!


----------



## {Unregistered}

Quote:


> Originally Posted by *Fantasy*
> 
> Why?!


Would you ever right an if conditional like...

Code:



Code:


if (formula == true)

?


----------



## Fantasy

Quote:


> Originally Posted by *{Unregistered}*
> 
> Would you ever right an if conditional like...
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> if (formula == true)
> 
> ?


Well no because this

Code:



Code:


if (formula == true)

equal this

Code:



Code:


if (formula)

But I wouldn't say its bad to do "== false". I think its more of a preference to use "!" rather than "== false".


----------



## {Unregistered}

Quote:


> Originally Posted by *Fantasy*
> 
> Well no because this
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> if (formula == true)
> 
> equal this
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> if (formula)
> 
> But I wouldn't say its bad to do "== false". I think its more of a preference to use "!" rather than "== false".


Think of this in another way.

The representation of falsity might be "false" in C# and some other languages but that's not always the case for all languages.

Some use 1 and 0 instead of true and false.
Some use True and False instead of true and false. (Note the capital letters).

If you stick to the style we've pointed out, you can use the same style without getting confused across many different languages. If you do what you're doing right now, you'll have to remember how a certain language represents the boolean values and that might get painfully confusing if you're switching between working with different languages.


----------



## Fantasy

Quote:


> Originally Posted by *{Unregistered}*
> 
> Think of this in another way.
> The representation of falsity might be "false" in C# and some other languages but that's not always the case for all languages.
> Some use 1 and 0 instead of true and false.
> Some use True and False instead of true and false. (Note the capital letters).
> If you stick to the style we've pointed out, you can use the same style without getting confused across many different languages. If you do what you're doing right now, you'll have to remember how a certain language represents the boolean values and that might get painfully confusing if you're switching between working with different languages.


That's an excellent point. Didn't think of it that way.


----------



## {Unregistered}

Quote:


> Originally Posted by *Fantasy*
> 
> That's an excellent point. Didn't think of it that way.


Glad to have been able to convince you.

My work here is done.


----------



## Fantasy

Quote:


> Originally Posted by *{Unregistered}*
> 
> Glad to have been able to convince you.
> My work here is done.


----------



## 3930K

I use ! instead of == false, mainly cos I'm lazy


----------



## 3930K

Is it a good idea to use async write and read methods if my program's not threaded?


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> Is it a good idea to use async write and read methods if my program's not threaded?


the day we can divide by 0, and not cause a wormhole.


----------



## Fantasy

Quote:


> Originally Posted by *andyroo89*
> 
> the day we can divide by 0, and not cause a wormhole.


Hahahah I loved that answer


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Is it a good idea to use async write and read methods if my program's not threaded?


Yes. Async does not mean threading necessarily. With I/O, async means that the whole task is offloaded to hardware and the CPU is left to do more work on the thread. The CPU is then woken up when the I/O hardware and subsequent drivers (i.e the "I/O subsystem") has completed (or failed, or cancelled) the request.


----------



## ripjack

Do you guys think it's better to have a little bit of knowledge in all the languages or to be really good at one.
I wouldn't call myself a programmer quite yet because all i know is VBA.

My employer is offering me a chance to go on some courses and I'm juggling which one i want to go on. Should I go on a broad programming course which covers all bases at a minimal basis, or if I should go on a VB intensive one which will go more in-depth.


----------



## deafboy

Quote:


> Originally Posted by *ripjack*
> 
> Do you guys think it's better to have a little bit of knowledge in all the languages or to be really good at one.
> I wouldn't call myself a programmer quite yet because all i know is VBA.
> My employer is offering me a chance to go on some courses and I'm juggling which one i want to go on. Should I go on a broad programming course which covers all bases at a minimal basis, or if I should go on a VB intensive one which will go more in-depth.


IMO, good at one major one (C namely). Rest kind of falls into place. Once you have one language down picking up a new one is quick. VB is meh.


----------



## andyroo89

I started with VB, and then I switched to C#, C++, Java, and python.


----------



## Bobicon

I started out in Ada then went to Python.

I recently started messing around with C++ which I will say is probably my least favorite of the three.


----------



## andyroo89

Quote:


> Originally Posted by *Bobicon*
> 
> I started out in Ada then went to Python.
> I recently started messing around with C++ which I will say is probably my least favorite of the three.


C++ can get very annoying simple mistype of a word without the proper capitalization, throws it off.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> C++ can get very annoying simple mistype of a word without the proper capitalization, throws it off.


That's not really an issue with the language, TBH.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Is it a good idea to use async write and read methods if my program's not threaded?
> 
> 
> 
> Yes. Async does not mean threading necessarily. With I/O, async means that the whole task is offloaded to hardware and the CPU is left to do more work on the thread. The CPU is then woken up when the I/O hardware and subsequent drivers (i.e the "I/O subsystem") has completed (or failed, or cancelled) the request.
Click to expand...

Thanks


----------



## Fantasy

Sometimes It takes me 10 - 15 minutes to come up with a class name. And after few days I change the name because I thought of a better one that describe what the class does.

Does this happen to you too?

Also when you hear about a class called ServerStatus. What do you think that class does?


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> Sometimes It takes me 10 - 15 minutes to come up with a class name. And after few days I change the name because I thought of a better one that describe what the class does.
> Does this happen to you too?
> Also when you hear about a class called ServerStatus. What do you think that class does?


Yeah all the time mate, don't worry you're not going insane. LOL. That's why I have ReSharper to refactor everything that depends on the new name









ServerStatus could contain information about the status of a "server", could be the result of a server request... it doesn't sound like a class that would control components of a program, more an intermediate view or window of information into an object or operation.


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Yeah all the time mate, *don't worry you're not going insane*. LOL. That's why I have ReSharper to refactor everything that depends on the new name
> 
> 
> 
> 
> 
> 
> 
> 
> ServerStatus could contain information about the status of a "server", could be the result of a server request... it doesn't sound like a class that would control components of a program, more an intermediate view or window of information into an object or operation.


that's good to hear









I just read up on ReSharper. How did I not hear about this software







Its amazing.


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> that's good to hear
> 
> 
> 
> 
> 
> 
> 
> 
> I just read up on ReSharper. How did I not hear about this software
> 
> 
> 
> 
> 
> 
> 
> Its amazing.


Haha!
Its worth the cash. Which isn't even that much.


----------



## Fantasy

I was using a software that increment my build version every time I build my program. Since the software only support VS 2010 I was hoping any of you know another software that does the same thing with VS 2012.

Here is the software that I used in VS 2010.
http://autobuildversion.codeplex.com/


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> I was using a software that increment my build version every time I build my program. Since the software only support VS 2010 I was hoping any of you know another software that does the same thing with VS 2012.
> Here is the software that I used in VS 2010.
> http://autobuildversion.codeplex.com/


Yeah, the software that supports it is Visual Studio. Using ClickOnce it can increment. Otherwise it can generate build numbers. http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.aspx

Also if that is an add-in for VS, you can hack the manifest so it installs on VS 2012.


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Yeah, the software that supports it is Visual Studio. Using ClickOnce it can increment. Otherwise it can generate build numbers. http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.aspx
> Also if that is an add-in for VS, you can hack the manifest so it installs on VS 2012.


thanks


----------



## Fantasy

Can someone explain why VS 2012 ultimate cost $14,000


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> Can someone explain why VS 2012 ultimate cost $14,000


Because it is not for solo-developers. You won't use the features of Ultimate unless you are in an organizational programming team (including using Team Foundation Server)


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Because it is not for solo-developers. You won't use the features of Ultimate unless you are in an organizational programming team (including using Team Foundation Server)


That make sense.


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> That make sense.


You may be able to get it via MSDN/Technet or DreamSpark, though


----------



## Fantasy

I think this is a good read.

String vs string in C#
http://stackoverflow.com/questions/7074/what-is-the-difference-between-string-and-string


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> I think this is a good read.
> String vs string in C#
> http://stackoverflow.com/questions/7074/what-is-the-difference-between-string-and-string


Indeed. Personally I keep everything consistent and use "string" everywhere.


----------



## 3930K

Which version of VS is best for me? (With ReSharper)

I'm a hobbyist who likes to do C# and C++, and is considering doing some freelance work.

I don't have access to much money though (about £500)

I could get Dreamspark but it's massive trouble because my school's not registered. I gave up after 3 weeks of fruitless work.


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> Which version of VS is best for me? (With ReSharper)
> I'm a hobbyist who likes to do C# and C++, and is considering doing some freelance work.
> I don't have access to much money though (about £500)
> I could get Dreamspark but it's massive trouble because my school's not registered. I gave up after 3 weeks of fruitless work.


Well you can get the Express edition which is free. or you can get the Pro version for $1200.

right now i'm using the pro edition which is great.

so my advice is, get the professional edition.

[edit]
The express edition does not support plugins. So you won't be able to install ReSharper.


----------



## ripjack

Quote:


> Originally Posted by *deafboy*
> 
> Quote:
> 
> 
> 
> Originally Posted by *ripjack*
> 
> Do you guys think it's better to have a little bit of knowledge in all the languages or to be really good at one.
> I wouldn't call myself a programmer quite yet because all i know is VBA.
> My employer is offering me a chance to go on some courses and I'm juggling which one i want to go on. Should I go on a broad programming course which covers all bases at a minimal basis, or if I should go on a VB intensive one which will go more in-depth.
> 
> 
> 
> IMO, good at one major one (C namely). Rest kind of falls into place. Once you have one language down picking up a new one is quick. VB is meh.
Click to expand...

Cool thanks







. I'll try and see if they offer a more C intensive course


----------



## 3930K

Quote:


> Originally Posted by *Fantasy*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Which version of VS is best for me? (With ReSharper)
> I'm a hobbyist who likes to do C# and C++, and is considering doing some freelance work.
> I don't have access to much money though (about £500)
> I could get Dreamspark but it's massive trouble because my school's not registered. I gave up after 3 weeks of fruitless work.
> 
> 
> 
> Well you can get the Express edition which is free. or you can get the Pro version for $1200.
> 
> right now i'm using the pro edition which is great.
> 
> so my advice is, get the professional edition.
> 
> [edit]
> The express edition does not support plugins. So you won't be able to install ReSharper.
Click to expand...

Damn, I need to get another 350odd pounds.


----------



## deafboy

I always hate coming up with personal projects, lol.

Ideas on an interesting project to brush up on C++ and python? Will be doing this in linux if it means anything to ya


----------



## 3930K

Quote:


> Originally Posted by *deafboy*
> 
> I always hate coming up with personal projects, lol.
> 
> Ideas on an interesting project to brush up on C++ and python? Will be doing this in linux if it means anything to ya


Custom XML parser that ignores everthing that is not an endelement, startelement, or text and can be configured to only parse preset elements?


----------



## andyroo89

Does anyone know in Eclipse how I can make my own update? As in when I load my program it will check for an update it will download the update from my pc like its a server?


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Does anyone know in Eclipse how I can make my own update? As in when I load my program it will check for an update it will download the update from my pc like its a server?


You could write a web service that runs on your PC or a server somewhere. When your program starts it talks to that web service and checks if a new version is available (by supplying the current version of the program). If there is the web service can reply with the URL to download the new version which your program can then download itself or send the user to in a web browser.

This is really not IDE-specific. I don't know Eclipse so unsure if it has anything built in, but this is how I've been doing it with all my applications.


----------



## andyroo89

OK, thanks, tompsonn


----------



## andyroo89

Ok, I ran into a problem. I am trying to make a program to transfer files off of my usb stick (this is in android on my tablet) into the internal memory. I am using fileinputstream and it is not working. Do I need to add code to give me SU?


----------



## qhduong92

Quote:


> Originally Posted by *ripjack*
> 
> Do you guys think it's better to have a little bit of knowledge in all the languages or to be really good at one.
> I wouldn't call myself a programmer quite yet because all i know is VBA.
> My employer is offering me a chance to go on some courses and I'm juggling which one i want to go on. Should I go on a broad programming course which covers all bases at a minimal basis, or if I should go on a VB intensive one which will go more in-depth.


I would learn and get comfortable with one compiled language like Java or C++, and a scripting language like Ruby or Python. I really wouldn't jump straight into C...


----------



## andyroo89

Quote:


> Originally Posted by *andyroo89*
> 
> Ok, I ran into a problem. I am trying to make a program to transfer files off of my usb stick (this is in android on my tablet) into the internal memory. I am using fileinputstream and it is not working. Do I need to add code to give me SU?


I am giving up on this, it only works if I specify a certain filename. I wanted to make it to where it will copy all the files without need to specify a filename. :/ Seems to be impossible, I checked google 40 times, all the links I clicked on almost turned another color from purple since I clicked on them so many times.


----------



## 3930K

Where is the goddamn Ribbons namespace...


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Where is the goddamn Ribbons namespace...


Ribbons?


----------



## andyroo89

Can anyone guide me to noob friend guide towards threading or a sync task? I found out the hard way while I was progamming that I cannot write code on ui thread, and have to do it in async task or threading.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Can anyone guide me to noob friend guide towards threading or a sync task? I found out the hard way while I was progamming that I cannot write code on ui thread, and have to do it in async task or threading.


You can write code on the UI thread, just not code that hangs the UI









If you are using .NET < 4.5 its best to use the Task Parallel Library. If .NET 4.5, you better use async and await.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Where is the goddamn Ribbons namespace...
> 
> 
> 
> Ribbons?
Click to expand...


----------



## tompsonn

Quote:


> Originally Posted by *3930K*


I know what it is LOL.

There is no native ribbon support for .NET.

You will need to use a wrapper that uses the native, unmanaged, Win32 Ribbon APIs (works on Vista SP2+ with an additional update, or Windows 7 and higher). - http://windowsribbon.codeplex.com/releases/view/32943

Alternatively you can use one of the many third party ribbon implementations for WPF or Windows Forms.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> I know what it is LOL.
> 
> There is no native ribbon support for .NET.
> 
> You will need to use a wrapper that uses the native, unmanaged, Win32 Ribbon APIs (works on Vista SP2+ with an additional update, or Windows 7 and higher). - http://windowsribbon.codeplex.com/releases/view/32943
> 
> Alternatively you can use one of the many third party ribbon implementations for WPF or Windows Forms.
Click to expand...

What?

It was there before!

Both as an xml schema and a clr namespace!


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> What?
> It was there before!
> Both as an xml schema and a clr namespace!












It is available as an installable control for WPF - http://msdn.microsoft.com/en-us/library/ff799534%28v=vs.100%29.aspx

Are you using WPF?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> What?
> It was there before!
> Both as an xml schema and a clr namespace!
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> It is available as an installable control for WPF - http://msdn.microsoft.com/en-us/library/ff799534%28v=vs.100%29.aspx
> 
> Are you using WPF?
Click to expand...

Uep, I am, but I never knew you had to download it


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Uep, I am, but I never knew you had to download it


Ya do


----------



## 3930K

Damn you RibbonControlsLibrary. HOW DO YOU ADD A REFERENCE TO IT IN XAML!


----------



## tompsonn

Quote:


> Note: There are a large number of design revisions in this release since the CTP version. This is mainly to facilitate MVVM-centric applications.
> 
> Install location: Ribbon binaries and sources are installed under the Program Files directory.
> 
> On x86 computers, %ProgramFiles%\Microsoft Ribbon for WPF\
> On AMD64 computers, %ProgramFiles(x86)%\Microsoft Ribbon for WPF\
> 
> Design-time: The MSI will install design-time support for Visual Studio 2010 and Expression Blend 4. This includes a project template for a 'WPF Ribbon Application', an item template for a 'Ribbon Window', and Ribbon controls in the toolbox such as, RibbonButton, RibbonToggleButton, RibbonMenuButton, etc.


http://www.microsoft.com/en-us/download/details.aspx?id=11877


----------



## 3930K

No, I just found out that .NET4.5 has ribbons built in. However...

Code:



Code:


Error        2       RibbonWindow is not supported in a Windows Presentation Foundation (WPF) project.


----------



## tompsonn

Are you targeting 4.5 though?
System.Windows.Controls.Ribbon is where it is located.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Are you targeting 4.5 though?
> System.Windows.Controls.Ribbon is where it is located.


Yeah, I am.
But I only have Controls.Primitives... This is VS Express 2012.


----------



## 3930K

Quote:


> Originally Posted by *3930K*
> 
> Quote:
> 
> 
> 
> Originally Posted by *tompsonn*
> 
> Are you targeting 4.5 though?
> System.Windows.Controls.Ribbon is where it is located.
> 
> 
> 
> Yeah, I am.
> But I only have Controls.Primitives... This is VS Express 2012.
Click to expand...

I still have this problem... and more.
I tried this: (in a Startup method)

Code:



Code:


this.StartupUri = new Uri("MainWindow.xaml");

But that REFUSES to work. Invalid URI, invalid URI, etc etc. But that's the same URI as they put in the XAML! (if you leave it there).









EDIT: All I needed to do was to put UriKind.Relative in the constructor as well. Damn.


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> You can write code on the UI thread, just not code that hangs the UI
> 
> 
> 
> 
> 
> 
> 
> 
> If you are using .NET < 4.5 its best to use the Task Parallel Library. If .NET 4.5, you better use async and await.


I am sorry I forgot to mention this is for android development on 3.0+


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Yeah, I am.
> But I only have Controls.Primitives... This is VS Express 2012.


Make sure your project is referencing System.Windows.Controls.Ribbon.dll
Quote:


> Originally Posted by *3930K*
> 
> I still have this problem... and more.
> I tried this: (in a Startup method)
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> this.StartupUri = new Uri("MainWindow.xaml");
> 
> But that REFUSES to work. Invalid URI, invalid URI, etc etc. But that's the same URI as they put in the XAML! (if you leave it there).
> 
> 
> 
> 
> 
> 
> 
> 
> EDIT: All I needed to do was to put UriKind.Relative in the constructor as well. Damn.











Quote:


> Originally Posted by *andyroo89*
> 
> I am sorry I forgot to mention this is for android development on 3.0+


Ah. Can't help you there I'm afraid


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Yeah, I am.
> But I only have Controls.Primitives... This is VS Express 2012.
> 
> 
> 
> Make sure your project is referencing System.Windows.Controls.Ribbon.dll
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> I still have this problem... and more.
> I tried this: (in a Startup method)
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> this.StartupUri = new Uri("MainWindow.xaml");
> 
> But that REFUSES to work. Invalid URI, invalid URI, etc etc. But that's the same URI as they put in the XAML! (if you leave it there).
> 
> 
> 
> 
> 
> 
> 
> 
> EDIT: All I needed to do was to put UriKind.Relative in the constructor as well. Damn.
> 
> Click to expand...
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Quote:
> 
> 
> 
> Originally Posted by *andyroo89*
> 
> I am sorry I forgot to mention this is for android development on 3.0+
> 
> Click to expand...
> 
> Ah. Can't help you there I'm afraid
Click to expand...

Where? In the AssemblyInformation?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Where? In the AssemblyInformation?


In your project references (References -> Add Reference).


----------



## 3930K

OK, I have another problem:

Code:



Code:


var loadNext = new (inherits from Window)();
            loadNext.Show();
            this.Close();

What I want is loadNext to be in the same location on the screen as this.


----------



## 3930K

Quote:


> Originally Posted by *3930K*
> 
> OK, I have another problem:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> var loadNext = new (inherits from Window)();
> loadNext.Show();
> this.Close();
> 
> What I want is loadNext to be in the same location on the screen as this.


Help?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Help?


Need to set WindowStartupLocation, Height, Width, Left, and Top


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Help?
> 
> 
> 
> Need to set WindowStartupLocation, Height, Width, Left, and Top
Click to expand...

Thanks!


----------



## 3930K

Visual Studio what in heaven's sake is wrong with you?

Builds a project, presses start, VS freezes, recovers in 5 minutes, says access is denied, accesses file manually, runs flawlessly.

WHY?


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> Visual Studio what in heaven's sake is wrong with you?
> Builds a project, presses start, VS freezes, recovers in 5 minutes, says access is denied, accesses file manually, runs flawlessly.
> WHY?


VS is evolving... kill it. Kill it with fire.


----------



## 3930K

Quote:


> Originally Posted by *Fantasy*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Visual Studio what in heaven's sake is wrong with you?
> Builds a project, presses start, VS freezes, recovers in 5 minutes, says access is denied, accesses file manually, runs flawlessly.
> WHY?
> 
> 
> 
> VS is evolving... kill it. Kill it with fire.
Click to expand...











Note to self: ALWAYS run VS w/ admin privileges.


----------



## 3930K

Can someone tell me what an installer actually does?

I need to know it all. (Including where to modify the registry, etc.)

inb4 someone tells me to use WiX, that's sadly not an option right now.


----------



## 3930K

Code:



Code:


Bump bump = new Bump();
bump.BumpThread("Programmer's lounge");


----------



## tompsonn

Why cant' you use WiX? LOL

Um. I'm not sure of all the intrinsic... however depending on your version of VS, it may have come with InstallShield LE (and I think VS 10 and lower have their own set up projects).


----------



## Fantasy

I just heard of an amazing book. If you love the following then you should definitely buy it or listen to the audio version read by the one and only Wil Wheaton.


Do you love games?
Do you love si-fi?
Do you love programming?
Do you love game programming?
Do you love John Carmack and DOOM and Quake and Id software?
then you should definitely read Masters of Doom or listen to the audio version.

I just thought I would share this with everyone









Hope you like it as much as I do.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Why cant' you use WiX? LOL
> 
> Um. I'm not sure of all the intrinsic... however depending on your version of VS, it may have come with InstallShield LE (and I think VS 10 and lower have their own set up projects).


I can't use ANY off the shelf installers. I HAVE to make it myself.


----------



## deafboy

Quote:


> Originally Posted by *Fantasy*
> 
> VS is evolving... kill it. Kill it with fire.


----------



## Fantasy

Quote:


> Originally Posted by *deafboy*












You too didn't like the new UI huu...









You should have pressed B to stop VS from evolving.


----------



## tompsonn

Dunno what ya'll complaining about.. VS 11 is the best release yet.


----------



## deafboy

Quote:


> Originally Posted by *Fantasy*
> 
> 
> 
> 
> 
> 
> 
> 
> 
> You too didn't like the new UI huu...
> 
> 
> 
> 
> 
> 
> 
> 
> You should have pressed B to stop VS from evolving.


Haven't used it, just thought I would make that for LOLs. Been playing my old gameboy lately, lol
Quote:


> Originally Posted by *tompsonn*
> 
> Dunno what ya'll complaining about.. VS 11 is the best release yet.


I honestly haven't used it in years, but that's good to hear...


----------



## Fantasy

Quote:


> Originally Posted by *deafboy*
> 
> Haven't used it, just thought I would make that for LOLs. *Been playing my old gameboy lately, lol*
> I honestly haven't used it in years, but that's good to hear...


Me too. Actually I have been playing pokemon red and blue on a gameboy emulator on my galaxy note 2







lots of childhoodh memories.
Quote:


> Originally Posted by *tompsonn*
> 
> Dunno what ya'll complaining about.. VS 11 is the best release yet.


Just joking







although many people don't like the new UI.


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> Just joking
> 
> 
> 
> 
> 
> 
> 
> although many people don't like the new UI.


Hehehe seems to be the main thing with Microsoft software releases this year doesn't it?


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Hehehe seems to be the main thing with Microsoft software releases this year doesn't it?


Yah









Its 21-12-12. We're still alive. Whoooooo.







dam. Now I have to pay my parking tickets.


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> Yah
> 
> 
> 
> 
> 
> 
> 
> 
> Its 21-12-12. We're still alive. Whoooooo.
> 
> 
> 
> 
> 
> 
> 
> dam. Now I have to pay my parking tickets.


----------



## deafboy

Quote:


> Originally Posted by *Fantasy*
> 
> Me too. Actually I have been playing pokemon red and blue on a gameboy emulator on my galaxy note 2
> 
> 
> 
> 
> 
> 
> 
> lots of childhoodh memories.
> Just joking
> 
> 
> 
> 
> 
> 
> 
> although many people don't like the new UI.


Been playing a lot of Red. haha Good times.
Quote:


> Originally Posted by *tompsonn*
> 
> Hehehe seems to be the main thing with Microsoft software releases this year doesn't it?


Yes, yes it does...lol
Quote:


> Originally Posted by *Fantasy*
> 
> Yah
> 
> 
> 
> 
> 
> 
> 
> 
> Its 21-12-12. We're still alive. Whoooooo.
> 
> 
> 
> 
> 
> 
> 
> dam. Now I have to pay my parking tickets.


----------



## andyroo89

ok, android programming is little annoying, and I was told if you have java programming knowledge it will be less annoying, and be easier to do. Which I don't blame them since android is based off of java.


----------



## Fantasy

I'm sorry . I'm so sorry







I know. I know what I said. But I couldn't help it. I just couldn't. I had to do it. It was looking right at me. It looked through me. IT WAS LOOKING AT MY SOUL







and I picked it up from the shelf and







...

Before I know it I was home. and I somehow managed to pass out. and when I woke up, I was hoping it was all a dream. but it wasn't







I tried to force my self to take it back, but I couldn't. It was whispering to me. It was TALKING TO ME







It said, "Install me. Install me". and I couldn't resist.

So now I have it. ITS LIVING IN MY COMPUTER
















HELP ME

















Spoiler: Warning: Spoiler!


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> I'm sorry . I'm so sorry
> 
> 
> 
> 
> 
> 
> 
> I know. I know what I said. But I couldn't help it. I just couldn't. I had to do it. It was looking right at me. It looked through me. IT WAS LOOKING AT MY SOUL
> 
> 
> 
> 
> 
> 
> 
> and I picked it up from the shelf and
> 
> 
> 
> 
> 
> 
> 
> ...
> Before I know it I was home. and I somehow managed to pass out. and when I woke up, I was hoping it was all a dream. but it wasn't
> 
> 
> 
> 
> 
> 
> 
> I tried to force my self to take it back, but I couldn't. It was whispering to me. It was TALKING TO ME
> 
> 
> 
> 
> 
> 
> 
> It said, "Install me. Install me". and I couldn't resist.
> So now I have it. ITS LIVING IN MY COMPUTER
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> HELP ME
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Spoiler: Warning: Spoiler!


Well done







I'm developing on it in a virtual machine because my physical Win 7 box keeps failing the upgrade, so I gave up.


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Well done
> 
> 
> 
> 
> 
> 
> 
> I'm developing on it in a virtual machine because my physical Win 7 box keeps failing the upgrade, so I gave up.


ohh sorry to hear that. Well after you return the start button and forget the fact that the metro UI exist, then it becomes a much better and fast version of windows 7. I mean honestly windows 8 is an amazing OS if you could return the start button. which you could









anyways i'm loving it. and now its time to install VS 11 pro


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> ohh sorry to hear that. Well after you return the start button and forget the fact that the metro UI exist, then it becomes a much better and fast version of windows 7. I mean honestly windows 8 is an amazing OS if you could return the start button. which you could
> 
> 
> 
> 
> 
> 
> 
> 
> anyways i'm loving it. and now its time to install VS 11 pro


I'm on the other side - Start Screen is where it is all at for me








But at least there's enough third-party stuff now for those who aren't.

VS 2012 is great on Windows 8, too


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> I'm on the other side - Start Screen is where it is all at for me
> 
> 
> 
> 
> 
> 
> 
> 
> But at least there's enough third-party stuff now for those who aren't.
> VS 2012 is great on Windows 8, too


yap


----------



## Fantasy

sorry for the double post


----------



## Blue Green

Quote:


> Originally Posted by *andyroo89*
> 
> ok, android programming is little annoying, and I was told if you have java programming knowledge it will be less annoying, and be easier to do. Which I don't blame them since android is based off of java.


Whoever said Android programming is annoying, clearly has never tried J2ME programming







(







)


----------



## Fantasy

lets say I have a class called "Client". is there a way in VS 2010 to see where is this class called? Because I have more than 90 classes in my project and i'm going to go through each one to see if this class is called in any of them.


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> lets say I have a class called "Client". is there a way in VS 2010 to see where is this class called? Because I have more than 90 classes in my project and i'm going to go through each one to see if this class is called in any of them.


Not that I know of. Although you can do a CTRL+F for the whole solution. Otherwise ReSharper has a thing called "Find usages" (you right click on the class name and choose Find usages - it shows you every place that declaration is referenced).


----------



## g00glen00b

If I remember correctly, you can view the call hierarchy (you need the Call hierarchy view/window to be open). But afaik that's on method level (so you can see where a specific method is called), not an entire class.
http://msdn.microsoft.com/en-us/library/dd409859.aspx


----------



## poroboszcz

Something really cool I've found today:
https://en.wikipedia.org/wiki/Fast_inverse_square_root


----------



## andyroo89

Quote:


> Originally Posted by *poroboszcz*
> 
> Something really cool I've found today:
> https://en.wikipedia.org/wiki/Fast_inverse_square_root


The comments made me lol. Thanks for the link.


----------



## Fantasy

Hay guys,

Its 12:05 2013 here in Dubai. Happy new year to everyone. may all your hopes, wishes and dreams come true. And may you have all the health and happiness in the world. God bless you all and happy new year.


----------



## andyroo89

Quote:


> Originally Posted by *Fantasy*
> 
> Hay guys,
> Its 12:05 2013 here in Dubai. Happy new year to everyone. may all your hopes, wishes and dreams come true. And may you have all the health and happiness in the world. God bless you all and happy new year.


I have a question, is it true you will see abandoned ferraris lamborghinis and other high end cars on side of the road collecting dust?


----------



## {Unregistered}

Quote:


> Originally Posted by *Fantasy*
> 
> Hay guys,
> Its 12:05 2013 here in Dubai. Happy new year to everyone. may all your hopes, wishes and dreams come true. And may you have all the health and happiness in the world. God bless you all and happy new year.











Quote:


> Originally Posted by *andyroo89*
> 
> I have a question, is it true you will see abandoned ferraris lamborghinis and other high end cars on side of the road collecting dust?


No, he will most probably not.


----------



## Fantasy

Quote:


> Originally Posted by *andyroo89*
> 
> I have a question, is it true you will see abandoned ferraris lamborghinis and other high end cars on side of the road collecting dust?


AHahahhah lol. who told you that







No No that is not true.

The only place I have seen that was in the police department where they impound cars. For example when a guy buys a half million dollar car and can't pay all the money, the police comes and takes his car and impound it. or a stolen car that get impound or someone who have tickets worth more than his Ferrari and doesn't pay them his car get impounded.

After a while the police sells these cars and pay the tickets and they give the rest to charity.

honestly I cried when I saw this.

Quote:


> The Ferrari Enzo, wanted by Interpol, was seized by the CID. Its British owner had left it in the parking lot for more than 20 months after traffic fines had piled up," Al Zaffin said.


Full Story


----------



## 3930K

Code:



Code:


for(;;)
{
if (DateTime.Now.Year == 2013) break;
Thread.Sleep(2);
}
MessageBox.Show("Happy new year!");


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> for(;;)
> {
> if (DateTime.Now.Year == 2013) break;
> Thread.Sleep(2);
> }
> Messagebox.Show("Happy new year!");


Unfortunately that won't compile


----------



## 3930K

I'm guessing it's because it's not in a static void main(string[] args)


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I'm guessing it's because it's not in a static void main(string[] args)


Nah (well that too LOL), but mainly because Messagebox is spelled wrong







(MessageBox)


----------



## 3930K




----------



## tompsonn

Quote:


> Originally Posted by *3930K*


It's OK - my brain can compile code... which is a bad thing sometimes.

Actually the other day I was reciting some code I had written the previous night during a day dreaming session and discovered a bug.

Most people say I'm not human


----------



## 3930K

How complex? I can't do programming when I'm sleepy, I wake up the next morning with 100 errors :/


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Nah (well that too LOL), but mainly because Messagebox is spelled wrong
> 
> 
> 
> 
> 
> 
> 
> (MessageBox)











Quote:


> Originally Posted by *tompsonn*
> 
> It's OK - my brain can compile code... which is a bad thing sometimes.
> Actually the other day I was reciting some code I had written the previous night during a day dreaming session and discovered a bug.
> Most people say I'm not human


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> How complex? I can't do programming when I'm sleepy, I wake up the next morning with 100 errors :/


I haven't done any coding for more than 2 weeks. I feel my project is staring to choke me little by little. I started to get really bored of programming.


----------



## {Unregistered}

Quote:


> Originally Posted by *Fantasy*
> 
> I haven't done any coding for more than 2 weeks. I feel my project is staring to choke me little by little. I started to get really bored of programming.


Don't let it get to you.


----------



## Fantasy

Quote:


> Originally Posted by *{Unregistered}*
> 
> Don't let it get to you.


How? I have tried almost everything to blow off some steam but I just can't code any more. I went out with my friends. I played every game I love. I watched every movie I love. but I still can't get my self to sit and code.

I don't know what else to do.


----------



## 3930K

@Fantasy: I would help but I don't know how :/

While I'm here, I might as well recommend Minify. Great code editor for WinRT. Unfortunately it doesn't support XAML.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> How complex? I can't do programming when I'm sleepy, I wake up the next morning with 100 errors :/


Not very complex








Anyway I sometimes have that problem... I write code a lot drunk too... Its not as bad as you might think either!
Quote:


> Originally Posted by *Fantasy*
> 
> I haven't done any coding for more than 2 weeks. I feel my project is staring to choke me little by little. I started to get really bored of programming.


I get like this too.
Quote:


> Originally Posted by *Fantasy*
> 
> How? I have tried almost everything to blow off some steam but I just can't code any more. I went out with my friends. I played every game I love. I watched every movie I love. but I still can't get my self to sit and code.
> I don't know what else to do.


This is normal. Try something programming something new. Watch programming videos. No seriously, head over to Channel 9 (channel9.msdn.com). I've watched programming videos there and without fail - inspiration.
Quote:


> Originally Posted by *3930K*
> 
> @Fantasy: I would help but I don't know how :/
> While I'm here, I might as well recommend Minify. Great code editor for WinRT. Unfortunately it doesn't support XAML.


No XAML, no potatoes


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> How complex? I can't do programming when I'm sleepy, I wake up the next morning with 100 errors :/
> 
> 
> 
> Not very complex
> 
> 
> 
> 
> 
> 
> 
> 
> Anyway I sometimes have that problem... I write code a lot drunk too... Its not as bad as you might think either!
> Quote:
> 
> 
> 
> Originally Posted by *Fantasy*
> 
> I haven't done any coding for more than 2 weeks. I feel my project is staring to choke me little by little. I started to get really bored of programming.
> 
> Click to expand...
> 
> I get like this too.
> Quote:
> 
> 
> 
> Originally Posted by *Fantasy*
> 
> How? I have tried almost everything to blow off some steam but I just can't code any more. I went out with my friends. I played every game I love. I watched every movie I love. but I still can't get my self to sit and code.
> I don't know what else to do.
> 
> 
> 
> 
> 
> 
> 
> 
> Click to expand...
> 
> This is normal. Try something programming something new. Watch programming videos. No seriously, head over to Channel 9 (channel9.msdn.com). I've watched programming videos there and without fail - inspiration.
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> @Fantasy: I would help but I don't know how :/
> While I'm here, I might as well recommend Minify. Great code editor for WinRT. Unfortunately it doesn't support XAML.
> 
> Click to expand...
> 
> No XAML, no potatoes
Click to expand...

It does support XML which makes it absolutely no difference as w/o Intellisense or window preview they are the same


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> It does support XML which makes it absolutely no difference as w/o Intellisense or window preview they are the same


I'll stick with Blend for XAML, thanks


----------



## 3930K

They put Blend on WinRT?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> They put Blend on WinRT?


Oh you meant actually FOR WinRT. LOL.

I took it as a code editor for WinRT as in... for creating WinRT apps. Not to run on WinRT.

/erasethetape

EDIT: Flippin hell this app is great. Now ... where's my Git and SVN clients for WinRT


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> They put Blend on WinRT?
> 
> 
> 
> Oh you meant actually FOR WinRT. LOL.
> 
> I took it as a code editor for WinRT as in... for creating WinRT apps. Not to run on WinRT.
> 
> /erasethetape
> 
> EDIT: Flippin hell this app is great. Now ... where's my Git and SVN clients for WinRT
Click to expand...

MetroGist lets you sync with GitHub Gists, but that's it. Nothing for SVN.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> MetroGist lets you sync with GitHub Gists, but that's it. Nothing for SVN.


Ah to hell with it, I can't do any serious development outside of VS. I've been too spoiled since I switched to it :/


----------



## 3930K

I can still manage it but it's slipping away. RDP TO THE RESCUE!


----------



## General121

Hey guys, I'm going through school, currently just high school, but wondering if programming such as Java programming is easy/able to find a job for once I go through college? And what kind of money does a programmer for Java or just general application programming make?


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> This is normal. Try something programming something new. Watch programming videos. No seriously, head over to Channel 9 (channel9.msdn.com). I've watched programming videos there and without


this site it awesome. thanks








Quote:


> Originally Posted by *General121*
> 
> Hey guys, I'm going through school, currently just high school, but *wondering if programming such as Java programming is easy/able to find a job for once I go through college?* And *what kind of money does a programmer for Java or just general application programming make*?



That also depends on which country you live in and how good your grades in college are.
That really depends on which country you live in. for example in my country a fresh graduate from college will get paid from $1500 - $3000 a month.


----------



## General121

Well I'm in the US and am looking to get into VT if that says anything about grades


----------



## g00glen00b

In Belgium you usually need to be graduated from college to find a job like a developer. Most people I know that dropped out of college only found jobs in the ICT helpdesk sector.
I (as a Junior Java developer) earn around €1900 but with a lot of extras like a car (with fuel card), a laptop, mobile subscription, some insurances, a mobile subscription, ... .

But like Fantasy said, many of those things depend on your grades. The top students will usually get enough job offers to find a job even before graduating. The other students will also find a job pretty soon (even the ones that didn't do that well) but companies aren't stupid, they will notice soon enough who is a hard/good developer and who isn't.


----------



## Fantasy

I thought this is interesting for beginners who want to learn coding.

http://www.codeyear.com/

http://www.codinghorror.com/blog/2012/05/please-dont-learn-to-code.html


----------



## deafboy

Out of curiosity... what's the longest break you've guys taken from programming?

I think my longest was ~4 months...although I might beat that, on a bit of a break if you will Sometimes you just have to take a step back lol.


----------



## tompsonn

Quote:


> Originally Posted by *deafboy*
> 
> Out of curiosity... what's the longest break you've guys taken from programming?
> I think my longest was ~4 months...although I might beat that, on a bit of a break if you will Sometimes you just have to take a step back lol.


I take a break for about 9 hours from about 11PM to about 8AM







I think my longest was about 12 hours - good breakfast that morning.


----------



## Fantasy

Quote:


> Originally Posted by *deafboy*
> 
> Out of curiosity... what's the longest break you've guys taken from programming?
> I think my longest was ~4 months...although I might beat that, on a bit of a break if you will Sometimes you just have to take a step back lol.


The longest break for me was 2 weeks and 3 days. Even though I didn't write any code, I was still thinking about how to solve code problems that were in my software. My brain is always trying to solve code problems even when I'm playing games or watching a movie. Honestly its really annoying sometimes.


----------



## deafboy

Pretty sure it's impossible to not think about problem solving...it can certainly be annoying at times.


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> The longest break for me was 2 weeks and 3 days. Even though I didn't write any code, I was still thinking about how to solve code problems that were in my software. My brain is always trying to solve code problems even when I'm playing games or watching a movie. Honestly its really annoying sometimes.


Oh yeah, he's one of us








Quote:


> Originally Posted by *deafboy*
> 
> Pretty sure it's impossible to not think about problem solving...it can certainly be annoying at times.


You are right, however you've just caused me a stack overflow - I tried to think about solving the problem about not thinking about problem solving. Good one.


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Oh yeah, he's one of us


----------



## deafboy

Quote:


> Originally Posted by *tompsonn*
> 
> Oh yeah, he's one of us
> 
> 
> 
> 
> 
> 
> 
> 
> You are right, however you've just caused me a stack overflow - I tried to think about solving the problem about not thinking about problem solving. Good one.


Damn it, now I have to debug you...


----------



## tompsonn

Quote:


> Originally Posted by *deafboy*
> 
> Damn it, now I have to debug you...


Well set a breakpoint on me because I'm all bugged out!


----------



## 3930K

Quote:


> Originally Posted by *deafboy*
> 
> Out of curiosity... what's the longest break you've guys taken from programming?
> I think my longest was ~4 months...although I might beat that, on a bit of a break if you will Sometimes you just have to take a step back lol.


For me one week, on a cruise ship with nothing to code on









I still spent most of my time while on the boat typing awy on my phone. I made a 2K words OneNote document









@Fantasy: Yeah that happens to me too!


----------



## deafboy

Quote:


> Originally Posted by *tompsonn*
> 
> Well set a breakpoint on me because I'm all bugged out!


Permission to step in


----------



## Fantasy

I have never use enum. So which one of these styles would you use?

Code:



Code:


if(login)
    Player.IsOnline = true;

or

Code:



Code:


enum PlayerStatus{Offline, Online};

if(login)
     Player.Status = PlayerStatus.Online;


----------



## 3930K

Quote:


> Originally Posted by *Fantasy*
> 
> I have never use enum. So which one of these styles would you use?
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> if(login)
> Player.IsOnline = true;
> 
> or
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> enum PlayerStatus{Offline, Online};
> 
> if(login)
> Player.Status = PlayerStatus.Online;


Bool covers that, I think.

Enums are more for thing that cover more than 2, for example, UriKind, Color, MessageBoxImage, etc.


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> Bool covers that, I think.
> 
> Enums are more for thing that cover more than 2, for example, UriKind, Color, MessageBoxImage, etc.


hmm... I see.


----------



## farmdve

I am just a hobbyist, a few weeks ago I decided to hop into the game development wagon and see what's there. I made, with the help of SDL and C a small not-yet-a-game program. I could move a character, shoot something that may be interpreted as a bullet and collision detection.

Needless to say, it ended up an ugly ugly mess. I personally have over a year of experience with C and none with none, however I realized that any kind of game, be it 2D or 3D should be in C++.

Obviously I was eager to start with 3D right off the bat, but 2D was hard to begin with.


----------



## Fantasy

Quote:


> Originally Posted by *farmdve*
> 
> I am just a hobbyist, a few weeks ago I decided to hop into the game development wagon and see what's there. I made, with the help of SDL and C a small not-yet-a-game program. I could move a character, shoot something that may be interpreted as a bullet and collision detection.
> 
> Needless to say, it ended up an ugly ugly mess. I personally have over a year of experience with C and none with none, however I realized that any kind of game, be it 2D or 3D should be in C++.
> 
> Obviously I was eager to start with 3D right off the bat, but 2D was hard to begin with.


If your going to use C++ then I think SFML is the way to go. It syntax is like C++ and its very easy and clean library to use. However I would recommend you take a look at XNA and C#. They will save you a lot of time that would be wasted in C++ trying to create code that was already created for you in C# and XNA.


----------



## farmdve

Well, I like to write everything from scratch. My plan is to eventually create my own engine with scripting and everything.


----------



## Fantasy

Quote:


> Originally Posted by *farmdve*
> 
> Well, I like to write everything from scratch. My plan is to eventually create my own engine with scripting and everything.


hahaha. I was just like you. but after a year I decided to actually make something useful and stop reinventing the wheel.

But I have to say, I think reinventing the wheel made me a better programmer. Because now I have a deep understand of how things work.

I don't think its a bad thing, but I would not necessarily recommend it.

Give this a read.

Good luck


----------



## farmdve

I've read that, quite a lot. However I must disagree today, in ~6 years, things have changed a lot.


----------



## Delphiwizard

I'm just curious, are there any other developers here that use the devexpress components?


----------



## 3930K

^They look awesome, but they're mighty expensive. Maybe when programming is my actual job


----------



## tompsonn

Quote:


> Originally Posted by *Delphiwizard*
> 
> I'm just curious, are there any other developers here that use the devexpress components?


Yeah I use DevExpress. I got mine for free


----------



## Delphiwizard

Cool, i use the VCL subscription myself (delphi components), been using them for like a decade.
I never used the visual studio components though but i assume they are equally good.


----------



## 3930K

Just a question: ways on how to stop yourself from web-browsing too much? I haven't done any programming today, I was webrowsing


----------



## 3930K

Nothing?


----------



## {Unregistered}

Quote:


> Originally Posted by *3930K*
> 
> Nothing?


The answer comes from within, young one.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Just a question: ways on how to stop yourself from web-browsing too much? I haven't done any programming today, I was webrowsing


Write your own web-browser. Both problems solved.


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Write your own web-browser. Both problems solved.


haha lol


----------



## Fantasy

I haven't done any work this week at all. and its all thanks to my stupid OC. I was getting all kind of BSODs. took me 4 days to get my PC stable again.









I guess it's not easy to get your 16GB ram to work at 2400MHz @ 9-11-11-38. Had to pump 1.68V to my DRAM and 1.3V to my VCCSA and VTT.


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> I haven't done any work this week at all. and its all thanks to my stupid OC. I was getting all kind of BSODs. took me 4 days to get my PC stable again.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> I guess it's not easy to get your 16GB ram to work at 2400MHz @ 9-11-11-38. Had to pump 1.68V to my DRAM and 1.3V to my VCCSA and VTT.


Did OCN help you get it stable?


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Did OCN help you get it stable?


Didn't post it on OCN. I just read this and worked my way from there









http://www.overclock.net/t/1189242/sandy-bridge-e-overclocking-guide-walk-through-explanations-and-support-for-all-x79-overclockers

I try my best to search for an answer before posting anything.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Just a question: ways on how to stop yourself from web-browsing too much? I haven't done any programming today, I was webrowsing
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Write your own web-browser. Both problems solved.
Click to expand...

I was actually wanting to do a HTML engine.

EDIT: lol MBAM thinks a program of mine is a Trojan.Agent lol


----------



## Fantasy

working long hours till 4AM will make you write stupid things like

Code:



Code:


for (int i = 0; i < FriendsList.Length; i++)
{
    if (FriendsList[i].Contains(PlayerName))
        //Do something
}











[Added]
Also which style do you prefer?

Code:



Code:


for (int i = 0; i < Length; i++)  {
    if ()
        //Do something
}

vs

Code:



Code:


for (int i = 0; i < Length; i++) 
{
    if ()
        //Do something
}


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> working long hours till 4AM will make you write stupid things like
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> for (int i = 0; i < FriendsList.Length; i++)
> {
> if (FriendsList[i].Contains(PlayerName))
> //Do something
> }
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> [Added]
> Also which style do you prefer?
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> for (int i = 0; i < Length; i++)  {
> if ()
> //Do something
> }
> 
> vs
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> for (int i = 0; i < Length; i++)
> {
> if ()
> //Do something
> }


The answer is: What do you prefer?


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> The answer is: What do you prefer?


I prefer the C++ and C# style.

Code:



Code:


for (int i = 0; i < Length; i++) 
{
    if ()
        //Do something
}

I have always hated the Java style which looks like this:-

Code:



Code:


for (int i = 0; i < Length; i++)  {
    if ()
        //Do something
}

However I read this amazing article and it opened my eyes. So I don't know anymore.

You should really read this. It's really good.
http://kotaku.com/5975610/the-exceptional-beauty-of-doom-3s-source-code?post=56177550


----------



## {Unregistered}

I prefer the latter style and have always used that. I don't have a particular reason to use it, though.


----------



## Fantasy

Quote:


> Originally Posted by *{Unregistered}*
> 
> I prefer the latter style and have always used that. I don't have a particular reason to use it, though.


hmm... I see


----------



## 3930K

I prefer the
{
//code
}

style. I think that the Java style was maybe started being used in books to save on spacing.


----------



## General121

Quote:


> Originally Posted by *3930K*
> 
> I prefer the
> {
> //code
> }
> 
> style. *I think that the Java style was maybe started being used in books to save on spacing.*


^^^That's what my teacher says.

Granted I'm only in my first year of coding class, though it is what freshmen learn in college and I'm only in HS







but I didn't think it mattered if it went either way. I'm learning java, but write it the way you list as "C++" style. Teacher taught us that way, though he didn't say it really mattered which way, and I prefer that style because it is easier to read.


----------



## om3nz

I prefer java style formatting, I think it looks cleaner and easier to read. Maybe that is because I mainly code in java.


----------



## FiX

Quote:


> Originally Posted by *om3nz*
> 
> I prefer java style formatting, I think it looks cleaner and easier to read. Maybe that is because I mainly code in java.


I actually find the C++/C# way easier to read (and I use that way). I do mainly program in C++ though.


----------



## 3930K

^Could you release the source code for PSUCalc? Please?


----------



## andyroo89

Latest project I whipped up in two minutes.


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> Latest project I whipped up in two minutes.


----------



## andyroo89

hehe. when I realized the url needed quotation marks, it stumped me for a second, I was like







then I thought if I do this (in C#) "\"" and it worked. hehe


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> hehe. when I realized the url needed quotation marks, it stumped me for a second, I was like
> 
> 
> 
> 
> 
> 
> 
> then I thought if I do this (in C#) "\"" and it worked. hehe


Or just @"""whatever'sinsidethequotationmarks"""


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> Or just @"""whatever'sinsidethequotationmarks"""


I will use that. Seems more efficient.


----------



## {Unregistered}

Hey guys.

Been a while since I've properly browsed through this section since I've been really busy with other stuff.

So what's happening?


----------



## FiX

Quote:


> Originally Posted by *3930K*
> 
> ^Could you release the source code for PSUCalc? Please?


Uh, why?


----------



## 3930K

I want to see how you embedded the webpage onto it.


----------



## 3930K

Anyone know how to get Segoe UI Mono?


----------



## BradleyW

Hello, Just wondering if someone can help me on visial basic?
http://www.overclock.net/t/1351091/help-with-multiplication-in-visual-basic
Thank you.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I want to see how you embedded the webpage onto it.


Simple web browser control. Plus you can run the binaries through reflector








Quote:


> Originally Posted by *3930K*
> 
> Anyone know how to get Segoe UI Mono?


http://www.myfonts.com/fonts/ascender/segoe-mono/


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> I want to see how you embedded the webpage onto it.
> 
> 
> 
> Simple web browser control. Plus you can run the binaries through reflector
> 
> 
> 
> 
> 
> 
> 
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Anyone know how to get Segoe UI Mono?
> 
> Click to expand...
> 
> http://www.myfonts.com/fonts/ascender/segoe-mono/
Click to expand...

It's dotfuscated, lol.

Damn, it costs money. I heard that it's in XNA 4.0 though.


----------



## FiX

3930K, it's just a WebBrowser control that I've hooked the NewWindow callback to open Seasonic's site.


----------



## 3930K

Quote:


> Originally Posted by *FiX*
> 
> 3930K, it's just a WebBrowser control that I've hooked the NewWindow callback to open Seasonic's site.


Ah, thanks.


----------



## BradleyW

Quote:


> Originally Posted by *{Unregistered}*
> 
> Hey guys.
> 
> Been a while since I've properly browsed through this section since I've been really busy with other stuff.
> 
> So what's happening?


Nothing much. We've been chatting over on my thread about matrices recently, along with general programming chit chat.


----------



## Fantasy

So is there a better way to backup your source code rather than just copy/past the whole project? I heard of some Source Control software but non of them are for free.


----------



## 3930K

Quote:


> Originally Posted by *Fantasy*
> 
> So is there a better way to backup your source code rather than just copy/past the whole project? I heard of some Source Control software but non of them are for free.


I'd be interested too.

Just wondering, is the earliest version you have saved fully functional?


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> I'd be interested too.
> 
> Just wondering, is the earliest version you have saved fully functional?


fully functional as in, it works. yes. but there are a lot of things missing. like almost everything is missing.


----------



## 3930K

Quote:


> Originally Posted by *Fantasy*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> I'd be interested too.
> 
> Just wondering, is the earliest version you have saved fully functional?
> 
> 
> 
> fully functional as in, it works. yes. but there are a lot of things missing. like almost everything is missing.
Click to expand...











I'd probably do that had I not only 14 gigs. :/


----------



## Waffleboy

Quote:


> Originally Posted by *Fantasy*
> 
> So is there a better way to backup your source code rather than just copy/past the whole project? I heard of some Source Control software but non of them are for free.


There's lots of good free stuff. I've used Git before, which is easy to use and really nice. Lots of people use Subversion as well.


----------



## Fantasy

Quote:


> Originally Posted by *Waffleboy*
> 
> There's lots of good free stuff. I've used Git before, which is easy to use and really nice. Lots of people use Subversion as well.


Thanks. I'll try them.









Hay everyone. Look where I am


----------



## Icekilla

I'd like to know something...

Take a look at this C code

Code:



Code:


#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 20, b = 14, c, d;

    //scanf("%i", &a);
    //scanf("%i", &b);

    c = a + b;

    //Establishes the values for the conditions
    if((c>=0) && (c<10))
        d = 1;
    else if((c>=10) && (c<20))
        d = 2;
    else if((c>=20) && (c<30))
        d = 3;
    else
        d = 4;

    switch(d)
    {
    case 1:
        printf("condition 1\n");
        break;
    case 2:
        printf("condition 2\n");
        break;
    case 3:
        printf("condition 3\n");
        break;
    default:
        printf("condition M\n");
        break;
    }

    return 0;

}

Now look at this code

Code:



Code:


#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 20, b = 14, c, d;

    //for( ;; )
    {
        //scanf("%i", &a);
        //scanf("%i", &b);

        c = a + b;

        switch( c )
        {
        case 0 ... 9:
            printf("condition 1\n");
            break;
        case 10 ... 19:
            printf("condition 2\n");
            break;
        case 20 ... 29:
            printf("condition 3\n");
            break;
        default:
            printf("condition M\n");
            break;
        }
    }

    return 0;

}

Both do the same, and in execution time, they pretty much take the same time to run. Only thing is, I think the 2nd algorithm is not ANSI compliant.

My question is: Why is the 2nd code working with Code::Blocks and pretty much every online c compiler out there if it's not ANSI compliant? Haven't tried it with Visual Studio 2012, but I guess I'll get the same results.

I thought you couldn't establish ranges in a case under C, only in languages like VB. According to this, it should work, but only for Sun C, which is not standard.


----------



## 3930K

Um... if it isn't ANSI C, then it won't compile in an ANSI C compiler.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Um... if it isn't ANSI C, then it won't compile in an ANSI C compiler.


Indeed. Code Blocks uses GCC by default I believe, and case ranges are a GNU extension to C - this is why it compiles.

http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Case-Ranges.html


----------



## Icekilla

I didn't know you could assign ranges in a switch-case structure.


----------



## 3930K

UGH.

Let's say I have an IOrderedEnumerable, which is declared outside a switch block so I can use it outside the switch block.

The switch block contains a case for every instance (it's a non-[Flags] enum), but when I try to use it in another switch block it says unassigned local variable, and fails to compile.

Any way to fix this? I mean, I would make a new (somethingthatimplenentsIOrderedEnumerable) to shut up the compiler, but there is nothing that implements it.

Help?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> UGH.
> 
> Let's say I have an IOrderedEnumerable, which is declared outside a switch block so I can use it outside the switch block.
> 
> The switch block contains a case for every instance (it's a non-[Flags] enum), but when I try to use it in another switch block it says unassigned local variable, and fails to compile.
> 
> Any way to fix this? I mean, I would make a new (somethingthatimplenentsIOrderedEnumerable) to shut up the compiler, but there is nothing that implements it.
> 
> Help?


Show some code please


----------



## 3930K

Here it is:

Code:



Code:


            IOrderedEnumerable<Homework> tempStore;
            switch (DataFromIni.Orders[0])
            {
                case SortOrder.DateDue:
                    {
                        tempStore = _hwkList.OrderBy((Homework hwk) => hwk.Due);
                        break;
                    }
                case SortOrder.Priority:
                    {
                        tempStore = _hwkList.OrderBy((Homework hwk) => hwk.Priority);
                        break;
                    }
                case SortOrder.DateSet:
                    {
                        tempStore = _hwkList.OrderBy((Homework hwk) => hwk.Set);
                        break;
                    }
                case SortOrder.Details:
                    {
                        tempStore = _hwkList.OrderBy((Homework hwk) => hwk.Details, new StringComparerLogical()); //hat tip for that :)
                        break;
                    }
                    //three more switches exactly like that but from the next one from the array, and using ThenBy on tempStore
            }

And the enum:

Code:



Code:


public enum SortOrder
    {
        DateDue, 
        Priority,
        DateSet,
        Details
    }


----------



## tompsonn

Code:



Code:


IOrderedEnumerable<Homework> tempStore = null;

You need to initialize your variables









Make sure you check for null later when you use it.
I know it looks to you that the variable is initialized in the switch statement, but the compiler doesn't know. For all it knows, none of those switch cases may ever get executed - leading to the use of an uninitialized variable later on.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> IOrderedEnumerable<Homework> tempStore = null;
> 
> You need to initialize your variables.


I knew that, but I forgot you could initialize it to null.









Thanks!


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I knew that, but I forgot you could initialize it to null.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Thanks!


Make sure you always check the variable though before using it! (i.e. make sure its not null







)


----------



## 3930K

It cant possibly be null unless someone DotPeeks it and then removes part of the switch.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> It cant possibly be null unless someone DotPeeks it and then removes part of the switch.


Well there you go


----------



## 3930K

Goddamn it.

Let's say I have a Task.Run like so: () => someThing = someFunc()

That may throw an exception. The problem is if I don't handle it in the lambda, VS gets all stupid about the "exception being unhandled", even though it's handled, just that it's handled outside the lambda. Rethrowing it is no avail either. Help?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Goddamn it.
> 
> Let's say I have a Task.Run like so: () => someThing = someFunc()
> 
> That may throw an exception. The problem is if I don't handle it in the lambda, VS gets all stupid about the "exception being unhandled", even though it's handled, just that it's handled outside the lambda. Rethrowing it is no avail either. Help?


More code please...


----------



## 3930K

It's be useless, if I don't Task.Run it it doesn't show me the message box warning me of the exception. The exceptions handled anyways, but why?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> It's be useless, if I don't Task.Run it it doesn't show me the message box warning me of the exception. The exceptions handled anyways, but why?


Show me the code, trust me. If VS is breaking in to the debugger then the exception is not being handled correctly.


----------



## 3930K

OK, then:

Code:



Code:


                try
                {
                    Task.Run(() => { try { someThing = XDocument.Load(SomeClass.Path, (LoadOptions.None)); } catch (Exception e) { throw e; } });
                }
                catch (Exception)
                {
                    return;
                }


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> OK, then:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> try
> {
> Task.Run(() => { try { someThing = XDocument.Load(SomeClass.Path, (LoadOptions.None)); } catch (Exception e) { throw e; } });
> }
> catch (Exception)
> {
> return;
> }


Thanks









No point re-throwing the exception - the Framework TPL will handle the exception for you and spit it out in your outer try...catch. Visual Studio breaks and throws up "user-handled" because, technically it IS unhandled by user-code; the framework caught the exception. However, exceptions will not be spun out to an outside handler unless you use async and await. Do the following:

1. Apply the "async" modifier to the parent method, and the caller method.
2. Modify the code to look like this:

Code:



Code:


async Task SomeMethod() /* Task is the same as "void" when using async */
{
                try
                {
                        await Task.Run( () =>
                                {
                                                someThing = XDocument.Load( SomeClass.Path, ( LoadOptions.None ) );
                                } );
                }
                catch (Exception)
                { /* Set a break-point here and press F5 once VS jumps in to the debugger - you'll notice the exception handler jumps here */ 
                    return;
                }
}

3. Change the caller to prefix "await" to the method, e.g. await SomeMethod()

---

Demonstrated with this test:

Code:



Code:


     static class Program
        {
                static void Main( string[] args )
                {
                        Task.Run( async () => await Test() );
                        Console.ReadLine();
                }

                static async Task Test()
                {
                        try
                        {
                                await Task.Run( () =>
                                        {
                                                throw new Exception();
                                        } );
                        }
                        catch ( Exception )
                        {
                                Console.WriteLine( "Exception caught" );
                        }

                        Console.ReadLine();
                }
        }

Async and await make exception handling MUCH easier when using the TPL. See here for info on handling exceptions when using the TPL - http://msdn.microsoft.com/en-us/library/dd997415.aspx


----------



## 3930K

I have a problem: SomeMethod is in System.Xml.Linq :/


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I have a problem: SomeMethod is in System.Xml.Linq :/


How? SomeMethod is the method containing your code that you posted.


----------



## 3930K

Brain-fart.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Brain-fart.


----------



## 3930K

UGH. Now it's breaking at the Task.Run in SomeMethod.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> UGH. Now it's breaking at the Task.Run in SomeMethod.


That's fine - its supposed to happen.

"the Framework TPL will handle the exception for you and spit it out in your outer try...catch. *Visual Studio breaks and throws up "user-handled" because, technically it IS unhandled by user-code; the framework caught the exception*."


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> UGH. Now it's breaking at the Task.Run in SomeMethod.
> 
> 
> 
> That's fine - its supposed to happen.
> 
> "the Framework TPL will handle the exception for you and spit it out in your outer try...catch. *Visual Studio breaks and throws up "user-handled" because, technically it IS unhandled by user-code; the framework caught the exception*."
Click to expand...

The problem is that when I run the code, I have to press continue every. single. time.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> The problem is that when I run the code, I have to press continue every. single. time.


Why is an exception being thrown every single time!?


----------



## 3930K

I'm testing with an empty file.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I'm testing with an empty file.


Press CTRL+ALT+E and turn off the exception - although it'd be better to not have it throw the exception in the first place


----------



## 3930K

I'll see if just writing a declaration fixes it.


----------



## 3930K

Nope. Goddamn it.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Nope. Goddamn it.


What is the exception being thrown? And the message.


----------



## andyroo89

Edit; Nevermind I figured it out.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Nope. Goddamn it.
> 
> 
> 
> What is the exception being thrown? And the message.
Click to expand...

I decided to hell with it and made a default empty document: it's something like and then I compared it to a parsed, hardcoded version of that.


----------



## andyroo89

Can anyone help me? I am working on a program to control my home server, the server is just windows 7 (pretty much a desktop in the corner with no monitor) , and I am wanting to add a feature where I can uninstall my own program or other programs on the network, sometimes this will be local from my laptop or I will be out of the house and using for example starbucks wifi and i need the program to still be connected to me (I know I can have it to where my program on my laptop can just search for my own ip, but I want to learn how to add this no-ip dns to my program)

If anyone is willing to help it will be appreciated.


----------



## andyroo89

Ok, I have a new problem. I was making a backspace button, and when I was testing it out it crashed after I used it. Since the textfield was blank and I hit the backspace it caused my program to crash.

here is the error.


----------



## tompsonn

Length of of text was zero (empty text) and you subtracted one from zero = -1
That's illegal for that call


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Length of of text was zero (empty text) and you subtracted one from zero = -1
> That's illegal for that call


Ya to keep my program from crashing, I decided if the textfield is 0 the backspace button will be grayed out until something has been typed in, and then it will be renabled.

edit; well thats fixed, but I felt like I did it inefficiently.

I put the if statements under

textBox1_TextChanged()
{

}

and I also put the if statement under form1_load

I tried to call my method under form1_load that way I didn't have to put that 2nd if statement, but I can't seem to get it to work? Any help?


----------



## 3930K

You could do

Code:



Code:


textBox1.Text = textBox1.Text.Remove((textBox1.Text.Length <= 1 ? 0 : textBox1.Text.Length -1), 0);

I love ternary statements


----------



## andyroo89

textBox1.Length would not work by itself, I had to use textBox1.Text.Length and even then it still caused my program to crash.


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> textBox1.Length would not work by itself, I had to use textBox1.Text.Length and even then it still caused my program to crash.


Whoops :/

But did it crash with that? Odd.

EDIT: Fixed some of the code, the startIndex was off.


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> Whoops :/
> 
> But did it crash with that? Odd.
> 
> EDIT: Fixed some of the code, the startIndex was off.


Still didn't work. I mean it works just fine if I use my if statement, and I kind of like using the if statement to disable the button when the textfield is empty. I wouldn't worry about it. I appreciate the help.


----------



## Icekilla

Hey guys. I'm trying to code a Newton-Raphson iteration for Numerical Methods. So far so good, except for an issue.

This is my algorithm in Python

Code:



Code:


#!/usr/bin/env python
#coding=utf-8

e = 2.71828182845904523536028747135266249775724709369995
ans = 0

for i in range (0, 4):
    ans = ans - (((e**(-ans)) - ans) / ((-e**(-ans)) - 1));

print ans

raw_input()

The output should be 0.56714329041

Now, this is my code in C

Code:



Code:


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    double ans = 0;
    char ansc[25];
    int i;

    for (i=0; i<5; i++)
    {
        ans = ans - ( (pow(M_E,(-ans)) - ans) / (-pow((M_E),(-ans)) - 1) );
    }

    sprintf(ansc, "%lf", ans);

    printf("%s \n", ansc);

    getchar();

    return 0;
}

It "works", but to a certain extent. I need it to have a higher precision of at least 10 decimals.

How can I achieve this? I though using double would work, but so far, no luck.

EDIT: I changed the code to the following

Code:



Code:


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    double ans = 0;

    int i;

    for (i=0; i<5; i++)
    {
        ans = ans - ( (pow(M_E,(-ans)) - ans) / (-pow((M_E),(-ans)) - 1) );
    }

    printf("%.12lf\n", ans);

    getchar();

    return 0;
}

It works now as intended


----------



## Icekilla

This is clever as hell. Has anybody tried it yet?


----------



## 3930K

Delete.


----------



## andyroo89

Ok, so, I took a break from android programming, and I was wondering if anyone can help me with threading or asynctask? It seems most of the stuff I want to make has to be done through threading or it will lock up the app, and crash.

Any help will be appreciated.


----------



## 3930K

jQuery, Y U NO WORK?









Ah you're working now


----------



## Icekilla

Hey guys. I have an issue at hand with a code in C

I have two arrays, the first one is a[8][100] and the 2nd one is b[8][100]. On a[8][100] I have a list of names that I wanna copy to the 2nd array, but in inverted order. I have an idea of how to do it BUT, I don't know how to do it exactly. I COULD copy it letter by letter with a nested for, but that's just too slow IMO. Is there a way to execute the copy with something like strcpy?

I was thinking of something like this

Code:



Code:


for (i = 7, j = 0; i >= 0; i--, j++){
  strcpy(b[j] [something], a[i] [something])
  }

But it's exactly that "something" what I'm missing. Therefore I can't finish my code.

The columns obviously contain the names. This is an input/output sample

Original list of names contained in a
Joanna
Vanessa
Sophie
Alisson
Jessica
Samara
Phoebe
Marlenne

What it should look like in b
Marlenne
Phoebe
Samara
Jessica
Alisson
Sophie
Vanessa
Joanna

Any ideas?

EDIT: Nevermind, got it to work.

Code:



Code:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char a[8][100], b[8][100];
    int i;

    for (i = 0; i < 8; i++)
    {
        gets(a[i]);
    }

    printf("\n\n\n");
    printf("Original list:\n\n");

    for (i = 0; i < 8; i++)
    {
        printf("%s\n", a[i]);
    }

    for (i = 7; i >= 0; i--)
    {
        strcpy(b[7-i], a[i]);
    }

    printf("\n\n\n");
    printf("Sorted list\n\n");

    for (i = 0; i < 8; i++)
    {
        printf("%s\n", b[i]);
    }

    return 0;
}


----------



## Icekilla

Looking for a suggestion: Which version of Visual Studio should I use? 2010 or 2012? I can access any of them thanks to Dreamspark for free.


----------



## tompsonn

Quote:


> Originally Posted by *Icekilla*
> 
> Looking for a suggestion: Which version of Visual Studio should I use? 2010 or 2012? I can access any of them thanks to Dreamspark for free.


I'd pick VS 2012 if you have no dependency on a previous version.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *Icekilla*
> 
> Looking for a suggestion: Which version of Visual Studio should I use? 2010 or 2012? I can access any of them thanks to Dreamspark for free.
> 
> 
> 
> I'd pick VS 2012 if you have no dependency on a previous version.
Click to expand...

This.

EDIT: Come on out Heisenbug...


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> This.
> 
> EDIT: Come on out Heisenbug...


Schrödinbug is much cooler


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> This.
> 
> EDIT: Come on out Heisenbug...
> 
> 
> 
> Schrödinbug is much cooler
Click to expand...

Byte it's not both a bug and a bug at the same time!


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Byte it's not both a bug and a bug at the same time!


Terrific!


----------



## 3930K

LOL









I figured it put, I was adding elements to a list when I should've just been changed the value at the index


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> LOL
> 
> 
> 
> 
> 
> 
> 
> 
> 
> I figured it put, I was adding elements to a list when I should've just been changed the value at the index


I'm trying to work out how you can confuse the two LOL. I'm sure there's some explanation...


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> LOL
> 
> 
> 
> 
> 
> 
> 
> 
> 
> I figured it put, I was adding elements to a list when I should've just been changed the value at the index
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> I'm trying to work out how you can confuse the two LOL. I'm sure there's some explanation...
Click to expand...

I still have no idea how *I* confused them







I probably was writing the code and then I had to rush and didn't finish writing it.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I still have no idea how *I* confused them
> 
> 
> 
> 
> 
> 
> 
> I probably was writing the code and then I had to rush and didn't finish writing it.


Seems plausible


----------



## ivr56

Some messing around with Kinect and Arduino. Testing serial communication between the two and some gesture recognition with Processing.


----------



## 3930K

Quote:


> Originally Posted by *ivr56*
> 
> Some messing around with Kinect and Arduino. Testing serial communication between the two and some gesture recognition with Processing.


Well done!


----------



## 3930K

Any good tutorials for Data Binding in WPF? I really can't wrap my head round it


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Any good tutorials for Data Binding in WPF? I really can't wrap my head round it


What you need to know?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Any good tutorials for Data Binding in WPF? I really can't wrap my head round it
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> What you need to know?
Click to expand...

Just generally how to use it. I haven't needed to use it, yet. I will soon.

Also, is it just me or is codeplex painfully slow in Chrome?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Just generally how to use it. I haven't needed to use it, yet. I will soon.
> 
> Also, is it just me or is codeplex painfully slow in Chrome?


How have you gotten by without data binding!?








http://msdn.microsoft.com/en-us/library/aa480224.aspx

And not sure...


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Just generally how to use it. I haven't needed to use it, yet. I will soon.
> 
> Also, is it just me or is codeplex painfully slow in Chrome?
> 
> 
> 
> How have you gotten by without data binding!?
> 
> 
> 
> 
> 
> 
> 
> 
> http://msdn.microsoft.com/en-us/library/aa480224.aspx
> 
> And not sure...
Click to expand...

No idea







Maybe some redundant code...

Hmm, odd. It pretty much crashes in Chrome for me.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> No idea
> 
> 
> 
> 
> 
> 
> 
> Maybe some redundant code...
> 
> Hmm, odd. It pretty much crashes in Chrome for me.










I think there is some WPF data binding stuff on channel9.msdn.com - head over there and check it out.


----------



## 3930K

Thanks









WHY DOES CHANGING DATEPICKER.SELECTEDDATE CAUSE A STACKOVERFLOW









God, these are SO hard to debug, especially as the code that's gone wrong is MS's.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Thanks
> 
> 
> 
> 
> 
> 
> 
> 
> 
> WHY DOES CHANGING DATEPICKER.SELECTEDDATE CAUSE A STACKOVERFLOW
> 
> 
> 
> 
> 
> 
> 
> 
> 
> God, these are SO hard to debug, especially as the code that's gone wrong is MS's.


Can I see the code?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Thanks
> 
> 
> 
> 
> 
> 
> 
> 
> 
> WHY DOES CHANGING DATEPICKER.SELECTEDDATE CAUSE A STACKOVERFLOW
> 
> 
> 
> 
> 
> 
> 
> 
> 
> God, these are SO hard to debug, especially as the code that's gone wrong is MS's.
> 
> 
> 
> Can I see the code?
Click to expand...

Eh, I found it. An event was indirectly calling a method which was causing that event. And this would be no problem if they had a TextChanged event for a text box that ignored programmatic text changes.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Eh, I found it. An event was indirectly calling a method which was causing that event. And this would be no problem if they had a TextChanged event for a text box that ignored programmatic text changes.


Yeah I don't see how that is Microsoft's fault... a TextChanged event that doesn't respond to text changing... um. Yeah... that'd cause more problems


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Eh, I found it. An event was indirectly calling a method which was causing that event. And this would be no problem if they had a TextChanged event for a text box that ignored programmatic text changes.
> 
> 
> 
> Yeah I don't see how that is Microsoft's fault... a TextChanged event that doesn't respond to text changing... um. Yeah... that'd cause more problems
Click to expand...

No, because in
No, a different event that covered all text changes DONE BY THE USER


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> No, because in
> No, a different event that covered all text changes DONE BY THE USER


Its not consistent, because then you need to handle two events. What about external code that you didn't write that programmatically changes the text?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> No, because in
> No, a different event that covered all text changes DONE BY THE USER
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Its not consistent, because then you need to handle two events. What about external code that you didn't write that programmatically changes the text?
Click to expand...

Still fine, this is only for the UI.


----------



## Icekilla

Hey guys. I have a code here, where I'm trying to implemente a simple input validation to make sure that the data inserted by the user are only numbers (be it integers or floating point).

The problem is, I really have no idea on how to implement that without making the user input the data as a string and then convert it to double. That takes some time, and quite frankly, I want to believe there's a simpler way. The issue is in line 21.

Here's my code in C. Can anybody guide me? Also, is there a safer alternative to fflush(stdin)?

Code:



Code:


#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define isr 0.11
#define iva 0.16
#define isr_to_retain 0.10

int main()
{
    float income, spend, subtotal, reten_isr, reten_iva;
    float iva_result, isr1, iva1, isrtopay, bruteprof, netprof;
    float total, iva_spend, ivatopay;

    printf("mete ingreso\n");
    scanf("%f", &income);

    printf("mete gasto\n");
    scanf("%f", &spend);

    if ( ( isdigit(income) && isdigit(spend) ) != 0) {  //I'm trying to validate the input data so it can only accept numbers
        //To cal
        iva_result = income * iva;
        subtotal = income + iva_result;
        reten_isr = income * isr_to_retain;
        reten_iva = reten_isr;                   //ver si vale la pena usar solo reten_isr par ambas
        total = subtotal - reten_isr - reten_iva;

        //Para calcular Tabla de ganancias
        bruteprof = income - spend;
        isr1 = bruteprof * isr;
        netprof = bruteprof - isr1;
        isrtopay = isr1 - reten_isr;

        //Para tabla de IVA
        iva1 = income * iva;
        iva_spend = spend * iva;
        ivatopay = iva1 - reten_iva - iva_spend;

        printf("\n\n\n\n");

        //Tabla de recibo de honorarios
        printf("****Tabla Recibo de Honorarios****\n");
        printf("Ingreso:                         $ %.2f", income);
        printf("\nIVA (16%% del ingreso)            $ %.2f", iva_result);
        printf("\nSubtotal                         $ %.2f", subtotal);
        printf("\nRetencion ISR (10%% del ingreso)  $ %.2f", reten_isr);
        printf("\nRetencion ISR (10%% del ingreso)  $ %.2f", reten_iva);
        printf("\nTotal                            $ %.2f\n\n\n", total);

        //Tabla de Ganancias
        printf("****Tabla de Ganancias****\n");
        printf("Ingreso:                         $ %.2f", income);
        printf("\nGasto                            $ %.2f", spend);
        printf("\nGanancia Bruta                   $ %.2f", bruteprof);
        printf("\nISR (11%% ganancia bruta)         $ %.2f", isr1);
        printf("\nGanancia Neta                    $ %.2f\n\n", netprof);

        //Tabla ISR
        printf("****Tabla ISR****\n");
        printf("ISR                              $ %.2f", isr1);
        printf("\nISR retenido                     $ %.2f", reten_isr);
        printf("\nISR a pagar                      $ %.2f\n\n", isrtopay);

        //Tabla IVA
        printf("****Tabla IVA****\n");
        printf("ISR                              $ %.2f", iva1);
        printf("\nGastos IVA                       $ %.2f", iva_spend);
        printf("\nRetencion IVA                    $ %.2f", reten_iva);
        printf("\nIVA a pagar                      $ %.2f\n\n", ivatopay);
    }

    printf("\n\nPresione una tecla para continuar..."); //Press a key to continue
    fflush(stdin);
    getchar();

    return 0;
}


----------



## 3930K

Is Blend for VS Express meant to be worse than the VS split view?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Is Blend for VS Express meant to be worse than the VS split view?


I don't use Blend unless I need to do storyboards


----------



## Fantasy

Is there a way to execute c# code at runtime from .cs file? How would you do it?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Is Blend for VS Express meant to be worse than the VS split view?
> 
> 
> 
> I don't use Blend unless I need to do storyboards
Click to expand...

Doesn't even have design view in mine.
Quote:


> Originally Posted by *Fantasy*
> 
> Is there a way to execute c# code at runtime from .cs file? How would you do it?


How I did it: Process.Started csc.exe with the right flags, and then I Process.Started the output exe.


----------



## ivr56

Quote:


> Originally Posted by *ivr56*
> 
> Some messing around with Kinect and Arduino. Testing serial communication between the two and some gesture recognition with Processing.


Got gesture recognition working now more reliabile and recognizes it in an instant.
Will be borrowing a bunch of servos tomorrow to start hooking it right up to start testing interaction ideas on this Kinetic Sculpture I'm working on.


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> Doesn't even have design view in mine.
> How I did it: Process.Started csc.exe with the right flags, and then I Process.Started the output exe.


oh. thanks









What was I thinking when I wrote this








Code:



Code:


if (xmlDoc.SelectSingleNode("MapData") != null)
{
     if (xmlDoc.SelectSingleNode("MapData/Textures") != null)
     {
          if (xmlDoc.SelectSingleNode("MapData/Textures/Terrain") != null)
          {
               //Do somthing


----------



## andyroo89

One of the reasons I don't code too often is because I feel like doing too many if statements seems to be bad programming practice.


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> One of the reasons I don't code too often is because I feel like doing too many if statements seems to be bad programming practice.


If you're using too many ifs you want to be ussing a switch.

EDIT: 2nd part figured


----------



## Fantasy

Man I'm so happy with the work I have done so far on my UI system in XNA. Before I wasn't using Inheritance and all the styling of my UI was hard coded. Today I decided to rewrite and clean it up. So I used Inheritance and I used XML to do all the styling. Before I had ~3000 lines of code and 21 classes. Now I have ~500 lines of code and 19 Classes









Code:



Code:


<UIStyle>
        <MouseState>
                <MouseNormal  TexturePath = "D:\Textures\DefaultBackground.png" TextureColorRGB = "255, 255, 255, 255" BorderColorRGB = "255, 255, 255, 255"/>
                <MouseHovered TexturePath = "D:\Textures\DefaultBackground.png" TextureColorRGB = "255, 255, 255, 255" BorderColorRGB = "255, 255, 255, 255"/>
                <MousePressed TexturePath = "D:\Textures\DefaultBackground.png" TextureColorRGB = "255, 255, 255, 255" BorderColorRGB = "255, 255, 255, 255"/>
        </MouseState>

        <Position X = "150" Y = "200" />
        <Size X = "100" Y = "25" />
        <Border Thickness = "5" />
        <Text String = "Button 1" ColorRGB = "255, 255, 255, 0" />
</UIStyle>


----------



## 3930K

^ How did you count lines of code?


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> ^ How did you measure lines of code?




But that is only available in the Ultimate version. You can install some add-on to the pro version to measure line of code.

Check this out


----------



## 3930K

I've express







I'll give the regex on that page a try tomorrow though









Also, from the peek at your code I can see, have you tried using enums instead of using strings? And instead of ORing you could use .ToLowerInvariant()


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> I've express
> 
> 
> 
> 
> 
> 
> 
> I'll give the regex on that page a try tomorrow though
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Also, from the peek at your code I can see, have you tried using enums instead of using strings? And instead of ORing you could use .ToLowerInvariant()


Thanks. That is a great idea


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> ^ How did you count lines of code?


There's a free piece of software called Line of Code counter by Microsoft


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> There's a free piece of software called Line of Code counter by Microsoft


Why not include it with the pro or the express version then









ahh Microsoft...


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> Why not include it with the pro or the express version then
> 
> 
> 
> 
> 
> 
> 
> 
> 
> ahh Microsoft...


Haha, this is an old school standalone app my friend


----------



## Fantasy

Quote:


> Originally Posted by *tompsonn*
> 
> Haha, this is an old school standalone app my friend


ohh lol


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> ohh lol


Plus being programmers there is no limit - we could just write our own


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *Fantasy*
> 
> ohh lol
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Plus being programmers there is no limit - we could just write our own
Click to expand...

Good point: I wrote my own build autoincrementer lol

EDIT: VS XAML UI designer coder: PLEASE stop the runtime exceptions. No, I don't care if I don't see the bindings in design view, but I DO care that I have to stop programming every 5 minutes to wait for you to handle your unhandled exception.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Good point: I wrote my own build autoincrementer lol
> 
> EDIT: VS XAML UI designer coder: PLEASE stop the runtime exceptions. No, I don't care if I don't see the bindings in design view, but I DO care that I have to stop programming every 5 minutes to wait for you to handle your unhandled exception.


Huh?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Good point: I wrote my own build autoincrementer lol
> 
> EDIT: VS XAML UI designer coder: PLEASE stop the runtime exceptions. No, I don't care if I don't see the bindings in design view, but I DO care that I have to stop programming every 5 minutes to wait for you to handle your unhandled exception.
> 
> 
> 
> Huh?
Click to expand...

It keeps giving me runtime exceptions, and according to the Internet, this is because it's trying to run my code when it shouldn't have.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> It keeps giving me runtime exceptions, and according to the Internet, this is because it's trying to run my code when it shouldn't have.


Something doesn't sound right - I've never experienced a single exception using the XAML designer :/


----------



## 3930K

It only happens when I add a new binding. I type something like this:

Code:



Code:


Content="{Binding }"

Then it locks up for a while. I've got a few hdmps though, I'll see if I can post them.
Seems the .hdmp s have disappeared, but I've got the exception:

Code:



Code:


System.Runtime.Remoting.RemotingException
[13092] Designer process terminated unexpectedly!


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> It only happens when I add a new binding. I type something like this:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> Content="{Binding }"
> 
> Then it locks up for a while. I've got a few hdmps though, I'll see if I can post them.
> Seems the .hdmp s have disappeared, but I've got the exception:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> System.Runtime.Remoting.RemotingException
> [13092] Designer process terminated unexpectedly!


There's nothing specified for your binding...
I'm confused why you're doing that...


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> It only happens when I add a new binding. I type something like this:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> Content="{Binding }"
> 
> Then it locks up for a while. I've got a few hdmps though, I'll see if I can post them.
> Seems the .hdmp s have disappeared, but I've got the exception:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> System.Runtime.Remoting.RemotingException
> [13092] Designer process terminated unexpectedly!
> 
> 
> 
> 
> 
> There's nothing specified for your binding...
> I'm confused why you're doing that...
Click to expand...

I was just writing it, it locked up. I was finishing the binding lol


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I was just writing it, it locked up. I was finishing the binding lol


OOOOOOH.









What the hell - that's about the point IntelliSense should step in. How is your data context defined?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> I was just writing it, it locked up. I was finishing the binding lol
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> OOOOOOH.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> What the hell - that's about the point IntelliSense should step in. How is your data context defined?
Click to expand...

It's defined as itself:

Code:



Code:


{Binding RelativeSource={RelativeSource Self}} //in the window definition

That's solely so I can access items in the codebehind.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> It's defined as itself:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> {Binding RelativeSource={RelativeSource Self}} //in the window definition
> 
> That's solely so I can access items in the codebehind.


It's probably valid, but you should implement the data context as a separate class and use the DataContext property of the Window to assign it in code. Then use dataContext in the XAML to use it properly in the markup.

e.g.

Code:



Code:


<Window ...
        xmlns:MyNamespace="using:MyApp.Mynamespace"
        d:DataContext="{d:DesignInstance MyNamespace:MyDataContextType}">


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> It's defined as itself:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> {Binding RelativeSource={RelativeSource Self}} //in the window definition
> 
> That's solely so I can access items in the codebehind.
> 
> 
> 
> It's probably valid, but you should implement the data context as a separate class and use the DataContext property of the Window to assign it in code. Then use dataContext in the XAML to use it properly in the markup.
Click to expand...

Could you give me an example?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Could you give me an example?


I edited the post, but I'll give you a better example, hang on.

For argument sake we'll pretend the namespace is MyApp.Demo.

DataContext.cs

Code:



Code:


public sealed class DataContext : INotifyPropertyChanged // MyApp.Demo.DataContext
{
        public event PropertyChangedEventHandler PropertyChanged;
        private string _firstProperty;

        public string FirstProperty 
        {
                get { return this._firstProperty; }
                set { this._firstProperty = value; this.OnPropertyChanged( "FirstProperty" ); }
        }

        private void OnPropertyChanged( string propertyName )
        {
                if ( this.PropertyChanged != null )
                {
                        this.PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
                }
        }
}

Window.xaml

Code:



Code:


<Window ...
        xmlns:Demo="using:MyApp.Demo"
        d:DataContext="{d:DesignInstance Demo:DataContext }">

<!-- demo -->
<TextBlock Text="{Binding FirstProperty}" />

</Window>

Window.xaml.cs

Code:



Code:


public partial class Window // MyApp.Demo.Window
{
        private readonly DataContext _dataContext = new DataContext();  // MyApp.Demo.DataContext

        public Window()
        {
                // Set data context
                this.DataContext = this._dataContext;

                // ...
                // Changing the property of the data context like so will automatically update the UI:
                //
                this._dataContext.FirstProperty = "Hello, World";
        }
}


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Could you give me an example?
> 
> 
> 
> I edited the post, but I'll give you a better example, hang on.
> 
> For argument sake we'll pretend the namespace is MyApp.Demo.
> 
> DataContext.cs
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> public sealed class DataContext : INotifyPropertyChanged // MyApp.Demo.DataContext
> {
> public event PropertyChangedEventHandler PropertyChanged;
> private string _firstProperty;
> 
> public string FirstProperty
> {
> get { return this._firstProperty; }
> set { this._firstProperty = value; this.OnPropertyChanged( "FirstProperty" ); }
> }
> 
> private void OnPropertyChanged( string propertyName )
> {
> if ( this.PropertyChanged != null )
> {
> this.PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
> }
> }
> }
> 
> Window.xaml
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> <Window ...
> xmlns:Demo="using:MyApp.Demo"
> d:DataContext="{d:DesignInstance Demo:DataContext }">
> 
> <!-- demo -->
> <TextBlock Text="{Binding FirstProperty}" />
> 
> </Window>
> 
> Window.xaml.cs
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> public partial class Window // MyApp.Demo.Window
> {
> private readonly DataContext _dataContext = new DataContext();  // MyApp.Demo.DataContext
> 
> public Window()
> {
> // Set data context
> this.DataContext = this._dataContext;
> 
> // ...
> // Changing the property of the data context like so will automatically update the UI:
> //
> this._dataContext.FirstProperty = "Hello, World";
> }
> }
Click to expand...

OK, so instead of having the properties in the window's class, you have it in a separate class? Thanks! +rep.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> OK, so instead of having the properties in the window's class, you have it in a separate class? Thanks! +rep.


Yes that's right. And implementing INotifyPropertyChanged allows the binding magician to subscribe to your data context and register for change notifications so that when you update a property of a data context in code, the UI will accordingly update.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> OK, so instead of having the properties in the window's class, you have it in a separate class? Thanks! +rep.
> 
> 
> 
> Yes that's right. And implementing INotifyPropertyChanged allows the binding magician to subscribe to your data context and register for change notifications so that when you update a property of a data context in code, the UI will accordingly update.
Click to expand...

I learnt that the downvote way in SO yesterday (INotifyPropertyChanged), but thanks!


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I learnt that the downvote way in SO yesterday (INotifyPropertyChanged), but thanks!


To help you further, here's my class that I use for the base of ALL data contexts, which automatically updates properties (requires .NET 4.5) - it is actually from WinRT but I modified the hell out of it:

Code:



Code:


     [DataContract]
        public abstract class BindableBase : INotifyPropertyChanged
        {
                public event PropertyChangedEventHandler PropertyChanged;
                private readonly List<string> _updateProperties = new List<string>();
                protected bool SuppressPropertyUpdate = false;

                protected bool SetProperty<T>( ref T storage, T value, [CallerMemberName] string propertyName = null )
                {
                        if ( object.Equals( storage, value ) )
                        {
                                return false;
                        }

                        storage = value;
                        this.OnPropertyChanged( propertyName );
                        return true;
                }

                protected virtual void OnPropertyChanged( [CallerMemberName] string propertyName = null )
                {
                        /* Are we suppressing property updates? */
                        if ( this.SuppressPropertyUpdate )
                        {
                                if ( !this._updateProperties.Contains( propertyName ) )
                                {
                                        this._updateProperties.Add( propertyName );
                                }

                                return;
                        }

                        var eventHandler = this.PropertyChanged;
                        if ( eventHandler != null )
                        {
                                eventHandler( this, new PropertyChangedEventArgs( propertyName ) );
                        }
                }

                internal virtual void BeginUpdate()
                {
                        this.SuppressPropertyUpdate = true;
                }

                internal virtual void EndUpdate()
                {
                        this.SuppressPropertyUpdate = false;

                        /* Update properties */
                        if ( this._updateProperties.Count > 0 )
                        {
                                for ( int i = 0; i < this._updateProperties.Count; ++i )
                                {
                                        this.OnPropertyChanged( this._updateProperties[ i ] );
                                }
                        }

                        this._updateProperties.Clear();
                }
        }

Now your data context is as simple as:

Code:



Code:


public sealed class DataContext : BindableBase
{
        /* Storage */
        private string _firstProperty;
        private int _secondProperty;

        /* Public accessors */
        public string FirstProperty
        {
                get     { return this._firstProperty;   }
                set { this.SetProperty( ref this._firstProperty, value ); }
        }

        public int SecondProperty
        {
                get { return this._secondProperty; }
                set { this.SetProperty( ref this._secondProperty, value ); }
        }
}


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> I learnt that the downvote way in SO yesterday (INotifyPropertyChanged), but thanks!
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> To help you further, here's my class that I use for the base of ALL data contexts, which automatically updates properties (requires .NET 4.5) - it is actually from WinRT but I modified the hell out of it:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> [DataContract]
> public abstract class BindableBase : INotifyPropertyChanged
> {
> public event PropertyChangedEventHandler PropertyChanged;
> private readonly List<string> _updateProperties = new List<string>();
> protected bool SuppressPropertyUpdate = false;
> 
> protected bool SetProperty<T>( ref T storage, T value, [CallerMemberName] string propertyName = null )
> {
> if ( object.Equals( storage, value ) )
> {
> return false;
> }
> 
> storage = value;
> this.OnPropertyChanged( propertyName );
> return true;
> }
> 
> protected virtual void OnPropertyChanged( [CallerMemberName] string propertyName = null )
> {
> /* Are we suppressing property updates? */
> if ( this.SuppressPropertyUpdate )
> {
> if ( !this._updateProperties.Contains( propertyName ) )
> {
> this._updateProperties.Add( propertyName );
> }
> 
> return;
> }
> 
> var eventHandler = this.PropertyChanged;
> if ( eventHandler != null )
> {
> eventHandler( this, new PropertyChangedEventArgs( propertyName ) );
> }
> }
> 
> internal virtual void BeginUpdate()
> {
> this.SuppressPropertyUpdate = true;
> }
> 
> internal virtual void EndUpdate()
> {
> this.SuppressPropertyUpdate = false;
> 
> /* Update properties */
> if ( this._updateProperties.Count > 0 )
> {
> for ( int i = 0; i < this._updateProperties.Count; ++i )
> {
> this.OnPropertyChanged( this._updateProperties[ i ] );
> }
> }
> 
> this._updateProperties.Clear();
> }
> }
> 
> Now your data context is as simple as:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> public sealed class DataContext : BindableBase
> {
> /* Storage */
> private string _firstProperty;
> private int _secondProperty;
> 
> /* Public accessors */
> public string FirstProperty
> {
> get     { return this._firstProperty;   }
> set { this.SetProperty( ref this._firstProperty, value ); }
> }
> 
> public int SecondProperty
> {
> get { return this._secondProperty; }
> set { this.SetProperty( ref this._secondProperty, value ); }
> }
> }
Click to expand...

That's very useful: thanks


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> That's very useful: thanks


No problemo


----------



## 3930K

Wait... porting to my code gives me an error:
Error 2 The property 'DataContext' must be in the default namespace or in the element namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'.
Error 1 The name "DataClass" does not exist in the namespace "using:MyNameSpace".

Window declaration:

Code:



Code:


<Window x:Class="MyNameSpace.MainClass"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        Title="MyTitle"  
        Height="415"
        Width="550"
        MinHeight="415"
        MinWidth="550"
        MaxHeight="830"
        MaxWidth="1100"
        xmlns:lcl="using:MyNameSpace"
        d:DataContext="{d:DesignInstance lcl:DataClass}">


----------



## tompsonn

Oops, sorry you need to add mc:Ignorable="d" and xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" to the Window element, and then rebuild your solution.


----------



## 3930K

It works fine now, but the designer just says error, and I can't design.









Any way to fix it?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> It works fine now, but the designer just says error, and I can't design.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Any way to fix it?


Literally just says error, or actually displays an error message that might be helpful (







) ?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> It works fine now, but the designer just says error, and I can't design.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Any way to fix it?


Literally just says error, or actually displays an error message that might be helpful (







) ?


----------



## 3930K

It used to just complain about d:. Now it's complaining about the class not existing, even though it does.
EDIT:Odd. Just removed the DataContext defined in XAML and now it works.


----------



## andyroo89

If only Im working with constant Values.


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> If only Im working with constant Values.


Whats the question here?


----------



## andyroo89

Nothing. Just making a remark to a post i forgot to quote


----------



## 3930K

Ah lol


----------



## 3930K

Sorry for doubleposting, but could anyone tell me the name of this control? I need to use it in my WPF app, but I forgot what it's called so I can't use it


----------



## 3930K

Help?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> It used to just complain about d:. Now it's complaining about the class not existing, even though it does.
> EDIT:Odd. Just removed the DataContext defined in XAML and now it works.


Yeah I get this too, its weird but I just ignore it. Often if I rebuild the solution and restart the designer (kill the designer process in Task Manager), it works fine.
Quote:


> Originally Posted by *3930K*
> 
> Sorry for doubleposting, but could anyone tell me the name of this control? I need to use it in my WPF app, but I forgot what it's called so I can't use it


Sorry I'm not sure


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> It used to just complain about d:. Now it's complaining about the class not existing, even though it does.
> EDIT:Odd. Just removed the DataContext defined in XAML and now it works.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Yeah I get this too, its weird but I just ignore it. Often if I rebuild the solution and restart the designer (kill the designer process in Task Manager), it works fine.
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Sorry for doubleposting, but could anyone tell me the name of this control? I need to use it in my WPF app, but I forgot what it's called so I can't use it
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Click to expand...
> 
> Sorry I'm not sure
Click to expand...

Asked in SO chat a while ago, it was a list box. But thanks!


----------



## tompsonn

I was going to say that, but then I saw the arrow buttons and got confused


----------



## 3930K

They're for moving items up and down.


----------



## 3930K

Anyone explain the concept of IVs for encryption?
Specifically, what I need to know is whether you need the same IV to decrypt a file.
For example. let's say I had a file. I encrypted it with key 2 and IV 321. Now, could I decrypt that same file with the IV 123?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Anyone explain the concept of IVs for encryption?
> Specifically, what I need to know is whether you need the same IV to decrypt a file.
> For example. let's say I had a file. I encrypted it with key 2 and IV 321. Now, could I decrypt that same file with the IV 123?


Correct, you need the same IV during decryption. It needs to be used only once per message, and must be random/pseudo-random. It can also be called a nonce (a number used once), and is analogous to a password salt.


----------



## ThePhlood

Sorry to butt in like this but I wanted some other programmers opinions in a thread I made about programming languages

http://www.overclock.net/t/1364653/what-language-to-use-for-first-official-game

You don't have to click it if you don't want, I just want to know yalls opinion on the best language for programming a 2D puzzle sidescroller.
Also what do you guys think of the XNA extension for C#

Also my programming "bio" is on that link for anyone interested and I would love to be a contributor to this thread as a computer science major.

Thanks!


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Anyone explain the concept of IVs for encryption?
> Specifically, what I need to know is whether you need the same IV to decrypt a file.
> For example. let's say I had a file. I encrypted it with key 2 and IV 321. Now, could I decrypt that same file with the IV 123?
> 
> 
> 
> Correct, you need the same IV during decryption. It needs to be used only once per message, and must be random/pseudo-random. It can also be called a nonce (a number used once), and is analogous to a password salt.
Click to expand...

OK, thanks!

EDIT: WiX, if you installed, where in heaven's sake can I access you?


----------



## 3930K

And of course the only Ribbon for WPF that has support for the new 2013 style is DevExpress', which is extremely expensive







They should do a hobbyist option, or you should be able to buy controls individually.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> And of course the only Ribbon for WPF that has support for the new 2013 style is DevExpress', which is extremely expensive
> 
> 
> 
> 
> 
> 
> 
> They should do a hobbyist option, or you should be able to buy controls individually.


Send them an e-mail, they might be able to help you out - they're pretty good!
Alternatively, you could develop your own control


----------



## andyroo89

I have been playing WoW lately, and been up all night, so, I made a auto email sender to my teachers to send a email at a specific time to let them know I won't be in for class, they usually or have pardon my absence.

here is roughed up version. I am planning to add status label to let me know if they got sent. I am also planning to have it send to multiple teachers, but I do have a question, to send it to more than one person do I just need to put a comma? its through gmail.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> I have been playing WoW lately, and been up all night, so, I made a auto email sender to my teachers to send a email at a specific time to let them know I won't be in for class, they usually or have pardon my absence.
> 
> here is roughed up version. I am planning to add status label to let me know if they got sent. I am also planning to have it send to multiple teachers, but I do have a question, to send it to more than one person do I just need to put a comma? its through gmail.


Firstly, the only thing you will know is if the message was transmitted successfully to the recipient SMTP server. If this is the status you mean, then that's fine - if you want to know if it actually reached the recipient mailbox after the SMTP server routes the message, this is not possible (well, it sort of is with message receipts, but not easy to implement).

Secondly, you should use a semicolon to delimit recipient addresses.


----------



## andyroo89

I already sent test emails and I am using SMTP, and it works.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> I already sent test emails and I am using SMTP, and it works.


Um, OK.. lol


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Um, OK.. lol


Haha I re-read what you said, and I realized what you meant I am just burned out from programming, and my college courses.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> And of course the only Ribbon for WPF that has support for the new 2013 style is DevExpress', which is extremely expensive
> 
> 
> 
> 
> 
> 
> 
> They should do a hobbyist option, or you should be able to buy controls individually.
> 
> 
> 
> Send them an e-mail, they might be able to help you out - they're pretty good!
> Alternatively, you could develop your own control
Click to expand...

thanks, I'll try.
If they refuse, that's three pretty big controls I have to dev for my app: a ribbon, a line numbered, linewrapped label,and a line numbered, linewrapped richtextbox


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> thanks, I'll try.
> If they refuse, that's three pretty big controls I have to dev for my app: a ribbon, a line numbered, linewrapped label,and a line numbered, linewrapped richtextbox


No only two - the wrapped and line-numbered label is simply the wrapped and line-numbered rich text box that is readonly


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> thanks, I'll try.
> If they refuse, that's three pretty big controls I have to dev for my app: a ribbon, a line numbered, linewrapped label,and a line numbered, linewrapped richtextbox
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> No only two - the wrapped and line-numbered label is simply the wrapped and line-numbered rich text box that is readonly
Click to expand...


----------



## tompsonn

Quote:


> Originally Posted by *3930K*












Don't worry you would have realized...

"Hey why am I writing the same code twice...."


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Don't worry you would have realized...
> 
> "Hey why am I writing the same code twice...."
Click to expand...

True haha


----------



## BradleyW

Anyone know of a good website that teaches C++ from a basic level and onwards? Thank you.


----------



## 3930K

Quote:


> Originally Posted by *BradleyW*
> 
> Anyone know of a good website that teaches C++ from a basic level and onwards? Thank you.


Sorry, I don't.

Books are quite good for learning though.

In an unrelated note: Y U CRASH APP?
It works perfectly on my computer, go to someone else's? KABOOM
EDIT: I want to MURDER YOU XAMLPARSEEXCEPTION


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Sorry, I don't.
> 
> Books are quite good for learning though.
> 
> In an unrelated note: Y U CRASH APP?
> It works perfectly on my computer, go to someone else's? KABOOM
> EDIT: I want to MURDER YOU XAMLPARSEEXCEPTION


Get a debugger on it


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Sorry, I don't.
> 
> Books are quite good for learning though.
> 
> In an unrelated note: Y U CRASH APP?
> It works perfectly on my computer, go to someone else's? KABOOM
> EDIT: I want to MURDER YOU XAMLPARSEEXCEPTION
> 
> 
> 
> Get a debugger on it
Click to expand...

Remote debugger was a pain,so I just wrapped a try-catch around Main. It was a filenotfound wrapped


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Remote debugger was a pain,so I just wrapped a *try-catch around Main*. It was a filenotfound wrapped












http://stackoverflow.com/questions/4827628/main-method-code-entirely-inside-try-catch-is-it-bad-practice

Please read first answer carefully


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Remote debugger was a pain,so I just wrapped a *try-catch around Main*. It was a filenotfound wrapped
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> http://stackoverflow.com/questions/4827628/main-method-code-entirely-inside-try-catch-is-it-bad-practice
> 
> Please read first answer carefully
Click to expand...

I've read that before. It was temporary to find the bug, as it happened before I could add an event to AppDomain.UnhandledException


----------



## Icekilla

How do my codes look? Are they readable or clean? What suggestions or techniques would you give me for my future code-writing? Also, sorry for not translating the comments to English.


Spoiler: Warning: Spoiler!



Code:



Code:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//Definición de constantes
#define isr 0.11
#define iva 0.16
#define isr_to_retain 0.10

//Función para verificar la entrada de datos
int checkchar(char *num)
{
    int i, j, k = strlen(num), l;
    for(i = 0; i < k; i++) {
        if(((num[i]>='0')&&(num[i]<='9')) || (num[i]=='.') || (j != 0)) {
            if (num[i] == '.') {
                for(l = i+1; l < (k - i); l++) {
                    if(num[l]=='.') {
                        j = 0;
                        break;
                    }
                }
            } else {
                if(j == 0) {
                    break;
                } else {
                    j = 1;
                }
            }
        } else {
            j = 0;
            break;
        }
    }
    return j;
}

int main()
{
    //Declaración de variables
    float subtotal, reten_isr, total, iva_spend,iva_result, isr1;
    float iva1, isrtopay, bruteprof, netprof, ivatopay;
    float income, spend;
    char income_string[15], spend_string[15], condit;

    do {
        system("cls");

        fflush(stdin);

        //Entrada de datos
        printf("Porfavor inserte la cantidad obtenida de ingresos\n");
        gets(income_string);

        printf("Porfavor inserte la cantidad de dinero gastado\n");
        gets(spend_string);

        //Validación de entradas
        if ( checkchar(income_string) && checkchar(spend_string) ) {
            //Conversión de cadenas a flotantes
            sscanf(income_string, "%f", &income);
            sscanf(spend_string, "%f", &spend);

            //Para calcular la tabla de honorarios
            iva_result = income * iva;
            subtotal = income + iva_result;
            reten_isr = income * isr_to_retain;

            total = subtotal - reten_isr * 2;

            //Para calcular Tabla de ganancias
            bruteprof = income - spend;
            isr1 = bruteprof * isr;
            netprof = bruteprof - isr1;
            isrtopay = isr1 - reten_isr;

            //Para tabla de IVA
            iva1 = income * iva;
            iva_spend = spend * iva;
            ivatopay = iva1 - reten_isr - iva_spend;

            system("cls");

            //Salida de datos
            printf("     ****Tabla de Impuestos****\n");
            printf("****Tabla Recibo de Honorarios****\n");
            printf("Ingreso:                         $ %.2f", income);
            printf("\nIVA (16%% del ingreso)            $ %.2f", iva_result);
            printf("\nSubtotal                         $ %.2f", subtotal);
            printf("\nRetencion ISR (10%% del ingreso)  $ %.2f", reten_isr);
            printf("\nRetencion IVA (10%% del ingreso)  $ %.2f", reten_isr);
            printf("\nTotal                            $ %.2f\n", total);

            printf("****Tabla de Ganancias****\n");
            printf("Ingreso:                         $ %.2f", income);
            printf("\nGasto                            $ %.2f", spend);
            printf("\nGanancia Bruta                   $ %.2f", bruteprof);
            printf("\nISR (11%% ganancia bruta)         $ %.2f", isr1);
            printf("\nGanancia Neta                    $ %.2f\n", netprof);

            printf("****Tabla ISR****\n");
            printf("ISR                              $ %.2f", isr1);
            printf("\nISR retenido                     $ %.2f", reten_isr);
            printf("\nISR a pagar                      $ %.2f\n", isrtopay);

            printf("****Tabla IVA****\n");
            printf("ISR                              $ %.2f", iva1);
            printf("\nGastos IVA                       $ %.2f", iva_spend);
            printf("\nRetencion IVA                    $ %.2f", reten_isr);
            printf("\nIVA a pagar                      $ %.2f\n", ivatopay);

            printf("\nDesea hacer otra operacion? Y/N  ");
            fflush(stdin);
            scanf("%c", &condit);
        }

        else {
            printf("\nEntrada invalida. Desea intentar de nuevo? Y/N  ");
            fflush(stdin);
            scanf("%c", &condit);
        }
        if ((condit == 'Y') || (condit == 'y')) {
            continue;
        }

        else if ((condit == 'N') || (condit == 'n')) {
            break;
        }

        else {
            printf("\nEntrada no reconocida. El programa se cerrara");
            break;
        }
    } while((condit == 'Y') || (condit == 'y'));
    return 0;
}







Spoiler: Warning: Spoiler!



Code:



Code:


#include <stdio.h>
#include <stdlib.h>

//Definition of constants
#define ASSIST_CONST 17
#define LATE_ASSIST_CONST 3
#define AST_PERCNT_CONST 100
#define HMWR_NUM_CONST 4
#define TEST_GRADE_CONST 100
#define POSITIVE 1
#define NEGATIVE 0

//Percentages for evaluation
#define NUMOF_MINIPRAC 9
#define NUMOF_CLASSES 17
#define HMWR_PRCN_CONST 15
#define TEST_PERCNT_CONST 10
#define MINIPRAC_PRCNT_CONST 18
#define DSPRAC_PRCT_INIT_CONST 40
#define DSPRAC_PRCT_FIN_CONST 17
#define NUM_OF_PRACTS 7
#define MIN_ASSIST_PRCT 80
#define MIN_GRADE_CONST 60

enum practnum {
    pract1,
    pract2,
    pract3,
    pract4,
    pract5,
    pract6,
    pract7,
};

int main()
{
    //The values for these variables will be inputted by the user
    float class_missed, class_late, hmwrk_delvrd, miniprac_delvrd, class_assist;
    float test_grade, prac_grade[NUM_OF_PRACTS];
    int count1, varstat = NEGATIVE;

    //The values for these variables will be either computed or outputted
    float assist_percent, hmwr_fin_pnt, tst_fin_pnt, pract_fin_pnt, fin_grade, miniprac_prct;
    float dsprac_prct_fin, dsprac_prct_init;
    char condit, yes1 = 'y', yes2 = 'Y';

    do { //Data input process
        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Cuantas faltas tuviste durante el semestre\n");
        scanf("%f", &class_missed);
        system("cls");

        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Cuantos ******os tuviste durante el semestre\n");
        scanf("%f", &class_late);
        system("cls");

        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Cuantas tareas entregaste?\n");
        scanf("%f", &hmwrk_delvrd);
        system("cls");

        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Que calificacion obtuviste en el examen?\n");
        scanf("%f", &test_grade);
        system("cls");

        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Cuantas minipracticas entregaste?\n");
        scanf("%f", &miniprac_delvrd);
        system("cls");

        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Que calificacion obtuviste en tu primer practica?\n");
        scanf("%f", &prac_grade[pract1]);
        system("cls");

        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Que calificacion obtuviste en tu segunda practica?\n");
        scanf("%f", &prac_grade[pract2]);
        system("cls");

        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Que calificacion obtuviste en tu tercer practica?\n");
        scanf("%f", &prac_grade[pract3]);
        system("cls");

        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Que calificacion obtuviste en tu cuarta practica?\n");
        scanf("%f", &prac_grade[pract4]);
        system("cls");

        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Que calificacion obtuviste en tu quinta practica?\n");
        scanf("%f", &prac_grade[pract5]);
        system("cls");

        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Que calificacion obtuviste en tu sexta practica?\n");
        scanf("%f", &prac_grade[pract6]);
        system("cls");

        printf("Evaluador del Taller de Estructura de Datos v4.0\n");
        printf("Que calificacion obtuviste en tu septima practica?\n");
        scanf("%f", &prac_grade[pract7]);
        system("cls");

        //Data validation to avoid higher than allowed inputs
        if((class_missed > NUMOF_CLASSES)||(hmwrk_delvrd > HMWR_NUM_CONST)||(test_grade > TEST_GRADE_CONST) || (miniprac_delvrd > NUMOF_MINIPRAC)) {
            varstat = POSITIVE;
        }

        //Data validation to avoid higher than allowed inputs
        if (varstat == NEGATIVE) {
            for (count1 = 0; count1 < NUM_OF_PRACTS; count1++) {
                if(prac_grade[count1+1] > TEST_GRADE_CONST) {
                    varstat = POSITIVE;
                }
            }
        }

        if(varstat == NEGATIVE) {
            //Computing of output data

            //Computing of assistance
            class_assist = ASSIST_CONST - class_missed - (class_late/LATE_ASSIST_CONST);
            assist_percent = ((ASSIST_CONST - class_missed - (class_late/LATE_ASSIST_CONST)) * AST_PERCNT_CONST) / ASSIST_CONST;

            //Computing of homeworks
            hmwr_fin_pnt = (hmwrk_delvrd * HMWR_PRCN_CONST) / HMWR_NUM_CONST;

            //Computing of test grades
            tst_fin_pnt = (test_grade * TEST_PERCNT_CONST) / TEST_GRADE_CONST;

            //Computing of practices
            miniprac_prct = (miniprac_delvrd * MINIPRAC_PRCNT_CONST) / NUMOF_MINIPRAC;
            dsprac_prct_init = ((prac_grade[pract1] + prac_grade[pract2] + prac_grade[pract3] + prac_grade[pract4] + prac_grade[pract5]) * DSPRAC_PRCT_INIT_CONST) / 500;
            dsprac_prct_fin = ((prac_grade[pract6] + prac_grade[pract7]) * DSPRAC_PRCT_FIN_CONST) / 200;
            pract_fin_pnt = miniprac_prct + dsprac_prct_init + dsprac_prct_fin;

            //Computing of final grade
            fin_grade = hmwr_fin_pnt + tst_fin_pnt + pract_fin_pnt;

            //Data output
            printf("Evaluador del Taller de Estructura de Datos v4.0\n\n");
            printf("Total de asistencias:        %10.2f\n", class_assist);
            printf("Porcentaje de asistencia:    %10.2f%%   ", assist_percent);
            assist_percent >= MIN_ASSIST_PRCT ? printf("Tiene derecho\n"):printf("Sin derecho\n");
            printf("Porcentaje de tareas:        %10.2f%%\n", hmwr_fin_pnt);
            printf("Porcentaje de examen:        %10.2f%%\n", tst_fin_pnt);
            printf("Porcentaje de practicas:     %10.2f%%\n", pract_fin_pnt);
            printf("Puntaje final:               %10.2f%%   ", fin_grade);
            fin_grade >= MIN_GRADE_CONST ? printf("Calificacion aprobatoria\n"):printf("Calificacion no aprobatoria\n");
            (assist_percent >= MIN_ASSIST_PRCT) && (fin_grade >= MIN_GRADE_CONST) ? printf("[email protected] [email protected]\n") : printf("[email protected] no [email protected]\n");
        }
        else
            printf("Entrada invalida. ");

        scanf ("%*[^\n]");
        getchar();

        printf("Desea hacer otra evaluacion? Y/N  ");
        scanf("%c", &condit);

        //Alternative to fflush(stdin), to clean input buffer
        scanf ("%*[^\n]");
        getchar();

        system("cls");

    } while((condit ==  yes1) || (condit == yes2));
    return varstat;
}


----------



## 3930K

ClickOnce, the hell is up with you?

*tries running off start menu shortcut*: Windows cannot access the specified path, file or drive. Blah blah.

*try run as admin*: Nothing.

*goes to .exe and runs manually*: perfect.


----------



## 3930K

Help?


----------



## {Unregistered}

Assembly is a pain.


----------



## andyroo89

Quote:


> Originally Posted by *{Unregistered}*
> 
> Assembly is a pain.


I picked up a book and put it on my nexus 7 to read, and I heard it was totally new level to programming. So, I am going to wait on actually doing something.


----------



## {Unregistered}

Quote:


> Originally Posted by *andyroo89*
> 
> I picked up a book and put it on my nexus 7 to read, and I heard it was totally new level to programming. So, I am going to wait on actually doing something.


Well it's not really a "totally _new_ level" of programming...


----------



## andyroo89

Quote:


> Originally Posted by *{Unregistered}*
> 
> Well it's not really a "totally _new_ level" of programming...


For you.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> I picked up a book and put it on my nexus 7 to read, and I heard it was totally new level to programming. So, I am going to wait on actually doing something.


Quote:


> Originally Posted by *{Unregistered}*
> 
> Well it's not really a "totally _new_ level" of programming...


Totally _low_ level of programming









What you need help with. Is it x86?


----------



## Icekilla

No one has given their opinion on my code


----------



## {Unregistered}

Quote:


> Originally Posted by *tompsonn*
> 
> Totally _low_ level of programming
> 
> 
> 
> 
> 
> 
> 
> 
> What you need help with. Is it x86?


Never mind.

It was Intel 64, by the way.
Quote:


> Originally Posted by *Icekilla*
> 
> No one has given their opinion on my code


Following a quick glance, it seems just fine. I'll take a proper look at it later.


----------



## Icekilla

Q: How many Prolog programmers do you need to change a lightbult?
A: Yes


----------



## tompsonn

Quote:


> Originally Posted by *Icekilla*
> 
> Q: How many Prolog programmers do you need to change a lightbult?
> A: Yes


----------



## 3930K

Help?
I've got some regex:

Code:



Code:


string.Join(" ",Regex.Split("a%string+test")((?=[^a-zA-Z0-9\+*/-])|(?<=[^a-zA-Z0-9\+*/-])));

This gets me doublespaces, eg

Code:



Code:


a  %  string+test

What have I done wrong?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Help?
> I've got some regex:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> string.Join(" ",Regex.Split("a%string+test")((?=[^a-zA-Z0-9\+*/-])|(?<=[^a-zA-Z0-9\+*/-])));
> 
> This gets me doublespaces, eg
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> a  %  string+test
> 
> What have I done wrong?


What are you trying to do?


----------



## andyroo89

Ok, I decided to tackle an old project I have laying around for android, How can I move files that is in a folder without specifying the file name(s)? It only works if I specify the file name.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Ok, I decided to tackle an old project I have laying around for android, How can I move files that is in a folder without specifying the file name(s)? It only works if I specify the file name.


Need some code, sir


----------



## andyroo89

gahh its on my laptop, hold on, I will edit this post or make a new one *if someone else replies before I do







*

Edit;; here we go http://pastebin.com/v0fuVuG2 code to my android file transfer


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Help?
> I've got some regex:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> string.Join(" ",Regex.Split("a%string+test")((?=[^a-zA-Z0-9\+*/-])|(?<=[^a-zA-Z0-9\+*/-])));
> 
> This gets me doublespaces, eg
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> a  %  string+test
> 
> What have I done wrong?
> 
> 
> 
> What are you trying to do?
Click to expand...

I realized that was wrong, but I still have no idea how to do what I want to do.
I'm getting in an equation-like string, like this:
(3n*345sd-4ns)
I would like to split it to this:

Code:



Code:


(,3n,*,345sd,-,4ns,)

Any idea on how to do this?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I realized that was wrong, but I still have no idea how to do what I want to do.
> I'm getting in an equation-like string, like this:
> (3n*345sd-4ns)
> I would like to split it to this:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> (,3n,*,345sd,-,4ns,)
> 
> Any idea on how to do this?


Code:



Code:


string str = "(3n*345sd-4ns)";
string[] parts = str.Split( new[] { '*', '-', '+' } );

Do you need the operators in the split array too? If so then you will need to use Regex:

Code:



Code:


string str = "(3n*345sd-4ns)";
string[] parts = Regex.Split( str, "(\*|\-|\+)" );


----------



## Icekilla

Hey guys. I'm building a Tic-Tac-Toe game for a programming class in C. So far, it seems to be working, but the compiler is throwing some warnings at me, which shouldn't appear. I think they're mistake I've made in my code.



Spoiler: Warning: Spoiler!



Code:



Code:


#include <stdio.h>
#include <stdlib.h>

#define SIZE_MATRIX 3
#define RESETVAL 0
#define POSITION1 0
#define POSITION2 1
#define POSITION3 2
#define SLOTS 9
#define PLAYER1 'X'
#define PLAYER2 'O'

void MatrixPrint(char matrix[SIZE_MATRIX][SIZE_MATRIX])
{
    printf("%c|%c|%c \n", matrix[POSITION1][POSITION1], matrix[POSITION1][POSITION2], matrix[POSITION1][POSITION3]);
    printf("_ _ _ \n");
    printf("%c|%c|%c \n", matrix[POSITION2][POSITION1], matrix[POSITION2][POSITION2], matrix[POSITION2][POSITION3]);
    printf("_ _ _ \n");
    printf("%c|%c|%c \n", matrix[POSITION3][POSITION1], matrix[POSITION3][POSITION2], matrix[POSITION3][POSITION3]);
}

void MatrixInput(char matrix[SIZE_MATRIX][SIZE_MATRIX], char *player)
{
    int vctr_a, vctr_b;

    printf("\nEs turno del jugador %c\n", player);
    printf("Dime la fila (1 a 3): \n");
    scanf("%d", &vctr_a);

    printf("Dime la columna (1 a 3): \n");
    scanf("%d", &vctr_b);

    matrix[vctr_a-1][vctr_b-1] = player;
}

void FunctionCall(char matrix[SIZE_MATRIX][SIZE_MATRIX], char *player)
{
    system("cls");
    MatrixPrint(matrix);
    MatrixInput(matrix, player);
}

void MatrixCleaner(char matrix[SIZE_MATRIX][SIZE_MATRIX])
{
    int vctr_a, vctr_b;
    for(vctr_a = RESETVAL; vctr_a < SIZE_MATRIX; vctr_a++) {
        for(vctr_b = RESETVAL; vctr_b < SIZE_MATRIX; vctr_b++) {
            matrix[vctr_a][vctr_b] = NULL;
        }
    }
}

int main(void)
{
    char matrix[SIZE_MATRIX][SIZE_MATRIX], player;
    int count1 = 0;

    MatrixCleaner(matrix);

    while(count1 < 5) {
        player = PLAYER1;
        FunctionCall(matrix, player);

        player = PLAYER2;
        FunctionCall(matrix, player);

        count1++;
    }

    return EXIT_SUCCESS;
}





The warnings thrown are the following:
Line 26: Format %c expects argument of type 'int', but argument 2 has type 'char *'
Line 33: Assignment makes integer from pointer without a cast (Enabled by default)
Line 48: Same as in line 33
Line 62: Passing argument 2 of 'FunctionCall' makes pointer from integer without a cast
Line 65: Same as in line 62

Also have a note:
Line 36: Expected 'char *' but argument is of type 'char'

I believe I'm getting these warning because I'm not using pointers properly. Anybody has an idea on how to fix that? When I compile and run the code, it works. But I don't want to ignore said notes and warnings to improve my programming skills.

EDIT: Nevermind. Got it to work.


----------



## 3930K

Tompsonn, sorry to bother you again









Could you help me with splitting this:

Code:



Code:


ss234523owre123

into

Code:



Code:


ss 234523 owre 123

? And could you put that in the previous regex? Sorry :/


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> Tompsonn, sorry to bother you again
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Could you help me with splitting this:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> ss234523owre123
> 
> into
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> ss 234523 owre 123
> 
> ? And could you put that in the previous regex? Sorry :/


An array wouldn't work?


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Tompsonn, sorry to bother you again
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Could you help me with splitting this:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> ss234523owre123
> 
> into
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> ss 234523 owre 123
> 
> ? And could you put that in the previous regex? Sorry :/
> 
> 
> 
> An array wouldn't work?
Click to expand...

I meant into an array. Treat ss,234523,owre and 123 as separate items.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Tompsonn, sorry to bother you again
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Could you help me with splitting this:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> ss234523owre123
> 
> into
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> ss 234523 owre 123
> 
> ? And could you put that in the previous regex? Sorry :/


Is it always the same? Or did you give me example text to work with?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Tompsonn, sorry to bother you again
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Could you help me with splitting this:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> ss234523owre123
> 
> into
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> ss 234523 owre 123
> 
> ? And could you put that in the previous regex? Sorry :/
> 
> 
> 
> Is it always the same? Or did you give me example text to work with?
Click to expand...

Example text.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Example text.


OK - is it always two characters, then six, then four and then three? More precisely, is it always two letters, six digits, then four letters, then three digits?


----------



## Fantasy

Guys I need some help.

I want to generate a random number every 255. In other words I want to get either 255 or 512 or 765 or 1020 etc...

I tried using Random class in C# but it only offer max and min values.

any ideas how can I do this?


----------



## 3930K

Quote:


> Originally Posted by *Fantasy*
> 
> Guys I need some help.
> 
> I want to generate a random number every 255. In other words I want to get either 255 or 512 or 765 or 1020 etc...
> 
> I tried using Random class in C# but it only offer max and min values.
> 
> any ideas how can I do this?


Code:



Code:


(Random.Next() % 255) * 255;

And I hope you mean 510 not 512 lol.
This'll get you anything from 0 to 255*255. To increase/decrease the range, change the number to mod by.
Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Example text.
> 
> 
> 
> OK - is it always two characters, then six, then four and then three? More precisely, is it always two letters, six digits, then four letters, then three digits?
Click to expand...

No, I just want to separate digits from characters. If it was a fixed length I would use "whatever".Substring lol.


----------



## andyroo89

In C# how would I send a string over tcp? I am making tcp server/client, and I think I have it to where it can handle multiple clients.

I have it to where it displays a message in notify bubble and I am wanting it to say "hostname" (which I have the string to get the hostname) has connected!

I am on port 9000 to connect back to me, if I want to send a string does it need to be on a different port, or can I use the same port?


----------



## 3930K

MSDN to the rescue!

http://msdn.microsoft.com/en-gb/library/system.net.sockets.tcplistener.aspx

Tutorial there is quite good.


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> (Random.Next() % 255) * 255;
> 
> *And I hope you mean 510 not 512 lol.*
> This'll get you anything from 0 to 255*255. To increase/decrease the range, change the number to mod by.


yah lol. I have been coding for 35 hours straight. my back, head and eyes are killing me.

thanks


----------



## 3930K

Quote:


> Originally Posted by *Fantasy*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> (Random.Next() % 255) * 255;
> 
> *And I hope you mean 510 not 512 lol.*
> This'll get you anything from 0 to 255*255. To increase/decrease the range, change the number to mod by.
> 
> 
> 
> yah lol. I have been coding for 35 hours straight. my back, head and eyes are killing me.
> 
> thanks
Click to expand...

No problem


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> MSDN to the rescue!
> 
> http://msdn.microsoft.com/en-gb/library/system.net.sockets.tcplistener.aspx
> 
> Tutorial there is quite good.


I already have my tcp connection working I am just wanting it to send the hostname to my end and have it say which hostname has connected. I just don't know if I need to do a ASCII encoding or what?


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> MSDN to the rescue!
> 
> http://msdn.microsoft.com/en-gb/library/system.net.sockets.tcplistener.aspx
> 
> Tutorial there is quite good.
> 
> 
> 
> I already have my tcp connection working I am just wanting it to send the hostname to my end and have it say which hostname has connected. I just don't know if I need to do a ASCII encoding or what?
Click to expand...

I think you're looking for a StreamReader/StreamWriter


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> (Random.Next() % 255) * 255;
> 
> And I hope you mean 510 not 512 lol.
> This'll get you anything from 0 to 255*255. To increase/decrease the range, change the number to mod by.
> No, I just want to separate digits from characters. If it was a fixed length I would use "whatever".Substring lol.


Oh I see.
(\w+)|(\d+) may work, I haven't tested it.


----------



## 3930K

Doesn't work


----------



## Icekilla

Hey guys. I'm having a little problem with conversion from character to integer.

I have a project where I have to do this, and that part just won't work. Because of that, I decided to make a small code to test a function named sscanf, which should convert a character, or string, into a number.

Here's the code. However, it won't work.


Spoiler: Warning: Spoiler!



Code:



Code:


#include <stdio.h>
#include <stdlib.h>

int main()
{
    char a, b;
    int a1 = 0, b1 = 0;

    printf("Gimme a number\n");
    scanf("%c", &a);

    scanf ("%*[^\n]");
    getchar();

    printf("Gimme a number\n");
    scanf("%c", &b);

    scanf ("%*[^\n]");
    getchar();

    a = atoi(ach);
    b = atoi(bch);

    printf("num 1: %d\n", a1);
    printf("num 1: %d\n", b1);

    getchar();

    return 0;
}





When I reach the data type conversion, the program crashes. Anyone knows why?


----------



## 3930K

Quote:


> Originally Posted by *Icekilla*
> 
> Hey guys. I'm having a little problem with conversion from character to integer.
> 
> I have a project where I have to do this, and that part just won't work. Because of that, I decided to make a small code to test a function named sscanf, which should convert a character, or string, into a number.
> 
> Here's the code. However, it won't work.
> 
> 
> Spoiler: Warning: Spoiler!
> 
> 
> 
> [#include <stdio.h> #include <stdlib.h> int main() { char a, b; int a1 = 0, b1 = 0; printf("Gimme a number\n"); scanf("%c", &a); scanf ("%*[^\n]"); getchar(); printf("Gimme a number\n"); scanf("%c", &b); scanf ("%*[^\n]"); getchar(); sscanf(a, "%d", &a1); sscanf(b, "%d", &b1); printf("num 1: %d\n", a1); printf("num 1: %d\n", b1); getchar(); return 0; } /CODE]
> 
> 
> When I reach the data type conversion, the program crashes. Anyone knows why?


The code formatting's not right, its unreadable. Wrap the code tags 


Code:


[#include
#include

int main()
{
char a, b;
int a1 = 0, b1 = 0;

printf("Gimme a number\n");
scanf("%c", &a);

scanf ("%*[^\n]");
getchar();

printf("Gimme a number\n");
scanf("%c", &b);

scanf ("%*[^\n]");
getchar();

sscanf(a, "%d", &a1);
sscanf(b, "%d", &b1);

printf("num 1: %d\n", a1);
printf("num 1: %d\n", b1);

getchar();

return 0;
}
/CODE][/SPOILER]

When I reach the data type conversion, the program crashes. Anyone knows why?[/QUOTE]
The code formatting's not right, its unreadable. Wrap the code tags [IMG alt="tongue.gif"]https://www.overclock.net/images/smilies/tongue.gif[/IMG]


----------



## Icekilla

Sorry XD

Fixed

Just to let you know, I changed sscanf for atoi.

NEVERMIND: I used this and it worked

Code:



Code:


a = ach - '0';
b = bch - '0';


----------



## Luminouslight

So the problem is that the input for atoi is that it takes a pointer. So if you

Code:



Code:


#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *  a = "123";
    char *  b = "456";

    printf("%d\n", atoi(a));
    printf("%d\n", atoi(b));

    return 0;
}

That will fix it.

Of course your solution will only work on characters and not strings.

Of course with C you would have to limit your input size otherwise you would get buffer overflow with just these C-Strings if you were to use scanf,

A more correct way to take integer input in C would be to just use scanf("%d", &myint).


----------



## JulioCesarSF

Any tips to translate Windows API to Delphi?









Delphi XE3 here.


----------



## Icekilla

Do people still use Delphi? I though it was deprecated.


----------



## 3930K

Quote:


> Originally Posted by *Icekilla*
> 
> Do people still use Delphi? I though it was deprecated.


It isn't.


----------



## General121

Im probably rather late to the joke, but my coding teacher showed us Google's recursion joke today. Hehe.
Recursion isnt too hard honestly (in java, for me). Granted we haven't gotten into super hard recursion yet I think, though we have done questions that would be on an AP exam (Basically around a 2nd year Comp Sci major class).


----------



## Nhb93

I know it's not the same, but I didn't really know where else to post about this.

I'm trying to transfer from mechanical engineering to computer science. Engineering just isn't what I thought it was going to be like, and I really don't enjoy it even a fraction of what I thought I would. So I'm considering the change, but from bouncing around in here for a while tonight, it sounds like computer science degrees can't get you employed very easily. Is this true? I'm just hoping I'm not throwing away something big.


----------



## 3930K

Not strictly programming, but here goes:


Spoiler: V1, adf.ly has fixed this!



*How to skip adf.ly links:*

Add a bookmark containing

Code:



Code:


javascript:countdown=0; window.location.href=zzz;

as the target.
Go to ad.fly link
Click bookmark
Let person who made whatever you're downloading get profit without waiting an age for it.




adf.ly has fixed it now







I'm still trying to find another way of doing it.


----------



## Fantasy

Why should you do this instead of this?

Code:



Code:


public int number;

Code:



Code:


public int number { get; set; }

I have done some reading and most people say only use properties in an interface. and properties are a wast of free space for other code. Is that true?


----------



## 3930K

Quote:


> Originally Posted by *Fantasy*
> 
> Why should you do this instead of this?
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> public int number;
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> public int number { get; set; }
> 
> I have done some reading and most people say only use properties in an interface. and properties are a wast of free space for other code. Is that true?


No, it's not.
You can say if you want it only to be set internally...

Code:



Code:


public int Number { get; protected set; }

Or even set at all!

Code:



Code:


public int Number { get; }

You can't use bindings with fields, either.


----------



## Fantasy

ok so in your projects, would you always use properties or only when u need them. The thing is I can't decided whether I should always use them or not. I like to keep my code consistent. So should I just stop using variables all together and just use proprieties instead?


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> ok so in your projects, would you always use properties or only when u need them. The thing is I can't decided whether I should always use them or not. I like to keep my code consistent. So should I just stop using variables all together and just use proprieties instead?


In general, publicly accessibly data should be implemented using properties (either auto-property, or a private field as backing store, which can be readonly if necessary, etc).


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *Fantasy*
> 
> ok so in your projects, would you always use properties or only when u need them. The thing is I can't decided whether I should always use them or not. I like to keep my code consistent. So should I just stop using variables all together and just use proprieties instead?
> 
> 
> 
> In general, publicly accessibly data should be implemented using properties (either auto-property, or a private field as backing store, which can be readonly if necessary, etc).
Click to expand...

I would post something like this, but this is explained perfectly. +1, rep+


----------



## Fantasy

ok thanks


----------



## tompsonn

Quote:


> Originally Posted by *Fantasy*
> 
> ok thanks


A property is the same as a method call (if you look at the IL, you'll see the compiler generate methods for the syntactic sugar that is properties), so there is extra overhead than direct access to memory (i.e. field), but not enough to matter.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *Fantasy*
> 
> ok thanks
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> A property is the same as a method call (if you look at the IL, you'll see the compiler generate methods for the syntactic sugar that is properties), so there is extra overhead than direct access to memory (i.e. field), but not enough to matter.
Click to expand...

Someone on SO did a test on this, they got that 1,000,000 accesses to a field is 250ms, and 1,000,000 accesses to a property is 550ms.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Someone on SO did a test on this, they got that 1,000,000 accesses to a field is 250ms, and 1,000,000 accesses to a property is 550ms.


Like I said, not enough to matter


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Someone on SO did a test on this, they got that 1,000,000 accesses to a field is 250ms, and 1,000,000 accesses to a property is 550ms.
> 
> 
> 
> Like I said, not enough to matter
Click to expand...

What I was trying to point out


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> What I was trying to point out


I know I was being a smart ass


----------



## stumped

Quote:


> Originally Posted by *Nhb93*
> 
> I know it's not the same, but I didn't really know where else to post about this.
> 
> I'm trying to transfer from mechanical engineering to computer science. Engineering just isn't what I thought it was going to be like, and I really don't enjoy it even a fraction of what I thought I would. So I'm considering the change, but from bouncing around in here for a while tonight, it sounds like computer science degrees can't get you employed very easily. Is this true? I'm just hoping I'm not throwing away something big.


It depends on the school and where you decide to focus you coding abilities.

For me, Oregon State University seems to have a great compute science program (iirc, one of the HP guys wen there, and I know nvidia co-founder and ceo jen-hsun went there), and intel like hiring/interning people from here. It just depends on the cs program at the school. Also, my area of interest is low-level firmware and systems programming (mainly c and also some assembly).


----------



## General121

Any if you guys know how well gmus comp sci program is?


----------



## General121

Any if you guys know how well gmus comp sci program is?


----------



## Icekilla

According to Wikipedia and this site, George Mason Uni is pretty decent school for CS.

Are you sure you want to transfer, though? There are mechanical engineers who do masters and Ph. D's in computer science and do some amazing things.


----------



## General121

Quote:


> Originally Posted by *Icekilla*
> 
> According to Wikipedia and this site, George Mason Uni is pretty decent school for CS.
> 
> Are you sure you want to transfer, though? There are mechanical engineers who do masters and Ph. D's in computer science and do some amazing things.


Transfer? Why, I am in High school currently haha


----------



## andyroo89

decided to look up on switches, and see if I can use them as a string. I found out I could so I made a text encryption, I do have a question though, how can I add the spaces where needed? lets say for example I put A B C but it spits out cdf without the spaces. or "hello my name is andy" but it spits out "idjenaospcmeajcndl" without the spaces.


----------



## andyroo89

double post (this new mouse causes me to click stuff twice instead of once, and yes it does get annoying when i dont want to double click).


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> decided to look up on switches, and see if I can use them as a string. I found out I could so I made a text encryption, I do have a question though, how can I add the spaces where needed? lets say for example I put A B C but it spits out cdf without the spaces. or "hello my name is andy" but it spits out "idjenaospcmeajcndl" without the spaces.


Split the string by spaces - encrypt each chunk, then join back with spaces.


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Split the string by spaces - encrypt each chunk, then join back with spaces.


Lol I guess mine is not considered an encryption for now (to get the concept down) I have it where it switches the letters nothing too special.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Lol I guess mine is not considered an encryption for now (to get the concept down) I have it where it switches the letters nothing too special.


I figured that bit (and how you were doing it)


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> I figured that bit (and how you were doing it)


oh right lol I mentioned how I was using switch statement and i forgot to mention in c# but I still don't know how though. LOL I tried

case ' ':
textoutput.text += " ";
break;

got an error


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> oh right lol I mentioned how I was using switch statement and i forgot to mention in c# but I still don't know how though. LOL I tried
> 
> case ' ':
> textoutput.text += " ";
> break;
> 
> got an error


A switch statement seems highly inefficient (mainly from a readability and maintainability perspective) for accomplishing this - however, what is the error you are receiving?


----------



## andyroo89

Well I thought I was receiving one, but I'm not now. Works perfect. Also just so I can start expanding my knowledge with encryption how would you go about making it more efficient? I assume algorithms play big part in this?


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Well I thought I was receiving one, but I'm not now. Works perfect. Also just so I can start expanding my knowledge with encryption how would you go about making it more efficient? I assume algorithms play big part in this?


Are you after encryption, or are you after encoding (what you are doing currently is encoding, not encryption)?

Encoding is relatively simple - their algorithms thus so.
Encryption is orders of magnitude more difficult - not being an encryption expert I can't help very much in that area. OpenSSL is a great project to check out the source code, though.


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Are you after encryption, or are you after encoding (what you are doing currently is encoding, not encryption)?
> 
> Encoding is relatively simple - their algorithms thus so.
> Encryption is orders of magnitude more difficult - not being an encryption expert I can't help very much in that area. OpenSSL is a great project to check out the source code, though.


ok um let me put it this way, I would like to encrypt a program or if I wanted to make a p2p and have the messages be encrypted instead of in open view.


----------



## 3930K

Can anyone help me with working out an exponent like this: 234.45^2.43 or something along those lines.

Background: I'm using BigRational for a project, and it doesn't include Pow. For my purposes, I need it. However, I'm really confused. I tried doing something like this:


Code:


pow(base, exponentTruncated) * (base * (exponent - exponentTruncated))

 but this does not work. At all. I don't think it should be worked out like this, anyways.

Sidenote: Huddler, you need an inline code option!


----------



## Sir Amik Vase

A question to anybody who knows about assembly programming,
Can I use two RETURN commands inside one sub-routine?

Ie.
BTFSS Input,0
RETURN
CALL Delaytimer
BSF Output,2
RETURN

Edit: Not sure if it matters but it's for a PIC16F819 controller


----------



## tompsonn

Quote:


> Originally Posted by *Sir Amik Vase*
> 
> A question to anybody who knows about assembly programming,
> Can I use two RETURN commands inside one sub-routine?
> 
> Ie.
> BTFSS Input,0
> RETURN
> CALL Delaytimer
> BSF Output,2
> RETURN
> 
> Edit: Not sure if it matters but it's for a PIC16F819 controller


x86 experience at least tells me that you can't do this. I'm not sure what you'd want to achieve with more than one return instruction...


----------



## {Unregistered}

I've not done a lot of Assembly, but why would you want to have to RETURN commands? Also, in your particular code, if you return, wouldn't it just return from the sub-routine and never reach the code after that?


----------



## tompsonn

Quote:


> Originally Posted by *{Unregistered}*
> 
> I've not done a lot of Assembly, but why would you want to have to RETURN commands? *Also, in your particular code, if you return, wouldn't it just return from the sub-routine and never reach the code after that?*


Yep, lol.


----------



## {Unregistered}

Quote:


> Originally Posted by *tompsonn*
> 
> Yep, lol.


I see.
So how's it going? I'm sorry I've been neglecting my duties on OCN for a while now.


----------



## tompsonn

Quote:


> Originally Posted by *{Unregistered}*
> 
> I see.
> So how's it going? I'm sorry I've been neglecting my duties on OCN for a while now.


Its going good








No need to apologize to me


----------



## {Unregistered}

Quote:


> Originally Posted by *tompsonn*
> 
> Its going good
> 
> 
> 
> 
> 
> 
> 
> 
> No need to apologize to me


----------



## 3930K

Quote:


> Originally Posted by *3930K*
> 
> Can anyone help me with working out an exponent like this: 234.45^2.43 or something along those lines.
> 
> Background: I'm using BigRational for a project, and it doesn't include Pow. For my purposes, I need it. However, I'm really confused. I tried doing something like this:
> 
> 
> Code:
> 
> 
> pow(base, exponentTruncated) * (base * (exponent - exponentTruncated))
> 
> but this does not work. At all. I don't think it should be worked out like this, anyways.
> 
> Sidenote: Huddler, you need an inline code option!


Help?


----------



## Bobicon

Quote:


> Originally Posted by *3930K*
> 
> Help?


This is Java correct?


----------



## briddell

So, I have been wondering, lately, what to do to get into web development, again. I used to mess with HTML5 and some CSS3, but at my heart, I am a desktop developer with C++, not an applet/JS script developer. Any advice for me to get back into it? I only messed around with web dev enough to have an offline copy of my site, before I had a PSU failure on my home-server (it was bound to happen eventually; I threw that thing together out of whatever I could find).

As I get more into web-based integration and internet connectivity with my local apps (all written in C++), I am starting to realize that C++ is not the best language for these projects. I have been looking for a good way to either integrate a higher level language to make the web-integration easier, or find an entirely new language for working with my apps. I am doing all of my dev in an Arch Linux VM running inside of Windows 7 64-bit (for gaming), so Unix compatibility is necessary. I have tried C#, and despite being very powerful for networking, I really hate being tied to Windows, and being so far away from the actual code. Any recommendations? I have considered looking into just using some PHP or Javascript embedded within my C++.

Furthermore, I am going to venture further into game development, now that I am getting pretty deep into C++. In the past, I tinkered with OpenGL, and even got a simple 3D scene to run around in, but as for any actual serious GL, I don't have any experience. How is GL any different from CL? From what I can tell, OpenCL is used for professional applications, such as Photoshop or Vegas, but not normally for games. Is GL more suitable for 2D and 3D game dev, whereas CL is better for hardware acceleration? My only GUI work with C++ has been simple forms and features within them; most of my work is "behind-the-scenes," or console-based.


----------



## 3930K

Quote:


> Originally Posted by *Bobicon*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Help?
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> This is Java correct?
Click to expand...

C#, (bcl.codeplex.com)


----------



## 3930K

Quote:


> Originally Posted by *briddell*
> 
> So, I have been wondering, lately, what to do to get into web development, again. I used to mess with HTML5 and some CSS3, but at my heart, I am a desktop developer with C++, not an applet/JS script developer. Any advice for me to get back into it? I only messed around with web dev enough to have an offline copy of my site, before I had a PSU failure on my home-server (it was bound to happen eventually; I threw that thing together out of whatever I could find).
> 
> As I get more into web-based integration and internet connectivity with my local apps (all written in C++), I am starting to realize that C++ is not the best language for these projects. I have been looking for a good way to either integrate a higher level language to make the web-integration easier, or find an entirely new language for working with my apps. I am doing all of my dev in an Arch Linux VM running inside of Windows 7 64-bit (for gaming), so Unix compatibility is necessary. I have tried C#, and despite being very powerful for networking, I really hate being tied to Windows, and being so far away from the actual code. Any recommendations? I have considered looking into just using some PHP or Javascript embedded within my C++.
> 
> Furthermore, I am going to venture further into game development, now that I am getting pretty deep into C++. In the past, I tinkered with OpenGL, and even got a simple 3D scene to run around in, but as for any actual serious GL, I don't have any experience. How is GL any different from CL? From what I can tell, OpenCL is used for professional applications, such as Photoshop or Vegas, but not normally for games. Is GL more suitable for 2D and 3D game dev, whereas CL is better for hardware acceleration? My only GUI work with C++ has been simple forms and features within them; most of my work is "behind-the-scenes," or console-based.


S
C#, use Mono, and MonoGame. They're really good libraries.


----------



## andyroo89

Which programming language(s) out there don't need dependencies on a windows computer? I think delphi is one of them?


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Which programming language(s) out there don't need dependencies on a windows computer? I think delphi is one of them?


They all need dependencies - where they are directly added in to the executable, or are external to it, is a different story. With Delphi, your program executable has all the required components statically linked in (you can optionally use what is called a Borland Package Library, which is a DLL that is dynamically linked and can be shared across Delphi programs).

The same applies, for example, to the Visual C++ runtime - you can either statically link it, or dynamically link it (dynamic linking requires that the target version of MSVC++ Runtime is installed on the target computer).\

In Delphi, static linking is the default (which is why you may be under the impression that is does not require dependencies).
In Visual C++, dynamic linking is the default.


----------



## {Unregistered}

@Tompsonn, is static linking with C++, usually considered a bad practice?


----------



## tompsonn

Quote:


> Originally Posted by *{Unregistered}*
> 
> @Tompsonn, is static linking with C++, usually considered a bad practice?


No, not really - they both have their ups and downs (applies to any form of static vs. dynamic linking):

- Dynamic linking can reduce resource consumption (DLLs can be shared across processes)
- Dynamic linking allows for bug fixes from the runtime developer to apply to your product without you needing to manually update it and re-distribute it.
- Static linking allows code to run in limited environments (e.g. during boot)
- Static linking makes products easier to distribute (though the product is larger)
- Dynamic linking can cause "DLL hell"
- Dynamic linking can affect performance (DLL load time, which is less of an issue, and code rebasing)


----------



## 3930K

Sorry to sound like a beggar but could someone please help me with my problem?


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> They all need dependencies - where they are directly added in to the executable, or are external to it, is a different story. With Delphi, your program executable has all the required components statically linked in (you can optionally use what is called a Borland Package Library, which is a DLL that is dynamically linked and can be shared across Delphi programs).
> 
> The same applies, for example, to the Visual C++ runtime - you can either statically link it, or dynamically link it (dynamic linking requires that the target version of MSVC++ Runtime is installed on the target computer).\
> 
> In Delphi, static linking is the default (which is why you may be under the impression that is does not require dependencies).
> In Visual C++, dynamic linking is the default.


So... Static linking it brings its own packages that can make itself executable with them

Dynamic linking the packages are on the target computer not with the program?

Any example of dynamic linking would be lets say im installing a game and it tells me I don't have certain version of c++ 2005 and I need to download it on my computer?


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> So... Static linking it brings its own packages that can make itself executable with them
> 
> Dynamic linking the packages are on the target computer not with the program?
> 
> Any example of dynamic linking would be lets say im installing a game and it tells me I don't have certain version of c++ 2005 and I need to download it on my computer?


Static linking causes the compiler to compile the dependencies directly into the executable, they are smart enough to only compile or statically link what is necessary.

Everything else is spot on


----------



## Bobicon

Quote:


> Originally Posted by *3930K*
> 
> Sorry to sound like a beggar but could someone please help me with my problem?


well without knowing Big Rational or C# I have a few questions to ask first.

Does

Code:



Code:


pow(base, exponentTruncated)

work and return a value when used alone?

if not I would assume you are either calling the method wrong or are inputting values which the method does not take.

If it is returning a value I would sugest saving that returned value into a variable and trying to calcuate the final result with third party variables instead of completing the entire calculation in one go.

Also do you have a API link to the Big Rational page for C#?


----------



## 3930K

Quote:


> Originally Posted by *Bobicon*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Sorry to sound like a beggar but could someone please help me with my problem?
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> well without knowing Big Rational or C# I have a few questions to ask first.
> 
> Does
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> pow(base, exponentTruncated)
> 
> work and return a value when used alone?
> 
> if not I would assume you are either calling the method wrong or are inputting values which the method does not take.
> 
> If it is returning a value I would sugest saving that returned value into a variable and trying to calcuate the final result with third party variables instead of completing the entire calculation in one go.
> 
> Also do you have a API link to the Big Rational page for C#?
Click to expand...

You mean a Pow(BigRational, BigInteger)? Yes there is, and it does work. And what do you mean with third-party variables?

BigRational is currently in beta. There isn't an API link.


----------



## Bobicon

Quote:


> Originally Posted by *3930K*
> 
> You mean a Pow(BigRational, BigInteger)? Yes there is, and it does work. And what do you mean with third-party variables?
> 
> BigRational is currently in beta. There isn't an API link.


What I mean by that is do each calculation or function call separately storing them in variables as you go so you know that a value exists then preforming the mathematical calculations (multiplying, subtracting the variables or whatever you need to do) and storing the final result in a variable.

doing it this way would ensure that values exist making it kind of a fool proof method despite the added variables and lines of codes.


----------



## 3930K

Quote:


> Originally Posted by *Bobicon*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> You mean a Pow(BigRational, BigInteger)? Yes there is, and it does work. And what do you mean with third-party variables?
> 
> BigRational is currently in beta. There isn't an API link.
> 
> 
> 
> What I mean by that is do each calculation or function call separately storing them in variables as you go so you know that a value exists then preforming the mathematical calculations (multiplying, subtracting the variables or whatever you need to do) and storing the final result in a variable.
> 
> doing it this way would ensure that values exist making it kind of a fool proof method despite the added variables and lines of codes.
Click to expand...

So like:


Code:


var intPart = Bigarational.Pow(base, truncatedExp);
var rest = //what?
return intPart * rest;


----------



## Bobicon

Quote:


> Originally Posted by *3930K*
> 
> So like:
> 
> 
> Code:
> 
> 
> var intPart = Bigarational.Pow(base, truncatedExp);
> var rest = //what?
> return intPart * rest;


var intPart = Bigarational.Pow(base, truncatedExp);
var sub = exponent - exponentTruncated
var basemult = base*sub
return int IntPart*basemult

maybe throw some print statements of the variables names in between to test that the values exist before and after the calculations as well.


----------



## 3930K

Quote:


> Originally Posted by *Bobicon*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> So like:
> 
> 
> Code:
> 
> 
> var intPart = Bigarational.Pow(base, truncatedExp);
> var rest = //what?
> return intPart * rest;
> 
> 
> 
> 
> 
> var intPart = Bigarational.Pow(base, truncatedExp);
> var sub = exponent - exponentTruncated
> var basemult = base*sub
> return int IntPart*basemult
> 
> maybe throw some print statements of the variables names in between to test that the values exist before and after the calculations as well.
Click to expand...

Doesn't give me the right result.


----------



## Bobicon

Quote:


> Originally Posted by *3930K*
> 
> Doesn't give me the right result.


What is the equation you are trying to replicate?

because you do follow order of operations doing it step by step it would be impossible to come up with a wrong answer unless floating point values are being cut off.


----------



## 3930K

Quote:


> Originally Posted by *Bobicon*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Doesn't give me the right result.
> 
> 
> 
> What is the equation you are trying to replicate?
> 
> because you do follow order of operations doing it step by step it would be impossible to come up with a wrong answer unless floating point values are being cut off.
Click to expand...

Its a pow method. I have no idea HOW to work it out, so the equation IS wrong. Lol


----------



## Sir Amik Vase

I don't suppose that anybody here knows whether using the GOTO function in visual basic for my AS computing exam would or wouldn't get awarded marks?
We haven't been taught to use them and the teacher usually gives me the impression I'm stupid for using it but I find it easier to use than other methods.
The exam is going to be based on writing and modifying encryption software.


----------



## {Unregistered}

Quote:


> Originally Posted by *Sir Amik Vase*
> 
> I don't suppose that anybody here knows whether using the GOTO function in visual basic for my AS computing exam would or wouldn't get awarded marks?
> We haven't been taught to use them and the teacher usually gives me the impression I'm stupid for using it but I find it easier to use than other methods.
> The exam is going to be based on writing and modifying encryption software.


----------



## Sir Amik Vase

Quote:


> Originally Posted by *{Unregistered}*


Maybe... Maybe I shouldn't use goto.
Why exactly is it a bad idea? It's the only command available for jumping around in assembly so I can't see why it's bad to use it in higher levels


----------



## {Unregistered}

Quote:


> Originally Posted by *Sir Amik Vase*
> 
> Maybe... Maybe I shouldn't use goto.
> Why exactly is it a bad idea? It's the only command available for jumping around in assembly so I can't see why it's bad to use it in higher levels


It isn't inherently a bad idea. It just leads to spaghetti code.
Chances are, if you're using a GOTO statement in a higher level language, there is probably a better way to do it.
The whole point of high level languages is that they allow you to structure your code in a better fashion.


----------



## stumped

Quote:


> Originally Posted by *{Unregistered}*
> 
> It isn't inherently a bad idea. It just leads to spaghetti code.
> Chances are, if you're using a GOTO statement in a higher level language, there is probably a better way to do it.
> The whole point of high level languages is that they allow you to structure your code in a better fashion.


But at the same time, goto can allow for better code flow than a large and clunky looking if statement.

@Sir Amik Vase, honestly, it depends on how you used it and the professor's styling preference. IF you do get marked off points and the professor never clearly indicated to you whether or not goto statements are ok, then you *SHOULDN'T* get marked points off, and if you do, you can try to argue them back.

Also, probably 90% of the time, if you are using goto statements in higher level language, then you're most likely writing it incorrectly.


----------



## 3930K

Quote:


> Originally Posted by *stumped*
> 
> Quote:
> 
> 
> 
> Originally Posted by *{Unregistered}*
> 
> It isn't inherently a bad idea. It just leads to spaghetti code.
> Chances are, if you're using a GOTO statement in a higher level language, there is probably a better way to do it.
> The whole point of high level languages is that they allow you to structure your code in a better fashion.
> 
> 
> 
> But at the same time, goto can allow for better code flow than a large and clunky looking if statement.
> 
> @Sir Amik Vase, honestly, it depends on how you used it and the professor's styling preference. IF you do get marked off points and the professor never clearly indicated to you whether or not goto statements are ok, then you *SHOULDN'T* get marked points off, and if you do, you can try to argue them back.
> 
> Also, probably 90% of the time, if you are using goto statements in higher level language, then you're most likely writing it incorrectly.
Click to expand...

I must note one very important exception: in C# switch statements.
For example,this is invalid:


Code:


switch someStr:
case "ab":
//something for the b and then carry on to a
case "a":
//something for a
break;

You have to do this:


Code:


switch someStr:
case "ab":
//something for the b and then carry on to a
goto "a";
case "a":
//something for a
break;

This is to avoid accidentally carrying on.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I must note one very important exception: in C# switch statements.
> For example,this is invalid:
> 
> 
> Code:
> 
> 
> switch someStr:
> case "ab":
> //something for the b and then carry on to a
> case "a":
> //something for a
> break;
> 
> You have to do this:
> 
> 
> Code:
> 
> 
> switch someStr:
> case "ab":
> //something for the b and then carry on to a
> goto "a";
> case "a":
> //something for a
> break;
> 
> This is to avoid accidentally carrying on.


Err...Seeing as there's no condition on your goto for the faux-fallthrough, goto is still unnecessary...

Code:



Code:


switch ( someStr )
{
case "ab":
case "a":
        // something for them both...
}

But its OK I know what you're on about







(Crap example







)


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> I must note one very important exception: in C# switch statements.
> For example,this is invalid:
> 
> 
> Code:
> 
> 
> switch someStr:
> case "ab":
> //something for the b and then carry on to a
> case "a":
> //something for a
> break;
> 
> You have to do this:
> 
> 
> Code:
> 
> 
> switch someStr:
> case "ab":
> //something for the b and then carry on to a
> goto "a";
> case "a":
> //something for a
> break;
> 
> This is to avoid accidentally carrying on.
> 
> 
> 
> Err...Seeing as there's no condition on your goto for the faux-fallthrough, goto is still unnecessary...
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> switch ( someStr )
> {
> case "ab":
> case "a":
> // something for them both...
> }
> 
> But its OK I know what you're on about
> 
> 
> 
> 
> 
> 
> 
> (Crap example
> 
> 
> 
> 
> 
> 
> 
> )
Click to expand...

Good point









Anyways has anoyne noticed how crap the WPF designer is at snapping to a grid's columns/rows, or is it just me?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Good point
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Anyways has anoyne noticed how crap the WPF designer is at snapping to a grid's columns/rows, or is it just me?


The designer is good for two things - previewing the work you did in XAML, and changing properties. It really does suck for "designing". Blend should be better


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Good point
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Anyways has anoyne noticed how crap the WPF designer is at snapping to a grid's columns/rows, or is it just me?
> 
> 
> 
> The designer is good for two things - previewing the work you did in XAML, and changing properties. It really does suck for "designing". Blend should be better
Click to expand...

I'm not doing anything wrong, this is a first! LOL


----------



## 3930K

Can anyone help me get binding into my objects? I'm confused by DependecyProperties


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Can anyone help me get binding into my objects? I'm confused by DependecyProperties


http://msdn.microsoft.com/en-us/library/ms752914.aspx


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Can anyone help me get binding into my objects? I'm confused by DependecyProperties
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> http://msdn.microsoft.com/en-us/library/ms752914.aspx
Click to expand...

MSDN is really good, shame that the search is terrible. Thanks!


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> MSDN is really good, shame that the search is terrible. Thanks!


Google is really good....!


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> MSDN is really good, shame that the search is terrible. Thanks!
> 
> 
> 
> Google is really good....!
Click to expand...

With a filter









Yeah, I know I should do


Code:


*query* site:msdn.microsoft.com


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> With a filter
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Yeah, I know I should do
> 
> 
> Code:
> 
> 
> *query* site:msdn.microsoft.com


Actually I just Googled dependency properties and that page came up first







No filters.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> With a filter
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Yeah, I know I should do
> 
> 
> Code:
> 
> 
> *query* site:msdn.microsoft.com
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Actually I just Googled dependency properties and that page came up first
> 
> 
> 
> 
> 
> 
> 
> No filters.
Click to expand...









Comes second for me, but your point still stands.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> 
> 
> 
> 
> 
> 
> 
> Comes second for me, but your point still stands.


What the one that Google is really good?















MSDN does stink though, unless you know what you're looking for.. or you know the structure of the site (which as you use it more, you end up learning that so its easy to find stuff).


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> 
> 
> 
> 
> 
> 
> 
> Comes second for me, but your point still stands.
> 
> 
> 
> What the one that Google is really good?
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> MSDN does stink though, unless you know what you're looking for.. or you know the structure of the site (which as you use it more, you end up learning that so its easy to find stuff).
Click to expand...

I know how to use the treeviews to find classes, but I can't find tutorials as easily.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I know how to use the treeviews to find classes, but I can't find tutorials as easily.


Start here: http://msdn.microsoft.com/library/default.aspx
Its all pretty logically organized - Google is easier but


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> I know how to use the treeviews to find classes, but I can't find tutorials as easily.
> 
> 
> 
> Start here: http://msdn.microsoft.com/library/default.aspx
> Its all pretty logically organized - Google is easier but
Click to expand...

Thanks


----------



## General121

Any of you know where I can easily learn how to code for Android? One of my friends in my high school class claims he is making 10k/month already off some apps and I need to make some stuff of my own...


----------



## Waffleboy

Quote:


> Originally Posted by *General121*
> 
> Any of you know where I can easily learn how to code for Android? One of my friends in my high school class claims he is making 10k/month already off some apps and I need to make some stuff of my own...


That seems a little dubious to me, but I would start at the source, Android's official documentation and guides: https://developer.android.com/guide/components/index.html


----------



## 3930K

Quote:


> Originally Posted by *General121*
> 
> Any of you know where I can easily learn how to code for Android? One of my friends in my high school class claims he is making 10k/month already off some apps and I need to make some stuff of my own...


Depends, which languages are you familiar with?

If C#: http://xamarin.com/monoforandroid
If C++: http://developer.android.com/tools/sdk/ndk/index.html
If Java: http://developer.android.com/sdk/index.html


----------



## General121

Quote:


> Originally Posted by *Waffleboy*
> 
> That seems a little dubious to me, but I would start at the source, Android's official documentation and guides: https://developer.android.com/guide/components/index.html


thanks. If he isn't lying, how he says he makes his money is he charges 50/month for people to use the program and it's related to mobile games so he would need 200 customers which seems possible


----------



## General121

Quote:


> Originally Posted by *3930K*
> 
> Depends, which languages are you familiar with?
> 
> If C#: http://xamarin.com/monoforandroid
> If C++: http://developer.android.com/tools/sdk/ndk/index.html
> If Java: http://developer.android.com/sdk/index.html


currently learning java, thanks


----------



## Waffleboy

Quote:


> Originally Posted by *General121*
> 
> thanks. If he isn't lying, how he says he makes his money is he charges 50/month for people to use the program and it's related to mobile games so he would need 200 customers which seems possible


It's definitely possible, I would just be skeptical if I were you. I can tell you that my school's average CS graduate makes between 60-70k a year, about half of what your friend is saying, and they are all far more than qualified to do android game dev work.

If you haven't done any programming before, like you indicated above, definitely start with Java before diving into the Android documentation. Start with the basics - learn how basic program flow works, how to use branching and loops, and focus on how to take a larger problem and convert it into smaller, codeable chunks.

Once you can do that decently, dive into the Object Oriented aspect of Java. Make sure you really understand not only what you're doing, but why OOP makes sense as an abstraction (in many cases). If you understand the why part, you will: a) Know when to it's a good idea to use OOP design and, b) Know when a different approach makes more sense.


----------



## andyroo89

Im pretty familiar with C# im gonna try making android apps in C#


----------



## General121

Well the latest work I'm doing in java in class is making guitar hero with a piano instead using Greenfoot


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> Im pretty familiar with C# im gonna try making android apps in C#


Just fyi: max 32KB of user generated IL for the free version!


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Just fyi: max 32KB of user generated IL for the free version!


Feels like you're back in the old days of all those tiny resource restrictions!


----------



## andyroo89

Omg seriously? Ugh.


----------



## DuckKnuckle

I've just started studying programming.

Starting with MIT's Introduction to programming with Python. After that I'll take on a full course with the help of my parents (20+ years in programming).

Is there anything else you guys would recommend when it comes to starting programming? Taking a course in Java?


----------



## andyroo89

Are you planning to use java wherever you work?


----------



## DuckKnuckle

Well programming is the job route I'd like to take. So whatever would be more recommended.


----------



## {Unregistered}

Java would be a good place to start for learning OOP.


----------



## General121

Quote:


> Originally Posted by *{Unregistered}*
> 
> Java would be a good place to start for learning OOP.


OOP?


----------



## tompsonn

Quote:


> Originally Posted by *General121*
> 
> OOP?


Object Oriented Programming. Usually includes examples with cars, dogs and shapes...


----------



## stumped

Quote:


> Originally Posted by *General121*
> 
> OOP?


oop == object oriented programming


----------



## tompsonn

Quote:


> Originally Posted by *stumped*
> 
> oop == object oriented programming


----------



## General121

Quote:


> Originally Posted by *tompsonn*
> 
> Object Oriented Programming. Usually includes examples with cars, dogs and shapes...


Ah, thanks. Nice 777 rep haha.

Im not entirely decided but I think for college I will be going to GMU for a Comp Sci major.
Ive heard wonders about a comp sci major but Ive also heard it was useless for a job/real world..Is this true? Living near DC (40MIN), what income can I roughly expect from a job in North VA, if one of you would know? Ive looked online but not sure about the numbers.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *stumped*
> 
> oop == object oriented programming
Click to expand...

Why are you headscratching?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Why are you headscratching?


Nevermind


----------



## MoonRunes

Quote:


> Originally Posted by *3930K*
> 
> Why are you headscratching?


Aren't programmers always head-scratching?


----------



## stumped

Quote:


> Originally Posted by *MoonRunes*
> 
> Aren't programmers always head-scratching?


touché.


----------



## tompsonn

Often I scratch my ass too.


----------



## MoonRunes

And balls. Don't forget about the balls.


----------



## tompsonn

Quote:


> Originally Posted by *MoonRunes*
> 
> And balls. Don't forget about the balls.


Nah that's the wife's job.


----------



## Delphiwizard

I actually find myself talking to my monitor sometimes while coding, like in 'huh, thats not possible, why doesn't it do that' etc









Like yesterday when i discovered(after 15 minutes) that the problem was my function not returning any result...


----------



## tompsonn

Quote:


> Originally Posted by *Delphiwizard*
> 
> I actually find myself talking to my monitor sometimes while coding, like in 'huh, thats not possible, why doesn't it do that' etc
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Like yesterday when i discovered(after 15 minutes) that the problem was my function not returning any result...


Heheheheheeh you are not alone!


----------



## Fantasy

I'm still alive guys. Don't worry









I have been working non stop and I didn't find the time to visit OCN lately.


----------



## 3930K

Quote:


> Originally Posted by *Fantasy*
> 
> I'm still alive guys. Don't worry
> 
> 
> 
> 
> 
> 
> 
> 
> 
> I have been working non stop and I didn't find the time to visit OCN lately.


How's the tower defence game going? I wanted to see the next beta!


----------



## lessismore11

what is the best place to start learning python???


----------



## 3930K

Quote:


> Originally Posted by *lessismore11*
> 
> what is the best place to start learning python???


If you have little/no programming experience:
codecademy.com

My stupidity. Kept doing


Code:


Matches()[1]

 instead of


Code:


Match().Groups[1]


----------



## Fantasy

Quote:


> Originally Posted by *3930K*
> 
> How's the tower defence game going? I wanted to see the next beta!


coming soon









hopefully next week.


----------



## 3930K

So annoyed, for two days now I've been attacked by serial downvotes on SO.







Someone probably didn't like my review of their question. Imagine how many rage downvotes Skeet gets...


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> So annoyed, for two days now I've been attacked by serial downvotes on SO.
> 
> 
> 
> 
> 
> 
> 
> Someone probably didn't like my review of their question. Imagine how many rage downvotes Skeet gets...


a lot of times I don't even like asking questions there. They just down vote you for no reason. I asked a question related to shell scripting on openwrt router, and I instantly get down voted.


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> So annoyed, for two days now I've been attacked by serial downvotes on SO.
> 
> 
> 
> 
> 
> 
> 
> Someone probably didn't like my review of their question. Imagine how many rage downvotes Skeet gets...
> 
> 
> 
> a lot of times I don't even like asking questions there. They just down vote you for no reason. I asked a question related to shell scripting on openwrt router, and I instantly get down voted.
Click to expand...

They are really quite picky about the right type of question there, newbies normally get voted down a LOT. They are really helpful when you get it right though.


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> They are really quite picky about the right type of question there, newbies normally get voted down a LOT. They are really helpful when you get it right though.


Ya I asked a question on recording from mic from usb soundcard and they were like ErMeRgErD ILLLEGIL DOWN SYNDROME VOTE


----------



## andyroo89

Has anyone done android development with C#? I am thinking of starting to do android development using C# instead of java.


----------



## Delphiwizard

I would like to see what you guys work on and or share what i've been creating the last years.
Is there a topic where developers showoff their creations here?


----------



## andyroo89

Quote:


> Originally Posted by *Delphiwizard*
> 
> I would like to see what you guys work on and or share what i've been creating the last years.
> Is there a topic where developers showoff their creations here?


thats probably xda for you. We really don't do that here. Only time we show our code is when we need help with something.


----------



## 3930K

^ To be fair, you CAN do it: Fantasy's done it with his Tower Defence game.


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> ^ To be fair, you CAN do it: Fantasy's done it with his Tower Defence game.


I didn't mean he couldn't post his code, just saying no one really does.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> I didn't mean he couldn't post his code, just saying no one really does.


I used to. But no one cared


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> I used to. But no one cared


I think some of the code you were posting was maybe too complex for the newb programmers to understand.


----------



## Delphiwizard

Quote:


> Originally Posted by *andyroo89*
> 
> thats probably xda for you. We really don't do that here. Only time we show our code is when we need help with something.


Well i was just curious, and didn't mean 'code' but more the visual aspects, like show the graphical parts of applications and explain what they do, what the purpose of the application is etc.
Sometimes one might pick up ideas that they like and implement them that way too, but i guess many of the appplications written are from peoples jobs and the companies might not like that.

Anyway, just curous.


----------



## 3930K

Quote:


> Originally Posted by *Delphiwizard*
> 
> Quote:
> 
> 
> 
> Originally Posted by *andyroo89*
> 
> thats probably xda for you. We really don't do that here. Only time we show our code is when we need help with something.
> 
> 
> 
> Well i was just curious, and didn't mean 'code' but more the visual aspects, like show the graphical parts of applications and explain what they do, what the purpose of the application is etc.
> Sometimes one might pick up ideas that they like and implement them that way too, but i guess many of the appplications written are from peoples jobs and the companies might not like that.
> 
> Anyway, just curous.
Click to expand...

I'd love it, if nothing just for more activity here


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> I think some of the code you were posting was maybe too complex for the newb programmers to understand.


Haha







I don't know any different


----------



## robE

What advice would you give to someone with 0 coding knowledge who want`s to learn c++ when it comes to IDE, should i use something like codeblocks or should i go hardcore with notepad and compiler ? i don`t care how hard it is, i just want to know what`s better in the long term.

Sorry if it`s off-topic but i didn`t saw any point to open a new topic just for this, thanks!


----------



## kelvintheiah

You could use Visual Studio for c++ coding i believe. I'm a VB.NET programmer in the company im working with.
Quote:


> Originally Posted by *robE*
> 
> What advice would you give to someone with 0 coding knowledge who want`s to learn c++ when it comes to IDE, should i use something like codeblocks or should i go hardcore with notepad and compiler ? i don`t care how hard it is, i just want to know what`s better in the long term.
> 
> Sorry if it`s off-topic but i didn`t saw any point to open a new topic just for this, thanks!


----------



## kelvintheiah

I need help. I would like to start a project to help my current company operation in processing reports. I would like to know if there are any OCR solution in reading handwritten document like sales report and translate it to a text which will be read by an application(which i will be developing using VB.NET). Thanks in advance.


----------



## 3930K

Quote:


> Originally Posted by *robE*
> 
> What advice would you give to someone with 0 coding knowledge who want`s to learn c++ when it comes to IDE, should i use something like codeblocks or should i go hardcore with notepad and compiler ? i don`t care how hard it is, i just want to know what`s better in the long term.
> 
> Sorry if it`s off-topic but i didn`t saw any point to open a new topic just for this, thanks!


I'd use Visual Studio 2012 Express. It's an awesome piece of kit.
Quote:


> Originally Posted by *kelvintheiah*
> 
> I need help. I would like to start a project to help my current company operation in processing reports. I would like to know if there are any OCR solution in reading handwritten document like sales report and translate it to a text which will be read by an application(which i will be developing using VB.NET). Thanks in advance.


That's quite the task, OCR is really very complicated, and then translating that PDF and then using the data, all in VB.NET? You'll lose more man-hours making and updating the program than you will gain using it.


----------



## beyonddc

Quote:


> Originally Posted by *robE*
> 
> What advice would you give to someone with 0 coding knowledge who want`s to learn c++ when it comes to IDE, should i use something like codeblocks or should i go hardcore with notepad and compiler ? i don`t care how hard it is, i just want to know what`s better in the long term.
> 
> Sorry if it`s off-topic but i didn`t saw any point to open a new topic just for this, thanks!


Aside from Visual Studio Express, you can also use Eclipse.
http://www.eclipse.org/downloads/


----------



## kelvintheiah

any solution in mind?
Quote:


> Originally Posted by *3930K*
> 
> I'd use Visual Studio 2012 Express. It's an awesome piece of kit.
> That's quite the task, OCR is really very complicated, and then translating that PDF and then using the data, all in VB.NET? You'll lose more man-hours making and updating the program than you will gain using it.


----------



## 3930K

Quote:


> Originally Posted by *kelvintheiah*
> 
> any solution in mind?
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> I'd use Visual Studio 2012 Express. It's an awesome piece of kit.
> That's quite the task, OCR is really very complicated, and then translating that PDF and then using the data, all in VB.NET? You'll lose more man-hours making and updating the program than you will gain using it.
Click to expand...

Yeah, *don't do it.*


----------



## andyroo89

Ok, peeps, a friend of mine has a small business, and he wants to send out email newsletters. He wants it to be automated, and he asked me if I can make a program for him to do that. I told him he can just add the recipients and do a mass email but, he insisted on having me make him a program.

So, how I have it so far, it uses smtp and I told him he just needs to put his username and password so it will use his gmail account. I also added a multiline textbox where you can add multiple emails (he has a notepad of the emails he wants to send newsletters too, which is why I had that idea to do that) But the problem I am having is, how would I go about having the program read the first line of the email address, send the email and wait a couple of seconds and goes to the next line and does the same thing.

I know I need to use a loop in some way, and tbh idk where to go from there if I need a stream reader or input stream reader.


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> Ok, peeps, a friend of mine has a small business, and he wants to send out email newsletters. He wants it to be automated, and he asked me if I can make a program for him to do that. I told him he can just add the recipients and do a mass email but, he insisted on having me make him a program.
> 
> So, how I have it so far, it uses smtp and I told him he just needs to put his username and password so it will use his gmail account. I also added a multiline textbox where you can add multiple emails (he has a notepad of the emails he wants to send newsletters too, which is why I had that idea to do that) But the problem I am having is, how would I go about having the program read the first line of the email address, send the email and wait a couple of seconds and goes to the next line and does the same thing.
> 
> I know I need to use a loop in some way, and tbh idk where to go from there if I need a stream reader or input stream reader.


You could do something like this:

Instead of pasting in all the emails, put in the path to the file.
Then you can do something like this:



Code:


foreach (var line in File.ReadAllLines(path))
{
	//send emails
	Thread.Sleep(2000); //or await Task.Delay(2000)
}


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> You could do something like this:
> 
> Instead of pasting in all the emails, put in the path to the file.
> Then you can do something like this:
> 
> 
> 
> Code:
> 
> 
> foreach (var line in File.ReadAllLines(path))
> {
> //send emails
> Thread.Sleep(2000); //or await Task.Delay(2000)
> }


I actually added a opefile dialog to load the emails to the textbox.


----------



## kelvintheiah

Hi, the first thing you need to do is to open that notepad of emails(which should be character delimited meaning the email address should be in a format that you can segregate each emails example

email1.yahoo.com;email2.yahoo,com;email3.yahoo.com (example of semi colon segregation)

email1.yahoo.com
email2.yahoo.com
email3.yahoo.com (example of end line or enter segregation)

i would consider using example 2(end line or enter segration) because its readable to the user when adding or removing emails. Next thing you need to do is to traverse that notepad using the preferred formatting by using stream reader. Try this

_*Another possibility is to just read the whole file as a block into a single string and the SPLIT the string on vbcrlf

Dim buf = My.Computer.FileSystem.ReadAllText(Filename)
Dim Lines() = Split(Buf, vbcrlf)
Then, lines will contain all the lines from the file, indexed.

So you could step through them to get each player and his other info.

For x = 0 to ubound(Lines)
'do whatever with each line
next
If the file was HUGE, you wouldn't necessarily want to do it this way, but for small files, it's a quick and easy way to handle it.*_

OR

you can create a module for inserting emails to a database.
Quote:


> Originally Posted by *andyroo89*
> 
> Ok, peeps, a friend of mine has a small business, and he wants to send out email newsletters. He wants it to be automated, and he asked me if I can make a program for him to do that. I told him he can just add the recipients and do a mass email but, he insisted on having me make him a program.
> 
> So, how I have it so far, it uses smtp and I told him he just needs to put his username and password so it will use his gmail account. I also added a multiline textbox where you can add multiple emails (he has a notepad of the emails he wants to send newsletters too, which is why I had that idea to do that) But the problem I am having is, how would I go about having the program read the first line of the email address, send the email and wait a couple of seconds and goes to the next line and does the same thing.
> 
> I know I need to use a loop in some way, and tbh idk where to go from there if I need a stream reader or input stream reader.


----------



## 3930K

I'd personally split it into lines and then do:

Code:



Code:


foreach(string email in File.ReadLines(emailFilePath))
{
   //send email
   await Task.Delay(20);
}


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I'd personally split it into lines and then do:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> foreach(string email in File.ReadLines(emailFilePath))
> {
> //send email
> await Task.Delay(20);
> }


+1
Pretty much wouldn't even bother looking any further past this sort of implementation.
If you're loading from a file to a text box for no benefit other than to just use the contents of the file, you can skip the text box step.


----------



## Icekilla

Hey guys. I'm trying to generate a bunch of struct arrays for a program I'm creating, but for some reason it won't work.

Here's the code in C

Code:



Code:


#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int clave;
    char nombre[50];
}DataBox;

typedef DataBox RegistroOrdenable;

int main()
{
    int n = 20000;
    RegistroOrdenable orig_box1[n];
    RegistroOrdenable orig_box2[n];
    RegistroOrdenable orig_box3[n]; //burbuja
    RegistroOrdenable box1[n];
    RegistroOrdenable box2[n];
    RegistroOrdenable box3[n];
    RegistroOrdenable box4[n];
    RegistroOrdenable box5[n];
    RegistroOrdenable box6[n];
    RegistroOrdenable box7[n];
    RegistroOrdenable box8[n];
    RegistroOrdenable box9[n];
    RegistroOrdenable box10[n];
    RegistroOrdenable box11[n];
    RegistroOrdenable box12[n]; //seleccion
    RegistroOrdenable box13[n];
    RegistroOrdenable box14[n];
    RegistroOrdenable box15[n]; //shellsort

    printf("Hello world!\n");

    return 0;
}

It manages to create orig_box1, but when it tries to generate orig_box 2 then the compiler throws a SIGSEV signal, segmentation fault. For some reason it works for up to 2,000 blocks in each array, but above that, it won't work.

Is there any way to fix this? I'm thinking I'll have to use dynamic memory for this.


----------



## stumped

Quote:


> Originally Posted by *Icekilla*
> 
> Hey guys. I'm trying to generate a bunch of struct arrays for a program I'm creating, but for some reason it won't work.
> 
> Here's the code in C
> 
> 
> Spoiler: Warning: Spoiler!
> 
> 
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> #include <stdio.h>
> #include <stdlib.h>
> 
> typedef struct{
> int clave;
> char nombre[50];
> }DataBox;
> 
> typedef DataBox RegistroOrdenable;
> 
> int main()
> {
> int n = 20000;
> RegistroOrdenable orig_box1[n];
> RegistroOrdenable orig_box2[n];
> RegistroOrdenable orig_box3[n]; //burbuja
> RegistroOrdenable box1[n];
> RegistroOrdenable box2[n];
> RegistroOrdenable box3[n];
> RegistroOrdenable box4[n];
> RegistroOrdenable box5[n];
> RegistroOrdenable box6[n];
> RegistroOrdenable box7[n];
> RegistroOrdenable box8[n];
> RegistroOrdenable box9[n];
> RegistroOrdenable box10[n];
> RegistroOrdenable box11[n];
> RegistroOrdenable box12[n]; //seleccion
> RegistroOrdenable box13[n];
> RegistroOrdenable box14[n];
> RegistroOrdenable box15[n]; //shellsort
> 
> printf("Hello world!\n");
> 
> return 0;
> }
> 
> 
> 
> 
> Spoiler: Warning: Spoiler!
> 
> 
> 
> It manages to create orig_box1, but when it tries to generate orig_box 2 then the compiler throws a SIGSEV signal, segmentation fault. For some reason it works for up to 2,000 blocks in each array, but above that, it won't work.
> 
> Is there any way to fix this? I'm thinking I'll have to use dynamic memory for this.


Because you have such a high number of static declarations so many times, you're trying to allocate a higher value than the stack will allow. You'll have to use dynamic allocation (which draws from the heap).


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> +1
> Pretty much wouldn't even bother looking any further past this sort of implementation.
> If you're loading from a file to a text box for no benefit other than to just use the contents of the file, you can skip the text box step.


I ended up using the timer since task delay was giving me trouble, i got it to send emails but it sent like 3 emails per email address.

I want to send 1 email to 1 person per tick


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> I ended up using the timer since task delay was giving me trouble, i got it to send emails but it sent like 3 emails per email address.
> 
> I want to send 1 email to 1 person per tick


Throw the code on a separate thread and use Thread.Sleep to provide your "tick".


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Throw the code on a separate thread and use Thread.Sleep to provide your "tick".


Here is my source code, I was messing with it so much last night it maybe a bit messy.

http://pastebin.com/eUagPR6C


----------



## kelvintheiah

This should do the trick. After you have send the email, use thread.sleep(xxxx) x means milliseconds of delay.
Quote:


> Originally Posted by *tompsonn*
> 
> Throw the code on a separate thread and use Thread.Sleep to provide your "tick".


----------



## andyroo89

Quote:


> Originally Posted by *kelvintheiah*
> 
> This should do the trick. After you have send the email, use thread.sleep(xxxx) x means milliseconds of delay.


worked perfect, as any programmer I came across another idea, I decided to have it display the last email it sent out, and when i tried to do it I kept getting cross thread problem. So, I used a invoke but I felt like it was just cutting corners

here is the source code to it.

http://pastebin.com/eJzYL8UK

is there a "cleaner" or more efficient way of doing that?


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> worked perfect, as any programmer I came across another idea, I decided to have it display the last email it sent out, and when i tried to do it I kept getting cross thread problem. So, I used a invoke but I felt like it was just cutting corners
> 
> here is the source code to it.
> 
> http://pastebin.com/eJzYL8UK
> 
> is there a "cleaner" or more efficient way of doing that?


There are cleaner ways, yes, but really they all rely on Invoke. This is because you can't perform cross-thread UI operations so you need to marshal yourself to the thread that contains the UI element you want to perform the update on. Which is what Control.Invoke does - it sends a message to the UI element you wish to update to run your callback. Basically the runtime sends a message with a pointer to your delegate to that UI element.

Here's what happens when you call Control.Invoke - it calls down to a private method called MarshaledInvoke:

Code:



Code:


private object MarshaledInvoke(Control caller, Delegate method, object[] args, bool synchronous)
{
      int num;
      if (!this.IsHandleCreated)
      {
            throw new InvalidOperationException(SR.GetString("ErrorNoMarshalingThread"));
      }
      if (((ActiveXImpl) this.Properties.GetObject(PropActiveXImpl)) != null)
      {
            IntSecurity.UnmanagedCode.Demand();
      }
      bool flag = false;
      if ((SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, this.Handle), out num) == SafeNativeMethods.GetCurrentThreadId()) && synchronous)
      {
            flag = true;
      }
      ExecutionContext executionContext = null;
      if (!flag)
      {
            executionContext = ExecutionContext.Capture();
      }
      ThreadMethodEntry entry = new ThreadMethodEntry(caller, this, method, args, synchronous, executionContext);
      lock (this)
      {
            if (this.threadCallbackList == null)
            {
                  this.threadCallbackList = new Queue();
            }
      }
      lock (this.threadCallbackList)
      {
            if (threadCallbackMessage == 0x0)
            {
                  threadCallbackMessage = SafeNativeMethods.RegisterWindowMessage(Application.WindowMessagesVersion + "_ThreadCallbackMessage");
            }
            this.threadCallbackList.Enqueue(entry);
      }
      if (flag)
      {
            this.InvokeMarshaledCallbacks();
      }
      else
      {
            UnsafeNativeMethods.PostMessage(new HandleRef(this, this.Handle), threadCallbackMessage, IntPtr.Zero, IntPtr.Zero);
      }
      if (!synchronous)
      {
            return entry;
      }
      if (!entry.IsCompleted)
      {
            this.WaitForWaitHandle(entry.AsyncWaitHandle);
      }
      if (entry.exception != null)
      {
            throw entry.exception;
      }
      return entry.retVal;
}


----------



## ronnin426850

I suggest opening a multiple-selection poll with IDEs to see which is most popular here on OCN


----------



## Icekilla

Ok, So I'm trying again, but this time with dynamic memory.

Code:



Code:


#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int clave;
    char nombre[50];
}DataBox;

typedef DataBox RegistroOrdenable;

int main()
{
    int n = 20000;
    RegistroOrdenable* orig_box1, orig_box2, orig_box3, //burbuja
                         box1, box2, box3; //I'm gonna recycle them all over and over

    orig_box1 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));
    orig_box2 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));
    orig_box3 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));
    box1 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));
    box2 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));
    box3 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));

    printf("Assignment succesful\n");

   return 0;
}

But on line 18 I get an error that says "Incompatible types when assigning to type 'RegistroOrdenable' from type 'struct RegistroOrdenable *'. Why is this happening?


----------



## {Unregistered}

Quote:


> Originally Posted by *Icekilla*
> 
> Ok, So I'm trying again, but this time with dynamic memory.
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> #include <stdio.h>
> #include <stdlib.h>
> 
> typedef struct{
> int clave;
> char nombre[50];
> }DataBox;
> 
> typedef DataBox RegistroOrdenable;
> 
> int main()
> {
> int n = 20000;
> RegistroOrdenable* orig_box1, orig_box2, orig_box3, //burbuja
> box1, box2, box3; //I'm gonna recycle them all over and over
> 
> orig_box1 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));
> orig_box2 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));
> orig_box3 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));
> box1 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));
> box2 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));
> box3 = (RegistroOrdenable*)malloc(n*sizeof(RegistroOrdenable));
> 
> printf("Assignment succesful\n");
> 
> return 0;
> }
> 
> But on line 18 I get an error that says "Incompatible types when assigning to type 'RegistroOrdenable' from type 'struct RegistroOrdenable *'. Why is this happening?


Are you trying to create all of orig_box1, 2, 3 and box 1,2,3 as pointers? Because your current code only creates orig_box1 as a pointer RegistroOrdenable*, but creates the rest as RegistroOrdenable types, instead.

You should put the * sign, in front of each of the variables defined:

Code:



Code:


RegistroOrdenable *orig_box1, *orig_box2, *orig_box3, //burbuja
                         *box1, *box2, *box3; //I'm gonna recycle them all over and over


----------



## tompsonn

Quote:


> Originally Posted by *{Unregistered}*
> 
> Are you trying to create all of orig_box1, 2, 3 and box 1,2,3 as pointers? Because your current code only creates orig_box1 as a pointer RegistroOrdenable*, but creates the rest as RegistroOrdenable types, instead.
> 
> You should put the * sign, in front of each of the variables defined:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> RegistroOrdenable *orig_box1, *orig_box2, *orig_box3, //burbuja
> *box1, *box2, *box3; //I'm gonna recycle them all over and over


Classic C mistake








+1


----------



## andyroo89

Hey guys I am back with another question, I currently made a if statement to send emails if whether or not they have an email attachment. It works and all but its only working because of this

Code:



Code:


TextBox.CheckForIllegalCrossThreadCalls = false;

I feel like its bad programming practice to use a shortcut like this, and would like to know how can I properly program it

here is small example of how I have it.

if(textBox3.TextLength > 0)
{
do stuff here
}
else if(textBox3.TextLength == 0)
{
do stuff
}

so how would I do it in good practice?


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> Hey guys I am back with another question, I currently made a if statement to send emails if whether or not they have an email attachment. It works and all but its only working because of this
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> TextBox.CheckForIllegalCrossThreadCalls = false;
> 
> I feel like its bad programming practice to use a shortcut like this, and would like to know how can I properly program it
> 
> here is small example of how I have it.
> 
> if(textBox3.TextLength > 0)
> {
> do stuff here
> }
> else if(textBox3.TextLength == 0)
> {
> do stuff
> }
> 
> so how would I do it in good practice?


WPF or Winforms?


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> WPF or Winforms?


winforms


----------



## 3930K

Try using


Code:


int textLength = (int)textBox3.Invoke(() => { return textBox3.TextLength; })

 and then using that int instead of the property. Do the same with all the other cross-thread calls.


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> Try using
> 
> 
> Code:
> 
> 
> int textLength = (int)textBox3.Invoke(() => { return textBox3.TextLength; })
> 
> and then using that int instead of the property. Do the same with all the other cross-thread calls.


I get a sqwiggle under (() and the error says "cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type.


----------



## 3930K

Try


Code:


int textLength = (int)textBox3.Invoke(new Func<int>(() => { return textBox3.TextLength; }))


----------



## andyroo89

Quote:


> Originally Posted by *3930K*
> 
> Try
> 
> 
> Code:
> 
> 
> int textLength = (int)textBox3.Invoke(new Func<int>(() => { return textBox3.TextLength; }))


thank you that worked.


----------



## tompsonn

I'd probably be setting a flag rather than checking the length of the text box.
Before you kick off the thread, set a variable (make it volatile) - then test the value of the variable in the thread. e.g.

Code:



Code:


class SomeClass
{
        private voltatile bool _hasAttachment;
        public void SendMail()
        {
                // .. init stuff
                this._hasAttachment = ( textBox3.Text.Length > 0 );

                // .. kick off thread
                //
        }

        private void _SendMailThread()
        {
                if ( this._hasAttachment )
                {
                        // ..
                }
                else
                {
                        // ..
                }
        }
}


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> I'd probably be setting a flag rather than checking the length of the text box.
> Before you kick off the thread, set a variable (make it volatile) - then test the value of the variable in the thread. e.g.
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> class SomeClass
> {
> private voltatile bool _hasAttachment;
> public void SendMail()
> {
> // .. init stuff
> this._hasAttachment = ( textBox3.Text.Length > 0 );
> 
> // .. kick off thread
> //
> }
> 
> private void _SendMailThread()
> {
> if ( this._hasAttachment )
> {
> // ..
> }
> else
> {
> // ..
> }
> }
> }


The problem is, what if the user types in before _SendMailThread but after capturing the variable? But I like volatile variables.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> The problem is, what if the user types in before _SendMailThread but after capturing the variable? But I like volatile variables.


Its not possible... the user would have to initiate the action of sending the mail. That would be after they fill all the fields in.

They type the fields in. They click a button. You call SendMail. You set up the state. You disable the form. You start the thread. No race condition


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> The problem is, what if the user types in before _SendMailThread but after capturing the variable? But I like volatile variables.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Its not possible... the user would have to initiate the action of sending the mail. That would be after they fill all the fields in.
> 
> They type the fields in. They click a button. You call SendMail. You set up the state. You disable the form. You start the thread. No race condition
Click to expand...

Good point there


----------



## 3930K

Just wondering, who agrees with this MSDN thread? http://social.msdn.microsoft.com/Forums/en-US/vssetup/thread/840efe4b-7e6a-4959-bbcc-0dfac4f766b6

I don't.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Just wondering, who agrees with this MSDN thread? http://social.msdn.microsoft.com/Forums/en-US/vssetup/thread/840efe4b-7e6a-4959-bbcc-0dfac4f766b6
> 
> I don't.


Yeah I don't agree. I don't even really care what it looks like, for I focus on the big white bit in the middle with the colored words.


----------



## ivr56

Messing with MaxMSP, Kinect/Synapze and Resolume Arena 4.
I can control video sequencing for live preformance by keeping track of head movements and then converting the value into a MIDI note.


----------



## Thereoncewasamaninparis

What are some good open source collaborative software development websites? Trying to get going with java on something but github is mostly javascript and javaforge appears to have mostly dead projects. Where the hell does everyone go?


----------



## tompsonn

Quote:


> Originally Posted by *Thereoncewasamaninparis*
> 
> What are some good open source collaborative software development websites? Trying to get going with java on something but github is mostly javascript and javaforge appears to have mostly dead projects. Where the hell does everyone go?


Sourceforge - http://sourceforge.net/directory/language:java/os:windows/freshness:recently-updated/
CodePlex - but doubt you'll find much, if any, Java there
Google Code - http://code.google.com/hosting/search?q=label%3aJava


----------



## Waffleboy

Quote:


> Originally Posted by *Thereoncewasamaninparis*
> 
> What are some good open source collaborative software development websites? Trying to get going with java on something but github is mostly javascript and javaforge appears to have mostly dead projects. Where the hell does everyone go?


Hmm, as far as I've seen at least, Java isn't hugely popular for open source developers. You'd have more luck with Python or C I think.


----------



## andyroo89

Does anyone else go on sourceforge or github or stackoverflow and look at source codes (if available) of a project your working on if youre having trouble with something? I do it sometimes if I am stuck, and in a way I feel like im cheating.







I have some ebooks for programming some of them have been somewhat helpful.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Does anyone else go on sourceforge or github or stackoverflow and look at source codes (if available) of a project your working on if youre having trouble with something? *I do it sometimes if I am stuck, and in a way I feel like im cheating*.
> 
> 
> 
> 
> 
> 
> 
> I have some ebooks for programming some of them have been somewhat helpful.


How else does one learn? I would be very surprised if any programmer here came and said "I've never googled something". Source code is great asset to have, especially if its a library you are using in one of your projects however the important thing to remember is to distinguish between was is implementation detail and what is contractual.

Its fine to look at the source code to see how something works, but if its implementation detail it is important to not program around it, because you cannot rely it will continue working that way in the future - however to better understand the internal workings of something, it is invaluable.

I myself have the CLR source code (albeit outdated, but still handy) if I need to find out how something works inside the CLI (http://en.wikipedia.org/wiki/Shared_Source_Common_Language_Infrastructure) - but of course after reading the documentation (which is contractual).

In fact I would encourage your usage of sourceforge, etc, it is very beneficial - looking at code is a great way to learn this art. Books are great, but I find practical resources such as real-world source code (not junk in a chapter example) are excellent for learning.


----------



## andyroo89

Ok, I feel better about myself.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Ok, I feel better about myself.


----------



## trollface123

hey, compile the assembly code in my avatar with FASM


----------



## Thereoncewasamaninparis

Quote:


> Originally Posted by *tompsonn*
> 
> Sourceforge - http://sourceforge.net/directory/language:java/os:windows/freshness:recently-updated/
> CodePlex - but doubt you'll find much, if any, Java there
> Google Code - http://code.google.com/hosting/search?q=label%3aJava


Thanks, it looks like google code will be my option. I've been wanting to reuild lemmings and I figured that is where I will go since a)more java jobs than c# and b)mobile is the future.


----------



## 3930K

Quote:


> Originally Posted by *Thereoncewasamaninparis*
> 
> Quote:
> 
> 
> 
> Originally Posted by *tompsonn*
> 
> Sourceforge - http://sourceforge.net/directory/language:java/os:windows/freshness:recently-updated/
> CodePlex - but doubt you'll find much, if any, Java there
> Google Code - http://code.google.com/hosting/search?q=label%3aJava
> 
> 
> 
> Thanks, it looks like google code will be my option. I've been wanting to reuild lemmings and I figured that is where I will go since a)more java jobs than c# and b)mobile is the future.
Click to expand...

Just wondering, where's your data saying that there's more Java jobs than C# jobs?


----------



## m98custom1212

I graduated with degree in Mechanical Engineering but going back in the Fall to learn programming. I need to learn C++ and Visual Basic for the CAD/CAM program, I use at work. This will allow me to can make custom dialog boxes, custom algorithms for machining parts and designing parts.

Highlights

Going to School in the Fall for computer programming looking at getting ahead start in c++ and visual basic


----------



## ltpenguin

Quote:


> Originally Posted by *m98custom1212*
> 
> Going to School in the Fall for computer programming looking at getting ahead start in c++ and visual basic


I personally wouldn't, classes are really boring when you aren't learning anything :I


----------



## m98custom1212

Quote:


> Originally Posted by *ltpenguin*
> 
> I personally wouldn't, classes are really boring when you aren't learning anything :I


Think its better move to just learn on my own then?


----------



## ivr56

Kinect Controlled Sequencer I finished
Tracking objects via infared in MaxMSP. Then values converted for use in the step sequencer. MIDI notes are created on bangs and sent to Resolume Arena 4 to trigger image clips.
Kinect Mask was taken from MaxMSP then sent through Syphon to Resolume Arena 4 to be layered on top of the video. Compiled video of movement sequenced images, live video and Kinect mask from Arena is sent though Syphpon to two versions of Madmapper to 3D projection map onto a wall and a Grand piano.



Max is a great piece of software if you happen to be into music or video processing and production. Easy to pick up and integrate with so many other pieces of software. Syphon is something on Windows I have yet to find a equivalent to. Daisy chaining multiple 720p video feeds though half a dozen pieces of software without lag? Yup


----------



## Thereoncewasamaninparis

Quote:


> Originally Posted by *3930K*
> 
> Just wondering, where's your data saying that there's more Java jobs than C# jobs?


Just observations for the Colorado front range area. Hell I see more ruby on rail jobs available on dice.com than I do .Net/C#(or even VB). Plus, even when you do find one, you have about a 50/50 chance of it being an ASP.net web development related job.


----------



## Thereoncewasamaninparis

Quote:


> Originally Posted by *m98custom1212*
> 
> Think its better move to just learn on my own then?


Unless you're someone like me without any imagination to come up with a project on their own, school has a nice flow to it for people that need a little more guidance. I can't come up with a problem to solve, but place one in front of me and I'll figure it out eventually.


----------



## 3930K

Quote:


> Originally Posted by *Thereoncewasamaninparis*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Just wondering, where's your data saying that there's more Java jobs than C# jobs?
> 
> 
> 
> Just observations for the Colorado front range area. Hell I see more ruby on rail jobs available on dice.com than I do .Net/C#(or even VB). Plus, even when you do find one, you have about a 50/50 chance of it being an ASP.net web development related job.
Click to expand...

Just looked it up on careers.stackoverflow.com, it seems like there's about 1.5x Java jobs as C#, but if you get to the UK C# overtakes. As you point out there does seem to be a lot of ASP.NET jobs & the locale really effects C# v Java.
What makes it even more interesting is that there is usually more questions in SO about C# in GMT time, but when you get to night Java overtakes.

Conclusion: Java is used more in USA, C# is (barely) used more in the UK/Europe.


----------



## andyroo89

I am a self taught "programmer" (WIP) I have couple of friends in programming class and they just work on the examples from the book. imo not very effective way of learning.


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> I am a self taught "programmer" (WIP) I have couple of friends in programming class and they just work on the examples from the book. imo not very effective way of learning.


Um, yeah: got experience with both here.
I agree with his advice, just reading and following books isn't good enough, even if they're Jon Skeet's books.


----------



## andyroo89

Ok, guys, I just started programming in pascal using lazarus, and I am trying to resize an image to same size at TImage (same thing as picturebox in C#) but I cannot seem to get it resized. I asked this question on stackoverflow. At the time of the post no one has responded. So, maybe someone will after I go to sleep. If anyone has any idea. Let me know.

http://stackoverflow.com/questions/17206156/resize-image-in-lazarus-or-delphi

edit; wow nevermind, someone helped me as I was posting this..


----------



## 3930K

Hey look, VS 2013 preview's announced, along with .NET 4.5.1 (what kind of a name is that!?)
http://www.microsoft.com/visualstudio/eng/2013-preview


----------



## BuizelON

Quote:


> Originally Posted by *3930K*
> 
> Hey look, VS 2013 preview's announced, along with .NET 4.5.1 (what kind of a name is that!?)
> http://www.microsoft.com/visualstudio/eng/2013-preview


NOOO!!! We must not fuel the evil Microsoft's life source (a.k.a. money) or it will continue to survive and dirty this world of crappy operating systems and closed source software!!!


----------



## andyroo89

I started to learn delphi well pascal but I see it as fun language. Great for side projects, and hobbying.


----------



## Delphiwizard

It should be the choice for main projects









(as my nickname tells, i'm a long term pascal/delphi fanatic)


----------



## andyroo89

Quote:


> Originally Posted by *Delphiwizard*
> 
> It should be the choice for main projects
> 
> 
> 
> 
> 
> 
> 
> 
> 
> (as my nickname tells, i'm a long term pascal/delphi fanatic)


Oh I have so many questions to ask. I may do it through pm if thats ok?


----------



## Delphiwizard

Sure, go ahead.

I hope i'll be able to answer, despite my long term use of Delphi there are parts i'm not 100% up to date on(like dotnet).


----------



## 179232

Should I take C at my college? I was thinking of minoring in CS but I had an extremely bad experience with Intro to Python. I had no prior programming experience when I took it. The first 80% of it was interesting, like learning syntax, lists, dictionaries, etc. However, when we got to GUI's, nobody understood anything that was going on. Hell I got a 12/33 on my final exam and that was a solid B. Like literally nobody in the class knew how to code for the GUI. Even the TA's were completely lost.

So should I take C?

Here is the course:
Quote:


> Expanded Course Description:
> 
> Introduction: The computer, steps in solving a problem using a computer.
> Algorithms: General concept, development of efficient algorithms.
> Programming in C
> Scalar data types, concept of data type, standard and user-defined scalar types.
> Simple Statements, arithmetic and boolean expressions, assignment statements, simple input and output statements.
> Flow of control, repetitive statements, conditional statements, unconditional branching
> Data structures: single and multidimensional arrays; character strings; structs.
> Functions: general concept; declaration and calls; & and * operators; parameters; introduction to recursion.
> Software engineering: running, debugging, testing programs, building quality programs.


http://www.cs.ucdavis.edu/courses/exp_course_desc/30.html


----------



## WroLeader

What do you people think of Microsoft's XAML? I've been messing with it so far in Visual Studio and find it to be pretty fun to play around with.


----------



## Xeio

Quote:


> Originally Posted by *WroLeader*
> 
> What do you people think of Microsoft's XAML? I've been messing with it so far in Visual Studio and find it to be pretty fun to play around with.


It's great as long as you don't mind the lack of mono compatibility. Particularly compared to win forms. Moving layouts to be more automatic like html is cool, and for that matter that you can work entirely in markup if you want.

My work uses winforms though so I haven't done much more than play around with it.


----------



## Ryanb213

Anyone care to scrutinize my pagination logic in php?

It works just fine, however I have the feeling it can be done more efficiently.

$page is the current page number.
$pages is the total number of pages.

Code:



Code:


            <?php
            //first page
            if (($page) > 4) {
                echo "[*][URL=]«[/URL]";
            }

            //previous page
            if ($page >= 2 && $page <= $pages) {
                echo "[*][URL=]‹[/URL]";
            } else {
                echo "[*]<a>‹</a>";
            }

            //3 pages ago
            if (($page - 3) > 0) {
                echo "[*][URL=]" . ( $page - 3) . "[/URL]";
            }

            //2 pages ago
            if (($page - 2) > 0) {
                echo "[*][URL=]" . ( $page - 2) . "[/URL]";
            }

            //1 page ago
            if (($page - 1) > 0) {
                echo "[*][URL=]" . ( $page - 1) . "[/URL]";
            }

            //current page
            echo "[*]<a>$page</a>";

            if (($page + 1) <= $pages) {
                //1 page forward
                echo "[*][URL=]" . ( $page + 1) . "[/URL]";
            }

            //2 pages forward
            if (($page + 2) <= $pages) {
                echo "[*][URL=]" . ( $page + 2) . "[/URL]";
            }

            //3 pages forward
            if (($page + 3) <= $pages) {
                echo "[*][URL=]" . ( $page + 3) . "[/URL]";
            }

            //next page
            if ($page < $pages && $page >= 1) {
                echo "[*][URL=]›[/URL]";
            } else {
                echo "[*]<a>›</a>";
            }

            //last page
            if (($page) <= ($pages -4)) {
                echo "[*][URL=]»[/URL]";
            }
            ?>


----------



## tompsonn

Quote:


> Originally Posted by *Ryanb213*
> 
> Anyone care to scrutinize my pagination logic in php?
> 
> It works just fine, however I have the feeling it can be done more efficiently.
> 
> $page is the current page number.
> $pages is the total number of pages.
> 
> --snip--


Functional, but messy... Potentially hard to maintain. I wrote a generic pagination class some time ago you may use if you wish:


Spoiler: Warning: Spoiler!



Code:



Code:


<?php
/**
 * PHP Portable Code Kernel
 * Kernel class for handling custom pagination methods.
 *
 * $Id: classPagination.php 1623 2011-01-23 14:19:56Z tompsonn $
 *
 * @author              $Author: tompsonn $
 * @version             $Revision: 1623 $
 * @copyright   (c) 2009 Futurion Power Interactive
 * @license     http://opensource.org/licenses/gpl-2.0.php
 * @package             coreKernel
 *
 **/

/**
 *
 */

/**
 * Kernel Pagination Class
 *
 * Manages pagination for dynamic content building and creates 
 * an extensible interface for doing so.
 *
 * @package             coreKernel::Classes
 */
class classPagination
{
        /**#@+
         * Auto Format Methods
         */
        const AF_METHOD_FIRST   = 0x1;
        const AF_METHOD_PREV    = 0x2;
        const AF_METHOD_PAGE    = 0x4;
        const AF_METHOD_NEXT    = 0x8;
        const AF_METHOD_LAST    = 0x16;
        const AF_METHOD_CURR    = 0x32;
        const AF_METHOD_DOTS    = 0x64;
        /**#@-*/

        /**
         * Data Object
         *
         * @access      protected
         * @var object
         */
        protected $dataObject;

        /**
         * Auto Format Method
         *
         * @access      protected
         * @var array
         */
        protected $autoFormatMethod;

        /**
         * Default Auto Format Method
         *
         * @access      protected
         * @var array
         */
        protected $defaultAutoFormatMethod;

        /**
         * Page Links Array
         *
         * @access      protected
         * @var array
         */
        protected $links;

        /**
         * Total Pages
         *
         * @access      protected
         * @var integer
         */
        protected $totalPages;

        /**
         * Current Page
         *
         * @access      protected
         * @var integer
         */
        protected $pageCurrent;

        /**
         * Create Wrapper
         *
         * Simplified interface to create a new pagination object
         * ready for use.
         *
         * @access      public
         * @param       integer Total number of results or items.
         * @param       integer Total number of items to show per page.
         * @param       integer Current page count.
         * @param       integer Number of pages to leave out on either side of the current page
         *                              in the page link listing.
         * @return      object
         */
        public static function create( $totalResults = 0, $perPage = 0, $current = 0, $strip = 2 )
        {
                /* Create */
                $obj = new self();
                $obj->init( ( object ) 
                                        array( 'total'   => $totalResults,
                                                 'perPage' => $perPage,
                                                 'current' => $current,
                                                 'strip'   => $strip ) );

                return $obj;    
        }

        /**
         * Initialize
         *
         * Sets up core components to run the pagination.
         *
         * @access      protected
         * @param       object  Data object containing configuration etc.
         * @return      void
         */
        protected function init( $dataObject )
        {
                /* INIT */
                $this->dataObject                    = $dataObject;
                $this->defaultAutoFormatMethod       = array( __CLASS__, '__autoFormatCallback' );

                /* Register default */
                $this->registerAutoFormatMethod( $this->defaultAutoFormatMethod );        
        }

        /**
         * Get Links
         *
         * Does the main work to get the page links and returns them as a
         * raw array.
         *
         * Note: The links may be auto-formatted using a custom or default
         * handler, or you can do your own processing altogether.
         *
         * @access      public
         * @return      array
         */
        public function getLinks()
        {
                /* INIT */
                $_d =& $this->dataObject;

                /* Declare links */
                $this->links         = array(        'PREV'  => NULL, 
                                                                'NEXT'  => NULL, 
                                                                'FIRST' => NULL, 
                                                                'LAST'  => NULL,
                                                                'PAGES' => NULL, 
                                                                'CURR'  => NULL );
                /* Declare vars */
                $this->totalPages            = 1;
                $this->pageCurrent   = NULL;

                /* Get total pages */
                $this->totalPages = ( ( $_d->total % $_d->perPage == 0 ) ? $_d->total / $_d->perPage : 
                                                                                             ceil( $_d->total / $_d->perPage ) );

                /* Current page */
                $this->pageCurrent = ( $_d->current > 0 ) ? ( $_d->current / $_d->perPage ) + 1 : 1;

                /* Process */
                if ( $this->totalPages > 1 )
                {
                        /* Previous page link */
                        if ( ( $_d->current - $_d->perPage ) >= 0 )
                        {
                                $previous = ( $_d->current - $_d->perPage );
                                $this->links['PREV'] = $previous;
                        }

                        /* Next page link */
                        if ( $this->pageCurrent < $this->totalPages )
                        {
                                $next = ( $_d->current + $_d->perPage );
                                $this->links['NEXT'] = $next;
                        }

                        /* Loop through page links */
                        for ( $i = 0; $i <= $this->totalPages - 1; $i++ )
                        {
                                $realPage       = $i * $_d->perPage;
                                $page           = $i + 1;

                                /* Current page */
                                if ( $realPage == $_d->current )
                                {
                                        $this->links['CURR'] = $realPage;
                                }

                                /* Strip out... */
                                if ( $page < ( $this->pageCurrent - $_d->strip ) )
                                {
                                        $this->links['PAGES'][ $realPage ] = $page;
                                        $this->links['PAGES'][ $realPage . '_dots' ] .= '...';

                                        $i = $this->pageCurrent - $_d->strip - 2;
                                        continue;
                                }

                                /* First and last */
                                $this->links['FIRST'] = ( $page < $this->pageCurrent ) ? 0 : $this->links['FIRST'];
                                $this->links['LAST']  = ( $page > $this->pageCurrent ) ? ( $this->totalPages - 1 ) * $_d->perPage 
                                                                                                         : ( $this->links['LAST']  ); /* Last */

                                /* Strip out... */
                                if ( $page > ( $this->pageCurrent + $_d->strip ) )
                                {
                                        $this->links['PAGES'][ $realPage . '_dots' ] = '...';
                                        $this->links['PAGES'][ $this->links['LAST'] ] .= $this->totalPages;

                                        break;
                                }

                                $this->links['PAGES'][ $realPage ] = $page;
                        }
                }
                else
                {
                        /* Only the one page */
                        $this->links['CURR']     = 0;
                        $this->links['PAGES'][0] = 1;
                }

                return $this->links;
        }

        /**
         * Auto Format
         *
         * Wrapper to automatically call the auto format method that has
         * been registered.
         *
         * @access      public
         * @return      string
         */
        public function autoFormat()
        {
                /* INIT */
                $links = $this->links;
                $pages = "";

                $first = ( $links['FIRST'] !== NULL ) ? $this->callAutoFormatMethod( self::AF_METHOD_FIRST, $links['FIRST'] ) : '';
                $prev  = ( $links['PREV']  !== NULL ) ? $this->callAutoFormatMethod( self::AF_METHOD_PREV, $links['PREV'] ) : '';
                $next  = ( $links['NEXT']  !== NULL ) ? $this->callAutoFormatMethod( self::AF_METHOD_NEXT, $links['NEXT'] ) : '';
                $last  = ( $links['LAST']  !== NULL ) ? $this->callAutoFormatMethod( self::AF_METHOD_LAST, $links['LAST'] ) : '';

                foreach ( $links['PAGES'] as $k => $v )
                {
                        $data = ( object ) array( 'real' => $k, 'page' => $v );

                        if ( ( $links['CURR'] !== NULL ) && ( $k == $links['CURR'] ) )
                        {
                                $pages .= $this->callAutoFormatMethod( self::AF_METHOD_CURR, $v );
                                continue;
                        }

                        if ( strrpos( $data->real, '_dots' ) !== FALSE )
                        {
                                $pages .= $this->callAutoFormatMethod( self::AF_METHOD_DOTS, $data );
                                continue;
                        }

                        $pages .= $this->callAutoFormatMethod( self::AF_METHOD_PAGE, $data );
                }

                return $first . $prev . $pages . $next . $last;
        }

        /**
         * Register Auto Format Method
         *
         * Loads the specified method callback into this object to be used
         * when {@link self::autoFormat()} is called.
         *
         * @access      public
         * @param       mixed           Valid method callback.
         * @return      boolean
         */
        public function registerAutoFormatMethod( $callback )
        {
                /* INIT */
                if ( is_callable( $callback ) )
                {
                        $this->autoFormatMethod = $callback;
                        return true;
                }

                return false;
        }

        /**
         * Call Auto Format Method
         *
         * Calls the registered auto format method and returns data.
         *
         * @access      protected
         * @param       integer Method type to be processed.
         * @param       mixed           Data to be passed.
         * @return      string
         */
        protected function callAutoFormatMethod( $method, $data )
        {
                /* INIT */
                $default = $this->defaultAutoFormatMethod;

                /* Handling this one? */
                $return = call_user_func( $this->autoFormatMethod, $method, $data );

                if ( ( $return == false ) && ( $this->autoFormatMethod[0] != $default[0] 
                                                        && $this->autoFormatMethod[1] != $default[1] ) )
                {
                        /* Redirect back to default... */
                        $return = call_user_func( $default, $method, $data );
                }

                return $return;
        }

        /* Auto Format Methods */
        /**
         * Default: Auto Format Callback
         *
         * Default auto format callback used when no user-defined callback
         * is registered.
         *
         * @access      protected
         * @param       integer Method type to be processed.
         * @param       mixed           Data to be passed.
         * @return      string
         */
        protected static function __autoFormatCallback( $method, $data )
        {
                /* INIT */
                $_d = $data;

                switch ( $method )
                {
                case self::AF_METHOD_FIRST:
                        return '[URL=?start=' .$_d. ']«[/URL] ';
                        break;

                case self::AF_METHOD_PREV:
                        return '[URL=?start=' .$_d. ']<[/URL] ';
                        break;

                case self::AF_METHOD_NEXT:
                        return '[URL=?start=' .$_d. ']>[/URL] ';
                        break;

                case self::AF_METHOD_LAST:
                        return '[URL=?start=' .$_d. ']»[/URL] ';
                        break;

                case self::AF_METHOD_CURR:
                        return '[B]' .$_d. '[/B] ';
                        break;

                case self::AF_METHOD_DOTS:
                        return $_d->page . ' ';
                        break;

                case self::AF_METHOD_PAGE:
                default:
                        return '[URL=?start=' .$_d->real. ']' .$_d->page. '[/URL] ';
                break;
                }
        }
}
?>





Usage:

Code:



Code:


$pagination = classPagination::create( $totalResults, $perPage, $current ); /* See function comment for what param values to pass */
if ( $pagination->getLinks() !== NULL )
        echo $pagination->autoFormat();


----------



## 3930K

Quote:


> Originally Posted by *WroLeader*
> 
> What do you people think of Microsoft's XAML? I've been messing with it so far in Visual Studio and find it to be pretty fun to play around with.


I quite like it, the amount of things you can do with it is amazing. Only problem with it is that it has a *few* limitations. (Binding to attached properties in styles, I'm looking at you).


----------



## mechtech

Quote:


> Originally Posted by *ComradeNF*
> 
> Should I take C at my college? I was thinking of minoring in CS but I had an extremely bad experience with Intro to Python. I had no prior programming experience when I took it. The first 80% of it was interesting, like learning syntax, lists, dictionaries, etc. However, when we got to GUI's, nobody understood anything that was going on. Hell I got a 12/33 on my final exam and that was a solid B. Like literally nobody in the class knew how to code for the GUI. Even the TA's were completely lost.
> 
> So should I take C?
> 
> Here is the course:
> http://www.cs.ucdavis.edu/courses/exp_course_desc/30.html


That sounds terrible. Intro to programming should never involve GUIs.

Yes, you should take C, it's very important if you are a CS major and you'll learn many aspects of languages that are hidden away in the more advanced languages (like Python).

It's also fairly elegant and easy to learn. Python syntax is loosely based on C so it will be very easy for you.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I quite like it, the amount of things you can do with it is amazing. Only problem with it is that it has a *few* limitations. (Binding to attached properties in styles, I'm looking at you).


Try using XAML for Modern UI apps - now that's limitation!







Though MS ran out of time so they'll be adding new features in eventually.


----------



## 3930K

Is it that bad? I was more worried about IList -> IVector and that sort of stuff.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Is it that bad? I was more worried about IList -> IVector and that sort of stuff.


No not really








After using WPF XAML you may miss some things, but I got over it and worked around it.

The CLR and WinRT automatically convert those types, and others. There's nothing to worry about lol.


----------



## 3930K

Oh I wasn't aware. Thanks!


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Oh I wasn't aware. Thanks!


IIterable is projected to .NET as IEnumerable, IVector is projected as IList, and IMap is projected as IDictionary. Projection goes both ways - both for consumption and for authoring - so you should simply always be using the projected versions of those interfaces in your .NET code. When you declare a member as returning IList, it will show up as IVector from WinRT perspective (e.g. from C++/CX). Similarly, if you implement IDictionary on your class, it'll show up as implementing IMap in C++/CX.

Microsoft thought about us


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Oh I wasn't aware. Thanks!
> 
> 
> 
> IIterable is projected to .NET as IEnumerable, IVector is projected as IList, and IMap is projected as IDictionary. Projection goes both ways - both for consumption and for authoring - so you should simply always be using the projected versions of those interfaces in your .NET code. When you declare a member as returning IList, it will show up as IVector from WinRT perspective (e.g. from C++/CX). Similarly, if you implement IDictionary on your class, it'll show up as implementing IMap in C++/CX.
> 
> Microsoft thought about us
Click to expand...

Which is good,


----------



## Hatakescreams

Hi all,
this is a tricky question.
so am a software engineering student and i have just finished my first year of my degree,
i am currently working through K&R and every now and then i get stuck,

when this happens i try to solve the problem my self before asking for help.

What has happened is
i have gotten stuck, but i have already asked a question on stackoverflow today an then there was a silly answer to said question.

the question:
http://stackoverflow.com/questions/17435528/kr-1-21-when-printing-array-new-line-is-inserted

so i dont want to post my question on stack again as i have a fear of asking something stupid.....
instead i got some friends to have a look an they dont know why my code is broke either

Sooo OCN where do you post your questions when you feel like this?


----------



## tompsonn

Quote:


> Originally Posted by *Hatakescreams*
> 
> Hi all,
> this is a tricky question.
> so am a software engineering student and i have just finished my first year of my degree,
> i am currently working through K&R and every now and then i get stuck,
> 
> when this happens i try to solve the problem my self before asking for help.
> 
> What has happened is
> i have gotten stuck, but i have already asked a question on stackoverflow today an then there was a silly answer to said question.
> 
> the question:
> http://stackoverflow.com/questions/17435528/kr-1-21-when-printing-array-new-line-is-inserted
> 
> so i dont want to post my question on stack again as i have a fear of asking something stupid.....
> instead i got some friends to have a look an they dont know why my code is broke either
> 
> Sooo OCN where do you post your questions when you feel like this?


Feel free to post them here - I certainly couldn't give a damn how stupid the question is - because, first, no question is stupid, and second, we all started somewhere! If its C or a C-like language I'll happily do my best to answer


----------



## Hatakescreams

Quote:


> Originally Posted by *tompsonn*
> 
> Feel free to post them here - I certainly couldn't give a damn how stupid the question is - because, first, no question is stupid, and second, we all started somewhere! If its C or a C-like language I'll happily do my best to answer


Wooohaaaaaay haha thanks much. well its a c question ill post it here then









Basically i am trying to make a function called detab which takes a Char array and lengh an then goes through until it finds a tab, at this point it shuffles the elements up the array and adds a blank space.
however when i hit enter the line is not printing out, my code is clearer then my explanation.

Code:



Code:


     /*replace tabs from input with equal number of spaces*/
#include<stdio.h>
#define MAXLINE 1000
#define TAB 8
int getliner(char line[], int max);
void detab(char line[], int lenght);
/*main:prints contents of line*/
int main(){
        char line[MAXLINE];
        int len=0;
        while((len=getliner(line,MAXLINE))>0){
                detab(line, len);
                printf("%s",line);
        }
        return 0;
}
/*getliner: takes input, returns length*/
int getliner(char s[], int max){
        int i;
        char c;
        for(i=0;i<max-1 && ((c=getchar())!=EOF && c!='\n');i++)
                s[i]=c;
        if((c=='\n')){
                s[i]='\0';
                ++i;
        }
        s[i]='\0';
        return i;
}
/*detab: removes tabs inserts blanks*/
void detab(char s[], int len){
        int i,j,k;
        for(i=0;i<len-1;i++)
                if((s[i]='\t')){
                        s[i]=' ';
                        for(k=0;k<TAB;k++){
                                for(j=i+TAB;j>i;j--){
                                        s[j]=s[j-1];
                                }
                                s[j-1]=' ';
                                i++;
                        }

                }
}

the output am supposed to get:

Code:



Code:


dom     dom  <--- this is input note the space is supposed to be a tab
dom     dom  <--- this is what output is supposed to be where the tab has been replaced by spaces

The ACTUAL output:

Code:



Code:


dom    dom   <-- input with tab
<-- nothing is output!

well thats the question xD

I am not sure where i have gone wrong i imagine its something to do with the detab function but i dont know what.

thanks for any help dom

EDIT: i figured it out, i needed paranthesis arround the first while statment in the main func,
now i am getting incorrect output so any ideas are appreciated still!!
by the way i have corrected the code


----------



## tompsonn

What's happening is that you're overwriting characters in the final string with spaces. Each character is a single byte (let's say) - so that means a TAB character is also a single byte. You can't then replace that single byte TAB with multiple spaces (which is multiple bytes). Well... you can, but you end up overwriting what's already there!

What you need to do is allocate a new buffer.

Here's how I would write it:

Code:



Code:


#include <stdio.h>
#define MAXLINE 1000
#define TAB 8

int countchar( const char *buf, const char match, const int length );
int getline( char *buf, const int max );
char *detab( const char *line, const int length );

int main()
{
        char line[ MAXLINE ];
        int len = 0;

        while ( ( len = getline( line, MAXLINE ) ) > 0 )
        {
                char *buf = detab( line, len );
                if ( buf )
                        printf( "%s", buf );

                free( buf ); /* make sure to free as this is malloc'd */
        }

        return 0;
}

int countchar( const char *buf, const char match, const int length )
{
        int i;
        int count = 0;

        if ( !buf || !length )
                return 0;

        for ( i = 0; i < length; ++i )
                if ( buf[i] == match )
                        ++count;

        return count;
}

int getline( char *buf, const int max )
{
        int i;
        char c;

        if ( !buf )
                return 0;

        for ( i = 0; i < max - 1 
                && ( ( c = getchar() ) != EOF && c != '\n' ); ++i )
                buf[i] = c;

        if ( c == '\n' )
        {
                buf[i] = '\0';
                ++i;
        }

        buf[i] = '\0';
        return i;
}

char *detab( const char *line, const int length )
{
        int i, k, j = 0;
        int count;
        char *buf = ( char* ) malloc( sizeof( char ) * length ); /* create initial buffer */

        if ( !buf )
                return NULL; /* out of memory? */

        if ( !line || !length )
                return NULL; /* not valid pointer */

        /* How many tabs in this line? */
        count = countchar( line, '\t', length );

        if ( !count )
        {
                /* No tab chars in the line - copy the current line to the return buffer */
                memcpy( buf, line, length );
                return buf;
        }

        /* Re-allocate new (bigger) buffer */
        buf = ( char* ) realloc( buf, sizeof( char ) * ( ( count * TAB ) + length ) );
        if ( !buf )
                return NULL; /* out of memory? */

        /* Start filling the new buffer */
        for ( i = 0; i < length; ++i )
        {
                if ( line[i] == '\t' )
                {
                        /* Got a tab character, fill with spaces */
                        for ( k = 0; k < TAB; ++k )
                                buf[j++] = ' ';
                        continue;
                }

                buf[j++] = line[i]; /* not a tab character, so add as normal */
        }

        return buf;
}


----------



## Hatakescreams

Quote:


> Originally Posted by *tompsonn*
> 
> What's happening is that you're overwriting characters in the final string with spaces. Each character is a single byte (let's say) - so that means a TAB character is also a single byte. You can't then replace that single byte TAB with multiple spaces (which is multiple bytes). Well... you can, but you end up overwriting what's already there!
> 
> What you need to do is allocate a new buffer.
> 
> Here's how I would write it:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> #include <stdio.h>
> #define MAXLINE 1000
> #define TAB 8
> 
> int countchar( const char *buf, const char match, const int length );
> int getline( char *buf, const int max );
> char *detab( const char *line, const int length );
> 
> int main()
> {
> char line[ MAXLINE ];
> int len = 0;
> 
> while ( ( len = getline( line, MAXLINE ) ) > 0 )
> {
> char *buf = detab( line, len );
> if ( buf )
> printf( "%s", buf );
> 
> free( buf ); /* make sure to free as this is malloc'd */
> }
> 
> return 0;
> }
> 
> int countchar( const char *buf, const char match, const int length )
> {
> int i;
> int count = 0;
> 
> if ( !buf || !length )
> return 0;
> 
> for ( i = 0; i < length; ++i )
> if ( buf[i] == match )
> ++count;
> 
> return count;
> }
> 
> int getline( char *buf, const int max )
> {
> int i;
> char c;
> 
> if ( !buf )
> return 0;
> 
> for ( i = 0; i < max - 1
> && ( ( c = getchar() ) != EOF && c != '\n' ); ++i )
> buf[i] = c;
> 
> if ( c == '\n' )
> {
> buf[i] = '\0';
> ++i;
> }
> 
> buf[i] = '\0';
> return i;
> }
> 
> char *detab( const char *line, const int length )
> {
> int i, k, j = 0;
> int count;
> char *buf = ( char* ) malloc( sizeof( char ) * length ); /* create initial buffer */
> 
> if ( !buf )
> return NULL; /* out of memory? */
> 
> if ( !line || !length )
> return NULL; /* not valid pointer */
> 
> /* How many tabs in this line? */
> count = countchar( line, '\t', length );
> 
> if ( !count )
> {
> /* No tab chars in the line - copy the current line to the return buffer */
> memcpy( buf, line, length );
> return buf;
> }
> 
> /* Re-allocate new (bigger) buffer */
> buf = ( char* ) realloc( buf, sizeof( char ) * ( ( count * TAB ) + length ) );
> if ( !buf )
> return NULL; /* out of memory? */
> 
> /* Start filling the new buffer */
> for ( i = 0; i < length; ++i )
> {
> if ( line[i] == '\t' )
> {
> /* Got a tab character, fill with spaces */
> for ( k = 0; k < TAB; ++k )
> buf[j++] = ' ';
> continue;
> }
> 
> buf[j++] = line[i]; /* not a tab character, so add as normal */
> }
> 
> return buf;
> }











thanks much i really like that code, some useful idea's in there,
The problem is it uses concepts not available to me in the K&R book at this point; like pointers...
But i got an idea, am going to create a new array in detab essentially the buffer from tompson, an then copy the buffer to the return array.
ill post my complete code when am done


----------



## tompsonn

Quote:


> Originally Posted by *Hatakescreams*
> 
> 
> 
> 
> 
> 
> 
> 
> 
> thanks much i really like that code, some useful idea's in there,
> The problem is it uses concepts not available to me in the K&R book at this point; like pointers...
> But i got an idea, am going to create a new array in detab essentially the buffer from tompson, an then copy the buffer to the return array.
> ill post my complete code when am done


Well by using an array you are implicitly using pointers.... Its just that when you declare an array using the square bracket syntax, you get memory allocated on the stack (consequently you don't have to free it explicitly because the stack is cleaned up at the end of the function call).

When you use the array though, for example foo[ i ] = bar, you're manipulating a pointer - the compiler is just hiding it from you. There's nothing fancy about an array in C (as opposed to say, C# or Java) - its simply a contiguous block of memory. When you declare an array, you essentially get a pointer to address that is the first element of the array. When you access an element in the array, the compiler performs pointer arithmetic for you, incrementing that base address by the data width (for example, 4 bytes for an integer).

For example:

Code:



Code:


int array[5];      /* Declares 5 contiguous integers */
int *ptr = array;  /* Arrays can be used as pointers */
ptr[0] = 1;        /* Pointers can be indexed with array syntax */
*(array + 1) = 2;  /* Arrays can be dereferenced with pointer syntax */
*(1 + array) = 3;  /* Pointer addition is commutative */
2[array] = 4;      /* Subscript operator is commutative */

IMO, pointers should be introduced fairly early in any C programming book.


----------



## Hatakescreams

Quote:


> Originally Posted by *tompsonn*
> 
> Well by using an array you are implicitly using pointers.... Its just that when you declare an array using the square bracket syntax, you get memory allocated on the stack (consequently you don't have to free it explicitly because the stack is cleaned up at the end of the function call).
> 
> When you use the array though, for example foo[ i ] = bar, you're manipulating a pointer - the compiler is just hiding it from you. There's nothing fancy about an array in C (as opposed to say, C# or Java) - its simply a contiguous block of memory. When you declare an array, you essentially get a pointer to address that is the first element of the array. When you access an element in the array, the compiler performs pointer arithmetic for you, incrementing that base address by the data width (for example, 4 bytes for an integer).
> 
> For example:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> int array[5];      /* Declares 5 contiguous integers */
> int *ptr = array;  /* Arrays can be used as pointers */
> ptr[0] = 1;        /* Pointers can be indexed with array syntax */
> *(array + 1) = 2;  /* Arrays can be dereferenced with pointer syntax */
> *(1 + array) = 3;  /* Pointer addition is commutative */
> 2[array] = 4;      /* Subscript operator is commutative */
> 
> IMO, pointers should be introduced fairly early in any C programming book.


Good Sir!
haha your stepping on thin ice there, this is Kernighan and Ritchie haha xD
jokes aside,

thanks again you have furthered my understanding of pointers, and i will keep this post for future reference,
I am nearly done with my own version i will post when complete.
Reps for you by the way!


----------



## tompsonn

Quote:


> Originally Posted by *Hatakescreams*
> 
> Good Sir!
> haha your stepping on thin ice there, this is Kernighan and Ritchie haha xD
> jokes aside,
> 
> thanks again you have furthered my understanding of pointers, and i will keep this post for future reference,
> I am nearly done with my own version i will post when complete.
> Reps for you by the way!


----------



## Hatakescreams

Before i forget here is my final solution.
In this solution i modified getliner(), when a tab is detected spaces are inserted, i was having trouble with this solution because when the spaces were inserted i was adding one extra null element at the end of the for statement, in which the spaces are added
by decrementing 'i', the bug was fixed.

Anyway here is the code:

Code:



Code:


     /*replace tabs from input with equal number of spaces*/
#include<stdio.h>
#define MAXLINE 1000
#define TAB 5
#define SPACE #
int getliner(char line[], int max);
void detab(char line[], int lenght);
/*main:prints contents of line*/
int main(){
        char line[MAXLINE];
        int len=0;
        while((len=getliner(line,MAXLINE))>1)
                printf("%s\n", line);
        return 0;
}
/*getliner: takes input, returns length*/
int getliner(char s[], int max){
        int i,j;
        char c;
        for(i=0;i<max-1 && ((c=getchar())!=EOF && c!='\n');i++){
                if((c=='\t')){
                        for(j=0;j<TAB;j++){
                                s[i]=' ';
                                i++;
                        }
                        i--;    //decrement was added here
                }else{
                        s[i]=c;
                }
        }
        if((c=='\n')){
                s[i]='\0';
                ++i;
        }
        s[i]='\0';
        return i;
}
void detab(char s[], int len){
        int i, j, count;
        char t[MAXLINE];
        i=j=count=0;
        for(i=0;i<len;i++){
                if((s[i]=='\t')){
                        for(j=0;j<TAB;j++, i++, len++, count++){
                                t[i]=' ';
                        }
                  i--;
                }else{
                        t[i]=s[i];
                        count++;
                }
        }

        for(i=0;i<count;i++){
                s[i]=t[i];
        }
        i++;
        s[i]='\0';
}

I have also left my detab function in there if anyone could spot were i was going wrong it would be appreciated,
Thanks much for the help Babble!


----------



## tompsonn

Not bad







Your "detab" function is way too messy so I can't begin to see what might be wrong with it.


----------



## Hatakescreams

Quote:


> Originally Posted by *tompsonn*
> 
> Not bad
> 
> 
> 
> 
> 
> 
> 
> Your "detab" function is way too messy so I can't begin to see what might be wrong with it.


haha not to worry i didnt think it was that messy but alright









EDIT:

Actually i see what you mean, i left it with alot of crap in there sorry about that xD


----------



## robE

Is there a good book you guys can recommend for problem solving thinking, or something related to logical thinking or this is something you will develop over time?


----------



## tompsonn

Quote:


> Originally Posted by *robE*
> 
> Is there a good book you guys can recommend for problem solving thinking, or something related to logical thinking or this is something you will develop over time?


I think the majority of the time this is something that comes natural - though it is certainly possible to develop, just a tad more difficult (but don't let that throw you off!). I haven't come across anything book wise, but the more you practice, the better you get.


----------



## robE

Thanks for your words









I`m coming up with another uber newbish question







but i just don`t understand what i`m missing, i really want to know the logic behind this.

"What does the expression !( true && !( false || true ) ) evaluate to?"

The result should be true but i see this as false in all the ways possible, can someone shed some light on my brain? thanks







!


----------



## abduct

Quote:


> Originally Posted by *robE*
> 
> Thanks for your words
> 
> 
> 
> 
> 
> 
> 
> 
> 
> I`m coming up with another uber newbish question
> 
> 
> 
> 
> 
> 
> 
> but i just don`t understand what i`m missing, i really want to know the logic behind this.
> 
> "What does the expression !( true && !( false || true ) ) evaluate to?"
> 
> The result should be true but i see this as false in all the ways possible, can someone shed some light on my brain? thanks
> 
> 
> 
> 
> 
> 
> 
> !


well

false = 0
true = 1

now lets work this starting with the inner most brackets

0 || 1 = 1 (OR returns true if any placeholder equals true)
!(1) = 0 (NOT inverts the binary)
1 && 0 = 0 (AND returns true per bits that are the same)
!(0) = 1

answer is 1

this is a pretty good read on bitwise math a friend did up a year ago. it covers most of everything.

http://pastebin.com/c0XaQejy


----------



## 3930K

Quote:


> Originally Posted by *robE*
> 
> Thanks for your words
> 
> 
> 
> 
> 
> 
> 
> 
> 
> I`m coming up with another uber newbish question
> 
> 
> 
> 
> 
> 
> 
> but i just don`t understand what i`m missing, i really want to know the logic behind this.
> 
> "What does the expression !( true && !( false || true ) ) evaluate to?"
> 
> The result should be true but i see this as false in all the ways possible, can someone shed some light on my brain? thanks
> 
> 
> 
> 
> 
> 
> 
> !


Do it step by step, and it will be simple.
!(true && !(false || true)) => !(true && !(*true*)) (OR (||) is only false if both inputs are false). => !(true && *false*) (NOT (!) makes true turn into false and vice versa) => !(*false*) (AND (&&) is only true if both inputs are true) => *true*.


----------



## andyroo89

Its been a while since people post in here, I guess we are too busy writing code in art form.


----------



## 3930K

Quote:


> Originally Posted by *andyroo89*
> 
> Its been a while since people post in here, I guess we are too busy writing code in art form.


----------



## tompsonn

If anyone cares, here's a PowerShell script I wrote today for someone (to their specification) to change DNS servers on computers:

Code:



Code:


# Script global parameters
Param(
    [Parameter( HelpMessage="Specify whether to enable dynamic DNS registration.")]
        [bool]$EnableDynamicDNS = $True
)

#
# DisplayNetworkInterfaces: Displays the list of NICs from the computer specified by the user.
#
Function DisplayNetworkInterfaces()
{
    # Wipe your mouth
    cls

    # Get computer to work with
    Write-Host "*************************************************"
    Write-Host "Enter the computer to connect to."
    Write-Host "*************************************************"

    $ComputerName = GetComputer

    # Wipe your mouth
    cls

    Write-Host "================================================="
    Write-Host "SELECTED: " $ComputerName
    Write-Host "================================================="

    $networkInterfaces = 
        Get-WmiObject Win32_NetworkAdapterConfiguration -computername $ComputerName | where { $_.IPEnabled -eq "TRUE" }

    If ( $networkInterfaces -eq $null )
    {
        Write-Host "There are no network interfaces on this computer, or WMI retrieval failed."
        return;
    }

    Write-Host "The following IP network interfaces exist on this computer:"

    $allInterfaces = @()

    Foreach ( $networkInterface in $networkInterfaces )
    {
        $allInterfaces += $networkInterface.Index
        $networkInterface | 
            Format-List Index, Caption, IPAddress, DNSServerSearchOrder, DefaultIPGateway, MACAddress, ServiceName
    }

    While ( $True )
    {
        $isAll = Read-Host "Would you like to select ALL network interfaces? (Y/N)"

        if ( $isAll.ToLower() -eq "y" )
        {
            # Perform on all interfaces
            ChangeDnsServers $ComputerName $allInterfaces
            return;
        }

        if ( $isAll.ToLower() -eq "n" )
        {
            # Ask them to specify which ones they want (sorry CPU more work for you)
            Write-Host "*************************************************"
            Write-Host "** Enter each network interface index you wish to change DNS servers. **"
            Write-Host "** When finished, leave blank and press ENTER. **"
            Write-Host "*************************************************"
            Write-Host

            ChangeDnsServers $ComputerName
            return;
        }
    }
}

#
# ChangeDnsServers: Performs the work of enumerating required NICs to
# change DNS servers on.
#
Function ChangeDnsServers( $ComputerName, [Parameter(Mandatory=$True)][int[]] $Interfaces )
{
    Write-Host
    Write-Host "================================================="
    Write-Host "DNS CHANGING FOR: " $ComputerName
    Write-Host "Network Interfaces: " $Interfaces
    Write-Host "================================================="
    Write-Host
    Write-Host "*************************************************"
    Write-Host "**Enter the DNS servers to change to.**"
    Write-Host "**When finished, leave blank and press ENTER.**"
    Write-Host "*************************************************"
    Write-Host

    $servers = GetDnsAddresses

    # Get all NICs specified by the interface index list
    $networkInterfaces = 
        Get-WmiObject Win32_NetworkAdapterConfiguration -computername $ComputerName | 
            where { $_.IPEnabled -eq "TRUE" -and $Interfaces -contains $_.Index }

    Foreach ( $networkInterface in $networkInterfaces )
    {
        # Redirect
        ChangeDnsServersCore $networkInterface $servers
    }
}

# 
# ChangeDnsServersCore: Changes the DNS servers specified by $Servers on the network
# interface specified by $NetworkInterface.
#
Function ChangeDnsServersCore( $NetworkInterface, $Servers )
{
    # Change the DNS servers
    If ( $NetworkInterface -ne $null )
    {
        Write-Host "Changing DNS for interface " $NetworkInterface.Caption "..."

        # Call WMI method
        $NetworkInterface.SetDNSServerSearchOrder( $Servers ) | Out-Null

        # Enable dynamic DNS registration
        If ( $EnableDynamicDNS -eq $True )
        {
            $NetworkInterface.SetDynamicDNSRegistration( "TRUE" ) | Out-Null
        }

        Write-Host "    ... done!"
        Write-Host
    }
}

#
# GetComputer: Retrieves the computer to perform the task from the user.
#
Function GetComputer()
{
    Param(
        [Parameter(Mandatory=$True, HelpMessage="Enter the computer to connect to.")]
        [ValidateNotNullOrEmpty()]
            [string]$ComputerName
    )

    return $ComputerName
}

#
# GetDnsAddresses: Retrieves DNS server input from the user.
#
Function GetDnsAddresses( [Parameter(Mandatory=$True)][string[]] $DNSServers )
{
    return $DNSServers
}

# Kick it off
DisplayNetworkInterfaces


----------



## Nestala

I think it would be a good idea to put code in codeform, but also in a quote form. So I don't have to scroll that much







.
Besides, I like your way of coding and commenting tompsonn.
# Wipe your mouth - pretty good







.


----------



## tompsonn

Quote:


> Originally Posted by *Nestala*
> 
> I think it would be a good idea to put code in codeform, but also in a quote form. So I don't have to scroll that much
> 
> 
> 
> 
> 
> 
> 
> .
> Besides, I like your way of coding and commenting tompsonn.
> # Wipe your mouth - pretty good
> 
> 
> 
> 
> 
> 
> 
> .


I aspire to write code that looks pleasing to the eye







And add in various snarky comments......


----------



## abduct

im currently working on a chatbot for this server i am reversing using ruby and ncurses for terminal interfaces. since i couldnt get rbcurse gem to install, one that already has listboxes, texboxes, labels, and such already made I am stuck working with ncurses. this means not only do i have to spawn the windows and place them on the screen and keep track of them, i also have to create classes for all the form structures i want to use such as listbox and such. although, i am cheating a bit and making the data array that holds the listbox items publicly assessable so i can just call its array methods to make life easier. all seems to be going well so far.


----------



## 3930K

I've got a small problem.

I can't afford an MSDN subscription, but I really want VS2013 Pro (I'm waiting until it comes out, and I currently have the Express Preview) and Expression Blend. The only problem is, I'll have to keep paying for it if they keep doing the 1y release cycle thing. What can I do?


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I've got a small problem.
> 
> I can't afford an MSDN subscription, but I really want VS2013 Pro (I'm waiting until it comes out, and I currently have the Express Preview) and Expression Blend. The only problem is, I'll have to keep paying for it if they keep doing the 1y release cycle thing. What can I do?


Are you eligible for any of the Microsoft education discount programs such as DreamSpark?
Also what's the reason you need Pro?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> I've got a small problem.
> 
> I can't afford an MSDN subscription, but I really want VS2013 Pro (I'm waiting until it comes out, and I currently have the Express Preview) and Expression Blend. The only problem is, I'll have to keep paying for it if they keep doing the 1y release cycle thing. What can I do?
> 
> 
> 
> Are you eligible for any of the Microsoft education discount programs such as DreamSpark?
> Also what's the reason you need Pro?
Click to expand...

I am, but MS is being a bit weird about it and not letting me use them.
Resharper mainly, and also a working version of Blend (it doesn't have split/design view in the Express, which relegates it to useless). I don't think there's a cheaper version that uses


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I am, but MS is being a bit weird about it and not letting me use them.
> Resharper mainly, and also a working version of Blend (it doesn't have split/design view in the Express, which relegates it to useless). I don't think there's a cheaper version that uses


What's their problem?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> I am, but MS is being a bit weird about it and not letting me use them.
> Resharper mainly, and also a working version of Blend (it doesn't have split/design view in the Express, which relegates it to useless). I don't think there's a cheaper version that uses
> 
> 
> 
> What's their problem?
Click to expand...

Basically I need to send too much IDs. I practically have to send my passport. (this is using the email option).


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Basically I need to send too much IDs. I practically have to send my passport. (this is using the email option).


So send the info... lol


----------



## 3930K

Haha







The problem is, apart from that, they also ask me to send some bills (iirc) that I don't have. The other option is to get an ISIC, which I probably will end up doing.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> Haha
> 
> 
> 
> 
> 
> 
> 
> The problem is, apart from that, they also ask me to send some bills (iirc) that I don't have. The other option is to get an ISIC, which I probably will end up doing.


Bank statement?

ISIC will be easier once you get it.


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> Haha
> 
> 
> 
> 
> 
> 
> 
> The problem is, apart from that, they also ask me to send some bills (iirc) that I don't have. The other option is to get an ISIC, which I probably will end up doing.
> 
> 
> 
> Bank statement?
> 
> ISIC will be easier once you get it.
Click to expand...

Can't remember, I tried about 6 months ago.

Yeah, I'm probably going to get it.


----------



## tompsonn

Whats new in 2013?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Whats new in 2013?


Definition Peek, more integration with TFS, reference list above methods, W8.1 development, .NET 4.5.1, x64 E+C, and a few more.

http://www.microsoft.com/visualstudio/eng/2013-preview

However all but the last two are disabled on Express (afaik)


----------



## tompsonn

Return of VS 2012 colors?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Return of VS 2012 colors?


What do you mean by that? In the dark scheme, it looks pretty much exactly the same as VS2012 with the dark scheme.


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> What do you mean by that? In the dark scheme, it looks pretty much exactly the same as VS2012 with the dark scheme.


Just looking at the screenshots on the website.


----------



## Androiid

Anyone learning Clojure? It requires a few steps to setup but it's an extremely effective, dynamic, and functional programming language. It's based on LISP and it uses the (massive) JVM library. There is even a way to use .NET if you're more familiar with it via ClojureCLR.


----------



## tompsonn

Quote:


> Originally Posted by *Androiid*
> 
> Anyone learning Clojure? It requires a few steps to setup but it's an extremely effective, dynamic, and functional programming language. It's based on LISP and it uses the (massive) JVM library. There is even a way to use .NET if you're more familiar with it via ClojureCLR.


For some reason these sorts of languages look like a big pile of goo to me!


----------



## Androiid

Quote:


> Originally Posted by *tompsonn*
> 
> For some reason these sorts of languages look like a big pile of goo to me!


I see what you mean. It can be a weakness sometimes if almost everything is mutable by default.


----------



## tompsonn

Quote:


> Originally Posted by *Androiid*
> 
> I see what you mean. It can be a weakness sometimes if almost everything is mutable by default.


I think my problem with those languages (and its entirely personal!) is that there's too much alphabet and not enough symbols!


----------



## 3930K

I've got DreamSpark now







It's even better with the free Dev Center membership


----------



## 3930K

I'm sad, ReSharper is smarter than me


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> I'm sad, ReSharper is smarter than me


That's kind of the whole point


----------



## 3930K

I thought I could do better


----------



## exhaile

vim, eclipse, visual Studio.
Mostly vim.


----------



## 3930K

Quote:


> Originally Posted by *exhaile*
> 
> vim, eclipse, visual Studio.
> Mostly vim.


Huh?


----------



## tompsonn

You and me both buddy!


----------



## BradleyW

Hey my fellow coders, any good online places to learn a very solid foundation of basic C++? I have 3 years of Visual Basic and 1 year of HTML coding currently.


----------



## poroboszcz

Quote:


> Originally Posted by *BradleyW*
> 
> Hey my fellow coders, any good online places to learn a very solid foundation of basic C++? I have 3 years of Visual Basic and 1 year of HTML coding currently.


http://www.parashift.com/c++-faq/


----------



## ivr56

Well I'm getting better at Java and Processing.

Prototype for a Interactive Installation:
http://www.youtube.com/watch?v=me***pX9W-0
(Replace *** with "w" "T" "F". Oddly youtube gave me the worst possible URL link that gets auto censored here)
Tell me what you guys think


----------



## willll162904

hey guys! im only 16 atm but i aspire to major in computer science. Im trying to learn java and i have some (but incredibly little) experience in c and c++, and html i guess if you would coun that as programming.. which it isnt ;p hopefully im welcome in the convo and i gues ill see what i can understand! haha


----------



## tompsonn

Quote:


> Originally Posted by *willll162904*
> 
> hey guys! im only 16 atm but i aspire to major in computer science. Im trying to learn java and i have some (but incredibly little) experience in c and c++, and html i guess if you would coun that as programming.. which it isnt ;p hopefully im welcome in the convo and i gues ill see what i can understand! haha


Of course you're welcome









Any questions, just post away.....!


----------



## willll162904

Quote:


> Originally Posted by *tompsonn*
> 
> Of course you're welcome
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Any questions, just post away.....!


Awesome!







ive been taking a break from java and programming all together and focusing on school, and hockey more. But also did alot of overclocking and computer knowledge. I'm looking at getting back into it. ATM my biggset downfall with java is arrays.. i just dont get that stuff. I can watch and read the lesson on them over and over and understand what they do in the class, but i dont really get the exact point of using them, and how they can be beneficial to the program overall.


----------



## 3930K

GhostDoc can be so funny:

Code:



Code:


/// 
/// Props the accessed.
/// 
/// The name of changed val.
[NotifyPropertyChangedInvocator]
protected void PropAccessed([CallerMemberName]string nameOfChangedVal = "")


----------



## Waffleboy

Here's a quick example where an array could be helpful. Let's say you have a math test in a class with 20 students. The teacher wants to find the average grade (using Java of course







). Now, it could be done like this:

int grade1 = 90;
int grade2 = 100;
int grade3 = 78;
...
int grade 20 = 85;

And then you could get the average like:

double average = (grade1 + grade2 + grade3 + grade4 + ... + grade20) / 20.0;

But this is so much typing! It's unwieldy and annoying to both read and write code like this. Arrays make it MUCH cleaner.

Instead, it would be done like:

int grades[] = {90, 100, 78...85};

And then you would use a loop to do the calculations.

Hopefully this makes sense. Basically, an array is a list, so use one whenever a list makes sense.


----------



## willll162904

Quote:


> Originally Posted by *Waffleboy*
> 
> Here's a quick example where an array could be helpful. Let's say you have a math test in a class with 20 students. The teacher wants to find the average grade (using Java of course
> 
> 
> 
> 
> 
> 
> 
> ). Now, it could be done like this:
> 
> int grade1 = 90;
> int grade2 = 100;
> int grade3 = 78;
> ...
> int grade 20 = 85;
> 
> And then you could get the average like:
> 
> double average = (grade1 + grade2 + grade3 + grade4 + ... + grade20) / 20.0;
> 
> But this is so much typing! It's unwieldy and annoying to both read and write code like this. Arrays make it MUCH cleaner.
> 
> Instead, it would be done like:
> 
> int grades[] = {90, 100, 78...85};
> 
> And then you would use a loop to do the calculations.
> 
> Hopefully this makes sense. Basically, an array is a list, so use one whenever a list makes sense.


ohhh ok. so its just a faster way of making a list without having to type every different variable out over and over. Thanks! that actually does make more sense now.


----------



## Waffleboy

Quote:


> Originally Posted by *willll162904*
> 
> ohhh ok. so its just a faster way of making a list without having to type every different variable out over and over. Thanks! that actually does make more sense now.


Yup. And of course, my example had 20 data points, but you can imagine writing a program with millions of similar data points to keep track of - it wouldn't be feasible at all without arrays.


----------



## willll162904

Quote:


> Originally Posted by *Waffleboy*
> 
> Yup. And of course, my example had 20 data points, but you can imagine writing a program with millions of similar data points to keep track of - it wouldn't be feasible at all without arrays.


Yeah that would get pretty crazy.


----------



## andyroo89

Quote:


> Originally Posted by *willll162904*
> 
> hey guys! im only 16 atm but i aspire to major in computer science. Im trying to learn java and i have some (but incredibly little) experience in c and c++, and html i guess if you would coun that as programming.. which it isnt ;p hopefully im welcome in the convo and i gues ill see what i can understand! haha


I would recommend computer engineer/software engineer


----------



## willll162904

Quote:


> Originally Posted by *andyroo89*
> 
> I would recommend computer engineer/software engineer


Really? I'll look some more into it. Also doing anything computer related in the military would be great. and theres obviously tons of computer related opportunities nowadays


----------



## andyroo89

Quote:


> Originally Posted by *willll162904*
> 
> Really? I'll look some more into it. Also doing anything computer related in the military would be great. and theres obviously tons of computer related opportunities nowadays


back in 07 when I was in high school computer science was in demand, now my lazy butt is in college and now engineering is in demand. So, I mean up to you.


----------



## willll162904

Quote:


> Originally Posted by *andyroo89*
> 
> back in 07 when I was in high school computer science was in demand, now my lazy butt is in college and now engineering is in demand. So, I mean up to you.


haha yeah that is true. It's all about what will get you a job after college.. especially with are rather crappy economy/gov. nowadays. TBH if it's something in computers im fairly content.. as long as i make money...


----------



## adridu59

Bumping the thread... anyone here has experience with D, Rust (or Go)?

They are good contenders as C++ successor, Rust being newer and still mostly in beta stage (constantly changing + sparse bugs).


----------



## 3930K

^ No, sorry.

My ReSharper trial's running out and I can't afford the real version...


----------



## tompsonn

Quote:


> Originally Posted by *3930K*
> 
> ^ No, sorry.
> 
> My ReSharper trial's running out and I can't afford the real version...


Its $150, it wouldn't take that long to save up would it?


----------



## 3930K

Quote:


> Originally Posted by *tompsonn*
> 
> Quote:
> 
> 
> 
> Originally Posted by *3930K*
> 
> ^ No, sorry.
> 
> My ReSharper trial's running out and I can't afford the real version...
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Its $150, it wouldn't take that long to save up would it?
Click to expand...

That's the plan, yeah.


----------



## andyroo89

Anyone familiar with delphi/pascal? I am trying to take a desktop pic and send it over sockets, I have the send image part down, and I am not sure how to receive the image and display it on TImage. If anyone is familiar with it, please pm me.


----------



## poroboszcz

This looks pretty awesome: http://codeandconquer.co/


----------



## Delphiwizard

Quote:


> Originally Posted by *andyroo89*
> 
> Anyone familiar with delphi/pascal? I am trying to take a desktop pic and send it over sockets, I have the send image part down, and I am not sure how to receive the image and display it on TImage. If anyone is familiar with it, please pm me.


Code:



Code:


var
  c: TCanvas;
  r: TRect;
begin
  c := TCanvas.Create;
  c.Handle := GetWindowDC(GetDesktopWindow);
  try
    r := Rect(0, 0, Screen.Width, Screen.Height);
    cxImage1.Width := Screen.Width;
    cxImage1.Height := Screen.Height;
    cxImage1.Picture.Bitmap.Width := Screen.Width;
    cxImage1.Picture.Bitmap.Height := Screen.Height;
    cxImage1.Picture.Bitmap.Canvas.CopyRect(r, c, r);
  finally
    ReleaseDC(0, c.Handle);
    c.Free;
  end;
end;


----------



## theRYB

Quote:


> Originally Posted by *andyroo89*
> 
> back in 07 when I was in high school computer science was in demand, now my lazy butt is in college and now engineering is in demand. So, I mean up to you.


I think it's all in demand. The problem is that there is a demand for _skilled_ workers in science and engineering and an overabundance of _underskilled_ workers.


----------



## Sanmayce

I need (again) help in running on some fast machine (3rd/4th generation i7, Vishera or alike) my latest fastest MEMMEM function:
http://www.codeproject.com/Articles/250566/Fastest-strstr-like-function-in-C

My wish is to compare results on my laptop 'Bonboniera' with next generation CPUs.
The idea is more people to see how the beautiful *Boyer-Moore-Horspool* algorithm reigning since 1980 now is replaced by its successor '*Railgun_Bari*' and what is the actual boost.

All high-level languages use BMH code, in my view it is time for change.

EDIT:
For those who have will to run the benchmark, here are the 2 steps:

- downloading the benchmark at http://www.sekireigan.com/_KAZE_32bit_memmem-like_showdown.7z
- run '*RUNME_WIKI_memmem.BAT*', it creates '*Results.txt*' - that's the goal.

I wanted the stats to be more accurate therefore I increased the trials so that even very fast CPUs to have some job to do.
The benchmark stresses CPU-RAM subsystem, CPU clock and fetching uncached main RAM small chunks (4-12 bytes) are responsible for speed performance.


----------



## andyroo89

Been messing wit shell scripting, and with my two days off I converted it to python and perl.


----------



## PolyMorphist

It's a shame this thread's become so lifeless; I would've enjoyed seeing it back when it was active. Does anyone know any active (>5 posts per day ) programming-related threads on OCN?


----------



## nooboc2012

The programming competition threads are pretty fun reads.


----------



## robE

Hello







Can you guys tell me if there is big real world difference between i7 and i5 in programming ? (compiling/etc?). I kinda guess visual studio for example will take advantage of more cores but I'm asking about programming as a whole


----------



## tompsonn

Quote:


> Originally Posted by *robE*
> 
> Hello
> 
> 
> 
> 
> 
> 
> 
> Can you guys tell me if there is big real world difference between i7 and i5 in programming ? (compiling/etc?). I kinda guess visual studio for example will take advantage of more cores but I'm asking about programming as a whole


Meh. Not really. Maybe if your project is as huge as something like Firefox it might make a difference.


----------



## ABD EL HAMEED

So today a mate in 4th year in CS told me that C is faster than C++(I used to think that C++ is the fastest language :/)is this true?how much faster?why is it faster?


----------



## stumped

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> So today a mate in 4th year in CS told me that C is faster than C++(I used to think that C++ is the fastest language :/)is this true?how much faster?why is it faster?


IIRC, it has to do with the way C++ sets up memory usage/access and C sets up memory usage/access.

Since C++ is object oriented, the functions and variables are behind an object which requires memory access to use the object. In C++, you are not always guaranteed to efficiently use this memory space.

In C however, memory access/usage/mapping is very well understood, optimized, and presented in a more straight forward fashion. Because of this, most people when coding in C are already programming in a way that can utilize the CPUs cache more efficiently which greatly speeds up memory access and allows the CPU to be working more of the time.

* discalimer: This is what I remember when I looked into why the Linux kernel is programmed in C and not C++ when there are a lot of constructs in the kernel that exhibit object oriented philosophies. I could also be very wrong here as well, but this is what I understand of the differences.


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *stumped*
> 
> IIRC, it has to do with the way C++ sets up memory usage/access and C sets up memory usage/access.
> 
> Since C++ is object oriented, the functions and variables are behind an object which requires memory access to use the object. In C++, you are not always guaranteed to efficiently use this memory space.
> 
> In C however, memory access/usage/mapping is very well understood, optimized, and presented in a more straight forward fashion. Because of this, most people when coding in C are already programming in a way that can utilize the CPUs cache more efficiently which greatly speeds up memory access and allows the CPU to be working more of the time.
> 
> * discalimer: This is what I remember when I looked into why the Linux kernel is programmed in C and not C++ when there are a lot of constructs in the kernel that exhibit object oriented philosophies. I could also be very wrong here as well, but this is what I understand of the differences.


Well that explains a lot,thanks!

But how much faster is C?


----------



## tompsonn

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> Well that explains a lot,thanks!
> 
> But how much faster is C?


Eh.

In C++, "you only pay for what you use." So there is nothing that would make it any slower than C. In particular for scientific programs, template expressions make it possible to perform some custom optimization using the template engine to process program semantics. Well written code in any language is always better than poorly written code in any other language.

I don't think that the reason is so much related to performance as it is to interoperability. The C++ language is more complex than the C language, but from a performance point of view there shouldn't be a notable difference in either way. Some C++ constructs are faster than the C equivalent (std::sort is faster than qsort) and there are probably good examples of the other way around.

C++ may be slower if you use its more advanced features but you have to ask yourself if you are micro-optimizing or if there really is a bottleneck.

I think your mate is in fairy land if he is going around saying C is definitely faster than C++. The same code in either language will have zero difference in speed and in some cases C++ can be faster depending on what you do, just like C can be as well.


----------



## tompsonn

Quote:


> Originally Posted by *stumped*
> 
> IIRC, it has to do with the way C++ sets up memory usage/access and C sets up memory usage/access.
> 
> Since C++ is object oriented, the functions and variables are behind an object which requires memory access to use the object. In C++, you are not always guaranteed to efficiently use this memory space.
> 
> In C however, memory access/usage/mapping is very well understood, optimized, and presented in a more straight forward fashion. Because of this, most people when coding in C are already programming in a way that can utilize the CPUs cache more efficiently which greatly speeds up memory access and allows the CPU to be working more of the time.
> 
> * discalimer: This is what I remember when I looked into why the Linux kernel is programmed in C and not C++ when there are a lot of constructs in the kernel that exhibit object oriented philosophies. I could also be very wrong here as well, but this is what I understand of the differences.


Reasons why the Linux kernel is written in C rather than C++:

- New architectures and platforms will typically have a C compiler long before they have a C++ compiler. C is a much simpler and easier language to implement.
- Portability of C code between compilers has been far better.
- C++ requires a more complicated runtime to support things like exception handling and RTTI.
- Apparently simple statements can hide expensive operations, thanks to operator-overloading. Good in user world, bad in kernel world.

NON-reasons why the Linux kernel is written in C rather than C++:

- *C++ is slower than C*. C++ has the same overheads as C. Additional overheads only arise when using features C doesn't support which you can't do at the kernel level anyway.
- Virtual functions are slow. Virtual dispatch is slower than static dispatch, but the performance penalty is modest, particularly when used sparingly. Many kernels already make wide use of function tables for performing dynamic dispatch.
- C++ Templates cause massive code bloat. This is potentially true. However again, many kernels use macros to perform similar code generation effects.


----------



## 8BitPandaz

Hey, all how's it going
Quote:


> Originally Posted by *axipher*
> 
> Maybe we can start off by getting people's preferred IDE for writing code for different languages.


I use Notepad++ for most things (HTML, PHP, JS, CSS) Java coding I used to use BlueJ before using NetBeans


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *tompsonn*
> 
> Eh.
> 
> In C++, "you only pay for what you use." So there is nothing that would make it any slower than C. In particular for scientific programs, template expressions make it possible to perform some custom optimization using the template engine to process program semantics. Well written code in any language is always better than poorly written code in any other language.
> 
> I don't think that the reason is so much related to performance as it is to interoperability. The C++ language is more complex than the C language, but from a performance point of view there shouldn't be a notable difference in either way. Some C++ constructs are faster than the C equivalent (std::sort is faster than qsort) and there are probably good examples of the other way around.
> 
> C++ may be slower if you use its more advanced features but you have to ask yourself if you are micro-optimizing or if there really is a bottleneck.
> 
> I think your mate is in fairy land if he is going around saying C is definitely faster than C++. The same code in either language will have zero difference in speed and in some cases C++ can be faster depending on what you do, just like C can be as well.


Well that explains it even more,but why use C for building OSs instead of C++ if the written code is what matters the most?

A while back I've started attending Computational Geometry lectures and damn I love that subject I've even implemented some of the algorithms it uses like the orientation test and it's been so much fun

this is the code I currently use


Spoiler: Warning: Spoiler!



Code:



Code:


#include <iostream>
#include <cmath>
using namespace std;

struct Points{
        float X, Y;//The X and Y elements of any point

        void operator () (float X1, float Y1){
                X = X1;
                Y = Y1;
        }//Assigns the value of a point
        void operator = (Points P){
                X = P.X;
                Y = P.Y;
        }//Assigns the value of a point to another point

        Points operator + (Points P){
                Points P1;
                P1.X = X + P.X;
                P1.Y = Y + P.Y;
                return P1;
        }//Sums a point with another point
        Points operator - (Points P){
                Points P1;
                P1.X = X - P.X;
                P1.Y = Y - P.Y;
                return P1;
        }//Substracts a point from another point

        void operator * (float Num){
                X = X * Num;
                Y = Y * Num;
        }//Multiplies the point by a number
        void operator / (float Num){
                X = X / Num;
                Y = Y / Num;
        }//Divides a point by a number

        float Distance (Points P){
                float Distance = sqrt((pow((X - P.X), 2.0) + pow((Y - P.Y), 2.0)));
                return Distance;
        }//Calculates the distance between two points

        void Display(){
                cout << "(" << X << "," << Y << ")\n";
        }//Displays the Point on the console
};

class OrientationTest{
public:
        //Checks if a point is on the same line,left or right of it
        int Point_Check(Points Start_P, Points End_P, Points Check_P){
                float AreaOfTriangle = 0.5 * (Start_P.X *(End_P.Y - Check_P.Y)) - (End_P.X * (Start_P.Y - Check_P.Y)) + (Check_P.X * (Start_P.Y - End_P.Y));
                if (AreaOfTriangle > 0)
                        return 1;
                else if (AreaOfTriangle < 0)
                        return -1;
                else
                        return 0;
        }//-1 means the point is on the right of the line,1 means the point is on the left of the line,0 means the point is on the same line/line extention

        //Checks if a line is intersected,on the right or on the left of another line
        int Line_Check(Points Start_P, Points End_P, Points Start_Check, Points End_Check){
                int Result[2];
                Result[0] = Point_Check(Start_P, End_P, Start_Check);
                Result[1] = Point_Check(Start_P, End_P, End_Check);
                if (Result[0] == 1 && Result[1] == 1)
                        return 1;
                else if (Result[0] == -1 && Result[1] == -1)
                        return -1;
                else{
                        Result[0] = Point_Check(Start_Check, End_Check, Start_P);
                        Result[1] = Point_Check(Start_Check, End_Check, End_P);
                        if (Result[0] == Result[1])
                                return 0;
                        else
                                return 10;
                }
        }//-1 means the line is on the right,1 means is on the left,0 means the line isn't intersecting,10 means the line is intersecting

        //Checks if a point is inside a triangle or not
        bool Triangle_Check(Points T1, Points T2, Points T3, Points Check){
                Points TrianglePoints[3] = { T1, T2, T3 };
                int Results[3], ReturnValue = 1;
                for (int i = 0; i < 3; ++i){
                        if (i < 2)
                                Results[i] = Point_Check(TrianglePoints[i], TrianglePoints[i + 1], Check);
                        else
                                Results[i] = Point_Check(TrianglePoints[i], TrianglePoints[i - 2], Check);
                        if (i > 0)
                                if (Results[i] != Results[i - 1]){
                                        ReturnValue = 0;
                                        break;
                                }
                }
                return ReturnValue;
        }//True means it's inside the triangle,false means it's not

#define PI 3.14159265
        //Checks if a point is inside a circle or not
        bool Circle_Check(Points Center, float Radius, Points Check){
                Points TheCurrentPoint, ThePreviousPoint;//TheCurrentPoint is the point that'll be used along with the Center point to test the orientation of the Check point

                //Initialize the value of TheCurrentPoint
                TheCurrentPoint.X = Center.X + Radius;
                TheCurrentPoint.Y = Center.Y;

                float Angle = 180, VectorsAngel = 180, Angle_In_Radians;//Angle represents the angle between the current point and the maximum X point(Except for when the maximum X point is the same as the CurrentPoint,in that case the angle is 0 not 180),VectorsAngle is the angle between the two vectors,Angle_In_Radians is the angle in redians
                bool ReturnValue = false;
                while (VectorsAngel >= 0.1){
                        if (Point_Check(Center, TheCurrentPoint, Check) == 0){
                                if (Check.Distance(Center) <= TheCurrentPoint.Distance(Center)){
                                        ReturnValue = true;
                                        break;
                                }
                                else
                                        break;
                        }
                        else{
                                if (Angle != 180){
                                        if (Point_Check(Center, TheCurrentPoint, Check) == 1)
                                                Angle += 0.5 * Angle;
                                        else
                                                Angle -= 0.5 * Angle;
                                }
                                else{
                                        if (Point_Check(Center, TheCurrentPoint, Check) == 1)
                                                Angle -= 0.5 * Angle;
                                        else
                                                Angle += 0.5 * Angle;
                                }
                        }

                        //The Angle in redians
                        Angle_In_Radians = (Angle * PI) / 180;

                        //The new CurrentPoint
                        TheCurrentPoint.X = (Radius * cos(Angle_In_Radians)) + Center.X;
                        TheCurrentPoint.Y = (Radius * sin(Angle_In_Radians)) + Center.Y;

                        ThePreviousPoint = TheCurrentPoint;
                        if (Triangle_Check(Center, TheCurrentPoint, ThePreviousPoint, Check) == true){
                                ReturnValue = true;
                                break;
                        }
                        VectorsAngel /= 2;
                }
                return ReturnValue;
        }//If it returns false then the point isn't in the circle and vice versa
};





Do you guys have any tips for me like how to name my variables and such?


----------



## tompsonn

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> Well that explains it even more,but why use C for building OSs instead of C++ if the written code is what matters the most?
> 
> A while back I've started attending Computational Geometry lectures and damn I love that subject I've even implemented some of the algorithms it uses like the orientation test and it's been so much fun
> 
> this is the code I currently use
> 
> 
> Spoiler: Warning: Spoiler!
> 
> 
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> #include <iostream>
> #include <cmath>
> using namespace std;
> 
> struct Points{
> float X, Y;//The X and Y elements of any point
> 
> void operator () (float X1, float Y1){
> X = X1;
> Y = Y1;
> }//Assigns the value of a point
> void operator = (Points P){
> X = P.X;
> Y = P.Y;
> }//Assigns the value of a point to another point
> 
> Points operator + (Points P){
> Points P1;
> P1.X = X + P.X;
> P1.Y = Y + P.Y;
> return P1;
> }//Sums a point with another point
> Points operator - (Points P){
> Points P1;
> P1.X = X - P.X;
> P1.Y = Y - P.Y;
> return P1;
> }//Substracts a point from another point
> 
> void operator * (float Num){
> X = X * Num;
> Y = Y * Num;
> }//Multiplies the point by a number
> void operator / (float Num){
> X = X / Num;
> Y = Y / Num;
> }//Divides a point by a number
> 
> float Distance (Points P){
> float Distance = sqrt((pow((X - P.X), 2.0) + pow((Y - P.Y), 2.0)));
> return Distance;
> }//Calculates the distance between two points
> 
> void Display(){
> cout << "(" << X << "," << Y << ")\n";
> }//Displays the Point on the console
> };
> 
> class OrientationTest{
> public:
> //Checks if a point is on the same line,left or right of it
> int Point_Check(Points Start_P, Points End_P, Points Check_P){
> float AreaOfTriangle = 0.5 * (Start_P.X *(End_P.Y - Check_P.Y)) - (End_P.X * (Start_P.Y - Check_P.Y)) + (Check_P.X * (Start_P.Y - End_P.Y));
> if (AreaOfTriangle > 0)
> return 1;
> else if (AreaOfTriangle < 0)
> return -1;
> else
> return 0;
> }//-1 means the point is on the right of the line,1 means the point is on the left of the line,0 means the point is on the same line/line extention
> 
> //Checks if a line is intersected,on the right or on the left of another line
> int Line_Check(Points Start_P, Points End_P, Points Start_Check, Points End_Check){
> int Result[2];
> Result[0] = Point_Check(Start_P, End_P, Start_Check);
> Result[1] = Point_Check(Start_P, End_P, End_Check);
> if (Result[0] == 1 && Result[1] == 1)
> return 1;
> else if (Result[0] == -1 && Result[1] == -1)
> return -1;
> else{
> Result[0] = Point_Check(Start_Check, End_Check, Start_P);
> Result[1] = Point_Check(Start_Check, End_Check, End_P);
> if (Result[0] == Result[1])
> return 0;
> else
> return 10;
> }
> }//-1 means the line is on the right,1 means is on the left,0 means the line isn't intersecting,10 means the line is intersecting
> 
> //Checks if a point is inside a triangle or not
> bool Triangle_Check(Points T1, Points T2, Points T3, Points Check){
> Points TrianglePoints[3] = { T1, T2, T3 };
> int Results[3], ReturnValue = 1;
> for (int i = 0; i < 3; ++i){
> if (i < 2)
> Results[i] = Point_Check(TrianglePoints[i], TrianglePoints[i + 1], Check);
> else
> Results[i] = Point_Check(TrianglePoints[i], TrianglePoints[i - 2], Check);
> if (i > 0)
> if (Results[i] != Results[i - 1]){
> ReturnValue = 0;
> break;
> }
> }
> return ReturnValue;
> }//True means it's inside the triangle,false means it's not
> 
> #define PI 3.14159265
> //Checks if a point is inside a circle or not
> bool Circle_Check(Points Center, float Radius, Points Check){
> Points TheCurrentPoint, ThePreviousPoint;//TheCurrentPoint is the point that'll be used along with the Center point to test the orientation of the Check point
> 
> //Initialize the value of TheCurrentPoint
> TheCurrentPoint.X = Center.X + Radius;
> TheCurrentPoint.Y = Center.Y;
> 
> float Angle = 180, VectorsAngel = 180, Angle_In_Radians;//Angle represents the angle between the current point and the maximum X point(Except for when the maximum X point is the same as the CurrentPoint,in that case the angle is 0 not 180),VectorsAngle is the angle between the two vectors,Angle_In_Radians is the angle in redians
> bool ReturnValue = false;
> while (VectorsAngel >= 0.1){
> if (Point_Check(Center, TheCurrentPoint, Check) == 0){
> if (Check.Distance(Center) <= TheCurrentPoint.Distance(Center)){
> ReturnValue = true;
> break;
> }
> else
> break;
> }
> else{
> if (Angle != 180){
> if (Point_Check(Center, TheCurrentPoint, Check) == 1)
> Angle += 0.5 * Angle;
> else
> Angle -= 0.5 * Angle;
> }
> else{
> if (Point_Check(Center, TheCurrentPoint, Check) == 1)
> Angle -= 0.5 * Angle;
> else
> Angle += 0.5 * Angle;
> }
> }
> 
> //The Angle in redians
> Angle_In_Radians = (Angle * PI) / 180;
> 
> //The new CurrentPoint
> TheCurrentPoint.X = (Radius * cos(Angle_In_Radians)) + Center.X;
> TheCurrentPoint.Y = (Radius * sin(Angle_In_Radians)) + Center.Y;
> 
> ThePreviousPoint = TheCurrentPoint;
> if (Triangle_Check(Center, TheCurrentPoint, ThePreviousPoint, Check) == true){
> ReturnValue = true;
> break;
> }
> VectorsAngel /= 2;
> }
> return ReturnValue;
> }//If it returns false then the point isn't in the circle and vice versa
> };
> 
> 
> 
> 
> 
> Do you guys have any tips for me like how to name my variables and such?


I posted reasons in the next post why the Linux kernel uses C over C++.


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *tompsonn*
> 
> I posted reasons in the next post why the Linux kernel uses C over C++.


I see,so C++ isn't that much slower than C after all but what about scientific applications performance using both?


----------



## QuietReading

Quote:


> Originally Posted by *axipher*
> 
> Maybe we can start off by getting people's preferred IDE for writing code for different languages.


Eclipse for Java and Notepad++ for C. Don't do much web development these days but that's usually a combination of Notepad++ and DreamWeaver.


----------



## tompsonn

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> I see,so C++ isn't that much slower than C after all but what about scientific applications performance using both?


I wouldn't read so much into it. Use what you know.

One of my tips: don't worry about performance until you have performance problems.


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *tompsonn*
> 
> I wouldn't read so much into it. Use what you know.
> 
> One of my tips: don't worry about performance until you have performance problems.


Well I was asking about performance because I was interested in CUDA parallel computing so performance is everything and that's why I was asking about it :/


----------



## hajile

Quote:


> Originally Posted by *tompsonn*
> 
> Reasons why the Linux kernel is written in C rather than C++:
> 
> - New architectures and platforms will typically have a C compiler long before they have a C++ compiler. C is a much simpler and easier language to implement.
> - Portability of C code between compilers has been far better.
> - C++ requires a more complicated runtime to support things like exception handling and RTTI.
> - Apparently simple statements can hide expensive operations, thanks to operator-overloading. Good in user world, bad in kernel world.
> 
> NON-reasons why the Linux kernel is written in C rather than C++:
> 
> - *C++ is slower than C*. C++ has the same overheads as C. Additional overheads only arise when using features C doesn't support which you can't do at the kernel level anyway.
> - Virtual functions are slow. Virtual dispatch is slower than static dispatch, but the performance penalty is modest, particularly when used sparingly. Many kernels already make wide use of function tables for performing dynamic dispatch.
> - C++ Templates cause massive code bloat. This is potentially true. However again, many kernels use macros to perform similar code generation effects.


New architectures aren't really a reason to write Linux in C. There hasn't been a new ISA (of any real significance) in a decade.

C++ is context-sensitive while C is a context-free grammar which means that a C compiler is far less prone to bugs and C++ is provably harder to optimize (context-sensitive grammars suffer from PSPACE-completeness).

C++ only has the same overhead as C provided that you stick to the subset of C++ that is already close to C (at which point you might as well use C).

Another important point is that many C programmers use object-oriented code (even in the Linux kernel) which reduces the appeal of C++ even more.

This is the actual reason why C is used is that Linus doesn't like it.


Spoiler: Warning: Spoiler!



note: there's more to the discussion here
http://article.gmane.org/gmane.comp.version-control.git/57918
Quote:


> From: Linus Torvalds linux-foundation.org>
> Subject: Re: [RFC] Convert builin-mailinfo.c to use The Better String Library.
> Newsgroups: gmane.comp.version-control.git
> Date: 2007-09-06 17:50:28 GMT (6 years, 28 weeks, 19 hours and 54 minutes ago)
> 
> On Wed, 5 Sep 2007, Dmitry Kakurin wrote:
> >
> > When I first looked at Git source code two things struck me as odd:
> > 1. Pure C as opposed to C++. No idea why. Please don't talk about portability,
> > it's BS.
> 
> *YOU* are full of bull****.
> 
> C++ is a horrible language. It's made more horrible by the fact that a lot
> of substandard programmers use it, to the point where it's much much
> easier to generate total and utter crap with it. Quite frankly, even if
> the choice of C were to do *nothing* but keep the C++ programmers out,
> that in itself would be a huge reason to use C.
> 
> In other words: the choice of C is the only sane choice. I know Miles
> Bader jokingly said "to piss you off", but it's actually true. I've come
> to the conclusion that any programmer that would prefer the project to be
> in C++ over C is likely a programmer that I really *would* prefer to piss
> off, so that he doesn't come and screw up any project I'm involved with.
> 
> C++ leads to really really bad design choices. You invariably start using
> the "nice" library features of the language like STL and Boost and other
> total and utter crap, that may "help" you program, but causes:
> 
> - infinite amounts of pain when they don't work (and anybody who tells me
> that STL and especially Boost are stable and portable is just so full
> of BS that it's not even funny)
> 
> - inefficient abstracted programming models where two years down the road
> you notice that some abstraction wasn't very efficient, but now all
> your code depends on all the nice object models around it, and you
> cannot fix it without rewriting your app.
> 
> In other words, the only way to do good, efficient, and system-level and
> portable C++ ends up to limit yourself to all the things that are
> basically available in C. And limiting your project to C means that people
> don't screw that up, and also means that you get a lot of programmers that
> do actually understand low-level issues and don't screw things up with any
> idiotic "object model" crap.
> 
> So I'm sorry, but for something like git, where efficiency was a primary
> objective, the "advantages" of C++ is just a huge mistake. The fact that
> we also piss off people who cannot see that is just a big additional
> advantage.
> 
> If you want a VCS that is written in C++, go play with Monotone. Really.
> They use a "real database". They use "nice object-oriented libraries".
> They use "nice C++ abstractions". And quite frankly, as a result of all
> these design decisions that sound so appealing to some CS people, the end
> result is a horrible and unmaintainable mess.
> 
> But I'm sure you'd like it more than git.
> 
> Linus






Linus had a less-famous discussion here


Spoiler: Warning: Spoiler!



http://www.realworldtech.com/forum/?threadid=104196&curpostid=104333
Quote:


> Oh Come On Dept ([email protected]) on 6/11/10 wrote:
> >
> >For debugging purposes, your debugger already knows which
> >function is called and can tell you exactly.
> 
> I'm amazed by this total inability to understand the whole
> message. It was about communication. I though that
> was entirely clear, it was what the entire and whole thing
> was talking about all the time.
> 
> There's no "debugger" in communication. There is no IDE
> that helps figure out what's going on. There is no syntax
> highlighting etc.
> 
> There are just emails with patches and suggestions flying
> around. There's no room for special tools - if you as a
> human cannot see what the code does from the change,
> it's a problem. And you usually see about three lines of
> context around the code.
> 
> So code that depends on types or other context that is not
> immediately visible is bad.
> 
> Oh, you can do bad things in C too. You can do macros that
> use variables (global or local) that aren't part of
> the arguments to the macro, etc. But in C you really have to
> work at it, or do things that are very much against all the
> regular C "culture". When people do that (and it does
> happen, I'll not deny it), everybody knows it's a crappy
> hack.
> 
> And don't get me wrong. With three lines of context you
> can't always tell what the code does in C either. You
> are easily missing all the locking rules etc that are
> required for the code to actually work correctly. But at
> the same time, C at least has less room for the
> kind of things that make it harder to see what happens.
> 
> So it's just much easier to create a mess in C++,
> exactly because the language has all those features that
> are literally designed to use invisible context.
> 
> The "invisible" context is all over in the C++ extensions
> to the C language. It's in all the implicit object
> creations, constructors and destructors. It's in default
> argument values, and in the type-based polymorphism. It's
> in the absolutely disgusting "pass by reference" crap.
> 
> And yes, you can use just a subset of C++ to limit the
> damage from the crazy language. But the problem is, there
> isn't even any "sane C++ culture". There are projects
> that have done a good job at it, but some people love
> using references ("it's safer than a pointer" - f*cking
> moronic argument), and others think almost everything
> should be done with a template.
> 
> So the "just use a subset" isn't actually a viable model
> either, because there isn't any sane standard subset that
> you can kind of rely on people agreeing to. What is an
> abomination to one person is the greatest feature of C++
> to another.
> 
> So what you get is "use the subset of C++ that is C". We
> can all agree on that, and we can trivially enforce it by
> using a C compiler. Problem solved. All the crap just goes
> out the window.
> 
> Linus








Spoiler: Warning: Spoiler!



http://www.realworldtech.com/forum/?threadid=104196&curpostid=104335
Quote:


> Mark Christiansen ([email protected]) on 6/11/10 wrote:
> 
> >Linus Torvalds ([email protected]) on 6/11/10 wrote:
> >
> >> Much about context in C++ vs. C.
> >
> >Is there anything the compiler and language could do to
> >help? What problems do you face that language might be
> >able to mitigate?
> 
> The thing is, we seldom have problems that are really
> about the language itself. C has a huge base of people who
> know it, which is a big deal. And the people who know it
> are the kind of people who tend to know about low-level
> things, so it's a good audience too.
> 
> People who worry about language details often worry about
> the wrong thing entirely. As long as the language is
> expressive enough, and doesn't cause unnecessary pain, I
> personally suspect the primary issues always end up being
> other things.
> 
> For example, one big issue for us is compiler stability.
> Maybe it's because we're the kernel, but the thing is, a
> compiler bug is really painful for us.
> 
> Similarly, for the kernel, we really end up having some
> very strict requirements about the code generated. We have
> a very limited stack, so the compiler can't just go around
> generating temporary structures on the stack willy nilly.
> 
> In fact, in the kernel, we tend to limit even our C use!
> We may do some things that almost nobody else does (like
> play with calling conventions, inline assembly etc), but
> at the same time we eschew things like 'typedef's of
> structures, exactly because if we have a local variable
> that is a structure - and thus potentially uses lots of
> stack space - it needs to be very visible in the source.
> 
> >What I wish for most is good descriptions of the data.
> 
> I violently agree in the sense that my personal opinion is
> that you should design the data structures first, and that
> good data structure design is much more important than the
> code for many things. If you get the data structures and
> locking right, the code will work - or at least be fixable
> when it doesn't.
> 
> So good code design revolves around thinking about how
> the data moves around, how it is organized, and how it is
> looked up and associated with other data.
> 
> But the OO languages tend to think that that means that
> objects are important, and should have methods that are
> associated with them. That's just crazy talk. A single
> object (or a trivial collection of objects of some type:
> think iterators etc) is not a really interesting thing.
> 
> When it gets interesting is when different objects of
> different types interact, and have locking rules etc. And
> at that point, trying to encapsulate some "object interface"
> is absolutely the wrong thing, because it's not about a
> single object any more.
> 
> So I think most of the OO examples are for trivial code
> that doesn't matter. It's very pretty to have operator
> overloading for different types, and it makes it easy to
> do things like vector or complex algebra without having
> to make the types be intrinsic to the language and still
> allow nice syntax.
> 
> But at the same time, that's a trivial and totally
> uninteresting problem. Making it easy to express that kind
> of stuff - which is what OO languages with type-based
> polymorphism (of functions and/or operators) tend to do -
> is simply not relevant for any complex data relationship.
> 
> So I agree that describing the data is important, but at
> the same time, the things that really need the most
> description are how the data hangs together, what the
> consistency requirements are, what the locking rules are
> (and not for a single data object either), etc etc.
> 
> And my suspicion is that you can't easily really describe
> those to a compiler. So you end up having to write that
> code yourself regardless.
> 
> And hey, maybe it's because I do just low-level programming
> that I think so. As mentioned, most of the code I work with
> really deeply cares about the kinds of things that most
> software projects probably never even think about: stack
> depth, memory access ordering, fine-grained locking, and
> direct hardware access.
> 
> C is good at that. I think the preprocessor sucks, and
> we abuse the thing mercilessly, but I don't think more
> "compiler makes things easier by automating things behind
> your back" would help for the kernel.
> 
> In fact, we have added things to make sure the compiler
> does less behind our back. Implicit and silent
> integer type conversions have caused lots of problems, so
> we have some exceedingly ugly C/preprocessor code to have
> our own "min()/max()" macros that simply error out if one
> side has a different type or signedness than the other.
> 
> Because by default, C actually ends up not being strict
> enough for us. The last thing I'd want is a compiler
> that does even more silent "helping".
> 
> (Again, security issues are a big deal. Most programmers
> don't much tend to worry about "what if somebody we don't
> trust passes us two large integers and the addition of them
> overflows?". We have tons of things like that in the
> kernel, so you'll see code like
> 
> if (a + b < a)
> return -EINVAL;
> 
> that protect against overflow. The "signed integer overflow
> is undefined" thing is actually annoying to us. Any such
> undefined behavior is not good. The compiler deciding that
> it can move things around because they'd be undefined if
> they ever happen is a bug for us.
> 
> (Example: we had a real security issue, because some
> code ended up basically - after various inlining etc - doing
> something like
> 
> var = ptr->xyz
> if (!ptr)
> return -EFAULT;
> use var
> 
> and the compiler just removed the conditional, because it
> "knew" that ptr cannot be NULL, because it would have
> faulted if it was. But the thing is, users can map the
> address at zero, and then the conditional actually did
> matter. We now have various automatic checkers for
> the above, but the thing is, for the kernel it would have
> been better to warn about this than just silently have the
> compiler be "helpful" and removing useless code).
> 
> It all ends up boiling down to:
> 
> - kernels are fragile and subtle things, and have very
> strict rules that people really need to be aware of.
> 
> - if the language/compiler makes it easy to write code
> where you can't see the things we have rules for (like
> stack usage), that's a bad thing.
> 
> - hidden/implicit things are usually bad. If we want
> code to be generated, we'd write that explicitly. Not
> have the compiler do it for us to "help".
> 
> >C++ has methods for directing the differences to different
> >code. I can't say I am real fond of inheritance as I don't
> >often have problems which are heirarchical refinements of a
> >generic base class.
> 
> Right. It's a trivial thing, and it's not very common in
> the end. Complicated problems don't have some simple
> strictly hierarchical data structures.
> 
> That said, the easy cases you can often easily do in C too.
> Embedding structures inside each other is not rocket
> science. The kernel does a few cases really well: see how
> we do things like lists by having generic list structures
> that can be embedded in other structures. Not just once,
> either - so we have "multiple inheritance" of these things.
> 
> But yes, you'll need to understand pointers. And pointers
> to pointers. And write some "interesting" macro wrappers
> once. And it's still not going to be so pretty that you
> can just consider them arbitrary iterators and pass them
> around to your generic iterator-based sort routine.
> 
> But it's really not all that horrible either for the
> trivial cases. And for the more complex cases, you really
> did need to write the code specially anyway, because the
> locking covers not a single operation, but multiple, and
> you can't describe that by describing the individual data
> structures anyway.
> 
> >Still, the features are good for directing differences to
> >different code.
> 
> Sure. And in the kernel, we generally have to handle that
> explicitly. Either we associate function pointers with
> the data (and make the accessors very explicit), or we
> do as you mention and have a common routine that just
> handles all the cases. Both exist.
> 
> And then, occasionally, we do some really ugly crud with
> the preprocessor and inlining and depend on the compiler
> optimizing away dead code. There's a few cases where we
> do "size-based polymorphism", where we literally have
> one function (well, macro from hell) that can take integer
> arguments of different size, and will do different things
> to them. It's unbelievably ugly, but it wouldn't have been
> any prettier in C++ either.
> 
> So you can do even polymorphism without strict language
> support.
> 
> >C++ and the whole object oriented area is focused on the
> >custom code model. Stroustrup in C++ specifically
> >disparages parameterization.
> 
> I generally agree on trying to avoid parameterization. I
> just don't think C++ is the answer to it. Or even the
> object-oriented approach.
> 
> We try to do static types as far as possible (and make
> the code-paths static, not parameterized). Avoid "flags"
> in types.
> 
> And when that doesn't work, do the OO thing, but do it with
> explicit function pointers. What's the advantage of the
> C++ syntax, except to hide what is actually going on?
> 
> >Give me a good description of the data and I can make
> >libraries which do useful things on structures, or classes
> >if you like, which were created long after my library
> >code was compiled.
> 
> I just don't think that the real problems are associated
> with one particular data description. You don't want a
> library routine for that kind of data - you want code that
> interacts between that data and other kinds of data.
> 
> And I point to the almost total lack of any reusable C++
> code as the proof in the pudding. Or just about any
> "object oriented" library. They just don't exist. The
> whole and only point of C++ seems to be Boost + STL. And
> those aren't really all that interesting and exciting
> problems, are they?
> 
> Why do you need a whole new language just to iterate over
> a list?
> 
> Linus


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *hajile*


Wow....that guy REALLY hated C++,what do you think?are his reasons for hating it valid?


----------



## tompsonn

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> Wow....that guy REALLY hated C++,what do you think?are his reasons for hating it valid?


Yes. But he sees the world from kernel-colored glasses.


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *tompsonn*
> 
> Yes. But he sees the world from kernel-colored glasses.


Interesting...I've used to think think C was a dead language really (and yes I know I'm an ultra NOOB),but now after seeing this I might do some projects with C too.....


----------



## poroboszcz

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> Well I was asking about performance because I was interested in CUDA parallel computing so performance is everything and that's why I was asking about it :/


CUDA actually uses its own compiler and programming language which is based on C/C++ syntax. If you intend to write CUDA code yourself than learning C first is probably the best thing to do, as the languages are very similar. The overall logic of a CUDA program is going to be quite different though from a typical C program. If you only intend to use CUDA, i.e. use GPU for massively parallel computations, then you can use an existing library, which is written in CUDA C/C++ and provides bindings to the language of your choice. In that case it doesn't really matter if you call some CUDA method from C, C++, Python or Matlab.

If you are interested in C++ then just a few days ago ISO C++ has launched a FAQ which answers most of the questions you may have about the language: http://isocpp.org/wiki/faq/

Here's what they have to say about C++ vs C:
Quote:


> In 99% of the cases, programming language selection is dominated by business considerations, not by technical considerations. Things that really end up mattering are things like availability of a programming environment for the development machine, availability of runtime environment(s) for the deployment machine(s), licensing/legal issues of the runtime and/or development environments, availability of trained developers, availability of consulting services, and corporate culture/politics. These business considerations generally play a much greater role than compile time performance, runtime performance, static vs. dynamic typing, static vs. dynamic binding, etc.
> 
> Those who ignore the (dominant!) business criteria when evaluating programming language tradeoffs expose themselves to criticism for having poor judgment. Be technical, but don't be a techie weenie. Business issues really do dominate technical issues, and those who don't realize that are destined to make decisions that have terrible business consequences - they are dangerous to their employer.(...)
> 
> Several reviewers asked me to compare C++ to other languages. This I have decided against doing. Thereby, I have reaffirmed a long-standing and strongly held view: Language comparisons are rarely meaningful and even less often fair. A good comparison of major programming languages requires more effort than most people are willing to spend, experience in a wide range of application areas, a rigid maintenance of a detached and impartial point of view, and a sense of fairness. I do not have the time, and as the designer of C++, my impartiality would never be fully credible.


And
Quote:


> C++ is a direct descendant of C95 (C90 plus an Amendment) that retains almost all of C95 as a subset. C++ provides stronger type checking than C and directly supports a wider range of programming styles than C. C++ is "a better C" in the sense that it supports the styles of programming done using C with better type checking and more notational support (without loss of efficiency). In the same sense, ANSI C90/C95 is a better C than K&R C. In addition, C++ supports data abstraction, object-oriented programming, and generic programming.
> 
> We have never seen a program that could be expressed better in C95 than in C++ (and we don't think such a program could exist - every construct in C95 has an obvious C++ equivalent). However, there still exist a few environments where the support for C++ is so weak that there is an advantage to using C instead. There aren't all that many of those left, though;


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *poroboszcz*
> 
> CUDA actually uses its own compiler and programming language which is based on C/C++ syntax. If you intend to write CUDA code yourself than learning C first is probably the best thing to do, as the languages are very similar. The overall logic of a CUDA program is going to be quite different though from a typical C program. If you only intend to use CUDA, i.e. use GPU for massively parallel computations, then you can use an existing library, which is written in CUDA C/C++ and provides bindings to the language of your choice. In that case it doesn't really matter if you call some CUDA method from C, C++, Python or Matlab.
> 
> If you are interested in C++ then just a few days ago ISO C++ has launched a FAQ which answers most of the questions you may have about the language: http://isocpp.org/wiki/faq/
> 
> Here's what they have to say about C++ vs C:
> And


Yes I'm aware that CUDA has its own compiler (which kinda sucks cause it isn't included with CUDA toolkit 6 which is the only toolkit available for Visual studio)and I don't think that I'll use CUDA only projects

Thanks for the link!and yes it does answer a lot of the questions I have


----------



## ABD EL HAMEED

So a while ago a mate asked me to make him a simple program to calculate the number "num" to the power "po" (and yes I know there's a function in c++ that does that for me but for some reason he wants me to make my own one)so I told him it'd be easy then he told me to create it using an O(logn) algorithm (I seriously don't know why since these are exponents and we don't deal with very large numbers and C++ doesn't have a data type to store very large numbers anyway) so I created one using this code


Spoiler: Warning: Spoiler!



Code:



Code:


#include <iostream>
#include <cmath>
using namespace std;

double power(double n, int p);

int main(){
        double n;
        int p;
        while (cin >> n >> p)
                cout << power(n, p) << endl;
        return 0;
}

double power(double n, int p){
        double newNum = n, Num = 1;
        int i, po = p;
        for (i = 2; i <= po; i *= 2){
                newNum *= newNum;
                if ((i * 2) > po && i < po){
                        po = abs(po - i);
                        i = 1;
                        Num *= newNum;
                        newNum = n;
                }
        }
        newNum *= Num;
        return newNum;
}





And it worked...well....kind of,when I try to calculate numbers with large exponents it doesn't give me the correct result,for example say I wanna calculate 2 to the power 63 the program's output will be 9.22337e+018 which means 9223370000000000000 now if I calculate that number using the default calculator in windows then it'll output 922337*2036854775808*, so this time I tried 2^21,my program will output 2.09715e+006 which is equal to 2097150 now if I calculate it with the calculator the result will be 209715*2*,so I'm kinda confused if this is a bug in my code which causes it to not work properly or is it perhaps precision limitations since both examples above (among others I've tried) have a precision of 5,so what do you more experienced programmers think?


----------



## tompsonn

Why so complicated?

Code:



Code:


long double power( long double value, long double power )
{
        long double result = 1;
        long double i;

        for ( i = 0; i < power; ++i ) 
                result *= value;

        return result;
}

BTW its calculating it properly (if you look in the debugger you'll see), you just need to change your cout:

Code:



Code:


int main()
{
        long double n;
        long double p;
        long double result;

        while ( cin >> n >> p )
                cout << fixed << ( result = power( n, p ) ) << endl;

        return 0;
}

http://www.cplusplus.com/reference/ios/fixed/


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *tompsonn*
> 
> Why so complicated?
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> long double power( long double value, long double power )
> {
> long double result = 1;
> long double i;
> 
> for ( i = 0; i < power; ++i )
> result *= value;
> 
> return result;
> }
> 
> BTW its calculating it properly (if you look in the debugger you'll see), you just need to change your cout:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> int main()
> {
> long double n;
> long double p;
> long double result;
> 
> while ( cin >> n >> p )
> cout << fixed << ( result = power( n, p ) ) << endl;
> 
> return 0;
> }
> 
> http://www.cplusplus.com/reference/ios/fixed/


It's complicated because my mate wants it to be an O(logn) algorithm for some unknown reason :/ (though I'll do some calculations first to make sure it's actually logn)


----------



## tompsonn

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> It's complicated because my mate wants it to be an O(logn) algorithm for some unknown reason :/ (though I'll do some calculations first to make sure it's actually logn)


Right. Missed that part. Still too complicated









Recursive O(log n) handling negatives:

Code:



Code:


long double power( long double x, long double y )
{
    long double temp;
    if ( y == 0 )
       return 1;

    temp = power( x, y / 2 );       
    if ( ( y % 2 ) == 0 )
        return temp * temp;
    else
    {
        if ( y > 0 )
            return x * temp * temp;
        else
            return ( temp * temp ) / x;
    }
}

Didn't test this one, just off the top of my head.


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *tompsonn*
> 
> Right. Missed that part. Still too complicated
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Recursive O(log n) *handling negatives*:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> long double power( long double x, long double y )
> {
> long double temp;
> if ( y == 0 )
> return 1;
> 
> temp = power( x, y / 2 );
> if ( ( y % 2 ) == 0 )
> return temp * temp;
> else
> {
> if ( y > 0 )
> return x * temp * temp;
> else
> return ( temp * temp ) / x;
> }
> }
> 
> Didn't test this one, just off the top of my head.


Code:



Code:


newNum *= (n < 0 && p % 2 != 0) ? -1 : 1;

^this handles it,and yes your code works very well now I should try to understand it


----------



## tompsonn

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> newNum *= (n < 0 && p % 2 != 0) ? -1 : 1;
> 
> ^this handles it,and yes your code works very well now I should try to understand it


Oh I know yours handled negatives, I was just pointing out that mine did too, not to imply yours didn't


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *tompsonn*
> 
> Oh I know yours handled negatives, I was just pointing out that mine did too, not to imply yours didn't


Actually mine didn't until you pointed at it.....


----------



## tompsonn

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> Actually mine didn't until you pointed at it.....


LOL. That makes sense. I didn't read your post OR your code, I sort of swished over it in one big chunk









Oh wait I saw you doing abs() and something clicked about negatives even though that's not the sort of negative handling we're talking about, but anyway, check my code properly because I've had too many beers tonight.


----------



## andyroo89

Why can't this thread be more active? are we too busy klaking a new program to discuss things in here? Just yesterday I am working on python script for my raspberry pi, and I am like man I sure wish I did have to make a list (similar to an array) of every letter of the alphabet, so, I did a quick search and found these map(chr, range(34,96)) <-- lower case and digits along with $#@ characters, then map(chr, range(97,127)) upper case and more @#! characters.

I am like sweet I can generate every character for my script with it manual putting it into a list... but it didn't work out and ended up using ascii_letters


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Why can't this thread be more active? are we too busy klaking a new program to discuss things in here? Just yesterday I am working on python script for my raspberry pi, and I am like man I sure wish I did have to make a list (similar to an array) of every letter of the alphabet, so, I did a quick search and found these map(chr, range(34,96)) <-- lower case and digits along with $#@ characters, then map(chr, range(97,127)) upper case and more @#! characters.
> 
> I am like sweet I can generate every character for my script with it manual putting it into a list... but it didn't work out and ended up using ascii_letters


I'm attempting to do something about this entire section as we speak







Stay tuned... hopefully. lol.


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> I'm attempting to do something about this entire section as we speak
> 
> 
> 
> 
> 
> 
> 
> Stay tuned... hopefully. lol.


Good to hear


----------



## Delphiwizard

I would love to see some gui's of the software other people here made...with some explanations what/how/why the software does.
'Show off your software' type...would it be allowed in this thread?


----------



## andyroo89

Quote:


> Originally Posted by *Delphiwizard*
> 
> I would love to see some gui's of the software other people here made...with some explanations what/how/why the software does.
> 'Show off your software' type...would it be allowed in this thread?


Eh I guess I can show some.. if I didn't delete it already from being scrapped projects.


----------



## CSCoder4ever

I can't believe I haven't posted in here yet! Just worked on a shell script to sync my Eclipse workspaces between my desktop and laptop.

I primarily use Eclipse and Emacs for my own projects, and jGrasp for college since that's what my Computer Science class uses. Currently trying to improve my C++ programming


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *CSCoder4ever*
> 
> I can't believe I haven't posted in here yet! Just worked on a shell script to sync my Eclipse workspaces between my desktop and laptop.
> 
> I primarily use Eclipse and Emacs for my own projects, and jGrasp for college since that's what my Computer Science class uses. Currently trying to improve my C++ programming


Hey I program in C++ too, C++ BUDDIESSSSSSSSSSS!!!!1!!!!


----------



## Delphiwizard

Quote:


> Originally Posted by *andyroo89*
> 
> Eh I guess I can show some.. if I didn't delete it already from being scrapped projects.


Well maybe i should start, feel free to ask questions or being critical, i am getting older and my programming skills are no longer what they once were









Ok, in the category 'show off your software', here's a bit of info on my biggest project.
This is a Windows client-server application with mdi made for small bussiness use and uses a firebird database.
And of course it is made in Delphi.
It can be used by multiple client pc's and use multiple databases (like if you need to keep data for several companies/purposes).

Because it is a client-server program it can of course also be used remotely, like connect to the database which is on the work server from home office or on the road.

The basic stuff of course is about keeping data, Customers, Suppliers, Invoices, Quotes, Delivery documents, Projects, Products, Product stock, group scheduler, Customer groups, Supplier groups, Indexing feature for products, car data, POS screen and of course graphs/statistics (like who bought how much of what product when, how much was this product sold and when and so on)
for each user features can be disabled/enabled by the administrator so it can for example be configured that user x has edit/add/delete access to the invoices, user y can only view invoices but not change them and user z can not see invoices at all.

One probably not important feature i wanted to add is that each user can chose a skin to change how the software looks, i hate it myself when i must use a tool that doesn't look fine to me.

The user can also chose if he prefers the ribbon looks or a normal menu.

Also it is very important that the data is loaded fast; in the first versions i had issues that for example loading 10.000 records took several minutes which caused me to do some serious changes; now it loads for instance 110.000 records in 2 seconds(of course depending on the speed of the pc/server).

And the user must be able to quickly search the data he is looking for, the devexpress grid i used allows all that, search, multi sort, multi group, move columns, resize columns, hide columns, multi filtering...

On with screenshots:

Login


Main screen


Google maps showing customer location


Statistics showing when the product was sold summed by month/year.


Scheduler showing appointments for 4 people


----------



## mocboy123

I'm a new programmer, so recently I've been going around and trying a bunch of different languages, my favorite so far has been HTML/CSS, and I'm going to eventually try and code my own website once I learn Javascript and PHP as well.


----------



## nooboc2012

The last kind of programming related thing I did was install ArcInfo and SQL server express 2008 in an effort to mess about with arc and learn a little about the mapping/GIS back end side of things.

I've been looking for work as well in a DBA/application support capacity. There's plenty of work going on in Australia compared to last year and I've had a few interviews. So hopefully not to long before I find something.


----------



## ABD EL HAMEED

Can someone give me some recursion exercises?I feel like I need to practice to get the hang of it


----------



## tom.slick

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> Can someone give me some recursion exercises?I feel like I need to practice to get the hang of it


http://www.bowdoin.edu/~ltoma/teaching/cs107/spring05/recursion.html
http://codingbat.com/java/Recursion-1
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-189-a-gentle-introduction-to-programming-using-python-january-iap-2011/lectures/MIT6_189IAP11_rec_problems.pdf
http://www.scs.ryerson.ca/~ikokkari/recursion.pdf
http://www.idt.mdh.se/kurser/cd5100/ht07/RecursionHaskell.pdf
https://wiki.engr.illinois.edu/display/cs125/Recursion+Exercises


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *tom.slick*
> 
> http://www.bowdoin.edu/~ltoma/teaching/cs107/spring05/recursion.html
> http://codingbat.com/java/Recursion-1
> http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-189-a-gentle-introduction-to-programming-using-python-january-iap-2011/lectures/MIT6_189IAP11_rec_problems.pdf
> http://www.scs.ryerson.ca/~ikokkari/recursion.pdf
> http://www.idt.mdh.se/kurser/cd5100/ht07/RecursionHaskell.pdf
> https://wiki.engr.illinois.edu/display/cs125/Recursion+Exercises


Thanks!this should keep me occupied for a while


----------



## ABD EL HAMEED

My first recursive function eva!WOOT!!!!









Code:



Code:


float sum(float num){
        return (num == 1) ? 1 : (num + sum(num - 1));
}

Note:it sums all the numbers from num to 1


----------



## robE

People, what would you choose or what would be better: 2 x 24' 1080p monitors or 1 x 27' 1440p monitor ? Actually i know that the best is something like 2-3 x 27' 1440p but my budget is somewhat tight
















Keep in mind that I'm not a full time job programmer, but i'm learning...fast, so maybe down the road(6months-1year) i can buy 1 more monitor or something.


----------



## alcal

Quote:


> Originally Posted by *robE*
> 
> People, what would you choose or what would be better: 2 x 24' 1080p monitors or 1 x 27' 1440p monitor ? Actually i know that the best is something like 2-3 x 27' 1440p but my budget is somewhat tight
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Keep in mind that I'm not a full time job programmer, but i'm learning...fast, so maybe down the road(6months-1year) i can buy 1 more monitor or something.


I would say 2x24" 1080p, as that is more pixels and can be arranged into 4 useful windows. The single 27" is harder to fit several windows into. My preferred setup at the moment is a 30" 2560x1600 with a 23" 1080p on the side (both in landscape). I usually put terminal/console windows on the small monitor and API's/Editors on the main monitor.


----------



## robE

Thanks! Your setup is sweet /envy









Another question: It's important when developing that the monitor to be able to stay in a vertical position? I'm asking that maybe i can squeeze a bit and get 3 monitor setup, or isn't worth it? Thanks !


----------



## andyroo89

Android programming is really making me mad, I realized now why I hate programming, but I am determined to get this. But I need help because #android-dev refuse to help me the 10 times I have been in there asking for help.

My goal is to have my phone automatically set its ringtone to vibrate late at night, and go back to medium volume in the morning. Someone attempted to help me but I tried the code he gave me, and it still does not work.

http://stackoverflow.com/questions/24196890/android-schedule-task-to-execute-at-specific-time-daily

Someone please help me.


----------



## Quantum Reality

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> Quote:
> 
> 
> 
> Originally Posted by *tompsonn*
> 
> Yes. But he sees the world from kernel-colored glasses.
> 
> 
> 
> Interesting...I've used to think think C was a dead language really (and yes I know I'm an ultra NOOB),but now after seeing this I might do some projects with C too.....
Click to expand...

You haven't been in a physics lab then







You'll find C still has a place in scientific applications.


----------



## tompsonn

I still use C in my applications, its certainly not dead


----------



## stumped

Quote:


> Originally Posted by *Quantum Reality*
> 
> You haven't been in a physics lab then
> 
> 
> 
> 
> 
> 
> 
> You'll find C *fortran* still has a place in scientific applications.


Fixed it for you


----------



## Quantum Reality

Quote:


> Originally Posted by *stumped*
> 
> Quote:
> 
> 
> 
> Originally Posted by *Quantum Reality*
> 
> You haven't been in a physics lab then
> 
> 
> 
> 
> 
> 
> 
> You'll find C *fortran* still has a place in scientific applications.
> 
> 
> 
> Fixed it for you
Click to expand...











That being said I've never personally used FORTRAN myself, and use C for pretty much anything.


----------



## Plan9

Quote:


> Originally Posted by *Quantum Reality*
> 
> You haven't been in a physics lab then
> 
> 
> 
> 
> 
> 
> 
> You'll find C still has a place in scientific applications.


I'm sure many do, but most of the labs I've visited have used Python quite heavily.


----------



## Sanmayce

@ABD EL HAMEED

Man, if you are gonna listen to one C amateur (as myself) C is alive and will never die, why, simply because it was conceived as PORTABLE ASSEMBLER targeted language ... sidekick.

I highly recommend reading one pamphlet explaining the very basis of REAL programming, a lot of fun it is, you can check it out http://www.codeproject.com/Lounge.aspx?msg=4744841#xx4744841xx

Also, it is good to read one Veteran of programming what have to say about old days, http://www.codeproject.com/Lounge.aspx?msg=4173251#xx4173251xx:

_...
The above information I learned from a Bell Labs programmer/developer at at DECUS (Digital Equipment Computer User's Society) meeting. He was one of the original creators of C, but unfortunately I forget his name.

He told me that when they developed C, they had in mind a "portable assembler" that would allow them to port code to any architecture by merely writing a translator for C for that new machine. Good C programmers, he said, visualized assembly code as they wrote in C.
...
_


----------



## wedge

Quote:


> Originally Posted by *robE*
> 
> Another question: It's important when developing that the monitor to be able to stay in a vertical position? I'm asking that maybe i can squeeze a bit and get 3 monitor setup, or isn't worth it? Thanks !


Get 2x 1920x1200. Much better than 1080p for doing real work. It doesn't seem like much difference. But the extra vertical space is what you need for programming/documents/web browsing.
1080p is only good for video and gaming. And even in gaming I still prefer 1200p.

I originally had 3 monitors, but found that I wasn't taking advantage of all 3 most of the time, just using 2. When one of them broke while under warranty, I just got my money back instead of replacing it.

Having said that, I do still want a 3k or 4k 27"+ as my next monitor. It will be center and my two current ones on the side. Think of it this way: Monitors are like cpu cores. Multiple smaller ones are good for multithreading (multitasking). But one big one can do a single task much better. The three monitor system I have in mind will be perfect for both.

Most people get exciting about the video quality of 4k resolution. But that doesn't interest me at all. I get excited about how many lines of text will fit on one of those screens... Mmmm.....


----------



## wedge

Quote:


> Originally Posted by *Sanmayce*
> 
> @ABD EL HAMEED
> 
> Man, if you are gonna listen to one C amateur (as myself) C is alive and will never die, why, simply because it was conceived as PORTABLE ASSEMBLER targeted language ... sidekick.
> 
> I highly recommend reading one pamphlet explaining the very basis of REAL programming, a lot of fun it is, you can check it out http://www.codeproject.com/Lounge.aspx?msg=4744841#xx4744841xx
> 
> Also, it is good to read one Veteran of programming what have to say about old days, http://www.codeproject.com/Lounge.aspx?msg=4173251#xx4173251xx:
> 
> _...
> The above information I learned from a Bell Labs programmer/developer at at DECUS (Digital Equipment Computer User's Society) meeting. He was one of the original creators of C, but unfortunately I forget his name.
> 
> He told me that when they developed C, they had in mind a "portable assembler" that would allow them to port code to any architecture by merely writing a translator for C for that new machine. Good C programmers, he said, visualized assembly code as they wrote in C.
> ...
> _


Yup, I've been getting into some hardware development as a hobby. It is all C programming, and that's not going to change for a very long time. So I'm having to learn that all over again. Going from OO to procedural feels like a step backwards...
I've discovered NetMF, which is extremely cool. Let's me do hardware development in C#. But that's still C/C++ at it's core, it just runs the C# user code like a script.


----------



## Plan9

Quote:


> Originally Posted by *wedge*
> 
> Yup, I've been getting into some hardware development as a hobby. It is all C programming, and that's not going to change for a very long time. So I'm having to learn that all over again. Going from OO to procedural feels like a step backwards...
> I've discovered NetMF, which is extremely cool. Let's me do hardware development in C#. But that's still C/C++ at it's core, it just runs the C# user code like a script.


You can still do OOP in C if you wanted to. Though personally, I often find myself drifting away from object-heavy paradigms these days.


----------



## Sanmayce

Quote:


> Originally Posted by *wedge*
> 
> Yup, I've been getting into some hardware development as a hobby. It is all C programming, and that's not going to change for a very long time. So I'm having to learn that all over again. Going from OO to procedural feels like a step backwards...


Man, you are so right, I sense you yourself have had some fun with hardware etudes at some time, don't stop the music.
Yes, my hobby is to explore small etudes in C.
At one time I looked at C++ and was frightened for life, you see the simplicity is dear to my heart, my personal belief is that one shouldn't run before learning to walk, well.
I mean everyone has his personal qualities and it is better to be adequate to them, this way he won't make unnecessary striving/ado.
Quote:


> Originally Posted by *wedge*
> 
> I've discovered NetMF, which is extremely cool. Let's me do hardware development in C#. But that's still C/C++ at it's core, it just runs the C# user code like a script.


Good to know, it is good when appreciation is among the driving forces, not money and some boss over your head.


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *Sanmayce*
> 
> @ABD EL HAMEED
> 
> Man, if you are gonna listen to one C amateur (as myself) C is alive and will never die, why, simply because it was conceived as PORTABLE ASSEMBLER targeted language ... sidekick.
> 
> I highly recommend reading one pamphlet explaining the very basis of REAL programming, a lot of fun it is, you can check it out http://www.codeproject.com/Lounge.aspx?msg=4744841#xx4744841xx
> 
> Also, it is good to read one Veteran of programming what have to say about old days, http://www.codeproject.com/Lounge.aspx?msg=4173251#xx4173251xx:
> 
> _...
> The above information I learned from a Bell Labs programmer/developer at at DECUS (Digital Equipment Computer User's Society) meeting. He was one of the original creators of C, but unfortunately I forget his name.
> 
> He told me that when they developed C, they had in mind a "portable assembler" that would allow them to port code to any architecture by merely writing a translator for C for that new machine. Good C programmers, he said, visualized assembly code as they wrote in C.
> ...
> _


Thanks!


----------



## andyroo89

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> Thanks!


Your avatar makes me laugh.


----------



## willll162904

Not sure how active this thread is anymore, but I've posted before and gotten some awesome help. I am starting to learn java and I do understand everything I'm learning, but I tend to not remember it. Is there any "tests" or sample programs I can try coding to help test myself?


----------



## LordOfTots

Quote:


> Originally Posted by *willll162904*
> 
> Not sure how active this thread is anymore, but I've posted before and gotten some awesome help. I am starting to learn java and I do understand everything I'm learning, but I tend to not remember it. Is there any "tests" or sample programs I can try coding to help test myself?


You could try this http://codingbat.com/java


----------



## Plan9

Quote:


> Originally Posted by *willll162904*
> 
> Not sure how active this thread is anymore, but I've posted before and gotten some awesome help. I am starting to learn java and I do understand everything I'm learning, but I tend to not remember it. Is there any "tests" or sample programs I can try coding to help test myself?


Have a go at the programming challenges Thompsonn has stickies in this forum. They have a range of tests to cover a range of programming abilities.


----------



## ABD EL HAMEED

I wanted to learn about BackTrack programming techniques so does anyone know useful links or books that I could use?


----------



## andyroo89

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> I wanted to learn about *BackTrack programming* techniques so does anyone know useful links or books that I could use?


backtrack is just a kubuntu variant. Pretty much those tools are made by people in OSS, python/bash/shell scripting. Backtrack is not a program language.


----------



## ABD EL HAMEED

http://en.wikipedia.org/wiki/Backtracking


----------



## andyroo89

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> http://en.wikipedia.org/wiki/Backtracking


I learn something new everyday.


----------



## Mrzev

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> http://en.wikipedia.org/wiki/Backtracking


A language devoted to recursion.


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *andyroo89*
> 
> I learn something new everyday.


Glad I helped








Quote:


> Originally Posted by *Mrzev*
> 
> A language devoted to recursion.


I don't think it's an actual language.


----------



## Mrzev

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> I don't think it's an actual language.


Quote:


> Originally Posted by *Wikipedia*
> 
> Backtracking is a general algorithm for finding all (or some) solutions to some computational problem, that incrementally builds candidates to the solutions, and abandons each partial candidate c ("backtracks") as soon as it determines that c cannot possibly be completed to a valid solution


You sir are correct =D I had just briefly scammed trough it and some some example code and jumped to conclusions heh. But YAY!!! Fancy recursion algorithms! And I'm proud that i quoted wiki with a link and all in it. Fancy WIZIWIG tools.


----------



## t00sl0w

guess i dont really need to say more than that i had a complete DB of an associate spouting around that only idiots and incompetent coders need to google things.
sure buddy.


----------



## Plan9

Quote:


> Originally Posted by *t00sl0w*
> 
> guess i dont really need to say more than that i had a complete DB of an associate spouting around that only idiots and incompetent coders need to google things.
> sure buddy.


I guess that's half true. Most of us don't _need_ 'Google' as we already know what online resources to turn to and are competent enough to use other search engines if we have to. But that's being pedantic.

If your colleague claims he doesn't need look stuff up then he clearly doesn't stretch himself much as a developer.


----------



## tompsonn

Quote:


> Originally Posted by *t00sl0w*
> 
> guess i dont really need to say more than that i had a complete DB of an associate spouting around that only idiots and incompetent coders need to google things.
> sure buddy.


Quote:


> Originally Posted by *Plan9*
> 
> I guess that's half true. Most of us don't _need_ 'Google' as we already know what online resources to turn to and are competent enough to use other search engines if we have to. But that's being pedantic.
> 
> If your colleague claims he doesn't need look stuff up then he clearly doesn't stretch himself much as a developer.


I use Google to find things on MSDN. I already know what I'm looking for, but Google does a better job of finding it









Very rarely do I ask Google a 'how' question anymore. And I might add, there is certainly nothing wrong with doing that either! It is generally inexperienced programmers who need to ask the 'how'. How else will they learn? What separates the incompetence from the competence of programmers who do this is whether they put in the effort to learn what they are reading about and not just blindly copy code and hope for the best.


----------



## FateousMaximous

Quote:


> Originally Posted by *tompsonn*
> 
> What separates the incompetence from the competence of programmers who do this is whether they put in the effort to learn what they are reading about and not just blindly copy code and hope for the best.


Sadly there are more people who want to blindly copy and paste then the people who try to learn. I had a group project in my programming class last semester, and whenever one group memeber had something to do he'd always complain that he couldn't find an example of it online.


----------



## andyroo89

Ok programmers of OCN, got a question, maybe one of you can help me with.

i am working on C# client / server program.

At the moment whenever client connects their ip is added to the listbox, now my question is, is adding clients ip address to listbox while they're connected a proper way to handle multiple connect clients in list format? I am working on share screen function and this is how I am planning to do it.

right click on highlight ip address, click view remote screen, sends command to highlighted ip to start remote screen share, new form pops up to view remote screen share.

As new to network programming, thats how I see a way (I really feel like there is more elegant way) of doing that.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Ok programmers of OCN, got a question, maybe one of you can help me with.
> 
> i am working on C# client / server program.
> 
> At the moment whenever client connects their ip is added to the listbox, now my question is, is adding clients ip address to listbox while they're connected a proper way to handle multiple connect clients in list format? I am working on share screen function and this is how I am planning to do it.
> 
> right click on highlight ip address, click view remote screen, sends command to highlighted ip to start remote screen share, new form pops up to view remote screen share.
> 
> As new to network programming, thats how I see a way (I really feel like there is more elegant way) of doing that.


Are you asking a GUI question or a network question...


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Are you asking a GUI question or a network question...


Both.


----------



## tompsonn

I don't really see the networking side of things in there. Client registers/connects with server, server maintains a list of connected clients - at this point the networking stuff is already done. That's really all there is to it (of course you need to handle disconnects [maybe send a ping every X seconds]), and sounds like it is what you are doing already.

What you do with that list, well you could represent it... as a list naturally. Which is what you're doing already.


----------



## NameUnknown

I'm feeling quite stupid right now, I blame the morning and a 50hr+ work week. Anyways, my stupidity is as follows.

Code:



Code:


    'If statement to prevent the upload and download of the Amada 13 macro at the same time
    '
    Private Sub CB_D_Macro_CheckedChanged(sender As Object, e As EventArgs) Handles CB_D_Macro.CheckedChanged
        If CB_D_Macro.Checked() = True Then
            CB_U_Macro.Enabled() = False
        ElseIf CB_D_Macro.Checked() = False Then
            CB_U_Macro.Enabled() = True
        End If

Code:



Code:


    'If statement to prevent the upload and download of the Amada 13 macro at the same time
    '
    Private Sub CB_U_Macro_CheckedChanged(sender As Object, e As EventArgs) Handles CB_U_Macro.CheckedChanged
        If CB_U_Macro.Checked() = True Then
            CB_D_Macro.Enabled() = False
        ElseIf CB_U_Macro.Checked() = False Then
            CB_D_Macro.Enabled() = True
        End If

Code:



Code:


    'If statement to control state of CB_D_Macro & CB_U_Macro based off the status of Amada 13 checkbox
    '
    Private Sub RB_Amada13_CheckedChanged(sender As Object, e As EventArgs) Handles RB_Amada13.CheckedChanged
        If RB_Amada13.Checked() = True Then
            CB_D_Macro.Enabled() = True
            CB_D_Macro.Checked() = False
            CB_U_Macro.Enabled() = True
            CB_U_Macro.Checked() = False
        ElseIf RB_Amada13.Checked() = False Then
            CB_D_Macro.Enabled() = False
            CB_D_Macro.Checked() = False
            CB_U_Macro.Enabled() = False
            CB_U_Macro.Checked() = False
        End If
    End Sub

The first block of code disabled or enables an upload & download checkbox depending on the change in state of the download box. This code works flawlessly for me.

The second block of code disabled or enables an upload & download checkbox depending on the change in state of the upload box. This code works flawlessly for me.

The third block of code is what controls the enabled state of both checkboxes according to a radio button. At the launch the upload and download checkboxes are disabled until you click the Amada13 radio button. Once that is clicked the two checkboxes are enabled and their states change according to the first two blocks of code just fine.

The problem I have is that when I go and click a different radio button if the upload checkbox is currently checked, then instead of disabling both checkboxes it disables upload and enables download. I can only assume that this is due to the second block of code. What gets me though is that if download is checked when a different radio button is selected I do not have this problem. Can anyone help me figure this out?


----------



## tompsonn

You should probably simplify that by using the result of the expression in the "if" statements to be the assignment rather than extra lines of code. May not fix your problem but will make maintenance easier.

Are the first controls in the third block supposed to be all True?


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> I don't really see the networking side of things in there. Client registers/connects with server, server maintains a list of connected clients - at this point the networking stuff is already done. That's really all there is to it (of course you need to handle disconnects [maybe send a ping every X seconds]), and sounds like it is what you are doing already.
> 
> What you do with that list, well you could represent it... as a list naturally. Which is what you're doing already.


yeah, I am controlling the disconnects with if statement and if the bytesread return (equal) 0 then client has disconnected which handles that very well. Its be a while since I have programmed, my code doesn't feel elegant. Feels like scattered papers on a desk. probably just me throwing a fit over nothing.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> yeah, I am controlling the disconnects with if statement and if the bytesread return (equal) 0 then client has disconnected which handles that very well. Its be a while since I have programmed, my code doesn't feel elegant. Feels like scattered papers on a desk. probably just me throwing a fit over nothing.


Throw us some code


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Throw us some code


ok here is the server side, so I have my ip addresses go to listbox (not storing the ip address any other way, maybe using dictionary?) It doesn't feel right to handle connected clients. also when I want to start remote screen share I try to transfer the ip address from the list box to another partial class, but it shows blank, and I get invalid IP address.

form1
http://pastebin.com/aLEqkSCy

server
http://pastebin.com/4tpk47h5

remotescreen
http://pastebin.com/BAifyCVe

I put messagebox in remotescreen class to view the selecteditem from listbox but returns blank. so somewhere from form1 to remotescreen my ip address string goes blank. I feel like im over thinking this.


----------



## geoxile

Are there any books that discuss good programming practices with "cutting edge" techniques and libraries?


----------



## tompsonn

Code:



Code:


Control.CheckForIllegalCrossThreadCalls

*Never* use this.

Also only use the listbox for UI. You should store the connected clients as a List< T > (preferably List< IPAddress > or List< string >).

Then you can display the items in the listbox from the internal list.


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> Control.CheckForIllegalCrossThreadCalls
> 
> *Never* use this.
> 
> Also only use the listbox for UI. You should store the connected clients as a List< T > (preferably List< IPAddress > or List< string >).
> 
> Then you can display the items in the listbox from the internal list.


Yes, I am aware never to use that code. Its temporary, I just wanted to get it working. Don't worry its temp.


----------



## Plan9

Quote:


> Originally Posted by *geoxile*
> 
> Are there any books that discuss good programming practices with "cutting edge" techniques and libraries?


There isn't such thing as cutting edge techniques as most paradigms have been around for 20+ years. And cutting edge libraries tend to be subject to a lot of API change, so I'd often just advise people stay clear of them until they become more standardized.

If you're interested in having the best available range of abilities then I'd suggest learning Object Oriented Programming, if you haven't already, then learn Functional Programming. The basics of FP I find to be particularly useful for writing web applications due to the RESTful nature of the HTTP protocol. But the benefits of FP extended well beyond that.

What side of programming did you want to learn? Systems, games development, web development, etc. What languages do you code in?


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Yes, I am aware never to use that code. Its temporary, I just wanted to get it working. Don't worry its temp.


Never means literally never. Not even temporarily. Turning off illegal cross thread checking can seriously cause all sorts of debugging nightmares, and you don't want this - temporarily or permanently.

When people check-in code for a review to me and if I see this in the diff, they get a right clip around the ear!

Besides its not hard to marshal your calls:

Code:



Code:


control.BeginInvoke( new MethodInvoker( () => /* blah blah blah */ ) );

I prefer BeginInvoke in all scenarios because its asynchronous, and unless you have a good reason that the calling thread must wait for the completion of the cross-thread marshal, always use BeginInvoke.

-
All in all, clients must register with the server, correct? Thus, you should maintain an internal state list of connected clients by their IP address.

Ideally you'd have a class for a client that has various properties such as their IP address. For example:

Code:



Code:


/* this class is immutable */
internal sealed class ConnectedClient
{
        private readonly IPAddress _address;
        internal IPAddress Address 
        {
                get { return this._address; }
        }

        internal ConnectedClient( IPAddress address )
        {
                this._address = address;
        }
}

Then have your server class store them like:

Code:



Code:


internal sealed class Server
{
        private readonly List<ConnectedClient> _connectedClients = new List<ConnectedClient>();
        internal ReadOnlyCollection<ConnectedClient> ConnectedClients 
        {
                get
                {
                        return new ReadOnlyCollection<ConnectedClient>( this._connectedClients );
                }
        }
}

You should also have an event in the server class that fires when a client is connected. This will allow things like UI to listen for state changes:

Code:



Code:


internal sealed class ClientConnectedEventArgs : EventArgs
{
        private readonly ConnectedClient _client;
        internal ConnectedClient Client
        {
                get { return this._client; }
        }

        internal ClientConnectedEventArgs( ConnectedClient client )
        {
                if ( client == null )
                {
                        throw new ArgumentNullException( "client" );
                }

                this._client = client;
        }
}

internal sealed class Server
{
        /* code from above here... */
        /** ** **/
        internal event EventHandler<ClientConnectedEventArgs> ClientConnected;

        /* call this method to fire the event when a client is connected */
        private void _OnClientConnected( ConnectedClient client )
        {
                if ( this.ClientConnected != null )
                {
                        ClientConnectedEventArgs args = new ClientConnectedEventArgsA( client );        
                        this.ClientConnected( this, args );
                }
        }
}

Then in your UI you can listen on the event and update the list accordingly:

Code:



Code:


public class ListForm : Form
{
        protected override void OnLoad()
        {
                base.OnLoad();

                /* Register event handler */
                this._server.ClientConnected += this._OnClientConnected;
        }

        private void _OnClientConnected( object sender, ClientConnectedEventArgs e )
        {
                this.ListView.Items.Add( new ListViewItem() { Text = e.Client.Address.ToString(), Tag = e.Client } );
        }
}

You pass around the ConnectedClient object in the list view item tag, and fish it out when you need to perform an action, say when the user double clicks the client in the list, e.g.:

Code:



Code:


ListViewItem selected = this.ListView.SelectedItem;
if ( selected != null )
{
        ConnectedClient client = selected.Tag as ConnectedClient;
        if ( client != null )
        {
                this._server.DoSomethingWithClient( client );
        }
}

Then do a similar thing for when clients are disconnected (i.e. remove them from the list and fire a disconnected event).

Using this model basically perfectly separates your UI and business logic.


----------



## geoxile

Quote:


> Originally Posted by *Plan9*
> 
> There isn't such thing as cutting edge techniques as most paradigms have been around for 20+ years. And cutting edge libraries tend to be subject to a lot of API change, so I'd often just advise people stay clear of them until they become more standardized.
> 
> If you're interested in having the best available range of abilities then I'd suggest learning Object Oriented Programming, if you haven't already, then learn Functional Programming. The basics of FP I find to be particularly useful for writing web applications due to the RESTful nature of the HTTP protocol. But the benefits of FP extended well beyond that.
> 
> What side of programming did you want to learn? Systems, games development, web development, etc. What languages do you code in?


I guess part of my post got cut off. I'm already moderately familiar with Java and OOP. I just wanted to brush up on up-to-date design patterns and general practices, commonly used libraries, etc.

edit: regarding what I'm interested in, GUI, graphics, concurrency, and possibly graphics tablet input. I've been wanting to create a simple drawing program that can take proper input from a pen


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Never means literally never. Not even temporarily. Turning off illegal cross thread checking can seriously cause all sorts of debugging nightmares, and you don't want this - temporarily or permanently.
> 
> When people check-in code for a review to me and if I see this in the diff, they get a right clip around the ear!
> 
> Besides its not hard to marshal your calls:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> control.BeginInvoke( new MethodInvoker( () => /* blah blah blah */ ) );
> 
> I prefer BeginInvoke in all scenarios because its asynchronous, and unless you have a good reason that the calling thread must wait for the completion of the cross-thread marshal, always use BeginInvoke.
> 
> -
> All in all, clients must register with the server, correct? Thus, you should maintain an internal state list of connected clients by their IP address.
> 
> Ideally you'd have a class for a client that has various properties such as their IP address. For example:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> /* this class is immutable */
> internal sealed class ConnectedClient
> {
> private readonly IPAddress _address;
> internal IPAddress Address
> {
> get { return this._address; }
> }
> 
> internal ConnectedClient( IPAddress address )
> {
> this._address = address;
> }
> }
> 
> Then have your server class store them like:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> internal sealed class Server
> {
> private readonly List<ConnectedClient> _connectedClients = new List<ConnectedClient>();
> internal ReadOnlyCollection<ConnectedClient> ConnectedClients
> {
> get
> {
> return new ReadOnlyCollection<ConnectedClient>( this._connectedClients );
> }
> }
> }
> 
> You should also have an event in the server class that fires when a client is connected. This will allow things like UI to listen for state changes:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> internal sealed class ClientConnectedEventArgs : EventArgs
> {
> private readonly ConnectedClient _client;
> internal ConnectedClient Client
> {
> get { return this._client; }
> }
> 
> internal ClientConnectedEventArgs( ConnectedClient client )
> {
> if ( client == null )
> {
> throw new ArgumentNullException( "client" );
> }
> 
> this._client = client;
> }
> }
> 
> internal sealed class Server
> {
> /* code from above here... */
> /** ** **/
> internal event EventHandler<ClientConnectedEventArgs> ClientConnected;
> 
> /* call this method to fire the event when a client is connected */
> private void _OnClientConnected( ConnectedClient client )
> {
> if ( this.ClientConnected != null )
> {
> ClientConnectedEventArgs args = new ClientConnectedEventArgsA( client );
> this.ClientConnected( this, args );
> }
> }
> }
> 
> Then in your UI you can listen on the event and update the list accordingly:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> public class ListForm : Form
> {
> protected override void OnLoad()
> {
> base.OnLoad();
> 
> /* Register event handler */
> this._server.ClientConnected += this._OnClientConnected;
> }
> 
> private void _OnClientConnected( object sender, ClientConnectedEventArgs e )
> {
> this.ListView.Items.Add( new ListViewItem() { Text = e.Client.Address.ToString(), Tag = e.Client } );
> }
> }
> 
> You pass around the ConnectedClient object in the list view item tag, and fish it out when you need to perform an action, say when the user double clicks the client in the list, e.g.:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> ListViewItem selected = this.ListView.SelectedItem;
> if ( selected != null )
> {
> ConnectedClient client = selected.Tag as ConnectedClient;
> if ( client != null )
> {
> this._server.DoSomethingWithClient( client );
> }
> }
> 
> Then do a similar thing for when clients are disconnected (i.e. remove them from the list and fire a disconnected event).
> 
> Using this model basically perfectly separates your UI and business logic.


gosh, I feel like my code is worthless after seeing this.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> gosh, I feel like my code is worthless after seeing this.


I aim to inspire + teach, not the opposite. I'm happy to answer any questions.


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> I aim to inspire + teach, not the opposite. I'm happy to answer any questions.


After seeing your code, after working on mine for 6+ hours I feel like I wasted time, and made it inefficient.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> After seeing your code, after working on mine for 6+ hours I feel like I wasted time, and made it inefficient.


We've all been there. Seeing how other do things and realizing that my ways weren't entirely the best, it made me a better programmer.


----------



## andyroo89

I am heading to be 3 am here , I will rework on my code, the code you provided seems to help with my server and my other classes. does it cover all three classes I linked?


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> I am heading to be 3 am here , I will rework on my code, the code you provided seems to help with my server and my other classes. does it cover all three classes I linked?


I wasn't really intent on entirely replacing your code. What I gave you was a sample object model and design that you can use to (re)write your own.


----------



## Plan9

Quote:


> Originally Posted by *andyroo89*
> 
> After seeing your code, after working on mine for 6+ hours I feel like I wasted time, and made it inefficient.


Dude, even know I often find myself rewriting hours of work because I'd realised that I'd either overlooked something during the planning stage or one of the requirements have changed mid-build which makes a partial rewrite more sensible than just kludging in a new feature. Or sometimes the original code written just isn't performant* enough for the job so a rethink needs to be had.

If you're not writing proper plans before you lay down code (and lets be honest, many of use don't), then there's no harm in thinking of your first chunks of code as like a first draft of a story book.

* I know that's not technically a word, but language is a constant evolution and I really like the term.


----------



## tompsonn

Quote:


> Originally Posted by *Plan9*
> 
> Dude, even know I often find myself rewriting hours of work because I'd realised that I'd either overlooked something during the planning stage or one of the requirements have changed mid-build which makes a partial rewrite more sensible than just kludging in a new feature. Or sometimes the original code written just isn't performant* enough for the job so a rethink needs to be had.
> 
> *If you're not writing proper plans before you lay down code (and lets be honest, many of use don't), then there's no harm in thinking of your first chunks of code as like a first draft of a story book.*
> 
> * I know that's not technically a word, but language is a constant evolution and I really like the term.


Yeah, I've done this a total of.... zero times. I find the revisions more exciting. I do try to get it as right as possible in the first place though (which is about never as well)


----------



## Plan9

Quote:


> Originally Posted by *FateousMaximous*
> 
> Sadly there are more people who want to blindly copy and paste then the people who try to learn. I had a group project in my programming class last semester, and whenever one group memeber had something to do he'd always complain that he couldn't find an example of it online.


To be fair, I get annoyed when I can't find code examples too. But not to copy and paste; I just find working code examples easier to understand than paragraphs of written English explaining a function. Though there's obviously a need for both as not all APIs are simple enough that a code example is sufficient example on it's own.


----------



## tompsonn

Quote:


> Originally Posted by *Plan9*
> 
> To be fair, I get annoyed when I can't find code examples too. But not to copy and paste; I just find working code examples easier to understand than paragraphs of written English explaining a function. Though there's obviously a need for both as not all APIs are simple enough that a code example is sufficient example on it's own.


Indeed. I do enjoy the code samples Microsoft provides on most documentation pages and it helps a lot especially when using a new API.

Though there are times when you have to fly solo. Its a bit like Lego without the instructions really.


----------



## Plan9

Quote:


> Originally Posted by *tompsonn*
> 
> Yeah, I've done this a total of.... zero times. I find the revisions more exciting. *I do try to get it as right as possible in the first place though* (which is about never as well)


Oh totally, it's a waste of time writing something that you know is going to be wrong from the outset. But it's amazing how wrong the "correct" solutions often turn out to be once you get knee deep in code. :lol:

The bit I often struggle with is knowing just how much to abstract the code away. Too many layers of abstraction can result in slower, verbose, code. And sometimes that additional verbosity can give too much unnecessary complexity which can introduce bugs or just make things harder to follow. But equally too little abstraction can result in duplicated and/or spaghetti code; which introduces bugs and can make code harder to follow. So often my rewrites are just adding or subtracting some level of abstraction to suite the problem that particular program is trying to solve.

Which -from an admittedly brief skim- seems to be some of the issue here actually. You were abstracting away some of the stuff that andyroo89 was storing in listboxes.


----------



## tompsonn

Quote:


> Originally Posted by *Plan9*
> 
> Oh totally, it's a waste of time writing something that you know is going to be wrong from the outset. But it's amazing how wrong the "correct" solutions often turn out to be once you get knee deep in code. :lol:
> 
> The bit I often struggle with is knowing just how much to abstract the code away. Too many layers of abstraction can result in slower, verbose, code. And sometimes that additional verbosity can give too much unnecessary complexity which can introduce bugs or just make things harder to follow. But equally too little abstraction can result in duplicated and/or spaghetti code; which introduces bugs and can make code harder to follow. So often my rewrites are just adding or subtracting some level of abstraction to suite the problem that particular program is trying to solve.
> 
> Which -from an admittedly brief skim- seems to be some of the issue here actually. You were abstracting away some of the stuff that andyroo89 was storing in listboxes.


With abstraction I work with three rules:

#1: Internal code has the least amount of abstraction possible, but not too little that refactoring or extension becomes impossible.
#2: Public code has enough abstraction to permit an easy to use API - put as much as you want, but don't go stupid (e.g. I like hot chilli sauce but I don't down the entire bottle over something).
#3: Future things can be done in the future, do what is required for present only (and if you need to do something for the *past*, please let me know as I'd like to see the project you're working on!)

Of course I don't always obey those









--

With andyroo89, most of it was separating UI from business logic, which is what I was going for (storing internal state on a UI control is a big no for me). There's a super-super thin layer of abstraction going on there. I could go really stupid and extend the ListView with all sorts of things like view models and what not but its really not necessary.


----------



## Plan9

Quote:


> Originally Posted by *tompsonn*
> 
> Indeed. I do enjoy the code samples Microsoft provides on most documentation pages and it helps a lot especially when using a new API.
> 
> Though there are times when you have to fly solo. Its a bit like Lego without the instructions really.


I got burnt from Microsoft code examples once. About 15 or so years ago I was trying to learn how DDE worked (does anyone remember using Dynamic Data Exchange in Windows







). The code MS provided basically called itself -via DDE- to fork itself. Stupidly I ran the code to see it in action before stripping it down and applying that to the application I was attempting to build. What happened next was the example code spawned hundreds of instances of itself before crashing Windows.

So well done Microsoft for publishing a fork bomb on your website. Idiots


----------



## tompsonn

That's gold.


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> I wasn't really intent on entirely replacing your code. What I gave you was a sample object model and design that you can use to (re)write your own.


Ok cool.


----------



## FateousMaximous

Quote:


> Originally Posted by *Plan9*
> 
> To be fair, I get annoyed when I can't find code examples too. But not to copy and paste; I just find working code examples easier to understand than paragraphs of written English explaining a function. Though there's obviously a need for both as not all APIs are simple enough that a code example is sufficient example on it's own.


I'm not saying looking up examples is bad, I do it all the time. The problem that I have with a lot of the people I've programmed with they don't look at the example try to figure out what's going on, try to adapt it to the actual problem at hand, or try to at least figure what needs to happen before they go looking for examples. When they need to program something they find an example that is fairly close to what they need and just stop at that.

edit
I guess I can sum up what I was saying earlier a little better. They don't try to learn from it, and end up looking for the same examples over and over again.


----------



## NameUnknown

Well this makes absolutely no sense at all the code is working just fine now without it being changed at all...


----------



## andyroo89

Quote:


> Originally Posted by *NameUnknown*
> 
> Well this makes absolutely no sense at all the code is working just fine now without it being changed at all...


Finally I have a use for this


----------



## stumped

Quote:


> Originally Posted by *NameUnknown*
> 
> Well this makes absolutely no sense at all the code is working just fine now without it being changed at all...


Did you look at your computer funny at all lately? Maybe you cast a stray photon to it...


----------



## Mrzev

Quote:


> Originally Posted by *andyroo89*
> 
> Finally I have a use for this


I had some code i was working with a couple months ago I had a packet I sent via UDP where it was basically a struct with a timestamp and a Struct of 3 variables. I could print the Hex values out on both sides and they would match perfectly , but when i read the values from the nested struct on the receive side, they were all incorrect, but the timestamp was correct. I ended up doing ntohl around the nested struct and not the timestamp and everything worked. Not sure why I had to do it there, but it made it work.


----------



## stumped

Quote:


> Originally Posted by *Mrzev*
> 
> I ended up doing ntohl around the nested struct and not the timestamp and everything worked. Not sure why I had to do it there, but it made it work.


If I remember right from my Operating Systems course, it has to do with little-endian/big-endian and networking choosing the one that x86 is not. Also since you were sending/reading raw from the socket, that adds to the issue of having to use ntohl.


----------



## Mrzev

Quote:


> Originally Posted by *stumped*
> 
> If I remember right from my Operating Systems course, it has to do with little-endian/big-endian and networking choosing the one that x86 is not. Also since you were sending/reading raw from the socket, that adds to the issue of having to use ntohl.


Yup, so why was 1 variable little endian, and one big endian? They were both in the same UDP packet sent.. .so why would only 1 change? If they were mixed, why would the hex value of the full array show correctly on both sides.


----------



## geoxile

Quote:


> Originally Posted by *geoxile*
> 
> I guess part of my post got cut off. I'm already moderately familiar with Java and OOP. I just wanted to brush up on up-to-date design patterns and general practices, commonly used libraries, etc.
> 
> edit: regarding what I'm interested in, GUI, graphics, concurrency, and possibly graphics tablet input. I've been wanting to create a simple drawing program that can take proper input from a pen


Can anyone help me?


----------



## t00sl0w

YES!
so, we were planning a release in the next couple weeks and got the update from the contractors today (gov job so yes, we contract stupid stuff out...out of anyone in the office's control, its silly), start to roll through it and like nothing we requested has been completed...they did one part and then nothing else...
some things we can change, other things...nope.
no telling how long it will take to push this back through.
fantastic


----------



## andyroo89

anyone do android programming? I am seeing if I can change the dot to different color or use custom image/icon.



edit; I did some driving earlier and my marker would jump to the new location then back to the old location on the map then back to the new location. Here is the code, I feel like I need to include some way to clear the current location after its been marked on the map or something.

http://pastebin.com/i2gGfVdG


----------



## poroboszcz

http://thedaily***.com/Articles/The-Fizz-Buzz-from-Outer-Space.aspx

Made me laugh out loud.


----------



## t00sl0w

Quote:


> Originally Posted by *poroboszcz*
> 
> http://thedaily***.com/Articles/The-Fizz-Buzz-from-Outer-Space.aspx
> 
> Made me laugh out loud.


oh that's mildly amazing


----------



## Ferrari8608

Today, I finally got around to learning how to use Python's namedtuple from the collections library. It was such a revelation, I had to post somewhere about my excitement.









I love me some namedtuples now.


----------



## dBlisse

What about na
Quote:


> Originally Posted by *Ferrari8608*
> 
> Today, I finally got around to learning how to use Python's namedtuple from the collections library. It was such a revelation, I had to post somewhere about my excitement.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> I love me some namedtuples now.


Named tuples are awesome


----------



## Ferrari8608

From the Python 3.4 documentation:
Quote:


> collections.namedtuple(typename, field_names, verbose=False, rename=False)
> Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable.


So you use the function namedtuple to create an object similar to a tuple in usage and performance but with more flexibility. For me, this has eliminated the need for using overly complex data structures (dictionary of tuples, tuple of dictionaries, etc.) or writing an overly simple class definition just for attributes, in some scenerios.

For example, I'm currently refining a script that includes a function for parsing a structured file, which returns data based on certain search strings. Each line has three specifically categorized fields. My original 'ugly' code returned a tuple of tuples. That is not necessarily a bad thing; it worked fine, but it did present a need for the next function using this data to have to unpack all of the tuples. I could just use indexes there to eliminate the need for unpacking, but that's what I consider ugly code since anyone reading it would have to examine the input data to determine exactly what the code is doing with it. I could also have defined a five line class, but that is an overkill solution for this simple problem. The Zen of Python states "Simple is better than complex".

Code:



Code:


LineData = namedtuple('LineData', ('field1', 'field2', 'field3'))
with open(some_file_path) as the_file:
    return tuple(LineData(*line.split()) for line in the_file
                 if any(search in line for search in search_strings))

...as a generically named example. Using the tuple returned by that code, you could do something like:

Code:



Code:


for thing in returned_tuples:
    print(thing.field1, 'corresponds to', thing.field2, 'and', thing.field3)

The next function using this data did not even need to be updated since the namedtuple inherits tuple and can do everything it can. I will be rewriting that function anyway to use attributes of the namedtuple items instead of unpacking though. There's no need for my script to have multiple references to data.

Code:



Code:


for thing in returned_tuples:
    field1, field2, field3 = thing
    print(field1, 'corresponds to', field2, 'and', field3)

...still works, but like I said, it's unnecessary.


----------



## ABD EL HAMEED

So today I tried to create a vector and fill it with 10^18 elements of type long.......my PC wasn't really happy about that...


----------



## andyroo89

Hopefully someone with php can help me, if anyone is familar with openwrt, and luci, I am attempting to custom version (small thought) well concept. I have the sell commands execute and output just fine. But whenever I click a button (they're two buttons) if I click one button is outputs just fine, if I click the other button it will remove output above.

Here is a picture.


also here is the code. someone said to use session and that works when I leave the web page and come back later SORRY FOR POOR CODE IM RATHER NEW TO PHP (8 hours)

Code:



Code:


[B][SIZE=15] Current Connection [/SIZE][/B]

<?php
 if(isset($_POST['uptimebutton']))
 {
        $_SESSION['uptime'] = shell_exec('uptime');
        print("$uptime");
 }
echo "" . (isset($_SESSION['uptime']) ? $_SESSION['uptime'] : "") . "";

?>

[B][SIZE=14] storage info [/SIZE][/B]

<?php
if(isset($_POST['storagebutton']))
{
        $_SESSION['storage'] = shell_exec('df -h');
        print("$storage");
}
echo "" . (isset($_SESSION['storage']) ? $_SESSION['storage'] : "") . "";

?>


----------



## tompsonn

Ajax time.

1. Move the display to the client side.
2. Write two new scripts, one to fetch the uptime and one to fetch the disk information.
3. Those scripts can just reply with plain text, no need to encode it in anything fancy for what you want to do (like XML or JSON).

Then, rather than submit a form, have the buttons send an ajax request to the appropriate scripts and if the request comes back OK then replace the contents of the appropriate HTML element with the response from the script. Shouldn't be any problem throwing the jQuery library in to do this very easily.

This way you avoid obnoxious page refreshes and won't need to deal with keeping session state around because the display is moved to the client.


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Ajax time.
> 
> 1. Move the display to the client side.
> 2. Write two new scripts, one to fetch the uptime and one to fetch the disk information.
> 3. Those scripts can just reply with plain text, no need to encode it in anything fancy for what you want to do (like XML or JSON).
> 
> Then, rather than submit a form, have the buttons send an ajax request to the appropriate scripts and if the request comes back OK then replace the contents of the appropriate HTML element with the response from the script. Shouldn't be any problem throwing the jQuery library in to do this very easily.
> 
> This way you avoid obnoxious page refreshes and won't need to deal with keeping session state around because the display is moved to the client.


1. Do you mean make an actual html/php that on my desktop? I am not sure what you mean move to client side?

2. on the two new scripts. this is literally all the code to fetch what I need. uptime$uptime = shell_exec('uptime'); echo "

$uptime

"







storage info$storage = shell_exec('df -h'); "

$storage

") other than wrapping the php around it of course.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> 1. Do you mean make an actual html/php that on my desktop? I am not sure what you mean move to client side?
> 
> 2. on the two new scripts. this is literally all the code to fetch what I need. uptime$uptime = shell_exec('uptime'); echo "
> 
> $uptime
> 
> "
> 
> 
> 
> 
> 
> 
> 
> storage info$storage = shell_exec('df -h'); "
> 
> $storage
> 
> ") other than wrapping the php around it of course.


Sorry I mean that the client code should manage the display of the output. So your two scripts:

fetch_uptime.php

Code:



Code:


<?php
@header( "Content-Type: text/plain" );
echo shell_exec( 'uptime' );
?>

fetch_diskinfo.php

Code:



Code:


<?php
@header( "Content-Type: text/plain" );
echo shell_exec( 'df -h' );
?>

Then in your HTML page, include the jQuery library and do something like this:

Code:



Code:


<!doctype html>

[B][SIZE=15]Uptime[/SIZE][/B]

[B][SIZE=15]Disk Info[/SIZE][/B]


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Sorry I mean that the client code should manage the display of the output. So your two scripts:
> 
> fetch_uptime.php
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> <?php
> @header( "Content-Type: text/plain" );
> echo shell_exec( 'uptime' );
> ?>
> 
> fetch_diskinfo.php
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> <?php
> @header( "Content-Type: text/plain" );
> echo shell_exec( 'df -h' );
> ?>
> 
> Then in your HTML page, include the jQuery library and do something like this:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> <!doctype html>
> 
> [B][SIZE=15]Uptime[/SIZE][/B]
> 
> [B][SIZE=15]Disk Info[/SIZE][/B]


Ok that sounds good. So all of these are on the server side (my router) and the html with jquery would be the page I open on my desktop/laptop?


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Ok that sounds good. So all of these are on the server side (my router) and the html with jquery would be the page I open on my desktop/laptop?


You could throw it all on the server. When the browser requests the HTML page, that code is for all intends and purposes running on the client and this is what I mean by moving the fetching/display of the information to the client.


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> You could throw it all on the server. When the browser requests the HTML page, that code is for all intends and purposes running on the client and this is what I mean by moving the fetching/display of the information to the *client*.


I am not sure what you mean by client. I am new with php/jquery everytime you say client I only think of the machine (desktop/laptop) should have the file, which doesn't make sense since there is now url (iport in this case) to fetch the data.

edit; I am really frustrated since I am not understanding what you mean, but I made a illustration to see if this is what you meant.


----------



## tompsonn

I should really be more clear. By client I mean the web browser. And by that I then mean that the code to request and display the information is anchored at the client-side.

And you can basically ignore all of that if you understand the code I've written for you already


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> I should really be more clear. By client I mean the web browser. And by that I then mean that the code to request and display the information is anchored at the client-side.
> 
> And you can basically ignore all of that if you understand the code I've written for you already


Look at the pic I posted above, is that what you mean, also I can't ignore it, cause if someone says ya just do it client side, and them I am like what?


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Look at the pic I posted above, is that what you mean, also I can't ignore it, cause if someone says ya just do it client side, and them I am like what?


Not to do everything client-side, the only thing to move to the client-side is the request and display of the data so that you don't need to manage any session handling rubbish on the server-side.

To be clearer, this doesn't mean store HTML or PHP files on the client device itself (as that would not work at all), it just means that more responsibility of the task is performed using client-side code, which is code running on the browser, rather than on the server.

Because you shift the responsibility of maintaining the display state to the client-side (i.e. the server is only there to give you data), the lifetime of that state is defined by the user's browser session, which solves the initial problem of data disappearing each time you submitted the form in the original code.


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> Not to do everything client-side, the only thing to move to the client-side is the request and display of the data so that you don't need to manage any session handling rubbish on the server-side.
> 
> To be clearer, *this doesn't mean store HTML or PHP files on the client device itself (as that would not work at all)*, it just means that more responsibility of the task is performed using client-side code, which is code running on the browser, rather than on the server.
> 
> Because you shift the responsibility of maintaining the display state to the client-side (i.e. the server is only there to give you data), the lifetime of that state is defined by the user's browser session, which solves the initial problem of data disappearing each time you submitted the form in the original code.


Yeah that threw me off when you first mentioned that, I looked at the syntax, and there was no url placement or anything like that.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> Yeah that threw me off when you first mentioned that, I looked at the syntax, and there was no url placement or anything like that.


My apologies


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> My apologies


I tried the php on my router, and php jquery work fine, when I click the button nothing happens. I put the full directory path but still no luck.

edit; could be something on my end, but I am looking at it.


----------



## tompsonn

Quote:


> Originally Posted by *andyroo89*
> 
> I tried the php on my router, and php jquery work fine, when I click the button nothing happens. I put the full directory path but still no luck.
> 
> edit; could be something on my end, but I am looking at it.


I wrote all of that off the top of my head, its possible its not 100% perfect, but it should be a good enough starter I think


----------



## andyroo89

Quote:


> Originally Posted by *tompsonn*
> 
> I wrote all of that off the top of my head, its possible its not 100% perfect, but it should be a good enough starter I think


yep thanks I am looking about jquery atm.


----------



## patriotaki

Hello im new to programming im trying to learn C for university. Installed C Free and Codeblocks but in both programs i couldnt run the hello.c file

here is the code

Code:



Code:


#include < stdio.h >
int main () {
printf("Hello Wolrd\n");
return 0;
}

how can i build it and run it in windows ?


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *patriotaki*
> 
> Hello im new to programming im trying to learn C for university. Installed C Free and Codeblocks but in both programs i couldnt run the hello.c file
> 
> here is the code
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> #include < stdio.h >
> int main () {
> printf("Hello Wolrd\n");
> return 0;
> }
> 
> how can i build it and run it in windows ?


Your code looks good to me so I guess something is wrong with codeblocks or your compiler.could you tell us what kind of error you're getting?


----------



## patriotaki

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> Your code looks good to me so I guess something is wrong with codeblocks or your compiler.could you tell us what kind of error you're getting?


i installed codeblocks version without preinstalled compiler..i fixed it now


----------



## Nomadskid

Hi guys, I have a question. so my girlfriend really needs my help with a project for the national science fair and I'm not sure how i can help her. She wants me to write a program that reads music,(sheet music) assigns each note a number, and at the end of each line of music all of the numbers will be added. I know how to do the summation but I don't know how to get the program to "read" the music.


----------



## Plan9

Quote:


> Originally Posted by *Nomadskid*
> 
> Hi guys, I have a question. so my girlfriend really needs my help with a project for the national science fair and I'm not sure how i can help her. She wants me to write a program that reads music,(sheet music) assigns each note a number, and at the end of each line of music all of the numbers will be added. I know how to do the summation but I don't know how to get the program to "read" the music.


That's a lot harder than it sounds. How good is your coding skills and what format is the sheet music currently stored in?


----------



## Nomadskid

Quote:


> Originally Posted by *Plan9*
> 
> That's a lot harder than it sounds. How good is your coding skills and what format is the sheet music currently stored in?


I can scan the music to be in a pdf. And I am fairly decent at coding.


----------



## Plan9

Quote:


> Originally Posted by *Nomadskid*
> 
> I can scan the music to be in a pdf. And I am fairly decent at coding.


I'm not really sure PDF is the best format for this. You could probably use a bitmap and scan for pixel colour changes, along each row. But you'd need to ensure that your sheet music is horizontally aligned perfectly for that to work (since you're scanning your sheet music in). There's also a whole boat load of other issues with the more complicated notations. So I couldn't see this being practical by any means.

If you can find the scores you're after in MusicXML format (http://en.wikipedia.org/wiki/MusicXML) then it might be a "trivial" case of parsing an XML file.


----------



## Nomadskid

Quote:


> Originally Posted by *Plan9*
> 
> I'm not really sure PDF is the best format for this. You could probably use a bitmap and scan for pixel colour changes, along each row. But you'd need to ensure that your sheet music is horizontally aligned perfectly for that to work (since you're scanning your sheet music in). There's also a whole boat load of other issues with the more complicated notations. So I couldn't see this being practical by any means.
> 
> If you can find the scores you're after in MusicXML format (http://en.wikipedia.org/wiki/MusicXML) then it might be a "trivial" case of parsing an XML file.


I can use xml if need be I'm just not sure where to start.


----------



## Plan9

Quote:


> Originally Posted by *Nomadskid*
> 
> I can use xml if need be I'm just not sure where to start.


Well I answered that question already









Find the music scores in MusicXML format,
look at the specification for MusicXML (there's a basic introduction to it on the link I gave, but I'd recommend you do a little more digging for a proper spec)
and then use the standard XML parsing libraries that your programming language of preference supports.
Since this is a school project, I don't really want to be writing the code for you, but you said you were fairly decent at coding anyway so this shouldn't be too difficult (the hardest bit is the XML parsing but you shouldn't need to do that manually anyway)

edit:
Just to add, I've found the superman theme: http://musescore.com/user/45603/scores/130897 this site supports MusicXML (*.mxl) so that looks a good place to find your scores. Just be mindful that, like OOXML, those files are zip archives with XML content. So you may have to cheat and extract the archives manually (you can do it programmatically if you really want, but I'm just trying to save you time).


----------



## ABD EL HAMEED

So I've been implementing the sieve algorithm to find primes and I wrote this code:

Code:



Code:


#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector <int> primes;
    int theLimit = 10E6;

    void sieve (vector <int> &primes, int theLimit);
    sieve (primes, theLimit);

    for (int i = 0; i < primes.size(); ++i){
        cout << primes[i] << "\n";
    }

    return 0;
}

void sieve (vector <int> &primes, int theLimit) {
    const int SIZE = theLimit;
    bool oddNonPrimes [SIZE];

    for (int i = 3; i < theLimit; i += 2){
        if (!oddNonPrimes[i]){
            int currNum = i;
            primes.push_back(currNum);
            for (int factor = 2; currNum <= theLimit; ++factor){
                currNum *= factor;
                oddNonPrimes[currNum] = true;
                currNum = i;
            }
        }
    }

}

But I'll get a "segementation fault (core dumped)" error which I belive is because I'm trying to access a value that isn't there (the "oddNonPrimes_" is not set to anything(?)),so my question is:Is there anyway to set the entire bool array to false WITHOUT having to step into each index individually and setting it to false?if so,how?

Edit:turns out it's not because the array is not set to false (I've tried to do that with a loop and still got the same error),it seems to give me this error whenever I try to access the array to read or write,which is weird.Could it be a compiler error?

Edit#2:nvm,I fixed it







_


----------



## poroboszcz

The _oddNonPrimes_ is too big to fit on the stack. Try using std::vector instead of C array. You also don't need to iterate all the way to _theLimit_ just up to _(i * i < theLimit)_.


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *poroboszcz*
> 
> The _oddNonPrimes_ is too big to fit on the stack. Try using std::vector instead of C array. You also don't need to iterate all the way to _theLimit_ just up to _(i * i < theLimit)_.


It is indeed too big to fit in the stack using the normal C array but it's not the only reason,this is the main one:

Code:



Code:


for (int factor = 2; currNum <= theLimit; ++factor)

instead it should be something like this:

Code:



Code:


for (int factor = 2; (currNum * factor) <= theLimit; ++factor)

Otherwise when currNum becomes big and then is multiplied by the factor it can produce a number bigger than theLimit,so when it executes this line

Code:



Code:


currNum *= factor;

and then executes the line after

Code:



Code:


nonOddPrimes[[B]currNum[/B]] = true;

it tries to access an index that is beyond the range of the array and thus a runtime error.

The reason it took me so long to debug is because in visual C++ which I'm used to,when you try to access and index beyond the array's limit it gives me a stack overflow (That's the name of the error,right?) error with some memory adress and then I know that I'm trying to access an index that's not there,in G++ however,I get that weird segmentation fault error which I'm not fimiliar with.
Quote:


> You also don't need to iterate all the way to _theLimit_ just up to _(i * i < theLimit)_.


I tried.

This is the biggest prime it found in the edited code:997.

This is the biggest prime it found in the original code:999983.


----------



## ABD EL HAMEED

This is my final sieves implementation code:

Code:



Code:


#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector <unsigned long long> primes;
    unsigned long long theLimit = 10E7;

    void sieve (vector <unsigned long long> &primes, unsigned long long theLimit);
    sieve (primes, theLimit);

    return 0;
}

void sieve (vector <unsigned long long> &primes, unsigned long long theLimit) {
    const unsigned long long SIZE = theLimit + 1;
    bool *oddNonPrimes = new bool [SIZE];

    for (unsigned long long i = 0; i < SIZE; ++i)
        oddNonPrimes[i] = false;

    primes.push_back(2);

    for (unsigned long long i = 3; i < theLimit; i += 2){
        if (!oddNonPrimes[i]){
            unsigned long long currNum = i;
            primes.push_back(currNum);
            for (currNum *= currNum; currNum <= theLimit; currNum += (i * 2)) {
                oddNonPrimes[currNum] = true;
            }
            currNum = i;
        }
    }

}

What do you guys think of code orginization?


----------



## poroboszcz

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> The reason it took me so long to debug is because in visual C++ which I'm used to,when you try to access and index beyond the array's limit it gives me a stack overflow (That's the name of the error,right?) error with some memory adress and then I know that I'm trying to access an index that's not there,in G++ however,I get that weird segmentation fault error which I'm not fimiliar with.


For this reason it's safer to use C++ collections, like std::vector and std::array, instead of C-style arrays which are basically pointers. Trying to access an element beyond array boundary will result in out of bounds exception which is easy to understand and debug.
Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> I tried.
> 
> This is the biggest prime it found in the edited code:997.
> 
> This is the biggest prime it found in the original code:999983.


The highest possible divisor of a number n is sqrt so there is no need to go beyond i = sqrt (or i * i = n) as you're removing multiples of i.

Code:



Code:


std::vector<bool> sieve(int limit)
{
        std::vector<bool> sieve(limit + 1, true);
        sieve[0] = sieve[1] = false;

        for (int i = 2; i * i <= limit; ++i) {
                if (sieve[i]) {
                        for (int k = i * i; k <= limit; k += i) {
                                sieve[k] = false;
                        }
                }
        }

        return sieve;
}


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *poroboszcz*
> 
> For this reason it's safer to use C++ collections, like std::vector and std::array, instead of C-style arrays which are basically pointers. Trying to access an element beyond array boundary will result in out of bounds exception which is easy to understand and debug.


I always thought that C-style arrays are the same as normal arrays









I tried to use a vector of booleans btw but it didn't use the operators ('!' and '=' weren't recognized and I couldn't do anything with it).
Quote:


> The highest possible divisor of a number n is sqrt so there is no need to go beyond i = sqrt (or i * i = n) as you're removing multiples of i.
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> std::vector<bool> sieve(int limit)
> {
> std::vector<bool> sieve(limit + 1, true);
> sieve[0] = sieve[1] = false;
> 
> for (int i = 2; i * i <= limit; ++i) {
> if (sieve[i]) {
> for (int k = i * i; k <= limit; k += i) {
> sieve[k] = false;
> }
> }
> }
> 
> return sieve;
> }


Yea I understand the concept but it didn't work for that's why I haven't implelmnted it,but now I figured out what I did wrong.

BTW,isn't returning a vector a bad idea since it might be huge?

Thanks mate.


----------



## tompsonn

I can't see why you would get a stack overflow trying to access random memory (which is what happens if you pass the end of a C array). You would either get random garbage back and no error, or you'll get an access violation or a segmentation fauly.

If you're doing plain C, you had better get your bounds checking up to scratch.


----------



## ABD EL HAMEED

OK,this is the most optimized sieve I could come up with:

Code:



Code:


void sieve (vector <unsigned long long> &primes, unsigned long long theLimit) {
    const unsigned long long SIZE = theLimit + 1;
    bool *oddNonPrimes = new bool [SIZE];
    unsigned long long squareRoot;

    for (unsigned long long i = 0; i < SIZE; ++i)
        oddNonPrimes[i] = false;

    primes.push_back(2);

    for (unsigned long long i = 3; i * i < theLimit; i += 2) {
        if (!oddNonPrimes[i]) {
            unsigned long long currNum = i;
            primes.push_back(currNum);
            for (currNum *= currNum; currNum <= theLimit; currNum += (i * 2)) {
                oddNonPrimes[currNum] = true;
            }
            currNum = i;
        }
        squareRoot = i - 2;
    }

    for (int i = squareRoot; i <= SIZE; i += 2)
        if (!oddNonPrimes[i])
            primes.push_back(i);

}


----------



## ABD EL HAMEED

Can anyone give me a link to an article or a website that explains how supercomputers store big numbers?I've tried googling but no luck. ._.


----------



## andyroo89

Anyone familiar with java/android programming that can help me?

I am working on a personal app that I can search for minecraft items, and have them display their recipe if I were to forget. I have the alphabetical listview working like I want, but, now.... I have another problem. to save some line of code I use nested for loop to compile list of items (you will see in the code if you ever play minecraft. if I click on any off the items from the nested for loop it wont display the recipe only if I click on the ones that are just like this...

recipes.add("wool"); also the taosted message for "visual" log here is a pastie.

http://pastie.org/9699474


----------



## patriotaki

Im trying to code a tic tac toe game in C language. Human vs Human not Human vs Computer and im having some trouble with the loop. It goes only 1 time into the loop i have a do while statement.

Can anyone help me out here ?

Code:



Code:


#include<stdio.h>

int X,i,sum,sym;
char board[10] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};

int drawboard() {

                printf("\n");printf("\n");
                printf(" %c | %c | %c\n", board[1], board[2], board[3]);
                printf("-----------\n");
                printf(" %c | %c | %c\n", board[4], board[5], board[6]);
                printf("-----------\n");
                printf(" %c | %c | %c\n", board[7], board[8], board[9]);
}

int playX()
{
        printf("Player X :");
        scanf("%d",&sym);
            if ((sym>=1) && (sym<=9)){
                board[sym] = 'X';
                drawboard();
                X=0;}
            else
                scanf("%d",&sym);
}
int playO()
{
        printf("Player O :");
        scanf("%d",&sym);
    if ((sym>=1) && (sym<=9)) {
        board[sym] = 'O';
        drawboard();
        X=1;}
    else
        scanf("%d",&sym);
}
int main () {

printf("\n");printf("\n");
printf(" %c | %c | %c\n", board[1], board[2], board[3]);
printf("-----------\n");
printf(" %c | %c | %c\n", board[4], board[5], board[6]);
printf("-----------\n");
printf(" %c | %c | %c\n", board[7], board[8], board[9]);

X=0;

do {
if (X==1)
    {
        playX();
        i=i+1;
    }
else
   {
        playO();
        i=i+1;

   }
}
while (i==9);

}


----------



## tom.slick

Quote:


> Originally Posted by *patriotaki*
> 
> Im trying to code a tic tac toe game in C language. Human vs Human not Human vs Computer and im having some trouble with the loop. It goes only 1 time into the loop i have a do while statement.
> 
> Can anyone help me out here ?
> 
> 
> Spoiler: Warning: Spoiler!
> 
> 
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> #include<stdio.h>
> 
> int X,i,sum,sym;
> char board[10] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
> 
> int drawboard() {
> 
> printf("\n");printf("\n");
> printf(" %c | %c | %c\n", board[1], board[2], board[3]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[4], board[5], board[6]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[7], board[8], board[9]);
> }
> 
> int playX()
> {
> printf("Player X :");
> scanf("%d",&sym);
> if ((sym>=1) && (sym<=9)){
> board[sym] = 'X';
> drawboard();
> X=0;}
> else
> scanf("%d",&sym);
> }
> int playO()
> {
> printf("Player O :");
> scanf("%d",&sym);
> if ((sym>=1) && (sym<=9)) {
> board[sym] = 'O';
> drawboard();
> X=1;}
> else
> scanf("%d",&sym);
> }
> int main () {
> 
> printf("\n");printf("\n");
> printf(" %c | %c | %c\n", board[1], board[2], board[3]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[4], board[5], board[6]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[7], board[8], board[9]);
> 
> X=0;
> 
> do {
> if (X==1)
> {
> playX();
> i=i+1;
> }
> else
> {
> playO();
> i=i+1;
> 
> }
> }
> while (i==9);
> 
> }


Code:



Code:


while (i<9);


----------



## patriotaki

Quote:


> Originally Posted by *tom.slick*
> 
> [/SPOILER]
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> while (i<9);


OMG lol how stupid am i ?

thanks alot


----------



## patriotaki

One more thing.. can i use 2 and statements ( &&) in If statement ?

For example i want to see if the boxnumber is empty

Code:



Code:


int playX()
{
        printf("Player X :");
        scanf("%d",&sym);
            if ((sym>=1) && (sym<=9) && (board[sym]=' ')){
                board[sym] = 'X';
                drawboard();
                X=0;}
            else
                scanf("%d",&sym);
}


----------



## tom.slick

Quote:


> Originally Posted by *patriotaki*
> 
> One more thing.. can i use 2 and statements ( &&) in If statement ?
> 
> For example i want to see if the boxnumber is empty
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> int playX()
> {
> printf("Player X :");
> scanf("%d",&sym);
> if ((sym>=1) && (sym<=9) && (board[sym]=' ')){
> board[sym] = 'X';
> drawboard();
> X=0;}
> else
> scanf("%d",&sym);
> }


yes, you can use as many and statements as you need


----------



## patriotaki

Quote:


> Originally Posted by *tom.slick*
> 
> yes, you can use as many and statements as you need


It doesnt work though









it still changes the value from X to O or vice versa if i enter the same number. The box has to be empty ' ' else it should ask again for the code

any help ?

Code:



Code:


#include<stdio.h>

int X,k,i,sum,sym;
char board[10] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};

int drawboard() {

                printf("\n");printf("\n");
                printf(" %c | %c | %c\n", board[1], board[2], board[3]);
                printf("-----------\n");
                printf(" %c | %c | %c\n", board[4], board[5], board[6]);
                printf("-----------\n");
                printf(" %c | %c | %c\n", board[7], board[8], board[9]);
}

int playX()
{
        printf("Player X :");
        scanf("%d",&sym);
            if ((sym>=1) && (sym<=9) && (board[sym]=' ')){
                board[sym] = 'X';
                drawboard();
                X=0;
                k++;}
            else
                scanf("%d",&sym);
}
int playO()
{
        printf("Player O :");
        scanf("%d",&sym);
    if ((sym>=1) && (sym<=9)&&(board[sym]=' ')

        ) {
        board[sym] = 'O';
        drawboard();
        X=1;
        k++;
        }
    else
        scanf("%d",&sym);
}
int main () {

printf("\n");printf("\n");
printf(" %c | %c | %c\n", board[1], board[2], board[3]);
printf("-----------\n");
printf(" %c | %c | %c\n", board[4], board[5], board[6]);
printf("-----------\n");
printf(" %c | %c | %c\n", board[7], board[8], board[9]);

X=0;

do {
if (X==1)
        playX();

else if (X==0)
        playO();
}
while (k<9);

}


----------



## tom.slick

if ((sym >= 1) && (sym <= 9 )&& (board[sym] *==* ' ')


----------



## patriotaki

Quote:


> Originally Posted by *tom.slick*
> 
> if ((sym >= 1) && (sym <= 9 )&& (board[sym] *==* ' ')


Thanks for your help bro!

i think i finished it if you have some spare time have a look at it and tell me how can i improve it?


Spoiler: Tic Tac Toe Code



Code:



Code:


#include<stdio.h>

int X,k,i,sum,sym;
char board[10] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};

int drawboard() {

                printf("\n");printf("\n");
                printf(" %c | %c | %c\n", board[1], board[2], board[3]);
                printf("-----------\n");
                printf(" %c | %c | %c\n", board[4], board[5], board[6]);
                printf("-----------\n");
                printf(" %c | %c | %c\n", board[7], board[8], board[9]);
}

int playX()
{
        printf("Player X :");
        scanf("%d",&sym);
            if ((sym>=1) && (sym<=9) && (board[sym]==' ')){
                board[sym] = 'X';
                drawboard();
                X=0;
                k++;}
            else{
                printf("Enter a number between 1-9\n");
                scanf("%d",&sym);

            }
}
int playO()
{
        printf("Player O :");
        scanf("%d",&sym);
    if ((sym>=1) && (sym<=9) && (board[sym]==' ')) {
        board[sym] = 'O';
        drawboard();
        X=1;
        k++;
        }
    else{
                printf("Enter a number between 1-9\n");
                scanf("%d",&sym);

            }
}

int rowcheckX()
{
    if ((board[1] == 'X') && (board[2] == 'X') && (board[3] == 'X'))
            printf("Player X won");
    if ((board[4] == 'X') && (board[5] == 'X') && (board[6] == 'X'))
            printf("Player X won");
    if ((board[7] == 'X') && (board[8] == 'X') && (board[9] == 'X'))
            printf("Player X won");

}

int rowcheckO()
{
    if ((board[1] == 'O') && (board[2] == 'O') && (board[3] == 'O'))
            printf("Player O won");
    if ((board[4] == 'O') && (board[5] == 'O') && (board[6] == 'O'))
            printf("Player O won");
    if ((board[7] == 'O') && (board[8] == 'O') && (board[9] == 'O'))
            printf("Player O won");

}

int columncheckX()
{

    if ((board[1] == 'X') && (board[4] == 'X') && (board[7] == 'X'))
            printf("Player X won");
    if ((board[2] == 'X') && (board[5] == 'X') && (board[8] == 'X'))
            printf("Player X won");
    if ((board[3] == 'X') && (board[6] == 'X') && (board[9] == 'X'))
            printf("Player X won");

}
int columncheckO()
{

    if ((board[1] == 'O') && (board[4] == 'O') && (board[7] == 'O'))
            printf("Player O won");
    if ((board[2] == 'O') && (board[5] == 'O') && (board[8] == 'O'))
            printf("Player O won");
    if ((board[3] == 'O') && (board[6] == 'O') && (board[9] == 'O'))
            printf("Player O won");
}

int diagcheckX()
{
    if ((board[1] == 'X') && (board[5] == 'X') && (board[9] == 'X'))
            printf("Player X won");
    if ((board[3] == 'X') && (board[5] == 'X') && (board[9] == '7'))
            printf("Player X won");
}

int diagcheckO()
{
    if ((board[1] == 'O') && (board[5] == 'O') && (board[9] == 'O'))
            printf("Player O won");
    if ((board[3] == 'O') && (board[5] == 'O') && (board[9] == 'O'))
            printf("Player O won");
}

int main () {

printf("\n");printf("\n");
printf(" %c | %c | %c\n", board[1], board[2], board[3]);
printf("-----------\n");
printf(" %c | %c | %c\n", board[4], board[5], board[6]);
printf("-----------\n");
printf(" %c | %c | %c\n", board[7], board[8], board[9]);

X=0;

do {
if (X==1)
        playX();

else if (X==0)
        playO();
}
while (k<9);

rowcheckX();
rowcheckO();
columncheckX();
columncheckO();
diagcheckX();
diagcheckO();

}


----------



## andyroo89

Looking at that tic tac toe game made in C makes me want to try it in python now.

edit; btw I am wondering if there is a different way more elegant way to check for winner, also you need to add a stalemate if no one wins.


----------



## patriotaki

Quote:


> Originally Posted by *andyroo89*
> 
> Looking at that tic tac toe game made in C makes me want to try it in python now.
> 
> edit; btw I am wondering if there is a different way more elegant way to check for winner, also you need to add a stalemate if no one wins.


ye i have updated it ..there is much more easier way to find a winner.. as long as it works im okay..now i have to make a sudoku game. Deadline until friday

Code:



Code:


#include<stdio.h>

int X,k,i,sum,ch,sym,sumtie;
char choice;
char board[10] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};

int drawboard() {

                printf("\n");printf("\n");
                printf(" %c | %c | %c\n", board[1], board[2], board[3]);
                printf("-----------\n");
                printf(" %c | %c | %c\n", board[4], board[5], board[6]);
                printf("-----------\n");
                printf(" %c | %c | %c\n", board[7], board[8], board[9]);
}

int playX()
{
        printf("Player X :");
        scanf("%d",&sym);
            if ((sym>=1) && (sym<=9) && (board[sym]==' ')){
                board[sym] = 'X';
                drawboard();
                X=0;
                k++;}
            else{
                printf("Enter a number between 1-9 ,it should be empty! \n");
            }
}
int playO()
{
        printf("Player O :");
        scanf("%d",&sym);
    if ((sym>=1) && (sym<=9) && (board[sym]==' ')) {
        board[sym] = 'O';
        drawboard();
        X=1;
        k++;
        }
    else{
                printf("Enter a number between 1-9 ,it should be empty! \n");
            }
}

int rowcheckX()
{
    if ((board[1] == 'X') && (board[2] == 'X') && (board[3] == 'X')){
            printf("---Player X won---");
            sumtie=1;}
    if ((board[4] == 'X') && (board[5] == 'X') && (board[6] == 'X')){
            printf("---Player X won---");
            sumtie=1;}
    if ((board[7] == 'X') && (board[8] == 'X') && (board[9] == 'X')){
            printf("---Player X won---");
            sumtie=1;}

}

int rowcheckO()
{
    if ((board[1] == 'O') && (board[2] == 'O') && (board[3] == 'O')){
            printf("---Player O won---");
            sumtie=1;}
    if ((board[4] == 'O') && (board[5] == 'O') && (board[6] == 'O')){
            printf("---Player O won---");
            sumtie=1;}
    if ((board[7] == 'O') && (board[8] == 'O') && (board[9] == 'O')){
            printf("---Player O won---");
            sumtie=1;}

}

int columncheckX()
{

    if ((board[1] == 'X') && (board[4] == 'X') && (board[7] == 'X')){
            printf("---Player X won---");
            sumtie=1;}
    if ((board[2] == 'X') && (board[5] == 'X') && (board[8] == 'X')){
            printf("---Player X won---");
            sumtie=1;}
    if ((board[3] == 'X') && (board[6] == 'X') && (board[9] == 'X')){
            printf("---Player X won---");
            sumtie=1;}
}
int columncheckO()
{

    if ((board[1] == 'O') && (board[4] == 'O') && (board[7] == 'O')){
            printf("---Player O won---");
            sumtie=1;}
    if ((board[2] == 'O') && (board[5] == 'O') && (board[8] == 'O')){
            printf("---Player O won---");
            sumtie=1;}
    if ((board[3] == 'O') && (board[6] == 'O') && (board[9] == 'O')){
            printf("---Player O won---");
            sumtie=1;}
}

int diagcheckX()
{
    if ((board[1] == 'X') && (board[5] == 'X') && (board[9] == 'X')){
            printf("---Player X won---");
            sumtie=1;}
    if ((board[3] == 'X') && (board[5] == 'X') && (board[7] == 'X')){
            printf("---Player X won---");
            sumtie=1;}
}

int diagcheckO()
{
    if ((board[1] == 'O') && (board[5] == 'O') && (board[9] == 'O')){
            printf("---Player O won---");
            sumtie=1;}
    if ((board[3] == 'O') && (board[5] == 'O') && (board[7] == 'O')){
            printf("---Player O won---");
            sumtie=1;}
}

int tiecheck()
{
    if (sumtie == 0){

        printf("\n");
        printf("---Tie---");}
}

int main () {

printf("\n");printf("\n");
printf(" %c | %c | %c\n", board[1], board[2], board[3]);
printf("-----------\n");
printf(" %c | %c | %c\n", board[4], board[5], board[6]);
printf("-----------\n");
printf(" %c | %c | %c\n", board[7], board[8], board[9]);

printf("Who starts first X or O? Type below \n");
ch=0;
sumtie=0;

while (ch!=1) {
if (choice=='X')
   {X=1;ch=1;}
else if (choice=='O')
    {X=0;ch=1;}
else
{

    ch=0;
    printf("Invalid character type either X or O\n");

}

scanf("%c",&choice);
}
do {
if (X==1)
        playX();

else if (X==0)
        playO();
}
while (k<9);

rowcheckX();
rowcheckO();
columncheckX();
columncheckO();
diagcheckX();
diagcheckO();
tiecheck();

}


----------



## tom.slick

Quote:


> Originally Posted by *patriotaki*
> 
> ye i have updated it ..there is much more easier way to find a winner.. as long as it works im okay..now i have to make a sudoku game. Deadline until friday
> 
> 
> Spoiler: Warning: Spoiler!
> 
> 
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> #include<stdio.h>
> 
> int X,k,i,sum,ch,sym,sumtie;
> char choice;
> char board[10] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
> 
> int drawboard() {
> 
> printf("\n");printf("\n");
> printf(" %c | %c | %c\n", board[1], board[2], board[3]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[4], board[5], board[6]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[7], board[8], board[9]);
> }
> 
> int playX()
> {
> printf("Player X :");
> scanf("%d",&sym);
> if ((sym>=1) && (sym<=9) && (board[sym]==' ')){
> board[sym] = 'X';
> drawboard();
> X=0;
> k++;}
> else{
> printf("Enter a number between 1-9 ,it should be empty! \n");
> }
> }
> int playO()
> {
> printf("Player O :");
> scanf("%d",&sym);
> if ((sym>=1) && (sym<=9) && (board[sym]==' ')) {
> board[sym] = 'O';
> drawboard();
> X=1;
> k++;
> }
> else{
> printf("Enter a number between 1-9 ,it should be empty! \n");
> }
> }
> 
> int rowcheckX()
> {
> if ((board[1] == 'X') && (board[2] == 'X') && (board[3] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> if ((board[4] == 'X') && (board[5] == 'X') && (board[6] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> if ((board[7] == 'X') && (board[8] == 'X') && (board[9] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> 
> }
> 
> int rowcheckO()
> {
> if ((board[1] == 'O') && (board[2] == 'O') && (board[3] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> if ((board[4] == 'O') && (board[5] == 'O') && (board[6] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> if ((board[7] == 'O') && (board[8] == 'O') && (board[9] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> 
> }
> 
> int columncheckX()
> {
> 
> if ((board[1] == 'X') && (board[4] == 'X') && (board[7] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> if ((board[2] == 'X') && (board[5] == 'X') && (board[8] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> if ((board[3] == 'X') && (board[6] == 'X') && (board[9] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> }
> int columncheckO()
> {
> 
> if ((board[1] == 'O') && (board[4] == 'O') && (board[7] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> if ((board[2] == 'O') && (board[5] == 'O') && (board[8] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> if ((board[3] == 'O') && (board[6] == 'O') && (board[9] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> }
> 
> int diagcheckX()
> {
> if ((board[1] == 'X') && (board[5] == 'X') && (board[9] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> if ((board[3] == 'X') && (board[5] == 'X') && (board[7] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> }
> 
> int diagcheckO()
> {
> if ((board[1] == 'O') && (board[5] == 'O') && (board[9] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> if ((board[3] == 'O') && (board[5] == 'O') && (board[7] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> }
> 
> int tiecheck()
> {
> if (sumtie == 0){
> 
> printf("\n");
> printf("---Tie---");}
> }
> 
> int main () {
> 
> printf("\n");printf("\n");
> printf(" %c | %c | %c\n", board[1], board[2], board[3]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[4], board[5], board[6]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[7], board[8], board[9]);
> 
> printf("Who starts first X or O? Type below \n");
> ch=0;
> sumtie=0;
> 
> while (ch!=1) {
> if (choice=='X')
> {X=1;ch=1;}
> else if (choice=='O')
> {X=0;ch=1;}
> else
> {
> 
> ch=0;
> printf("Invalid character type either X or O\n");
> 
> }
> 
> scanf("%c",&choice);
> }
> do {
> if (X==1)
> playX();
> 
> else if (X==0)
> playO();
> }
> while (k<9);
> 
> rowcheckX();
> rowcheckO();
> columncheckX();
> columncheckO();
> diagcheckX();
> diagcheckO();
> tiecheck();
> 
> }


that is a lot of work to check for a winner
instead of 2 sets of functions (one of x and one for o)
combine them all in to one function and why not just pass the function a variable that tells it who's turn it is
maybe an array
char player[2] = {'X', 'O'};
and use a couple of for loops
and return a value so you know that somebody won and you can end the game


Spoiler: Warning: Spoiler!



Code:



Code:


int checkwin(int p)
{
    char player[2] = {'X', 'O'};

    for (int a = 0;a < 9;a += 3){
        if ((board[a + 1] == player[p]) && (board[a + 2] == player[p]) && (board[a + 3] == player[p])){
            printf("Player %c Won\n", player[p]);
            return 1;
        }
    }
    for (int a = 0;a < 3;a++){
        if ((board[a + 1] == player[p]) && (board[a + 4] == player[p]) && (board[a + 7] == player[p])){
            printf("Player %c Won\n", player[p]);
            return 1;
        }
    }
    if (((board[1] == player[p]) && (board[5] == player[p]) && (board[9] == player[p])) || 
        ((board[3] == player[p]) && (board[5] == player[p]) && (board[7] == player[p]))){
            printf("Player %c Won\n", player[p]);
            return 1;
    }   
    return 0;





call it in your play() function

Code:



Code:


if (checkwin(X) == 1 ){
            // do something to quit the game
        }

Quote:


> Originally Posted by *andyroo89*
> 
> Looking at that tic tac toe game made in C makes me want to try it in python now.
> 
> edit; btw I am wondering if there is a different way more elegant way to check for winner, also you need to add a stalemate if no one wins.





Spoiler: Warning: Spoiler!



Code:



Code:


board = [" " for a in range(11)]
player = ["X", "O"]
X = False;
counter = 1;

def drawboard():

    print("\n\n");
    print " {0} | {1} | {2}".format(board[1], board[2], board[3])
    print "-----------";
    print " {0} | {1} | {2}".format(board[4], board[5], board[6])
    print "-----------";
    print " {0} | {1} | {2}".format(board[7], board[8], board[9])

def checkwin(p):

    for a in range(0,9,3):
        if board[a + 1] == player[p] and board[a + 2] == player[p] and board[a + 3] == player[p]:
            print "Player {0} Won".format(player[p])
            return True

    for a in range(3):
        if board[a + 1] == player[p] and board[a + 4] == player[p] and board[a + 7] == player[p]:
            print "Player {0} Won".format(player[p])
            return True

    if (board[1] == player[p] and board[5] == player[p] and board[9] == player[p]) or\
        (board[3] == player[p] and board[5] == player[p] and board[7] == player[p]):
         print "Player {0} Won".format(player[p])
         return True
    return False

def play(p):
    global X, counter
    turn = raw_input("Player {0} :".format(player[p]))
    try:
        turn = int(turn)
    except:
        print "Enter a number between 1-9"
        return

    if 0 < turn < 10 and board[turn] == ' ':
        board[turn] = player[p]
        drawboard()

        if checkwin(X):
            counter += 10

        X = 0

        if p == 0:
            X = 1

        counter += 1

    else:
        print "Enter a number between 1-9"

def main():
    drawboard()
    while counter < 10:
       play(X)

    print "GAME OVER"

if __name__ == '__main__':
    main()


----------



## andyroo89

Quote:


> Originally Posted by *tom.slick*
> 
> that is a lot of work to check for a winner
> instead of 2 sets of functions (one of x and one for o)
> combine them all in to one function and why not just pass the function a variable that tells it who's turn it is
> maybe an array
> char player[2] = {'X', 'O'};
> and use a couple of for loops
> and return a value so you know that somebody won and you can end the game
> 
> 
> Spoiler: Warning: Spoiler!
> 
> 
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> int checkwin(int p)
> {
> char player[2] = {'X', 'O'};
> 
> for (int a = 0;a < 9;a += 3){
> if ((board[a + 1] == player[p]) && (board[a + 2] == player[p]) && (board[a + 3] == player[p])){
> printf("Player %c Won\n", player[p]);
> return 1;
> }
> }
> for (int a = 0;a < 3;a++){
> if ((board[a + 1] == player[p]) && (board[a + 4] == player[p]) && (board[a + 7] == player[p])){
> printf("Player %c Won\n", player[p]);
> return 1;
> }
> }
> if (((board[1] == player[p]) && (board[5] == player[p]) && (board[9] == player[p])) ||
> ((board[3] == player[p]) && (board[5] == player[p]) && (board[7] == player[p]))){
> printf("Player %c Won\n", player[p]);
> return 1;
> }
> return 0;
> 
> 
> 
> 
> 
> call it in your play() function
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> if (checkwin(X) == 1 ){
> // do something to quit the game
> }
> 
> 
> 
> 
> Spoiler: Warning: Spoiler!
> 
> 
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> board = [" " for a in range(11)]
> player = ["X", "O"]
> X = False;
> counter = 1;
> 
> def drawboard():
> 
> print("\n\n");
> print " {0} | {1} | {2}".format(board[1], board[2], board[3])
> print "-----------";
> print " {0} | {1} | {2}".format(board[4], board[5], board[6])
> print "-----------";
> print " {0} | {1} | {2}".format(board[7], board[8], board[9])
> 
> def checkwin(p):
> 
> for a in range(0,9,3):
> if board[a + 1] == player[p] and board[a + 2] == player[p] and board[a + 3] == player[p]:
> print "Player {0} Won".format(player[p])
> return True
> 
> for a in range(3):
> if board[a + 1] == player[p] and board[a + 4] == player[p] and board[a + 7] == player[p]:
> print "Player {0} Won".format(player[p])
> return True
> 
> if (board[1] == player[p] and board[5] == player[p] and board[9] == player[p]) or\
> (board[3] == player[p] and board[5] == player[p] and board[7] == player[p]):
> print "Player {0} Won".format(player[p])
> return True
> return False
> 
> def play(p):
> global X, counter
> turn = raw_input("Player {0} :".format(player[p]))
> try:
> turn = int(turn)
> except:
> print "Enter a number between 1-9"
> return
> 
> if 0 < turn < 10 and board[turn] == ' ':
> board[turn] = player[p]
> drawboard()
> 
> if checkwin(X):
> counter += 10
> 
> X = 0
> 
> if p == 0:
> X = 1
> 
> counter += 1
> 
> else:
> print "Enter a number between 1-9"
> 
> def main():
> drawboard()
> while counter < 10:
> play(X)
> 
> print "GAME OVER"
> 
> if __name__ == '__main__':
> main()


that is not python is it? Doesn't look like the syntax.


----------



## tom.slick

The two bits at the top are C, but the last part is Python 2.7


----------



## andyroo89

Quote:


> Originally Posted by *patriotaki*
> 
> ye i have updated it ..there is much more easier way to find a winner.. as long as it works im okay..now i have to make a sudoku game. Deadline until friday
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> #include<stdio.h>
> 
> int X,k,i,sum,ch,sym,sumtie;
> char choice;
> char board[10] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
> 
> int drawboard() {
> 
> printf("\n");printf("\n");
> printf(" %c | %c | %c\n", board[1], board[2], board[3]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[4], board[5], board[6]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[7], board[8], board[9]);
> }
> 
> int playX()
> {
> printf("Player X :");
> scanf("%d",&sym);
> if ((sym>=1) && (sym<=9) && (board[sym]==' ')){
> board[sym] = 'X';
> drawboard();
> X=0;
> k++;}
> else{
> printf("Enter a number between 1-9 ,it should be empty! \n");
> }
> }
> int playO()
> {
> printf("Player O :");
> scanf("%d",&sym);
> if ((sym>=1) && (sym<=9) && (board[sym]==' ')) {
> board[sym] = 'O';
> drawboard();
> X=1;
> k++;
> }
> else{
> printf("Enter a number between 1-9 ,it should be empty! \n");
> }
> }
> 
> int rowcheckX()
> {
> if ((board[1] == 'X') && (board[2] == 'X') && (board[3] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> if ((board[4] == 'X') && (board[5] == 'X') && (board[6] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> if ((board[7] == 'X') && (board[8] == 'X') && (board[9] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> 
> }
> 
> int rowcheckO()
> {
> if ((board[1] == 'O') && (board[2] == 'O') && (board[3] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> if ((board[4] == 'O') && (board[5] == 'O') && (board[6] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> if ((board[7] == 'O') && (board[8] == 'O') && (board[9] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> 
> }
> 
> int columncheckX()
> {
> 
> if ((board[1] == 'X') && (board[4] == 'X') && (board[7] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> if ((board[2] == 'X') && (board[5] == 'X') && (board[8] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> if ((board[3] == 'X') && (board[6] == 'X') && (board[9] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> }
> int columncheckO()
> {
> 
> if ((board[1] == 'O') && (board[4] == 'O') && (board[7] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> if ((board[2] == 'O') && (board[5] == 'O') && (board[8] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> if ((board[3] == 'O') && (board[6] == 'O') && (board[9] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> }
> 
> int diagcheckX()
> {
> if ((board[1] == 'X') && (board[5] == 'X') && (board[9] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> if ((board[3] == 'X') && (board[5] == 'X') && (board[7] == 'X')){
> printf("---Player X won---");
> sumtie=1;}
> }
> 
> int diagcheckO()
> {
> if ((board[1] == 'O') && (board[5] == 'O') && (board[9] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> if ((board[3] == 'O') && (board[5] == 'O') && (board[7] == 'O')){
> printf("---Player O won---");
> sumtie=1;}
> }
> 
> int tiecheck()
> {
> if (sumtie == 0){
> 
> printf("\n");
> printf("---Tie---");}
> }
> 
> int main () {
> 
> printf("\n");printf("\n");
> printf(" %c | %c | %c\n", board[1], board[2], board[3]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[4], board[5], board[6]);
> printf("-----------\n");
> printf(" %c | %c | %c\n", board[7], board[8], board[9]);
> 
> printf("Who starts first X or O? Type below \n");
> ch=0;
> sumtie=0;
> 
> while (ch!=1) {
> if (choice=='X')
> {X=1;ch=1;}
> else if (choice=='O')
> {X=0;ch=1;}
> else
> {
> 
> ch=0;
> printf("Invalid character type either X or O\n");
> 
> }
> 
> scanf("%c",&choice);
> }
> do {
> if (X==1)
> playX();
> 
> else if (X==0)
> playO();
> }
> while (k<9);
> 
> rowcheckX();
> rowcheckO();
> columncheckX();
> columncheckO();
> diagcheckX();
> diagcheckO();
> tiecheck();
> 
> }


I just thought of something else, instead of making checkdiagX checkdiagO etc.. you should just remove half of those and toggle between X and O should shave your code down a bit.


----------



## dBlisse

more elegant way is iterating through a list of indices

const int checkIndices[8][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}};

just a for loop.

they're constant indices anyways. might as well define them as constants.

even more "elegant" way is building a trie and only checking the paths that could possibly have changed, but that relies too much on your program not exploding

---

lots of improvements possible but good enough for a first or second program


----------



## tom.slick

Quote:


> Originally Posted by *dBlisse*
> 
> more elegant way is iterating through a list of indices
> 
> const int checkIndices[8][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}};
> 
> just a nested for loop.
> 
> they're constant indices anyways. might as well define them as constants.
> 
> even more "elegant" way is building a trie and only checking the paths that could possibly have changed, but that relies too much on your program not exploding
> 
> ---
> 
> lots of improvements possible but good enough for a first or second program


I don't know why I didn't think of that +1


----------



## patriotaki

I need to make a program that scans 81 numbers (sudoku) and checks if the sudoku is correct. (it does not solve it!) . If it finds a mistake it needs to remmeber the row or column or block position.

for example the output will be :

Invalid rows: 1 2 8
Invalid columns: 1
Invalid blocks: 1 7

My code is really really messed up and long its just a quick solution. Any recommendaitons for improvement are appriciated!












Spoiler: Code!



#include

int array [1000][1000];
int colcounter,rowcounter,blockcounter1,blockcounter2,blockcounter3,blockcounter4,blockcounter5,blockcounter6,blockcounter7,blockcounter8,blockcounter9,block,col,row,tmp1,i,j,counter1,counter2,counter3,counter4,counter5,counter6,counter7,counter8,counter9,num;

int printarray()
{
for (i=1;i<=9;i++)
printf(" %d %d %d %d %d %d %d %d %d \n", array[1], array[2], array[3],array[4], array[5], array[6],array[7], array[8], array[9]);
}

int checkrow()

{
for (i=1;i<=9;i++)
{
counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
tmp1=0;
}
for (j=0;j<=9;j++) {

if (array_[j]==1) {
counter1++;
tmp1=i;
row=tmp1;
}
if (array_[j]==2){
counter2++;
tmp1=i;
row=tmp1;
}
if (array_[j]==3)
{
counter3++;
tmp1=i;
row=tmp1;
}
if (array_[j]==4)
{
counter4++;
tmp1=i;
row=tmp1;
}
if (array_[j]==5)
{
counter5++;
tmp1=i;
row=tmp1;
}
if (array_[j]==6)
{
counter6++;
tmp1=i;
row=tmp1;
}
if (array_[j]==7)
{
counter7++;
tmp1=i;
row=tmp1;
}
if (array_[j]==8)
{
counter8++;
tmp1=i;
row=tmp1;
}
if (array_[j]==9)
{
counter9++;
tmp1=i;
row=tmp1;
}

}
if ( (counter1>=2) || (counter2>=2) || (counter3>=2) || (counter4>=2) || (counter5>=2) || (counter6>=2) || (counter7>=2) || (counter8>=2) || (counter9>=2) )
{
printf("Invalid Rows : %d \n",row);
rowcounter=1;}
rowcounter=0;
}

int checkcolumn()
{
for (j=1;j<=9;j++)
{
counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
tmp1=0;
}
for (i=0;i<=9;i++) {

if (array_[j]==1) {
counter1++;
tmp1=j;
col=tmp1;
}
if (array_[j]==2){
counter2++;
tmp1=j;
col=tmp1;
}
if (array_[j]==3)
{
counter3++;
tmp1=j;
col=tmp1;
}
if (array_[j]==4)
{
counter4++;
tmp1=j;
col=tmp1;
}
if (array_[j]==5)
{
counter5++;
tmp1=j;
col=tmp1;
}
if (array_[j]==6)
{
counter6++;
tmp1=j;
col=tmp1;
}
if (array_[j]==7)
{
counter7++;
tmp1=j;
col=tmp1;
}
if (array_[j]==8)
{
counter8++;
tmp1=j;
col=tmp1;
}
if (array_[j]==9)
{
counter9++;
tmp1=j;
col=tmp1;
}

}
if ( (counter1>=2) || (counter2>=2) || (counter3>=2) || (counter4>=2) || (counter5>=2) || (counter6>=2) || (counter7>=2) || (counter8>=2) || (counter9>=2) )
{printf("Invalid Columns : %d \n",col);
colcounter=1;}
colcounter=0;
}

int checkblock1()

{
for (i=1; i<=3; i++){
for (j=1; j<=3; j++){

counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;

if (array_[j]==1)
{
counter1++;
block=1;

}
if (array_[j]==2)
{
counter2++;
block=1;

}
if (array_[j]==3)
{
counter3++;
block=1;

}
if (array_[j]==4)
{
counter4++;
block=1;

}
if (array_[j]==5)
{
counter5++;
block=1;

}
if (array_[j]==6)
{
counter6++;
block=1;

}
if (array_[j]==7)
{
counter7++;
block=1;

}

if (array_[j]==8)
{
counter8++;
block=1;

}
if (array_[j]==9)
{
counter9++;
block=1;

}
}

if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
{

printf("invalid block 1 \n");
blockcounter1=1;}

}
blockcounter1=0;
}

int checkblock2()

{
for (i=1; i<=3; i++){
for (j=4; j<=6; j++){

counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;

if (array_[j]==1)
{
counter1++;
block=1;

}
if (array_[j]==2)
{
counter2++;
block=1;

}
if (array_[j]==3)
{
counter3++;
block=1;

}
if (array_[j]==4)
{
counter4++;
block=1;

}
if (array_[j]==5)
{
counter5++;
block=1;

}
if (array_[j]==6)
{
counter6++;
block=1;

}
if (array_[j]==7)
{
counter7++;
block=1;

}

if (array_[j]==8)
{
counter8++;
block=1;

}
if (array_[j]==9)
{
counter9++;
block=1;

}
}

if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
{printf("invalid block 2 \n");
blockcounter2=1;}

}
blockcounter2=0;
}

int checkblock3()

{
for (i=1; i<=3; i++){
for (j=7; j<=9; j++){

counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;

if (array_[j]==1)
{
counter1++;
block=1;

}
if (array_[j]==2)
{
counter2++;
block=1;

}
if (array_[j]==3)
{
counter3++;
block=1;

}
if (array_[j]==4)
{
counter4++;
block=1;

}
if (array_[j]==5)
{
counter5++;
block=1;

}
if (array_[j]==6)
{
counter6++;
block=1;

}
if (array_[j]==7)
{
counter7++;
block=1;

}

if (array_[j]==8)
{
counter8++;
block=1;

}
if (array_[j]==9)
{
counter9++;
block=1;

}
}

if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
{printf("invalid block 3 \n");
blockcounter3=1;}

}
blockcounter3=0;
}
int checkblock4()

{
for (i=4; i<=6; i++){
for (j=1; j<=3; j++){

counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;

if (array_[j]==1)
{
counter1++;
block=1;

}
if (array_[j]==2)
{
counter2++;
block=1;

}
if (array_[j]==3)
{
counter3++;
block=1;

}
if (array_[j]==4)
{
counter4++;
block=1;

}
if (array_[j]==5)
{
counter5++;
block=1;

}
if (array_[j]==6)
{
counter6++;
block=1;

}
if (array_[j]==7)
{
counter7++;
block=1;

}

if (array_[j]==8)
{
counter8++;
block=1;

}
if (array_[j]==9)
{
counter9++;
block=1;

}
}

if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
{

printf("invalid block 4 \n");
blockcounter4=1;}

}
blockcounter4=0;
}
int checkblock5()

{
for (i=4; i<=6; i++){
for (j=4; j<=6; j++){

counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;

if (array_[j]==1)
{
counter1++;
block=1;

}
if (array_[j]==2)
{
counter2++;
block=1;

}
if (array_[j]==3)
{
counter3++;
block=1;

}
if (array_[j]==4)
{
counter4++;
block=1;

}
if (array_[j]==5)
{
counter5++;
block=1;

}
if (array_[j]==6)
{
counter6++;
block=1;

}
if (array_[j]==7)
{
counter7++;
block=1;

}

if (array_[j]==8)
{
counter8++;
block=1;

}
if (array_[j]==9)
{
counter9++;
block=1;

}
}

if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
{

printf("invalid block 5 \n");
blockcounter5=1;}
}
blockcounter5=0;
}
int checkblock6()

{
for (i=4; i<=6; i++){
for (j=7; j<=9; j++){

counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;

if (array_[j]==1)
{
counter1++;
block=1;

}
if (array_[j]==2)
{
counter2++;
block=1;

}
if (array_[j]==3)
{
counter3++;
block=1;

}
if (array_[j]==4)
{
counter4++;
block=1;

}
if (array_[j]==5)
{
counter5++;
block=1;

}
if (array_[j]==6)
{
counter6++;
block=1;

}
if (array_[j]==7)
{
counter7++;
block=1;

}

if (array_[j]==8)
{
counter8++;
block=1;

}
if (array_[j]==9)
{
counter9++;
block=1;

}
}

if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
{printf("invalid block 6 \n");
blockcounter6=1;}
}
blockcounter6=0;
}
int checkblock7()

{
for (i=7; i<=9; i++){
for (j=1; j<=3; j++){

counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;

if (array_[j]==1)
{
counter1++;
block=1;

}
if (array_[j]==2)
{
counter2++;
block=1;

}
if (array_[j]==3)
{
counter3++;
block=1;

}
if (array_[j]==4)
{
counter4++;
block=1;

}
if (array_[j]==5)
{
counter5++;
block=1;

}
if (array_[j]==6)
{
counter6++;
block=1;

}
if (array_[j]==7)
{
counter7++;
block=1;

}

if (array_[j]==8)
{
counter8++;
block=1;

}
if (array_[j]==9)
{
counter9++;
block=1;

}
}

if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
{

printf("invalid block 7 \n");
blockcounter7=1;}

}
blockcounter7=0;
}

int checkblock8()

{
for (i=7; i<=9; i++){
for (j=4; j<=6; j++){

counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;

if (array_[j]==1)
{
counter1++;
block=1;

}
if (array_[j]==2)
{
counter2++;
block=1;

}
if (array_[j]==3)
{
counter3++;
block=1;

}
if (array_[j]==4)
{
counter4++;
block=1;

}
if (array_[j]==5)
{
counter5++;
block=1;

}
if (array_[j]==6)
{
counter6++;
block=1;

}
if (array_[j]==7)
{
counter7++;
block=1;

}

if (array_[j]==8)
{
counter8++;
block=1;

}
if (array_[j]==9)
{
counter9++;
block=1;

}
}

if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
{printf("invalid block 8 \n");
blockcounter8=1;}

}
blockcounter8=0;
}
int checkblock9()

{
for (i=7; i<=9; i++){
for (j=7; j<=9; j++){

counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;

if (array_[j]==1)
{
counter1++;
block=1;

}
if (array_[j]==2)
{
counter2++;
block=1;

}
if (array_[j]==3)
{
counter3++;
block=1;

}
if (array_[j]==4)
{
counter4++;
block=1;

}
if (array_[j]==5)
{
counter5++;
block=1;

}
if (array_[j]==6)
{
counter6++;
block=1;

}
if (array_[j]==7)
{
counter7++;
block=1;

}

if (array_[j]==8)
{
counter8++;
block=1;

}
if (array_[j]==9)
{
counter9++;
block=1;

}
}

if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
{printf("invalid block 9 \n");
blockcounter9=1;}

}
blockcounter9=0;
}
int main ()

{
printf("Type the Sudoku \n");
for (i=1;i<=9;i++)
for (j=1;j<=9;j++)
{
do {scanf("%d",&num);} while (num<0 && num>9);
array_[j]=num;
}

printarray();
checkrow();
checkcolumn();
checkblock1();
checkblock2();
checkblock3();
checkblock4();
checkblock5();
checkblock6();
checkblock7();
checkblock8();
checkblock9();

if (colcounter,rowcounter,blockcounter1,blockcounter2,blockcounter3,blockcounter4,blockcounter5,blockcounter6,blockcounter7,blockcounter8,blockcounter9=0)
printf("OK");

}


----------



## dBlisse

yo aint nobody going to read that

pastebin it

also, seeing new programmers makes me all giddy inside :3


----------



## patriotaki

Quote:


> Originally Posted by *dBlisse*
> 
> yo aint nobody going to read that
> 
> pastebin it
> 
> also, seeing new programmers makes me all giddy inside :3


http://pastebin.com/4juVhAeG

here you go


----------



## Plan9

Quote:


> Originally Posted by *patriotaki*
> 
> I need to make a program that scans 81 numbers (sudoku) and checks if the sudoku is correct. (it does not solve it!) . If it finds a mistake it needs to remmeber the row or column or block position.
> 
> for example the output will be :
> 
> Invalid rows: 1 2 8
> Invalid columns: 1
> Invalid blocks: 1 7
> 
> My code is really really messed up and long its just a quick solution. Any recommendaitons for improvement are appriciated!
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Spoiler: Code!
> 
> 
> 
> #include
> 
> int array [1000][1000];
> int colcounter,rowcounter,blockcounter1,blockcounter2,blockcounter3,blockcounter4,blockcounter5,blockcounter6,blockcounter7,blockcounter8,blockcounter9,block,col,row,tmp1,i,j,counter1,counter2,counter3,counter4,counter5,counter6,counter7,counter8,counter9,num;
> 
> int printarray()
> {
> for (i=1;i<=9;i++)
> printf(" %d %d %d %d %d %d %d %d %d \n", array[1], array[2], array[3],array[4], array[5], array[6],array[7], array[8], array[9]);
> }
> 
> int checkrow()
> 
> {
> for (i=1;i<=9;i++)
> {
> counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
> tmp1=0;
> }
> for (j=0;j<=9;j++) {
> 
> if (array_[j]==1) {
> counter1++;
> tmp1=i;
> row=tmp1;
> }
> if (array_[j]==2){
> counter2++;
> tmp1=i;
> row=tmp1;
> }
> if (array_[j]==3)
> {
> counter3++;
> tmp1=i;
> row=tmp1;
> }
> if (array_[j]==4)
> {
> counter4++;
> tmp1=i;
> row=tmp1;
> }
> if (array_[j]==5)
> {
> counter5++;
> tmp1=i;
> row=tmp1;
> }
> if (array_[j]==6)
> {
> counter6++;
> tmp1=i;
> row=tmp1;
> }
> if (array_[j]==7)
> {
> counter7++;
> tmp1=i;
> row=tmp1;
> }
> if (array_[j]==8)
> {
> counter8++;
> tmp1=i;
> row=tmp1;
> }
> if (array_[j]==9)
> {
> counter9++;
> tmp1=i;
> row=tmp1;
> }
> 
> }
> if ( (counter1>=2) || (counter2>=2) || (counter3>=2) || (counter4>=2) || (counter5>=2) || (counter6>=2) || (counter7>=2) || (counter8>=2) || (counter9>=2) )
> {
> printf("Invalid Rows : %d \n",row);
> rowcounter=1;}
> rowcounter=0;
> }
> 
> int checkcolumn()
> {
> for (j=1;j<=9;j++)
> {
> counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
> tmp1=0;
> }
> for (i=0;i<=9;i++) {
> 
> if (array_[j]==1) {
> counter1++;
> tmp1=j;
> col=tmp1;
> }
> if (array_[j]==2){
> counter2++;
> tmp1=j;
> col=tmp1;
> }
> if (array_[j]==3)
> {
> counter3++;
> tmp1=j;
> col=tmp1;
> }
> if (array_[j]==4)
> {
> counter4++;
> tmp1=j;
> col=tmp1;
> }
> if (array_[j]==5)
> {
> counter5++;
> tmp1=j;
> col=tmp1;
> }
> if (array_[j]==6)
> {
> counter6++;
> tmp1=j;
> col=tmp1;
> }
> if (array_[j]==7)
> {
> counter7++;
> tmp1=j;
> col=tmp1;
> }
> if (array_[j]==8)
> {
> counter8++;
> tmp1=j;
> col=tmp1;
> }
> if (array_[j]==9)
> {
> counter9++;
> tmp1=j;
> col=tmp1;
> }
> 
> }
> if ( (counter1>=2) || (counter2>=2) || (counter3>=2) || (counter4>=2) || (counter5>=2) || (counter6>=2) || (counter7>=2) || (counter8>=2) || (counter9>=2) )
> {printf("Invalid Columns : %d \n",col);
> colcounter=1;}
> colcounter=0;
> }
> 
> int checkblock1()
> 
> {
> for (i=1; i<=3; i++){
> for (j=1; j<=3; j++){
> 
> counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
> 
> if (array_[j]==1)
> {
> counter1++;
> block=1;
> 
> }
> if (array_[j]==2)
> {
> counter2++;
> block=1;
> 
> }
> if (array_[j]==3)
> {
> counter3++;
> block=1;
> 
> }
> if (array_[j]==4)
> {
> counter4++;
> block=1;
> 
> }
> if (array_[j]==5)
> {
> counter5++;
> block=1;
> 
> }
> if (array_[j]==6)
> {
> counter6++;
> block=1;
> 
> }
> if (array_[j]==7)
> {
> counter7++;
> block=1;
> 
> }
> 
> if (array_[j]==8)
> {
> counter8++;
> block=1;
> 
> }
> if (array_[j]==9)
> {
> counter9++;
> block=1;
> 
> }
> }
> 
> if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
> {
> 
> printf("invalid block 1 \n");
> blockcounter1=1;}
> 
> }
> blockcounter1=0;
> }
> 
> int checkblock2()
> 
> {
> for (i=1; i<=3; i++){
> for (j=4; j<=6; j++){
> 
> counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
> 
> if (array_[j]==1)
> {
> counter1++;
> block=1;
> 
> }
> if (array_[j]==2)
> {
> counter2++;
> block=1;
> 
> }
> if (array_[j]==3)
> {
> counter3++;
> block=1;
> 
> }
> if (array_[j]==4)
> {
> counter4++;
> block=1;
> 
> }
> if (array_[j]==5)
> {
> counter5++;
> block=1;
> 
> }
> if (array_[j]==6)
> {
> counter6++;
> block=1;
> 
> }
> if (array_[j]==7)
> {
> counter7++;
> block=1;
> 
> }
> 
> if (array_[j]==8)
> {
> counter8++;
> block=1;
> 
> }
> if (array_[j]==9)
> {
> counter9++;
> block=1;
> 
> }
> }
> 
> if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
> {printf("invalid block 2 \n");
> blockcounter2=1;}
> 
> }
> blockcounter2=0;
> }
> 
> int checkblock3()
> 
> {
> for (i=1; i<=3; i++){
> for (j=7; j<=9; j++){
> 
> counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
> 
> if (array_[j]==1)
> {
> counter1++;
> block=1;
> 
> }
> if (array_[j]==2)
> {
> counter2++;
> block=1;
> 
> }
> if (array_[j]==3)
> {
> counter3++;
> block=1;
> 
> }
> if (array_[j]==4)
> {
> counter4++;
> block=1;
> 
> }
> if (array_[j]==5)
> {
> counter5++;
> block=1;
> 
> }
> if (array_[j]==6)
> {
> counter6++;
> block=1;
> 
> }
> if (array_[j]==7)
> {
> counter7++;
> block=1;
> 
> }
> 
> if (array_[j]==8)
> {
> counter8++;
> block=1;
> 
> }
> if (array_[j]==9)
> {
> counter9++;
> block=1;
> 
> }
> }
> 
> if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
> {printf("invalid block 3 \n");
> blockcounter3=1;}
> 
> }
> blockcounter3=0;
> }
> int checkblock4()
> 
> {
> for (i=4; i<=6; i++){
> for (j=1; j<=3; j++){
> 
> counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
> 
> if (array_[j]==1)
> {
> counter1++;
> block=1;
> 
> }
> if (array_[j]==2)
> {
> counter2++;
> block=1;
> 
> }
> if (array_[j]==3)
> {
> counter3++;
> block=1;
> 
> }
> if (array_[j]==4)
> {
> counter4++;
> block=1;
> 
> }
> if (array_[j]==5)
> {
> counter5++;
> block=1;
> 
> }
> if (array_[j]==6)
> {
> counter6++;
> block=1;
> 
> }
> if (array_[j]==7)
> {
> counter7++;
> block=1;
> 
> }
> 
> if (array_[j]==8)
> {
> counter8++;
> block=1;
> 
> }
> if (array_[j]==9)
> {
> counter9++;
> block=1;
> 
> }
> }
> 
> if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
> {
> 
> printf("invalid block 4 \n");
> blockcounter4=1;}
> 
> }
> blockcounter4=0;
> }
> int checkblock5()
> 
> {
> for (i=4; i<=6; i++){
> for (j=4; j<=6; j++){
> 
> counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
> 
> if (array_[j]==1)
> {
> counter1++;
> block=1;
> 
> }
> if (array_[j]==2)
> {
> counter2++;
> block=1;
> 
> }
> if (array_[j]==3)
> {
> counter3++;
> block=1;
> 
> }
> if (array_[j]==4)
> {
> counter4++;
> block=1;
> 
> }
> if (array_[j]==5)
> {
> counter5++;
> block=1;
> 
> }
> if (array_[j]==6)
> {
> counter6++;
> block=1;
> 
> }
> if (array_[j]==7)
> {
> counter7++;
> block=1;
> 
> }
> 
> if (array_[j]==8)
> {
> counter8++;
> block=1;
> 
> }
> if (array_[j]==9)
> {
> counter9++;
> block=1;
> 
> }
> }
> 
> if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
> {
> 
> printf("invalid block 5 \n");
> blockcounter5=1;}
> }
> blockcounter5=0;
> }
> int checkblock6()
> 
> {
> for (i=4; i<=6; i++){
> for (j=7; j<=9; j++){
> 
> counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
> 
> if (array_[j]==1)
> {
> counter1++;
> block=1;
> 
> }
> if (array_[j]==2)
> {
> counter2++;
> block=1;
> 
> }
> if (array_[j]==3)
> {
> counter3++;
> block=1;
> 
> }
> if (array_[j]==4)
> {
> counter4++;
> block=1;
> 
> }
> if (array_[j]==5)
> {
> counter5++;
> block=1;
> 
> }
> if (array_[j]==6)
> {
> counter6++;
> block=1;
> 
> }
> if (array_[j]==7)
> {
> counter7++;
> block=1;
> 
> }
> 
> if (array_[j]==8)
> {
> counter8++;
> block=1;
> 
> }
> if (array_[j]==9)
> {
> counter9++;
> block=1;
> 
> }
> }
> 
> if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
> {printf("invalid block 6 \n");
> blockcounter6=1;}
> }
> blockcounter6=0;
> }
> int checkblock7()
> 
> {
> for (i=7; i<=9; i++){
> for (j=1; j<=3; j++){
> 
> counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
> 
> if (array_[j]==1)
> {
> counter1++;
> block=1;
> 
> }
> if (array_[j]==2)
> {
> counter2++;
> block=1;
> 
> }
> if (array_[j]==3)
> {
> counter3++;
> block=1;
> 
> }
> if (array_[j]==4)
> {
> counter4++;
> block=1;
> 
> }
> if (array_[j]==5)
> {
> counter5++;
> block=1;
> 
> }
> if (array_[j]==6)
> {
> counter6++;
> block=1;
> 
> }
> if (array_[j]==7)
> {
> counter7++;
> block=1;
> 
> }
> 
> if (array_[j]==8)
> {
> counter8++;
> block=1;
> 
> }
> if (array_[j]==9)
> {
> counter9++;
> block=1;
> 
> }
> }
> 
> if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
> {
> 
> printf("invalid block 7 \n");
> blockcounter7=1;}
> 
> }
> blockcounter7=0;
> }
> 
> int checkblock8()
> 
> {
> for (i=7; i<=9; i++){
> for (j=4; j<=6; j++){
> 
> counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
> 
> if (array_[j]==1)
> {
> counter1++;
> block=1;
> 
> }
> if (array_[j]==2)
> {
> counter2++;
> block=1;
> 
> }
> if (array_[j]==3)
> {
> counter3++;
> block=1;
> 
> }
> if (array_[j]==4)
> {
> counter4++;
> block=1;
> 
> }
> if (array_[j]==5)
> {
> counter5++;
> block=1;
> 
> }
> if (array_[j]==6)
> {
> counter6++;
> block=1;
> 
> }
> if (array_[j]==7)
> {
> counter7++;
> block=1;
> 
> }
> 
> if (array_[j]==8)
> {
> counter8++;
> block=1;
> 
> }
> if (array_[j]==9)
> {
> counter9++;
> block=1;
> 
> }
> }
> 
> if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
> {printf("invalid block 8 \n");
> blockcounter8=1;}
> 
> }
> blockcounter8=0;
> }
> int checkblock9()
> 
> {
> for (i=7; i<=9; i++){
> for (j=7; j<=9; j++){
> 
> counter1=0;counter2=0;counter3=0;counter4=0;counter5=0;counter6=0;counter7=0;counter8=0;counter9=0;
> 
> if (array_[j]==1)
> {
> counter1++;
> block=1;
> 
> }
> if (array_[j]==2)
> {
> counter2++;
> block=1;
> 
> }
> if (array_[j]==3)
> {
> counter3++;
> block=1;
> 
> }
> if (array_[j]==4)
> {
> counter4++;
> block=1;
> 
> }
> if (array_[j]==5)
> {
> counter5++;
> block=1;
> 
> }
> if (array_[j]==6)
> {
> counter6++;
> block=1;
> 
> }
> if (array_[j]==7)
> {
> counter7++;
> block=1;
> 
> }
> 
> if (array_[j]==8)
> {
> counter8++;
> block=1;
> 
> }
> if (array_[j]==9)
> {
> counter9++;
> block=1;
> 
> }
> }
> 
> if (counter1>=2 || counter2>=2 || counter3>=2 ||counter4>=2 ||counter5>=2 ||counter6>=2 || counter7>=2 ||counter8>=2 ||counter9>=2 )
> {printf("invalid block 9 \n");
> blockcounter9=1;}
> 
> }
> blockcounter9=0;
> }
> int main ()
> 
> {
> printf("Type the Sudoku \n");
> for (i=1;i<=9;i++)
> for (j=1;j<=9;j++)
> {
> do {scanf("%d",&num);} while (num<0 && num>9);
> array_[j]=num;
> }
> 
> printarray();
> checkrow();
> checkcolumn();
> checkblock1();
> checkblock2();
> checkblock3();
> checkblock4();
> checkblock5();
> checkblock6();
> checkblock7();
> checkblock8();
> checkblock9();
> 
> if (colcounter,rowcounter,blockcounter1,blockcounter2,blockcounter3,blockcounter4,blockcounter5,blockcounter6,blockcounter7,blockcounter8,blockcounter9=0)
> printf("OK");
> 
> }


I'll be honest with you, it's not great. The logic might be solid but your method doesn't demonstrate much awareness of control flow. Thankfully it shouldn't be too hard to clean up









First of all, instead of having long chains of _if_ blocks, you can use _switch case_ instead. eg

Code:



Code:


// old
if (array[j]==1)
{
    counter1++;
    block=1;
}

if (array[j]==2)
{
    counter2++;
    block=1;
}

if (array[j]==3)
{
    counter3++;
    block=1;
}

if (array[j]==4)
{
    counter4++;
    block=1;
}

// new
switch (array[j])
{
case 1:
    counter1++;
    break;
case 2:
    counter2++;
    break;
case 3:
    counter3++;
    break;
case 4:
    counter4++;
    break;
}
block = 1;

(though personally I'd turn _counter_ into an array and use a _for loop_)

Secondly, where you have a lot of code duplication because you're repeating functions / conditions but with different numbers; instead I'd recommend wrapping them in a _for loop_ using the incrementer from the _for loop_. eg

Code:



Code:


// old
checkblock1();
checkblock2();
checkblock3();
checkblock4();
checkblock5();
checkblock6();
checkblock7();
checkblock8();
checkblock9();

//new
for (i = 1; i < 10; i++) {
    checkblock(i);
}

Quote:


> Originally Posted by *patriotaki*
> 
> http://pastebin.com/4juVhAeG
> 
> here you go


I'd also recommend you spend a little care with the formatting of your code. While it seems like an annoyance now, you'll be massively grateful in the long run when you go back over old code


----------



## ABD EL HAMEED

So I wanna make a windows program in C++ with a GUI interface and I was wondering if I could use any of the .NET languages to design it,and how do I link between the main program and the GUI?


----------



## Plan9

You could write the performance dependant code in C++ and compile them to a DLL. Then make API calls to those DLLs in C# as you would with any other DLL (I've not written an C# so can't comment how that's done, but I should imagine it's possible)


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *Plan9*
> 
> You could write the performance dependant code in C++ and compile them to a DLL. Then make API calls to those DLLs in C# as you would with any other DLL (I've not written an C# so can't comment how that's done, but I should imagine it's possible)


Will try,thanks!


----------



## dBlisse

Quote:


> Originally Posted by *patriotaki*
> 
> http://pastebin.com/4juVhAeG
> 
> here you go


http://pastebin.com/zY2NVfb2

you can do row and column checks like that. infinitely easier to read imo.

my comments are wrong so ignore them lol.

block check is similar but a bit more complicated.


----------



## 21cage12

...want to reference a link of a page that i will create later, in my home page, so if i click on it it will open the link as if i have linked a different website. How do I make my life easier in doing this (organization, maybe), or how should it be done, before uploading it onto the net?


----------



## patriotaki

Quote:


> Originally Posted by *dBlisse*
> 
> http://pastebin.com/zY2NVfb2
> 
> you can do row and column checks like that. infinitely easier to read imo.
> 
> my comments are wrong so ignore them lol.
> 
> block check is similar but a bit more complicated.


i have worked my code and make it alot better!

http://pastebin.com/qfGTy0tB

have a look...some variables are in greeklish..if you need any help to understand tell me


----------



## Plan9

Quote:


> Originally Posted by *patriotaki*
> 
> i have worked my code and make it alot better!
> 
> http://pastebin.com/qfGTy0tB
> 
> have a look...some variables are in greeklish..if you need any help to understand tell me


From initial glancing I can see you're still chaining _if else_ blocks instead of using _switch case_.

Also, you've taken a step backwards with your use of functions as this whole program is just one long function. You need to think about your code like Lego bricks and decide which parts of code are fairly self contained or can be reused in a few places; then put those chunks of code in a function. That way your code starts to become self-documenting (ie smaller chunks of code will have a function name that briefly summarises it's purpose - so you can glance at your code and understand what each bit does).

Lastly the code formatting still isn't all that clean (though definitely better than before). However this might just be Pastebin breaking your indentation with tab to space conversion.

You're getting there though dude


----------



## dBlisse

Quote:


> Originally Posted by *patriotaki*
> 
> i have worked my code and make it alot better!
> 
> http://pastebin.com/qfGTy0tB
> 
> have a look...some variables are in greeklish..if you need any help to understand tell me


A bit better, but your code doesn't really check if the sudoku solution is valid, just if the user has written anything in array[][]

You can factor it even more though if you try

edit: procrastinating so i did it in a better but not optimal way http://pastebin.com/p5PHXnGe would prefer structs and malloc might be too much. honestly i dont think there's any way to explain what improvements you can do without actually showing you.


----------



## andyroo89

Hey guys, While back I used listview to load connect clients data on my app, and I am wondering if I can switch it to expandable listview instead? can expandable listview be used on arrayadapter? I tried googling but it kept showing me listview not expandable.


----------



## ABD EL HAMEED

How can I import images using C++ so I can edit them?I've asked google but I didn't get any specific answers. ._.


----------



## poroboszcz

You can load images just as any other files with fstream, you then get binary data which you need to interpret. There are many libraries which will make it easy for you, like libjpg or libpng. You'll generally end up with an array of pixel color values.

Now what do you mean by editing? Do you want to apply some filters to the image? Or do you want to draw on top of the image? In the first case you may be interested in looking at OpenCV, which comes with both loaders and a huge collection of algorithms for processing images (e.g. blur, sharpen, feature detection etc.). In the second case I'd suggest looking at Qt, although it's not going to be a trivial task.


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *poroboszcz*
> 
> You can load images just as any other files with fstream, you then get binary data which you need to interpret. There are many libraries which will make it easy for you, like libjpg or libpng. You'll generally end up with an array of pixel color values.
> 
> Now what do you mean by editing? Do you want to apply some filters to the image? Or do you want to draw on top of the image? In the first case you may be interested in looking at OpenCV, which comes with both loaders and a huge collection of algorithms for processing images (e.g. blur, sharpen, feature detection etc.). In the second case I'd suggest looking at Qt, although it's not going to be a trivial task.


Some filter,rotating images,cropping, and re-size them and then compile the thing as a DLL like plan9 said and use C# for the GUI stuff.


----------



## dBlisse

http://www.codecodex.com/wiki/Read_a_file_into_a_byte_array

your filters and rotations are just transformations on bytes


----------



## ABD EL HAMEED

So all I need to do is open it as a binary file using fstream and then use a library like libpng or libjpg to turn the raw binary data to an array full of pixels and now I can do operations on them?


----------



## willll162904

Hey guys  I've been doing Java lessons on youtube for a little while and im trying to think about my first program I want to code. I'm taking geometry in high school right now and we're doing conditionals and biconditionals and I was thinking I could link my programming with my math class. Using if and else statements could I test a conditional and it's inverse then have the program output the biconditional if it's possible, and output a "not reversible" text line if it doesn't work? I was thinking using a scanner to let the user input the conditional, but im not sure how to have the conditional and inverse tested. Obviously the "not reversible" text could be output using an else block of code. Right?


----------



## Ferrari8608

I don't know anything about Java, but I do know of a great site for getting mathematical problems to solve with programming. Check out Project Euler.


----------



## willll162904

After playing around with it for a bit I've made some ground, and encountered some problems. I need to use a scanner to assign 2 variables that are assigned through user input. The two variables are the conditional, and converse. I want to have the program ask for a TRUE conditional from the user, assign that to a cond variable, and then ask for the converse, and assign that to variable converse. I initially wanted the program to create the converse on it's own, but I think that would be too difficult for me to do. Then I would want the program to test the conditional and converse for truth value, which though I would like the program to do, but not sure if that would work. I could just prompt the user to give a true or false for each, and save that input in a boolean variable, then I want it to output either an else statement saying that the conditional is "not reversible" or output the correct biconditional. That's another issue, how would the program take the conditional and converse, then turn it into a biconditoinal. Thanks for help in advanced


----------



## patriotaki

any help for my situation ?


----------



## tompsonn

Quote:


> Originally Posted by *patriotaki*
> 
> any help for my situation ?


I felt your post might be better in its own thread: http://www.overclock.net/t/1527828/understanding-tower-of-hanoi-code/0_20


----------



## yawa77

Great Thread! I'm doing college later in life. Taking "Advanced" Java. We are made to use Netbeans. I am looking into Python in my off time though. I wanted to do C++ but they only offer it during certain semesters.


----------



## xlink

Any data geeks here? I'm trying to get good with R and Python.


----------



## andyroo89

Quote:


> Originally Posted by *xlink*
> 
> Any data geeks here? I'm trying to get good with R and Python.


I have done some python, not too familiar with ruby, though. What do you need help with?


----------



## Ferrari8608

I'm pretty bored. Ask me anything Python related.

Code unrelated, just something my boredom produced.

Code:



Code:


import random

class SchroedingerCat(object):
    def __init__(self, a_box):
        self.the_box = a_box
        _possible_states = ('Dead', 'Alive')
        self.state = random.choice(_possible_states)

    def observe(self):
        if self in self.the_box:  # Useless check, cats always get in a box.
            return self.state

if __name__ == '__main__':
    box = list()
    cat = SchroedingerCat(box)

    box.append(cat)  # Cats have a hard
    box.remove(cat)  # time making up
    box.append(cat)  # their minds with boxes.

    # Moment of truth time
    cat_state = cat.observe()
    print(cat_state)


----------



## Plan9

Quote:


> Originally Posted by *Ferrari8608*
> 
> I'm pretty bored. Ask me anything Python related.


What's the largest mammal eaten by pythons?


----------



## Ferrari8608

The largest? Hmm...

Code:



Code:


max('mammal eaten')

It's 't'

Apparently that's bigger than an antelope.


----------



## NameUnknown

Does anyone in here know SNMP well? I want to replace all my little apps and batch files I have with a script or process that runs on a schedule via Task Scheduler. I want it to run a ping test on every IP and poll what is there if there is a response. Going to make that my next little project.


----------



## andyroo89

Hopefully someone can help me with this I have been looking for an answer for a long time, and I haven't found the answer I am looking for OR I have given the correct answer, and thought it wasn't what I expect.

I am wanting to make android app that uses tcp between two android phones. Basically client / server where my tablet is the server and my phone is the client.

I am wanting to have my tablet to be "command" server, I want to prank my friends by putting client app on their phone and make their phones go off whenever I "command" it from my tablet, or make it vibrate or ring. Now, all I have seen is these tutorials here

http://systembash.com/content/a-simple-java-tcp-server-and-tcp-client/

basically it closes the connection as soon as it connects, BUT I have to removing the "close socket" command to keep the connection alive.

I have it to where I can list them with listview, but whenever I click on the row idk how I can send "commands" to the phone like

incoming pseudo code

Tablet send command "vibrate"

android phone receive command "vibrate"

Hopefully someone can help me out all the tutorials out there haven't helped me achieve what I want.


----------



## ABD EL HAMEED

So I'm getting a "Error 2 error C2676: binary '*' : 'matrix' does not define this operator or a conversion to a type acceptable to the predefined operator" in this line:

Code:



Code:


return (aMatrix * (*this));

In this function:

Code:



Code:


Vector operator *(matrix &aMatrix) {
                return (aMatrix * (*this));
        }

In the beginning I thought maybe something was wrong with the "*" operator function but I couldn't find any problems with it,here it is:

Code:



Code:


Vector operator *(Vector &aVector) {
                if (aVector.Size() != cols)
                        return NULL;
                Vector result;
                for (int i = 0; i < cols; ++i)
                        result.push_back(theMatrix.at(i) * aVector);
                return result;
        }

Here's the whole thing if you want to see it:


Spoiler: Warning: Spoiler!



Code:



Code:


#include <iostream>
#include <vector>

using namespace std;

struct matrix;

struct Vector{
private:
        vector <float> rows;
        int size;
public:
        Vector() : size(0) {}
        Vector(int theSize) : size(theSize) { append(theSize); }
        void append(int theSize) {
                size = theSize;
                for (int i = 0; i < theSize; ++i){
                        float currIndex;
                        cin >> currIndex;
                        rows.push_back(currIndex);
                }
        }
        void push_back(float num) { rows.push_back(num); ++size; }
        int Size() { return size; }
        void operator =(Vector &aVector) {
                rows = aVector.theVector();
        }
        float at(int index) {
                if (index >= size)
                        return NULL;
                return rows.at(index);
        }
        float operator *(Vector &aVector) {
                if (aVector.Size() != size)
                        return NULL;
                float result = 0;
                for (int i = 0; i < size; ++i)
                        result += (rows.at(i) * aVector.at(i));
                return result;
        }
        Vector operator *(float factor) {
                Vector result;
                for (int i = 0; i < rows.size(); ++i)
                        result.push_back(rows.at(i) * factor);
                return result;
        }
        Vector operator *(matrix &aMatrix) {
                return (aMatrix * (*this));
        }
        Vector operator +(Vector &aVector) {
                if (aVector.Size() != size)
                        return NULL;
                Vector result;
                for (int i = 0; i < size; ++i)
                        result.push_back(rows.at(i) + aVector.at(i));
                return result;
        }
        Vector operator -(Vector &aVector) {
                if (aVector.Size() != size)
                        return NULL;
                Vector result;
                for (int i = 0; i < size; ++i)
                        result.push_back(rows.at(i) - aVector.at(i));
                return result;
        }
        Vector operator /(float divisor) {
                Vector result;
                for (int i = 0; i < rows.size(); ++i)
                        result.push_back(rows.at(i) / divisor);
                return result;
        }
        vector <float> theVector() {
                return rows;
        }
        void clear() {
                rows.clear();
        }
};

struct matrix{
private:
        int cols, rows;
        vector <Vector> theMatrix;
public:
        matrix() : cols(0), rows(0) {}
        matrix(int num1, int num2) { append(num1, num2); }
        void append(int num1, int num2) {
                theMatrix.clear();
                rows = num1;
                cols = num2;
                for (int i = 0; i < rows; ++i){
                        Vector currRow;
                        currRow.append(cols);
                        theMatrix.push_back(currRow);
                        currRow.clear();
                }
        }
        void interchange(int row1, int row2) {
                if (row1 > rows && row2 > rows)
                        return;
                swap(theMatrix.at(row1 - 1), theMatrix.at(row2 - 1));
        }
        Vector operator *(Vector &aVector) {
                if (aVector.Size() != cols)
                        return NULL;
                Vector result;
                for (int i = 0; i < cols; ++i)
                        result.push_back(theMatrix.at(i) * aVector);
                return result;
        }
        void operator *(float factor) {
                for (int i = 0; i < rows; ++i)
                        theMatrix.at(i) = theMatrix.at(i) * factor;
        }
        float at(int row, int col) {
                if (row >= rows || col >= cols)
                        return NULL;
                return theMatrix.at(row).at(col);
        }
        Vector at(int row) {
                if (row >= rows)
                        return NULL;
                return theMatrix.at(row);
        }
        void clear() { theMatrix.clear(); }
        int Rows() { return rows; }
        int Cols() { return cols; }
};





Can anyone see the problem?

Edit:I fixed it.turns out the matrix's 'operator *' needs to be at least declared before I use it,so I declared the Vector's 'operator *' function in the class definition and then defined it AFTER the matrix class difinition.Hope.Hope this helps.


----------



## twerk

Hey guys, I've got a bit stuck with Java... I created a new thread because it would be a bit much for here.
http://www.overclock.net/t/1534026/beginner-java-programmer-need-help-debugging/0_100

If any gurus want to help it would be greatly appreciated.


----------



## dBlisse

Quote:


> Originally Posted by *ABD EL HAMEED*
> 
> Edit:I fixed it.turns out the matrix's 'operator *' needs to be at least defined before I use it,so I defined the Vector's 'operator *' function in the class deceleration and then declared it AFTER the matrix class deceleration.Hope this helps.


to nitpick but you have the words backwards, you have to declare the operator* before it's used, and you can define it later in the compilation unit.


----------



## ABD EL HAMEED

Quote:


> Originally Posted by *dBlisse*
> 
> to nitpick but you have the words backwards, you have to declare the operator* before it's used, and you can define it later in the compilation unit.


Sorry lol,sometimes I just can't think straight


----------



## dBlisse

np, that's like every other week for me


----------



## 21cage12

hi everyone,
using notepad++ I have made couple of pages (home, etc) I want all my navs including "home" to be selected when I visit it or click on it but I can't seem to get it to work, any help will be great.

Many thanks


----------



## Plan9

Quote:


> Originally Posted by *21cage12*
> 
> hi everyone,
> using notepad++ I have made couple of pages (home, etc) I want all my navs including "home" to be selected when I visit it or click on it but I can't seem to get it to work, any help will be great.
> 
> Many thanks


You've been wonderfully specific there









Can you post code and describe exactly what happens when "It [doesn't] work" please.


----------



## 21cage12

I meant I don't have the correct code for it to work from css. That's where am stuck, Have been looking for answers from google but those codes are unreadable, will do with simple and straight forward codes to control it from css.


----------



## Plan9

Quote:


> Originally Posted by *21cage12*
> 
> I meant I don't have the correct code for it to work from css. That's where am stuck, Have been looking for answers from google but those codes are unreadable, will do with simple and straight forward codes to control it from css.


That's still a massively vague description of the error and you've still not posted any code.

Without being psychic, it sounds like an issue with relative paths. But working in IT, you should be more familiar than most about the need for precision when tracking down a fault. So get some detail up and someone will be able to assist better


----------



## mllrkllr88

Have you guys played with the C4droid IDE for android yet? I just got it today and its is pretty comprehensive. Only played around with .h and .cpp files but I think it can handle a decent range of file types. The nice part is that I can work on files on my desktop, and sync them on my android device. Its worth checking out....

Also, someone should make a signature for this lounge.


----------



## Microx256

Quote:


> Originally Posted by *mllrkllr88*
> 
> Have you guys played with the C4droid IDE for android yet? I just got it today and its is pretty comprehensive. Only played around with .h and .cpp files but I think it can handle a decent range of file types. The nice part is that I can work on files on my desktop, and sync them on my android device. Its worth checking out....
> 
> Also, someone should make a signature for this lounge.


I have o/ the SDL plugin for C4droid is also worth checking out, if you like to do graphical things with SDL.







The C4droid on its own is quite nice as well, I tend to write short applications on-the-go with my tablet (eg. on train trips etc)


----------



## mllrkllr88

Quote:


> Originally Posted by *Microx256*
> 
> I have o/ the SDL plugin for C4droid is also worth checking out, if you like to do graphical things with SDL.
> 
> 
> 
> 
> 
> 
> 
> The C4droid on its own is quite nice as well, I tend to write short applications on-the-go with my tablet (eg. on train trips etc)


I didn't know about that, I will have to check it out. I am using the GCC plugin for C4droid which allows you to use a bunch of common #include's, like iostream and cstring, among other things.


----------



## Microx256

Quote:


> Originally Posted by *mllrkllr88*
> 
> Quote:
> 
> 
> 
> Originally Posted by *Microx256*
> 
> I have o/ the SDL plugin for C4droid is also worth checking out, if you like to do graphical things with SDL.
> 
> 
> 
> 
> 
> 
> 
> The C4droid on its own is quite nice as well, I tend to write short applications on-the-go with my tablet (eg. on train trips etc)
> 
> 
> 
> I didn't know about that, I will have to check it out. I am using the GCC plugin for C4droid which allows you to use a bunch of common #include's, like iostream and cstring, among other things.
Click to expand...

Yeah, the GCC plugin is kind of "mandatory" if you want to do anything "advanced". There are also a bunch of other plugins available, though I haven't used others, I think.


----------



## patriotaki

hey guys can someone help me out ?

Hello all i have a new assignment for university called the subtraction game.
Its a human vs computer game. You just enter the number you want to start subtracting and the maximum number you should subtract with.

For example : If you enter the number (6) to start with and the maximum number to subtract with (2) You have 2 options either subtract with 1 or with 2. The one who gets in 0 or under 0 first wins!

My problem is that when the computer wins the program asks the player a number to subtract .. and in the end the program shows two winners

strnum = starting number , max= maximum number to substract with. Im also using the library the university provides us here is the link to download it if you want : http://www.filedropper.com/stdlibfacilities

here is my code :


Spoiler: Warning: Spoiler!



Code:



Code:


#include "std_lib_facilities.h";

void check1(int strnum,int c)
{

        if (strnum <= 0  && c == 1){
                cout << "computer won!";
                c = 2;
        }

}

void check2(int strnum,int c)
{

        if (strnum <= 0 && c == 0){
                cout << "player won!";
                c = 2;
        }

}

int main()

{

        int c, y;
        int max,strnum;
        c = 1;
        cin >> strnum;
        cin >> max;

        while (max <= 0){
                cin >> max;
        }

        while (strnum > 0 && c != 2)

        {

                if (c == 1){
                        int x = rand() % max + 1;
                        cout << "computer wants to subtract with " << x << endl;
                        strnum -= x;
                        cout << "the new total is : " << strnum << endl;
                        cout << "\n";
                        check1(strnum,c);
                        c = 0;
                }

                 if (c==0) {
                        cout << "enter number to subtract between 1 - " << max << endl;
                        cin >> y;
                        while (y < 1 || y > max){
                                cout << "Invalid number, please enter a number between 1 - " << max << endl;
                                cin >> y;
                        }

                        strnum -= y;
                        cout << "the new total is : " << strnum << endl;
                        cout << "\n";
                        check2(strnum,c);
                        c = 1;
                 }
                 if (c == 2)
                         keep_window_open();
        }

}


----------



## patriotaki

i think i fixed it lol


----------



## andyroo89

anyone willing to help me with my piece of code in java?
I made a android app (as the client) to connect to my linux server. I ave my android app send pre configured shell commands (ls, uptime, who, etc.. tc.. my android sends the string just fine, but I am wanting my server to send the output back to my android device (its 1 am here as I am writing this with my eyes closed since I am so tired. I have provided both pasties as my attempt to have client/server talk, and the toast message is only temporary.

server:
http://pastebin.com/Fmj99nup

Client:
http://pastebin.com/tYAnPA8F

I only put verose commands for different reasons, mostly to see if piece of code is able to get acess.


----------



## dBlisse

Does shellprocess ever actually write any data? If it doesn't then nothing's going to get sent. Replace it with a paragraph in aa stringreader or something and try again.


----------



## Plan9

If I had to guess, I'd say it was down to the way how your passing your arguments to _exec_. A quick google through up the following SO which recommended using _process builder_ instead:

Code:



Code:


import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Shell {

    /** Returns null if it failed for some reason.
     */
    public static ArrayList<String> command(final String cmdline,
    final String directory) {
        try {
            Process process = 
                new ProcessBuilder(new String[] {"bash", "-c", cmdline})
                    .redirectErrorStream(true)
                    .directory(new File(directory))
                    .start();

            ArrayList<String> output = new ArrayList<String>();
            BufferedReader br = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
            String line = null;
            while ( (line = br.readLine()) != null )
                output.add(line);

            //There should really be a timeout here.
            if (0 != process.waitFor())
                return null;

            return output;

        } catch (Exception e) {
            //Warning: doing this is no good in high quality applications.
            //Instead, present appropriate error messages to the user.
            //But it's perfectly fine for prototyping.

            return null;
        }
    }

    public static void main(String[] args) {
        test("which bash");

        test("find . -type f -printf '%[email protected]\\\\t%p\\\\n' "
            + "| sort -n | cut -f 2- | "
            + "sed -e 's/ /\\\\\\\\ /g' | xargs ls -halt");

    }

    static void test(String cmdline) {
        ArrayList<String> output = command(cmdline, ".");
        if (null == output)
            System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
        else
            for (String line : output)
                System.out.println(line);

    }
}

source: https://stackoverflow.com/questions/1410741/want-to-invoke-a-linux-shell-command-from-java

You shouldn't need quite as much boiler plate code as that because you're just wanting to execute command line programs rather than a full POSIX shell, but that should give you some code to work from.


----------



## andyroo89

Quote:


> Originally Posted by *dBlisse*
> 
> Does shellprocess ever actually write any data? If it doesn't then nothing's going to get sent. Replace it with a paragraph in aa stringreader or something and try again.


Thats what I was wondering, too. In the code I read the inputstream from "shellprocess" and I then have it in the while loop, and you see "s"? I have that println in the terminal (when I have it open on my end) and it outputs shellprocess command.

Thanks plan9 I will see if I can get this working.


----------



## andyroo89

I cannot understand how hard it is for client side of my app to receive a response from the server. I mean this is infuriating.


----------



## Plan9

Quote:


> Originally Posted by *andyroo89*
> 
> I cannot understand how hard it is for client side of my app to receive a response from the server. I mean this is infuriating.


If you zip up your client and server project files and host them somewhere (or dump them on a git repository) then I'll take a look if and when I next get time









(if you need somewhere to host them to, I can give you a temporary SFTP login)


----------



## jakethesnake438

Wow, just discovered this place!

I am a mobile app developer (iOS/Android) working for a medium sized firm in NZ.
In my spare time I am currently working on a client application for MSI Afterburner remote server in OSX so while I am gaming I can have my laptop showing me performance info.
Also working on a mobile game server browser
I also do some C# stuff

I am always interested in cool ideas, so hit me up


----------



## dBlisse

If it's not school or work stuff, host it on Github. You should be using it anyways to track progress.


----------



## andyroo89

Quote:


> Originally Posted by *Plan9*
> 
> If you zip up your client and server project files and host them somewhere (or dump them on a git repository) then I'll take a look if and when I next get time
> 
> 
> 
> 
> 
> 
> 
> 
> 
> (if you need somewhere to host them to, I can give you a temporary SFTP login)


You guys make it sound so easy, I am getting errors that I cant publish my stuff. Nothing wants to work for me.

edit; Deleted the repos and started over.


----------



## Ferrari8608

Quote:


> Originally Posted by *andyroo89*
> 
> edit; Deleted the repos and started over.


I suppose that's one way to solve all the problems.


----------



## Plan9

Quote:


> Originally Posted by *dBlisse*
> 
> If it's not school or work stuff, host it on Github. You should be using it anyways to track progress.


I disagree with "should". Version control is a great tool, but git isn't the only solution out there and github isn't the only git solution.


----------



## dBlisse

Regardless of what you think, Github is the defacto standard and that is why I said Github.


----------



## Plan9

Quote:


> Originally Posted by *dBlisse*
> 
> Regardless of what you think, Github is the defacto standard and that is why I said Github.


It's not even the de facto standard. Plenty or organizations use their own hosted solutions and many FOSS projects don't even use git (Mercual and SVN being two popular competitors). Heck, even Linux, the project that git was invented for, doesn't use github.

Github is popular amongst freelance developers but to argue it's a necessity or the de facto really demonstrates a lack of experience with version control and/or professionally managed code repositories. Sorry, but it's just a popular (and admitted well polished) product, but nothing more.


----------



## dBlisse

You're really trying hard to start an argument here... Like you said, Github is the most popular choice among anyone that's not a company, i.e. git and Github is the defacto standard to host your random stuff...

And your subtle jab at my professional experience is very... unprofessional... I work at Microsoft and we use all of git/tfs/sd... and I've worked at 500-people companies that used Github primarily and another that rolled their own git server... why was that necessary.

I don't see why you seem to have a problem with Github or git being the most popular tools. They're easy to get set up with, easy to find documentation and help, and the benefits/advantages versus the other systems for users and small groups is very clear.


----------



## Plan9

Well hopefully you'll then learn from this and stop using absolutes to recommend a personal preference from a crowded industry.

I have no issue with the github suggestion. But I do take issue when people say you *should* be using a proprietary front end for an open source project over the thousands of other solutions on the market that all do exactly the same thing (and many of which are not proprietary)

It's all about choices and not blindly supporting monopolies because we're too lazy to try anything else.


----------



## dBlisse

lol i can't even


----------



## tompsonn

Take it easy guys


----------



## Ferrari8608

Bitbucket is another name that also comes to mind, though I've never used it. Then there's GitLab, which has acquired Gitorious. Github is easily the biggest name, but there are many others to consider.


----------



## Plan9

Quote:


> Originally Posted by *dBlisse*
> 
> lol i can't even


Yeah sorry. This is just the 3rd time this week I've read someone talk github as if anyone that uses anything other than that is an oldball goth who just accidentally wondered into a sports bar. I just get a little sick of it to be honest as github is only an abstraction of git, and not even _the_ only web-based abstraction. Plus many of the open source projects I work with don't use git at all, let alone the github front end.

Don't get me wrong, I do actually quite like github. But considering I've never needed to use it for either my professional career (and neither have you, by the sounds of it) nor my freelancing work, it seems quite disingenuous to argue that all developers *should* be using github specifically.

I guess I just wish people would learn to promote the use of tools rather than products. Tools largely remain the same, but products can come and go from favour (just look at how Sourceforge has ended up these days).


----------



## yawa77

Quote:


> Originally Posted by *Plan9*
> 
> Yeah sorry. This is just the 3rd time this week I've read someone talk github as if anyone that uses anything other than that is an oldball goth who just accidentally wondered into a sports bar. I just get a little sick of it to be honest as github is only an abstraction of git, and not even _the_ only web-based abstraction. Plus many of the open source projects I work with don't use git at all, let alone the github front end.
> 
> Don't get me wrong, I do actually quite like github. But considering I've never needed to use it for either my professional career (and neither have you, by the sounds of it) nor my freelancing work, it seems quite disingenuous to argue that all developers *should* be using github specifically.
> 
> I guess I just wish people would learn to promote the use of tools rather than products. Tools largely remain the same, but products can come and go from favour (just look at how Sourceforge has ended up these days).


You had me at sports bar LMMFFAO!!!


----------



## Plan9

Hahaha. I was originally going to say "village pub" but then wondered if that's one of those quaintly British things so opted for "sports bar" instead


----------



## hajile

Atlassian (bitbucket) allows you to create closed-source repositories for free (and costs less when you only have a couple dozen developers). That puts them far above github IMHO. JIRA and their other professional-grade tools make them a far better choice if you need to grow as well (and you can self-host these if you need/want). Another big issue with github in my experience is that their catch-all issue idea becomes very unwieldy when projects grow.


----------



## dBlisse

you took it so far out of line and context it's ridiculous. it was an offhand suggestion, so stop trying to "levitate" above me. are you seriously arguing with my use of the word "should"? really?

you're not an idiot. stop treating me like i'm some dumb hippie who doesn't know what he's doing so he only uses the FOTM tools. jeez. and don't elevate yourself above people like "we should use tools and not products, that's how I think and you are wrong blisse". i understand the ideology but the nerve of talking to me like that is insane.

sorry for arguing but how can I not be annoyed here by some guy jumping on to my one line comment asking someone else to host their content so we can see their code.


----------



## Plan9

Quote:


> Originally Posted by *dBlisse*
> 
> you took it so far out of line and context it's ridiculous. it was an offhand suggestion, so stop trying to "levitate" above me. are you seriously arguing with my use of the word "should"? really?
> 
> you're not an idiot. stop treating me like i'm some dumb hippie who doesn't know what he's doing so he only uses the FOTM tools. jeez. and don't elevate yourself above people like "we should use tools and not products, that's how I think and you are wrong blisse". i understand the ideology but the nerve of talking to me like that is insane.
> 
> sorry for arguing but how can I not be annoyed here by some guy jumping on to my one line comment asking someone else to host their content so we can see their code.


I'm not trying to levitate above you. My point was sincere, albeit inappropriately phrased (hence the apology at the start of my previous post)


----------



## dBlisse

oops sorry, didn't see your earlier sorry somehow... thanks, just got a bit angry there


----------



## Plan9

Quote:


> Originally Posted by *dBlisse*
> 
> oops sorry, didn't see your earlier sorry somehow... thanks, just got a bit angry there


Understandable really


----------



## geoxile

I'm working on a little image viewer that operates heavily on tags, if anyone has used a booru (like safebooru) you'll get the idea. Each image stores the tags that it has but I can't decide how to store them. When I view an image I want the tags to be on the side in alphabetic order, but I also want to be able to search by multiple tags. What data structure should I be using here? I thought Java's standard hashmap at first but I would have to sort the tags every time an image is viewed, though it could be faster to search. On the other hand an array could be presorted (sort only when tags are added) but it would be longer to search.

I'm thinking about an array of linked lists or something. With the first character of each tag being hashed to a unique spot on the array. It could be presorted and could speed up search by tag. Any other ideas?


----------



## Sanmayce

Quote:


> Originally Posted by *geoxile*
> 
> ... but I also want to be able to search by multiple tags. What data structure should I be using here?


An interesting and often occurring task you are wrestling with.
The ugliest way to do it is to presort every time, you can expand the idea of "hashing" the first character to 2 but this also is not fast.
Since you mention the need for multiple tags why don't you "rip" all the tags (or tag-fields) as words (or numbers for that matter) and put them into B-tree or Binary tree!?

I tried that approach in my word-ripping tool *Leprechaun* while enforcing all the B-TREE to be on external memory (a single file).
If you are interested you can copy the corresponding sections from the C source at: http://www.sanmayce.com/MSKR/
That way you can access 100 million tags with just 4 READ SEEKS.

The downside of BTREE is its relative complexity, I still wonder is there a better/easier way to search into multi-millions of records/tags/strings!


----------



## Sanmayce

Just saw a single instance for TAGS on http://safebooru.org/index.php?page=post&s=view&id=1457264

Code:



Code:


Tags

    blush 237318
    braids 507
    brown hair 226620
    idolmaster 33402
    idolmaster cinderella girls 13312
    long hair 522306
    ninomiya asuka 45
    purple eyes 95322

As I thought it is a matter of word ripping, you need just to rip the tags as n-grams, that is, as phrases. Each phrase is n words long, for example:
*idolmaster cinderella girls*
becomes the 3-gram *idolmaster_cinderella_girls* or a single sub-tag or tag-field, in fact a element in the BTREE.
On second thought, if images are only few millions (their tags fittable in RAM) maybe BTREE is an overkill.


----------



## geoxile

So just put the entire tag in B-Tree? Would in-order traversal always give alphabetic ordering?


----------



## andyroo89

Ok I was searching in this thread for my post, but idk what happen to it.

In android I have it create a new thread when a user connects, that way each user is on its own thread. How can I choose which user to interact with since its in its own thread?


----------



## Microx256

Quote:


> Originally Posted by *andyroo89*
> 
> Ok I was searching in this thread for my post, but idk what happen to it.
> 
> In android I have it create a new thread when a user connects, that way each user is on its own thread. How can I choose which user to interact with since its in its own thread?


Firstly, you should (if not already) have references to each thread, save them in an List for example. Then, you can iterate through the List to find the thread serving the specific user you want. Alternatively, if you have an identifier for each user, and know what identifier you should interact with, a Map would be a better choice than a List, there the Key is the identifier, and the Value is the Thread where the user with the said identifier is "connected to". I can give more specific examples if you have some code to share for the relevant parts (the 'connecting' part, thread creation, where and how you would like to interact with a user etc)


----------



## Sanmayce

Quote:


> Originally Posted by *geoxile*
> 
> So just put the entire tag in B-Tree? Would in-order traversal always give alphabetic ordering?


In your case not so, I guess.
And yes B-tree's traversals are no different from Binary-Tree. However I didn't write it to traverse in-orderly despite being most wanted type of traversal.

This kind of search interests me as well, but I haven't looked it thoroughly, how exactly do you want to manage the tags.
As I see on the site they have functionality different than my first guess, for example http://safebooru.org/index.php?page=post&s=view&id=564543
My first thought was of converging the tags into unique results/hits. The tags describing this picture result in one hit. But this is not an unique situation it just happens that this picture is tagged as *girl_in_bottle* and having 1 appearance.

Code:



Code:


Tags

    3d 880
    against glass 248
    ahoge 49812
    alternate hairstyle 13863
    animal ears 90091
    ascot 22430
    bottle 5889
    bottle meme (pixiv) 25
    brown eyes 130521
    cat ears 37807
    cat tail 20168
    chibi 51008
    child 15132
    girl in a bottle 16
[B]    girl in bottle 1[/B]
    green hair 80687
    in bottle 78
    in container 2146
    kazami yuuka 9080
    kemonomimi mode 8001
    long hair 522431
    plaid 15688
    plaid skirt 10646
    plaid vest 3826
    shii (cocoa) 35
    simple background 86256
    skirt 206586
    skirt set 12178
    solo 527099
    tail 70356
    touhou 349369
    very long hair 71512
    youkai 1791

When entering in search field *girl_in_a_bottle green_hair*, the hits are 3 http://safebooru.org/index.php?page=post&s=list&tags=girl_in_a_bottle+green_hair+
When entering in search field *girl_in_a_bottle green_hair barefoot*, the hit is 1 http://safebooru.org/index.php?page=post&s=list&tags=girl_in_a_bottle+green_hair+barefoot

Now after seeing and entering all the tags *absurdres ahoge bad_id bare_shoulders barefoot bottle girl_in_a_bottle green_eyes green_hair hatsune_miku highres in_bottle in_container kinoko0302 long_hair open_mouth simple_background solo twintails very_long_hair vocaloid* describing the last hit the search engine gives it as it should http://safebooru.org/index.php?page=post&s=list&tags=absurdres+ahoge+bad_id+bare_shoulders+barefoot+bottle+girl_in_a_bottle+green_eyes+green_hair+hatsune_miku+highres+in_bottle+in_container+kinoko0302+long_hair+open_mouth+simple_background+solo+twintails+very_long_hair+vocaloid

The thing that confused me is the idea of having an unique string (a sequence of tags) mapped onto something-or-nothing, that way If I had to find a picture matching all the above tags I would know after 3-4 external RAM seeks/fetches that such a match exists-or-not.

Do you want the same functionality as the site or you want to search into tags differently. tell me more and I will give some thoughts.
Also, I didn't write the deletion - it is a bit complicated, in short, B-tree is not your case, Binary-tree is more useful codewise.
Personally I hate databases (which is the case with above site), they are easy to feed/retrieve but dumbify your vision and future plans.


----------



## Plan9

Would it not be simpler to throw this data into a sqlite database:

Code:



Code:


table: pictures
======

picture_id:     path:    (other metadata:)
-----------     -----    -----------------
auto_increment  varchar  (you decide)

table: tags
======

unique_id:      picture_id:          tag:
----------      -----------          ----
auto_increment  int (foriegn key     varchar (indexed)
                from picture table)

That way all of your searches are optimised out-of-the-box (sqlites performance can be quite impressive) and you have a clean and easy data structure to work with.

edit: just looked up the reference URL and it turns out you're building a web site. If that's the case then you _definitely_ want to use a database - though definitely not sqlite.







You can also go down the nosql route if you feel SQL / RDBMS aren't for you, but on this occasion I think they'd be well suited


----------



## Sanmayce

Yes, databases are too seductive, but as the old saying goes nothing good comes easy.



Luke: Vader/database... Is the dark side stronger?
Yoda: No, no, no. Quicker, easier, more seductive.

Also, you can consider the well-known approach of vectors-mapped-on-one-another, just build an array of bits where each bit position corresponds to a number, let's say we have 100,000,000 pictures which is 0..99,999,999 bits or ~12MB of size.
If each tag has its own vector than finding the 1's (marked bits) at same positions will result in pictures/numbers with their corresponding tags.

By the way I am thinking of tags how many are they, as I see it they can be an arbitrarily big number, in above anime site probably only a few hundred.


----------



## Plan9

If you think you can write faster indexing and search algorithms in one week than teams of experts have in years of database engine development, then be my guest. And that's without addressing the other big elephants in the room: 1) persistent storage of your in-memory data structures 2) data security (even with read only access, you could leak data outside your web application if you're not careful) and 3) data integrity (as you scale up, so will the risk of corruption in your database)

To be quite frank, reinventing the wheel just for the sake of NIH (not invented here) is dumb. If current database solutions are inadequate (which I highly doubt) then that's a different matter. Or if this is purely an academic exercise not intended for public consumption, then that would be fine as well. But even there I'd probably recommend he still looks to reuse established libraries.


----------



## geoxile

Quote:


> Originally Posted by *Sanmayce*
> 
> snip.


I think safebooru is just having some errors. I want a search of tags to return anything that contains the tags unless excluded by boolean search.

So girl_in_bottle should return every picture that has that tag, rather than just the one.

Quote:


> Originally Posted by *Plan9*
> 
> Would it not be simpler to throw this data into a sqlite database:
> 
> That way all of your searches are optimised out-of-the-box (sqlites performance can be quite impressive) and you have a clean and easy data structure to work with.
> 
> edit: just looked up the reference URL and it turns out you're building a web site. If that's the case then you _definitely_ want to use a database - though definitely not sqlite.
> 
> 
> 
> 
> 
> 
> 
> You can also go down the nosql route if you feel SQL / RDBMS aren't for you, but on this occasion I think they'd be well suited


I'm not building a website. I guess I'm creating an app version of the booru-type sites. Can sqlite be embedded? I mean, in such a way that the end user doesn't have to install anything or set up anything?
Quote:


> Originally Posted by *Sanmayce*
> 
> Yes, databases are too seductive, but as the old saying goes nothing good comes easy.
> 
> Luke: Vader/database... Is the dark side stronger?
> Yoda: No, no, no. Quicker, easier, more seductive.
> 
> Also, you can consider the well-known approach of vectors-mapped-on-one-another, just build an array of bits where each bit position corresponds to a number, let's say we have 100,000,000 pictures which is 0..99,999,999 bits or ~12MB of size.
> If each tag has its own vector than finding the 1's (marked bits) at same positions will result in pictures/numbers with their corresponding tags.
> 
> By the way I am thinking of tags how many are they, as I see it they can be an arbitrarily big number, in above anime site probably only a few hundred.


Can you explain this further? How is this different from a normal array if I still need to store images and tags?


----------



## Plan9

Yeah sqlite would be compiled into your binary, so it's totally portable. In fact that's the very reason I recommended it over other database solutions.









I've used sqlite on some of my own projects (written in Go) and it's very easy to use, providing you're already familiar with the basics of databases (eg SQL). And you can use an in memory schema rather than a disk-based database if you want additional performance - though that would be at the cost of persistence (I don't know if that's an issue for you or not, but you'd be facing the same dilemma with a bespoke solution anyway)


----------



## Sanmayce

Databases are optimized by an army of PROs, yet they cannot cover the full spectrum - in many cases plain C is unbeatable without need of having hundreds of thousands of mumbo-jumbo code, I mean extras like security and what not not counting the Hash plus B-tree structure which I believe is the backbone of every database (including my amateurish Leprechaun HASH+BTREES structure).
The big pluses of databases are many and maybe it is just for you, my tirades are usually about losing the simplicity and freedom to tweak and develop an existing FREE source code. My vision is to have the code of your application as independent as possible not using third-party closed or patented code.

> I think safebooru is just having some errors. I want a search of tags to return anything that contains the tags unless excluded by boolean search.
I don't think so, they just use a different collision policy, AFAIU they make a logical AND instead of your desired OR.

> So girl_in_bottle should return every picture that has that tag, rather than just the one.
Don't get it, *girl in bottle 1* has only one appearance, the tag search is not fuzzy but exact.

>How is this different from a normal array if I still need to store images and tags?
Well, you didn't say what are your structures nor premises, I can't guess what are your goals. As for the difference, as I see it, you don't need any fancy structure just vectors(arrays of bits) for each TAG housed on external RAM. Let's say you have 300 tags, each tag will have its own vector of length Number-of-Images/8 bytes long. I f you have 100,000,000 images then you will need 300*12MB=~4GB in order to check the positions within the vector marked as 1. In your case if you want all images tagged (partially as *bottle*) you have to look up the two arrays/vectors of tags *girl in a bottle* and *girl in bottle*, since the first has 16 images and the second 1 after ORing the two vectors you will have 17 results ... or 16 depending on whether the two tags overlap (someone could have tagged *girl in bottle* as *girl in a bottle*).
In short your app is pretty simple and needs not heavy lifting, you just need to do "dumping&ORing" of bits marked as 1 within the vector. Then e.g. if the 34,222,992nd bit is 1 it means that on some offset (probably 34,222,992*8) you can retrieve the address of your 34,222,992nd file description (name,path, ...).


----------



## Plan9

Quote:


> Originally Posted by *Sanmayce*
> 
> Databases are optimized by an army of PROs, yet they cannot cover the full spectrum - in many cases plain C is unbeatable without need of having hundreds of thousands of mumbo-jumbo code, I mean extras like security and what not not counting the Hash plus B-tree structure which I believe is the backbone of every database (including my amateurish Leprechaun HASH+BTREES structure).


You can't really describe all databases with a single brush stroke like that. There's simple key-value stores which are highly performant in-memory stores designed entirely around performance (they're what a lot of high traffic sites use as the backbone of their caching), graph databases, relational databases, and more. And each particular solution within any of the aforementioned categories will have their own strengths and weaknesses. So it's fair to say that databases do cover the full spectrum. In fact what you're advocating is still a database, it's just a bespoke one built for this application specifically.

The reason why I recommended sqlite was because the data being queried in this scenario struck me as being as typical a "hello world" example for relational databases as it gets. Plus as sqlite can run in-memory (*file::memory:*) and compiles into the standalone EXE / ELF, you have all the benefits of rolling your own database along with all the benefits of using a 3rd party solution; win win









Of course, it's entirely up to the developer to use existing solutions or not. There's a lot of experience to be gained by writing your own code, but the potential costs are numerous:

possible performance losses where less time has been spent optimizing the code
possible security concerns where your code hasn't been audited
the possibility of more bugs where your solution hasn't been as thoroughly tested
development time (it's great to say that using existing libraries is lazy, but we all have deadlines).
This is why I think it's dangerous to get too caught up in the NIH (not invented here) mentality.
Quote:


> Originally Posted by *Sanmayce*
> 
> The big pluses of databases are many and maybe it is just for you, my tirades are usually about losing the simplicity and freedom to tweak and develop an existing FREE source code. My vision is to have the code of your application as independent as possible not using third-party closed or patented code.


Open source code _is_ free source code. And sqlite specifically is public domain (https://www.sqlite.org/copyright.html) which means you can do whatever the hell you like with it. It's literally as just as free to use in whichever way you want as your own homebrew database.

edit: I really need to learn to spell


----------



## Sanmayce

Good, I actually agree with your statements.
Didn't know that SQLite went really FREE, very very good old (but new for me) news.

_"We the developers hope that you find SQLite useful and we charge you to use it well: to make good and beautiful products that are fast, reliable, and simple to use. Seek forgiveness for yourself as you forgive others. And just as you have received SQLite for free, so also freely give, paying the debt forward."_ https://www.sqlite.org/about.html

Bravo, quite as what I cherish most - the free and happy use of one product without any hidden agendas.

>... you have all the benefits of rolling your own database along with all the benefits of using a 3rd party solution; win win
Yes, it's good but not enough, my eyes are on trifecta i.e. win-win-win, I need&cherish the third win (being "experience to be gained by writing your own code") most.

And didn't know the word 'bespoke', yes, that's the case to "custom-made". Just think of fast&furious movies where all not custom-made rides are regarded as toys-of-the-spoiled-rich-snotty-snobs.

Yoda: Strong is Vader/Database. Mind what you have learned. Save you it can.



My point, writing your code by yourself and rewriting/tweaking external/free sources is what can make your neck thick as the old Bulgarian saying goes "The wolf's neck is thick because it does the job all by itself."

And just to mention one case where the full spectrum is not covered (yet) http://jayztwocents.com/forum/phpBB3/viewtopic.php?f=32&t=2380
No database is able to retrieve the misspelled phrases out of Wikipedia corpus, or I haven't heard the new good news.


----------



## geoxile

I think I'll probably go with the database solution if I can. This was actually supposed to be an exercise in JavaFX and Scenebuilder, and apparently it's branched out into something completely different.

That said, I was going to have a main collection of all tags in a trie, so that I can have some sort of auto-complete functionality when tagging images, or possibly when searching for tags. Does SQLite have some sort of functionality that will facilitate this?


----------



## Plan9

Quote:


> Originally Posted by *Sanmayce*
> 
> And just to mention one case where the full spectrum is not covered (yet) http://jayztwocents.com/forum/phpBB3/viewtopic.php?f=32&t=2380
> No database is able to retrieve the misspelled phrases out of Wikipedia corpus, or I haven't heard the new good news.


Funny enough, that was something I was researching myself last year. I did find a few products that did it, such as Lucene (https://lucene.apache.org/). But I decided against using them at the time (mostly down to time constraints learning a new database). As for how they compare to your project, I couldn't comment. You might be solving a different but similar problem so Lucene might not be compatible.
Quote:


> Originally Posted by *geoxile*
> 
> I think I'll probably go with the database solution if I can. This was actually supposed to be an exercise in JavaFX and Scenebuilder, and apparently it's branched out into something completely different.
> 
> That said, I was going to have a main collection of all tags in a trie, so that I can have some sort of auto-complete functionality when tagging images, or possibly when searching for tags. Does SQLite have some sort of functionality that will facilitate this?


AFAIK sqlite doesn't support trie tables. But I have done auto-complete lookups on slow relational tables before (MySQL, specifically) where I've read in every item where the first character matched the first keystroke, and then held that in memory and ran a lazy recursive if statement (if memory serves) on each subsiquent keystroke. Despite being poorly optimised, performance on that was still really good (even on mobile phones). So I'm sure you could work out something if you needed to


----------



## KYKYLLIKA

Building bicycles is all fun, but if you don't use third party stuff nowadays, you will struggle to make any useful functionality. Mainly because next to everything that can be built from scratch in a lifetime has probably been already built from scratch and used.

I mean there is only so much you can manage from scratch. Someday you'll find you want to make something so big, you will need third party developments, need to license tools and libraries, grab open source stuff and incorporate it all in a giant monstrosity that lets you shift mountains.


----------



## NameUnknown

Got tuition reimbursement through work so I am going to go back to college and finish my bachelors. Before I start going back I wanted to brush up on my C++, VB.Net, and Java. Does anyone know of good sources of free\low cost training in them that I could use as a refresher?


----------



## Sanmayce

The Lucene's homepage https://lucene.apache.org boasts:

_"Lucene is the de facto standard for search libraries"_

Hm, after browsing http://wiki.apache.org/lucene-java/LuceneFAQ I find Lucene incapable to address the needs of wildcard/fuzzy searches.
Sadly, their objectives are far from what I need most - full-text simple functions allowing versatile queries.

Just to make clear how far from the most wanted functionality nowadays (known to me) search-tools are:

Code:



Code:


01/18/2015  09:07 PM    51,344,631,742 enwiki-20150112-pages-articles.xml
01/18/2015  11:21 PM     8,999,203,582 enwiki-20150112-pages-articles.xml.graffith

"enwiki-20150112-pages-articles.xml":
LineWordreporter: Encountered lines in all files: 818,147,784
LineWordreporter: Encountered words in all files: 6,815,252,734
LineWordreporter: Longest line: 826,738
LineWordreporter: Longest word: 103,230

The above stats tell us that Wikipedia is composed of 800+ million lines (being paragraphs) with longest of them being 800+ thousand chars long.
Now, I don't see anywhere a snippet/library/tool capable of finding a phrase using straightforward wildcard/fuzzy search mode. The several search engines that I looked at a glance (Lucene including) are so stripped of this basic functionality that disappointment immediately made me forget about them.
In simple words, if I need a context/movie where two beloved actors perform together in a form of a sentence (or a paragraph) housing both _Dolph Lundgren_ and _Mickey Rourke_ I would need this simple query:
**Dolph Lundgren*Mickey Rourke**

The following paragraph being a physical line (don't be fooled by the wrapping) is taken from Wikipedia's dump. This very line will become a hit if the above pattern/query is applied.

Code:



Code:


[I][URL=https://en.wikipedia.org/wiki/The_Expendables_%282010_film%29]The Expendables[/URL][/I]
 was Stallone's big success of 2010. The movie, which was filmed during 
summer/winter 2009, was released on August 13, 2010. Stallone wrote, 
directed and starred in the movie. Joining him in the film were fellow 
action stars [URL=https://en.wikipedia.org/wiki/Jason_Statham]Jason Statham[/URL], [URL=https://en.wikipedia.org/wiki/Jet_Li]Jet Li[/URL], and [URL=https://en.wikipedia.org/wiki/Dolph_Lundgren]Dolph Lundgren[/URL], as well as [URL=https://en.wikipedia.org/wiki/Terry_Crews]Terry Crews[/URL], [URL=https://en.wikipedia.org/wiki/Mickey_Rourke]Mickey Rourke[/URL], [URL=https://en.wikipedia.org/wiki/Randy_Couture]Randy Couture[/URL], [URL=https://en.wikipedia.org/wiki/Eric_Roberts]Eric Roberts[/URL], and [URL=https://en.wikipedia.org/wiki/Stone_Cold_Steve_Austin]Stone Cold Steve Austin[/URL], and cameos by fellow '80s action icons [URL=https://en.wikipedia.org/wiki/Bruce_Willis]Bruce Willis[/URL] and [URL=https://en.wikipedia.org/wiki/Arnold_Schwarzenegger]Arnold Schwarzenegger[/URL].[URL=#cite_note-40][40][/URL]
 The movie took $34,825,135 in its opening weekend, going straight in at
 No. 1 in the US box office. The figure marked the biggest opening 
weekend in Stallone's career.[URL=#cite_note-41][41][/URL]
 In summer 2010, Brazilian company O2 Filmes released a statement saying
 it was still owed more than US$2 million for its work on the film.[URL=#cite_note-42][42][/URL] A sequel, [I][URL=https://en.wikipedia.org/wiki/The_Expendables_2]The Expendables 2[/URL][/I] was released August 17, 2012 to a positive critical reception of 67% on [URL=https://en.wikipedia.org/wiki/Rotten_Tomatoes]Rotten Tomatoes[/URL],[URL=#cite_note-43][43][/URL] as opposed to the original's 41%.[URL=#cite_note-44][44][/URL] As well as returning cast members from the first film, the ensemble cast also included [URL=https://en.wikipedia.org/wiki/Jean-Claude_Van_Damme]Jean-Claude Van Damme[/URL] and [URL=https://en.wikipedia.org/wiki/Chuck_Norris]Chuck Norris[/URL].

Quote:


> Originally Posted by *KYKYLLIKA*
> 
> Building bicycles is all fun, but if you don't use third party stuff nowadays, you will struggle to make any useful functionality. Mainly because next to everything that can be built from scratch in a lifetime has probably been already built from scratch and used.
> 
> I mean there is only so much you can manage from scratch. Someday you'll find you want to make something so big, you will need third party developments, need to license tools and libraries, grab open source stuff and incorporate it all in a giant monstrosity that lets you shift mountains.


Agreed partially. The stress is NOT on the results achieved during one's lifetime but on one's intention. To me, contributing to humanity, no matter what the sphere is, in spirit of GOODWILL is the ultimate profession, if you like. My religion is out of this crazy world where money rules, my belief is that good things live their own life independent from all craziness that is imposed on humans. Many useful things are built/born out of moneylust, however this changes nothing, the universal law is indifferent to the material world(s) - the path&goal is spirit of unity. Unity is broken when copyrighters lay limitations everywhere thus preventing the majority of people to use the knowhow already obtained by previously working individuals. I speak of the widespread sickness to copyright everything, if you analyze just for a minute this trend you will realize the lack of spirit in those people, in my eyes they are consumed by the material so badly that they are blinded to feel/see the importance of unity.

I really appreciate Openness not only in programming but in all spheres of life, to me closing things up is an ugly and sinful practice or as Sai Baba described it once:
_"when you pour water from the ocean into a bottle thus having removed it from the source soon it will corrupt/decay."_

And not to be claptrappy, here I come up with one example from the world of speed racing, the fastest car WW Bugatti Veyron vs Venturi's VBB-3








I watched a very interesting documentary about Veyron making/designing and with no doubt WW did a great job, but my point is that If the legacy of Nikola Tesla (an idol of mine) is to be applied into cars they easily would break even the sound barrier, not to mention the economic and environmental effects, oh and the smooth acceleration, the Veyron's double clutch is simply no more it can't compete with ... clutchless car.


----------



## KYKYLLIKA

Quote:


> Originally Posted by *Sanmayce*
> 
> The Lucene's homepage https://lucene.apache.org boasts:
> 
> _"Lucene is the de facto standard for search libraries"_
> 
> Hm, after browsing http://wiki.apache.org/lucene-java/LuceneFAQ I find Lucene incapable to address the needs of wildcard/fuzzy searches.
> Sadly, their objectives are far from what I need most - full-text simple functions allowing versatile queries.
> 
> Just to make clear how far from the most wanted functionality nowadays (known to me) search-tools are:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> 01/18/2015  09:07 PM    51,344,631,742 enwiki-20150112-pages-articles.xml
> 01/18/2015  11:21 PM     8,999,203,582 enwiki-20150112-pages-articles.xml.graffith
> 
> "enwiki-20150112-pages-articles.xml":
> LineWordreporter: Encountered lines in all files: 818,147,784
> LineWordreporter: Encountered words in all files: 6,815,252,734
> LineWordreporter: Longest line: 826,738
> LineWordreporter: Longest word: 103,230
> 
> The above stats tell us that Wikipedia is composed of 800+ million lines (being paragraphs) with longest of them being 800+ thousand chars long.
> Now, I don't see anywhere a snippet/library/tool capable of finding a phrase using straightforward wildcard/fuzzy search mode. The several search engines that I looked at a glance (Lucene including) are so stripped of this basic functionality that disappointment immediately made me forget about them.
> In simple words, if I need a context/movie where two beloved actors perform together in a form of a sentence (or a paragraph) housing both _Dolph Lundgren_ and _Mickey Rourke_ I would need this simple query:
> **Dolph Lundgren*Mickey Rourke**
> 
> The following paragraph being a physical line (don't be fooled by the wrapping) is taken from Wikipedia's dump. This very line will become a hit if the above pattern/query is applied.
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> [I][URL=https://en.wikipedia.org/wiki/The_Expendables_%282010_film%29]The Expendables[/URL][/I]
> was Stallone's big success of 2010. The movie, which was filmed during
> summer/winter 2009, was released on August 13, 2010. Stallone wrote,
> directed and starred in the movie. Joining him in the film were fellow
> action stars [URL=https://en.wikipedia.org/wiki/Jason_Statham]Jason Statham[/URL], [URL=https://en.wikipedia.org/wiki/Jet_Li]Jet Li[/URL], and [URL=https://en.wikipedia.org/wiki/Dolph_Lundgren]Dolph Lundgren[/URL], as well as [URL=https://en.wikipedia.org/wiki/Terry_Crews]Terry Crews[/URL], [URL=https://en.wikipedia.org/wiki/Mickey_Rourke]Mickey Rourke[/URL], [URL=https://en.wikipedia.org/wiki/Randy_Couture]Randy Couture[/URL], [URL=https://en.wikipedia.org/wiki/Eric_Roberts]Eric Roberts[/URL], and [URL=https://en.wikipedia.org/wiki/Stone_Cold_Steve_Austin]Stone Cold Steve Austin[/URL], and cameos by fellow '80s action icons [URL=https://en.wikipedia.org/wiki/Bruce_Willis]Bruce Willis[/URL] and [URL=https://en.wikipedia.org/wiki/Arnold_Schwarzenegger]Arnold Schwarzenegger[/URL].[URL=#cite_note-40][40][/URL]
> The movie took $34,825,135 in its opening weekend, going straight in at
> No. 1 in the US box office. The figure marked the biggest opening
> weekend in Stallone's career.[URL=#cite_note-41][41][/URL]
> In summer 2010, Brazilian company O2 Filmes released a statement saying
> it was still owed more than US$2 million for its work on the film.[URL=#cite_note-42][42][/URL] A sequel, [I][URL=https://en.wikipedia.org/wiki/The_Expendables_2]The Expendables 2[/URL][/I] was released August 17, 2012 to a positive critical reception of 67% on [URL=https://en.wikipedia.org/wiki/Rotten_Tomatoes]Rotten Tomatoes[/URL],[URL=#cite_note-43][43][/URL] as opposed to the original's 41%.[URL=#cite_note-44][44][/URL] As well as returning cast members from the first film, the ensemble cast also included [URL=https://en.wikipedia.org/wiki/Jean-Claude_Van_Damme]Jean-Claude Van Damme[/URL] and [URL=https://en.wikipedia.org/wiki/Chuck_Norris]Chuck Norris[/URL].
> 
> Agreed partially. The stress is NOT on the results achieved during one's lifetime but on one's intention. To me, contributing to humanity, no matter what the sphere is, in spirit of GOODWILL is the ultimate profession, if you like. My religion is out of this crazy world where money rules, my belief is that good things live their own life independent from all craziness that is imposed on humans. Many useful things are built/born out of moneylust, however this changes nothing, the universal law is indifferent to the material world(s) - the path&goal is spirit of unity. Unity is broken when copyrighters lay limitations everywhere thus preventing the majority of people to use the knowhow already obtained by previously working individuals. I speak of the widespread sickness to copyright everything, if you analyze just for a minute this trend you will realize the lack of spirit in those people, in my eyes they are consumed by the material so badly that they are blinded to feel/see the importance of unity.
> 
> I really appreciate Openness not only in programming but in all spheres of life, to me closing things up is an ugly and sinful practice or as Sai Baba described it once:
> _"when you pour water from the ocean into a bottle thus having removed it from the source soon it will corrupt/decay."_
> 
> And not to be claptrappy, here I come up with one example from the world of speed racing, the fastest car WW Bugatti Veyron vs Venturi's VBB-3
> 
> 
> 
> 
> 
> 
> 
> 
> I watched a very interesting documentary about Veyron making/designing and with no doubt WW did a great job, but my point is that If the legacy of Nikola Tesla (an idol of mine) is to be applied into cars they easily would break even the sound barrier, not to mention the economic and environmental effects, oh and the smooth acceleration, the Veyron's double clutch is simply no more it can't compete with ... clutchless car.


So&#8230; What is your intended search term and result?

From what I know about Lucene, it feels like a tool you apply to narrow your search basis before running it through a regular expression.


----------



## Plan9

Quote:


> Originally Posted by *Sanmayce*
> 
> The Lucene's homepage https://lucene.apache.org boasts:
> 
> _"Lucene is the de facto standard for search libraries"_
> 
> Hm, after browsing http://wiki.apache.org/lucene-java/LuceneFAQ I find Lucene incapable to address the needs of wildcard/fuzzy searches.
> Sadly, their objectives are far from what I need most - full-text simple functions allowing versatile queries.


What you're talking about then is a "fuzzy grep" rather than a database with fuzzy text searching (which is what you originally asked about). Something like Lucene would be overkill for what you're after.


----------



## Sanmayce

Quote:


> Originally Posted by *Plan9*
> 
> ... Something like Lucene would be overkill for what you're after.


I believe the two don't contradict each other, whether in greppy scenario or in the fields of a database it doesn't matter - the need for strong grip is there - searching using some weak word-based indexes is not enough to say the least.

That's why I gave a Wikipedia's paragraph - either approaches (grep-like or database) are dealing with this physical line ~3000 bytes long - in my view the whole line should be put in a field and treated as ... one basic unit. That way the 818,147,784 lines could be traversed as full-text (database can't escape that mode for wildcard/fuzzy needs) by both programs. The wildcard functionality within Lucene is simply too primitive and far from needed.


----------



## Sanmayce

>So&#8230; What is your intended search term and result?
They vary, mostly I need broad collection of hits (resultant lines) and as you suggested in second pass running some more restrictive pattern (not so loose as the first). The thing that disturbs me how easy coders want to impose some weak but superfast query scheme while sacrificing the versatility, I need tight grip, that's all.


----------



## Plan9

Quote:


> Originally Posted by *Sanmayce*
> 
> I believe the two don't contradict each other, whether in greppy scenario or in the fields of a database it doesn't matter - the need for strong grip is there - searching using some weak word-based indexes is not enough to say the least.
> 
> That's why I gave a Wikipedia's paragraph - either approaches (grep-like or database) are dealing with this physical line ~3000 bytes long - in my view the whole line should be put in a field and treated as ... one basic unit. That way the 818,147,784 lines could be traversed as full-text (database can't escape that mode for wildcard/fuzzy needs) by both programs. The wildcard functionality within Lucene is simply too primitive and far from needed.


Oh right, I missed that bit about how you take the sentence and apply heuristics to determine the likelihood of specific terms.

Have you ever considered writing AI? As I was looking to write a sentence recognition engine like yours as an interface to an AI model I'd thought out. Sadly I just never got the time to prototype it so it remains a concept in my head.


----------



## Sanmayce

Quote:


> Originally Posted by *Plan9*
> 
> ... Have you ever considered writing AI? As I was looking to write a sentence recognition engine like yours as an interface to an AI model I'd thought out. Sadly I just never got the time to prototype it so it remains a concept in my head.


I haven't, it is a too high ball to consider even a poor resemblance of AI. AI is for PROs I stick with sentence-like haystacks (data to be searched into) - whether an actual grammatical line or a multi-sentence single physical line i.e. paragraph. If one sticks to the basics there is a lot to be exploited, I mean the associativity between words within a single logical unit (usually a sentence) holds diamonds.

As you can see from this post of mine Google uses (in Google Books project) a variant of n-grams now called *n-arcs* (arc is used to denote a jump over some data between words):
http://www.codeproject.com/Articles/96397/B-Tree-Sorted-Dictionary?msg=5063499#xx5063499xx

I use an alternative rip, more clean and well-defined, called *x-grams* - they are the real skeleton of any sentence, very clean&powerful phrase-like entity it is. However, finding your patterns into grammatical sentences brings logical clarity in the resultant lines i.e. the dump is more human-friendly.

In short, when all kinds of filtering and superficial trade-offs are put aside then the x-grams shine, I have thought it thoroughly and see no alternative up to now. My dream is to have both search systems operative - full-text within physical lines (as *Kazahana* searches) and searches within x-grams done by *Leprechaun* - they both complement one another. A significant slice of English language is about to get x-grammed:

Code:



Code:


03/21/2015  02:26 AM    93,871,711,744 _Gamera_r27.tar.txt
03/20/2015  07:17 PM    18,075,707,387 _Gamera_r27.tar.txt.graffith

03/23/2015  03:40 PM    85,569,698,812 _Gamera_r27.tar.LBL.txt
03/24/2015  12:48 AM    17,113,403,593 _Gamera_r27.tar.LBL.txt.graffith

"_Gamera_r27.tar.txt":
LineWordreporter: Encountered lines in all files: 1,597,875,618
LineWordreporter: Encountered words in all files: 14,684,748,399
LineWordreporter: Longest line: 779,733
LineWordreporter: Longest word: 1,046

"_Gamera_r27.tar.LBL.txt":
LineWordreporter: Encountered lines in all files: 1,242,138,296
LineWordreporter: Encountered words in all files: 14,684,196,811
LineWordreporter: Longest line: 24,823,093
LineWordreporter: Longest word: 1,928

Roughly speaking, I have 1+ billion sentences (probably a half is a junk) and adding to them Wikipedia's 800+ million lines (probably a half is a junk) the outcome is again 1+ billion lines.
Oh, and adding to them the precious 4+ billion n-arcs of GoogleBooks rips (corpus of 3.5 million English books ripped):

Code:



Code:


01/10/2015  12:41 PM    10,624,363,237 Google_Books_corpus_version_20130501_English_All_Nodes.txt
01/10/2015  02:38 PM     1,844,711,941 Google_Books_corpus_version_20130501_English_All_Nodes.txt.graffith

01/13/2015  08:59 AM   179,736,720,202 Google_Books_corpus_version_20130501_English_All_Arcs.txt
01/15/2015  05:19 AM    23,990,734,563 Google_Books_corpus_version_20130501_English_All_Arcs.txt.graffith

01/18/2015  04:46 AM   298,223,429,647 Google_Books_corpus_version_20130501_English_All_BiArcs.txt
01/18/2015  11:07 PM    32,885,642,660 Google_Books_corpus_version_20130501_English_All_BiArcs.txt.graffith

01/22/2015  04:19 PM   302,743,777,792 Google_Books_corpus_version_20130501_English_All_TriArcs.txt
01/23/2015  07:23 AM    28,396,779,848 Google_Books_corpus_version_20130501_English_All_TriArcs.txt.graffith

"Google_Books_corpus_version_20130501_English_All_Nodes.txt":
LineWordreporter: Encountered lines in all files: 46,104,611
LineWordreporter: Encountered words in all files: 178,441,681
LineWordreporter: Longest line: 4,901
LineWordreporter: Longest word: 123

"Google_Books_corpus_version_20130501_English_All_Arcs.txt":
LineWordreporter: Encountered lines in all files: 918,860,187
LineWordreporter: Encountered words in all files: 7,419,031,777
LineWordreporter: Longest line: 4,244
LineWordreporter: Longest word: 217

"Google_Books_corpus_version_20130501_English_All_BiArcs.txt":
LineWordreporter: Encountered lines in all files: 1,783,018,535
LineWordreporter: Encountered words in all files: 20,599,208,820
LineWordreporter: Longest line: 3,722
LineWordreporter: Longest word: 217

"Google_Books_corpus_version_20130501_English_All_TriArcs.txt":
LineWordreporter: Encountered lines in all files: 1,876,974,527
LineWordreporter: Encountered words in all files: 28,304,385,066
LineWordreporter: Longest line: 3,346
LineWordreporter: Longest word: 394

The only obstacle in front of me is the lack of powerful computer in my room. This machine is good enough to meet my heavy ripping:

MOBO:
Asus Z10PE-D16 WS


CPU:
Total 64 threads.
Xeon E7-8867 v3 (# of Threads 32)
Xeon E7-8867 v3 (# of Threads 32)

RAM:
Total 512GB.
16 sticks of those: Kingston 32GB (1x32GB) Memory Module DDR4 2133MHz ECC

Kingston
Memory Speed: 2133Mhz PC3-17000
Capacity: 32GB (1x 32GB Modules)
Pins: 288 DIMM
RAM Type: DDR4 DIMM
Data Integrity Check: ECC
Specification: LRDIMM Load Reduced
CAS Latency (CL): 15

Yeah, the several billions of x-grams need space, also sorting and what not them.
I am short roughly $513 + 2x$4672 + 16x£420, the lack of money is not important, the lack of tools utilizing such power is what disturbs me.


----------



## Plan9

Quote:


> Originally Posted by *Sanmayce*
> 
> I haven't, it is a too high ball to consider even a poor resemblance of AI. AI is for PROs


You're thinking of _machine learning_ and such like. Anyone can write AI.
Quote:


> Originally Posted by *Sanmayce*
> 
> The only obstacle in front of me is the lack of powerful computer in my room. This machine is good enough to meet my heavy ripping:
> 
> MOBO:
> Asus Z10PE-D16 WS
> 
> 
> CPU:
> Total 64 threads.
> Xeon E7-8867 v3 (# of Threads 32)
> Xeon E7-8867 v3 (# of Threads 32)
> 
> RAM:
> Total 512GB.
> 16 sticks of those: Kingston 32GB (1x32GB) Memory Module DDR4 2133MHz ECC
> 
> Kingston
> Memory Speed: 2133Mhz PC3-17000
> Capacity: 32GB (1x 32GB Modules)
> Pins: 288 DIMM
> RAM Type: DDR4 DIMM
> Data Integrity Check: ECC
> Specification: LRDIMM Load Reduced
> CAS Latency (CL): 15


It sounds like you'd be better off scaling horizontally rather than up. ie build a few low footprint machines and cluster them.


----------



## Sanmayce

Just saw how (outside *NIX) those 500GB could be utilized:
http://www.tekrevue.com/tip/create-10-gbs-ram-disk-windows/



How one cannot love those *749MB/s* within 4KB granularity?! The *26MB/s* achieved by SATA III Samsung 830 SSD look as a bad joke.
The good stuff doesn't end here, it goes up one 1GB/s higher








http://www.xtremesystems.org/forums/showthread.php?267096-RAMdisk-scores&s=713c8115fc12313545e5cf806a935f59&p=4755560&viewfull=1#post4755560



Simply AMAZING!


----------



## Sanmayce

Quote:


> Originally Posted by *Plan9*
> 
> ...
> It sounds like you'd be better off scaling horizontally rather than up. ie build a few low footprint machines and cluster them.


Sure, but not anymore, too very often I need 128++GB of memory block, just try to compress in high orders with my favorite compressor BSC when using 1GB blocks for each thread, 300GB won't suffice (5*1*64):

_"Compression and decompression requirements are the same and in bytes, can be estimated as 16Mb + 5 x block size x number of blocks processed in parallel."
_

As for current best result (*7440 seconds*) for finding "Silvestor Staloune" LD=4 into Wikipedia when using 5960X running at 4.5 GHz I aim for more painless times as I don't know maybe 64/16 = 4 times. This cannot be achieved on distributing computing without ugly hacks. As of now, this machine could run 4 instances of Kazahana (it still uses 16 threads), so if I have 4 moderate powered computers I don't see the gain.


----------



## Plan9

Your storage IOPS isn't going to be the real bottleneck. It's going to be network throughput. And you're not going to solve that one by throwing more RAM into a PC. You're better off clustering a number of modest Linux servers. I pick Linux for good reason as it's TCP/IP stack has been optimized to shortcut the 3-way handshake on successive TCP/IP requests (the "TCP Fast Open" / TFO extension). Since you'll be making numerous HTTP requests to pull your data, you really need every optimization in the book. (HTTP keepalive would also work in your favour, but at least TFO works transparently in your networking stack were as your HTTP API might not support keepalive)


----------



## Sanmayce

I am not aware of what *NIX world could offer really, just making some speculative calculations if I had the opportunity to buy a monstrous machine. It is interesting, though, to consider your idea.


----------



## geoxile

I've been reading up on database theory and SQL these past few days. How would I store multiple values of the same type? Like the tags for an image? It seems like my only option is to create a large table from the get go and then somehow expand it if it runs out of space on a tuple.


----------



## Plan9

Quote:


> Originally Posted by *Sanmayce*
> 
> I am not aware of what *NIX world could offer really, just making some speculative calculations if I had the opportunity to buy a monstrous machine. It is interesting, though, to consider your idea.


There's a few advantages of scaling horizonally:
1) lower entry level cost
2) better scalability

Which means you could just rent 3 or 4 AWS / Digital Ocean / OVH / whatever virtual servers (you needn't even go through the hassle of renting physical boxes for now) and trial your routine for a few weeks to see how things perform.

As for your code, because (from past conversations) you like to write parallel, mult-threaded code, it might not be too hard to convert your program into a distributed routine. Assuming yuo have a core server thread that passes code to workers via shared memory or other messenging pipeline, you could use the same model with your workers communicating to the server thread via TCP/IP sockets.

It should be mentioned though, that regardless of whether you're hitting Wikipedia from 1 IP or several dozen, Wikimedia could view these searches of yours as a DoS attack. So if you're looking at writing performant routines then you may need to discuss your idea with them beforehand.
Quote:


> Originally Posted by *geoxile*
> 
> I've been reading up on database theory and SQL these past few days. How would I store multiple values of the same type? Like the tags for an image? It seems like my only option is to create a large table from the get go and then somehow expand it if it runs out of space on a tuple.


It sounds counter intuitive, but the key to databases is duplication of meta-fields.

Code:



Code:


table: pictures
======

columns:
========
picture_id:  file_name:
-----------  ----------
1            c:\users\plan9\english-landscape.jpg
2            c:\users\plan9\amy-pond.jpg
3            c:\users\plan9\dalek.jpg

---------------------------------------------------------------------------------------------------

table: tags
======

columns:
========
picture_id:  tag:
-----------  ----
1            landscape            
1            summer
1            england
2            portrait            
2            woman
2            ginger
2            doctor who
3            robot
3            doctor who
3            alien

So basically your first table (pictures) would only have details that only have one valid field. eg filename as each image can only be one file.

Then for all your metadata that can have multiple fields, such as tags, you have a dedicated table for them and each row would be it's own field.

So you'd query all the tags like so:

Code:



Code:


-- select all pictures with the tag "doctor who"
SELECT file_name
FROM   pictures,
       tags
WHERE  pictures.picture_id = tags.picture_id
AND    tags.tag = "doctor who"

/*
  results:
  ========
  file_name
  ----------
  c:\users\plan9\amy-pond.jpg
  c:\users\plan9\dalek.jpg
*/

-- select all tags for "c:\users\plan9\english-landscape.jpg"
SELECT tag
FROM   pictures,
       tags
WHERE  pictures.picture_id = tags.picture_id
AND    pictures.file_name = "c:\users\plan9\english-landscape.jpg"

/*
  results:
  ========
  tag
  ----------
  landscape            
  summer
  england
*/

The SQL on there can be tidied up with table aliases and such like, but that's the basic queries and table struture you'd be looking to do


----------



## tompsonn

I love this Doctor Who example. Check that SQL to make sure it actually runs though


----------



## Plan9

Quote:


> Originally Posted by *tompsonn*
> 
> I love this Doctor Who example. Check that SQL to make sure it actually runs though


What did I miss?


----------



## tompsonn

Code:



Code:


Unknown column 'tags.picture_id' in 'where clause'
Unknown column 'pictures.picture_id' in 'where clause'

You're just missing a JOIN in there









Code:



Code:


SELECT file_name
FROM   pictures
LEFT JOIN tags on pictures.picture_id = tags.picture_id
WHERE    tags.tag = "doctor who"

Or anything else equivalent (few different ways to get the result set).


----------



## Plan9

Quote:


> Originally Posted by *tompsonn*
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> Unknown column 'tags.picture_id' in 'where clause'
> Unknown column 'pictures.picture_id' in 'where clause'
> 
> You're just missing a JOIN in there
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> SELECT file_name
> FROM   pictures
> LEFT JOIN tags on pictures.picture_id = tags.picture_id
> WHERE    tags.tag = "doctor who"
> 
> Or anything else equivalent (few different ways to get the result set).


oh crap yeah. database 101









Thank you, post updated with a quick and nasty non-ANSI syntax


----------



## tompsonn

Quote:


> Originally Posted by *Plan9*
> 
> oh crap yeah. database 101
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Thank you, post updated with a quick and nasty non-ANSI syntax


----------



## KYKYLLIKA

Quote:


> Originally Posted by *Sanmayce*
> 
> >So&#8230; What is your intended search term and result?
> They vary, mostly I need broad collection of hits (resultant lines) and as you suggested in second pass running some more restrictive pattern (not so loose as the first). The thing that disturbs me how easy coders want to impose some weak but superfast query scheme while sacrificing the versatility, I need tight grip, that's all.


I meant this particular example when asking the question. For example, when I am looking for a solution, I develop a bunch of use cases:

Suppose I have entities called "nodes".

I have other entities called "categories".

Code:



Code:


public class Node {

public Guid ID {get;}
public string Name {get;set;}
public Guid CategoryID {get;set;}
public Category Category {get;}
public Guid? ParentID{get;set;}
public Node? Parent {get;}

}

In which Parent Guid is keyed from the same database of nodes. So nodes can be parents to each other.

Now, I want to grab all nodes with category where

Code:



Code:


Node.Category.Name == "Business".

So I search for

Code:



Code:


db.Nodes.Where(n => n.Category.Name == "Business")

But I also want to return all those nodes whose ancestors also are in "Business" so they are automatically inherit "Business".
So&#8230;

Code:



Code:


public List<String> Categories (this) {
    List<String> result = new List<String>();
    if (this.Parent != null) {
        result.Add(this.Parent.Category.Name);
        result.AddRange(this.Parent.Categories());
    }
    return result;
}

&#8230;

List<Node> RelevantNodes = db.Where(n => n.Categories.Contains("searchTerm")).ToList();

If I didn't narrow down to an actual query-result use case and have intermediate results that do not satisfy me, I wouldn't know where to go to improve. So that was my idea: get an actual use case scenario, where you have your desired input (just one narrow example, for starters), and the desired output (for this particular example input you choose). Then you can generalize this use case scenario, but in very definite terms. Definite terms translate to code very well.


----------



## geoxile

Ah yes, I see now. Thanks.


----------



## Sanmayce

Quote:


> Originally Posted by *KYKYLLIKA*
> 
> I meant this particular example when asking the question...


Sadly I am not into that stuff, if I need some graph-exploiting technique I would write it myself not relying on object-oriented products.
I failed to understand what your snippet does, if you are interested in (I am) converging your view (about narrowing query patterns) with mine let us consider some more clear example.

For example, in a previous post I did a mistake (I do them all the time) when used '*distributing*' instead of '*distributive*' in the sentence 'This cannot be achieved *on distributing computing* without ugly hacks.'
Also, I fear that I misused the preposition 'on' too.

If you like this one please elaborate on how you are seeing your sequence of narrowing.
*distributive computing* vs *distributing computing*
https://books.google.com/ngrams/graph?content=distributive+computing%2C+distributing+computing&year_start=1800&year_end=2000&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Cdistributive%20computing%3B%2Cc0%3B.t1%3B%2Cdistributing%20computing%3B%2Cc0

To me, this example is quite helpful, in order to understand your logic I would like to know how you are gonna determine that '*distributing*' was used incorrectly, what type of queries in what structure you intend to use?!
In my case I would have in my disposal several billions phrases (x-grams and n-arcs) and would rank the above x-grammed sentence by comparing the occurrences of source and target phrases.

Please some native speaker to express the difference (if any) between usage of *distributive computing* vs *distributing computing*, are they interchangeable?!

After I sought for *"on distributing computing"* found only 6 but well-established instances, so I guess I did no mistake:
https://www.google.bg/search?q=%22distributing+computing%22&tbs=bks:1,cdr:1,cd_min:1998,cd_max:2000&lr=lang_en&gws_rd=cr,ssl&ei=7oBnVeWPG8OuswH6woAo#lr=lang_en&tbs=cdr:1%2Ccd_min:1998%2Ccd_max:2000%2Clr:lang_1en&tbm=bks&q=%22on+distributing+computing%22

1] Its main objective is to provide an architecture based on distributing computing technologies to enable telecommunications networks to support the rapid and flexible introduction of new services and the ability to manage both the services and ...
2] ... an architecture based on distributing computing concepts in a technology-independent way.
3] Proceeding of the 15th International Conference on Distributing Computing System, Purdue University, Dept. of Comp. 1995.
4] Andreas regularly publishes and speaks on distributing computing topics.
5] He regularly publishes and speaks on distributing computing topics. Andreas holds a M.Sc. and a Ph.D. in Computer Science from the Humboldt-University at Berlin, Germany.
6] The new networks will withstand typical outages experienced in client/server networks. The TTNA-C model for telecommunications software is an architecture based on distributing computing concepts in a technology independent way[Fue95].

Hope I will learn something new...


----------



## KYKYLLIKA

Quote:


> Originally Posted by *Sanmayce*
> 
> Sadly I am not into that stuff, if I need some graph-exploiting technique I would write it myself not relying on object-oriented products.
> I failed to understand what your snippet does, if you are interested in (I am) converging your view (about narrowing query patterns) with mine let us consider some more clear example.
> 
> For example, in a previous post I did a mistake (I do them all the time) when used '*distributing*' instead of '*distributive*' in the sentence 'This cannot be achieved *on distributing computing* without ugly hacks.'
> Also, I fear that I misused the preposition 'on' too.
> 
> 
> Spoiler: rest of post
> 
> 
> 
> If you like this one please elaborate on how you are seeing your sequence of narrowing.
> *distributive computing* vs *distributing computing*
> https://books.google.com/ngrams/graph?content=distributive+computing%2C+distributing+computing&year_start=1800&year_end=2000&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Cdistributive%20computing%3B%2Cc0%3B.t1%3B%2Cdistributing%20computing%3B%2Cc0
> 
> To me, this example is quite helpful, in order to understand your logic I would like to know how you are gonna determine that '*distributing*' was used incorrectly, what type of queries in what structure you intend to use?!
> In my case I would have in my disposal several billions phrases (x-grams and n-arcs) and would rank the above x-grammed sentence by comparing the occurrences of source and target phrases.
> 
> Please some native speaker to express the difference (if any) between usage of *distributive computing* vs *distributing computing*, are they interchangeable?!
> 
> After I sought for *"on distributing computing"* found only 6 but well-established instances, so I guess I did no mistake:
> https://www.google.bg/search?q=%22distributing+computing%22&tbs=bks:1,cdr:1,cd_min:1998,cd_max:2000&lr=lang_en&gws_rd=cr,ssl&ei=7oBnVeWPG8OuswH6woAo#lr=lang_en&tbs=cdr:1%2Ccd_min:1998%2Ccd_max:2000%2Clr:lang_1en&tbm=bks&q=%22on+distributing+computing%22
> 
> 1] Its main objective is to provide an architecture based on distributing computing technologies to enable telecommunications networks to support the rapid and flexible introduction of new services and the ability to manage both the services and ...
> 2] ... an architecture based on distributing computing concepts in a technology-independent way.
> 3] Proceeding of the 15th International Conference on Distributing Computing System, Purdue University, Dept. of Comp. 1995.
> 4] Andreas regularly publishes and speaks on distributing computing topics.
> 5] He regularly publishes and speaks on distributing computing topics. Andreas holds a M.Sc. and a Ph.D. in Computer Science from the Humboldt-University at Berlin, Germany.
> 6] The new networks will withstand typical outages experienced in client/server networks. The TTNA-C model for telecommunications software is an architecture based on distributing computing concepts in a technology independent way[Fue95].
> 
> Hope I will learn something new...


Sorry, I meant the example you gave with searching Wikipedia for actors. I provided my own example to show you the process of drilling down into the logic with the help of a real-life use case scenario.

Now. Since you provided a great example for distributing vs distributive computing, let's pick that one apart and try to produce some logic out of that.

If I understand it correctly, you want to have the queries "*on distributing computing*" and "*on distributive computing*" return you similar results.
Particularly, you want it so that both search queries return these (amongst other results):

Code:



Code:


1] Its main objective is to provide an architecture based [U]on distributing computing[/U] technologies to enable telecommunications networks to support the rapid and flexible introduction of new services and the ability to manage both the services and ...
2] ... an architecture based [U]on distributing computing[/U] concepts in a technology-independent way.
3] Proceeding of the 15th International Conference [U]on Distributing Computing[/U] System, Purdue University, Dept. of Comp. 1995.
4] Andreas regularly publishes and speaks [U]on distributing computing[/U] topics. 
5] He regularly publishes and speaks [U]on distributing computing[/U] topics. Andreas holds a M.Sc. and a Ph.D. in Computer Science from the Humboldt-University at Berlin, Germany.
6] The new networks will withstand typical outages experienced in client/server networks. The TTNA-C model for telecommunications software is an architecture based [U]on distributing computing[/U] concepts in a technology independent way[Fue95].

Each query would give slightly different results, but both would contain the ones on the list.

So you want your query to grab approximated string matches.

All of these matches have an edit distance of 0 with "*on distributing computing*" and 2 with "*on distributive computing*" (one for changing "*n*" to "*v*" and one for changing "*g*" to "*e*"). This distance is used as a filtering/sorting factor in "fuzzy" searches (for example, a more advanced concept: Levenshtein distance).

Lucene uses searches based on edit distance when using keywords with tilde appended. After tilde, you can specify the required similarity. I'm guessing it is equivalent to 1 - (edit distance/number of characters in the keyword), the default similarity is 0.5 (used when you do not specify a required similarity).

In your case, when telling Lucene to search "on distributive~0.83 computing" you should find these results.

Brute force would be to just grab your search query, split by space, and then append tilde to every keyword. But I expect poor results with *on~0.8*" or anything like that.

Before looking at approximated string matches, I naturally thought about semantics and linguistics. Imagine your search query as a structure of interconnected abstract concepts: + + . In this case, you are identifying parts of speech: conjunction followed by adjective or adjectival form, followed by a noun or present participle.

In case you get confused by "*distributing computing*", they are both *present participles*, but for the sake of convention we will assume that among successive participles, the object is the last one acting in place of a noun while the previous ones are acting as adjectival forms of present participle.

Frankly, semantic searches are something that large well-funded companies and scientific researchers have been trying to nail for years, and there is no reliable result still, so I'll just put it in the long shelf and focus on task at hand.

All I need to do is find words proper in the search query (rule of thumb: anything longer than 3 letters, extend it to 4, if you like), and extract the stems from them. There are numerous dictionaries out there to find stems and roots of words, like http://nlpdotnet.com/services/Morphparser.aspx
Notice that we don't need the root because many times you can break down a word into a bunch of affixes and a stem, and then break down the stem to a bunch of affixes and another, smaller stem. The last, smallest stem is the root. A good example is "*distributing*" which breaks into "*distribute*" and "ing", but "distribute" also breaks down into "dis" and "tribute".

As it stands, we have the logic:

1) Grab search query; Example: "*on distributing computing*"
2) Extract words proper; "*distributing*" and "*computing*"
3) Extract stems from each word; "*distribute*" and "*compute*"
4) Apply search term modifiers to stems; example: "*distribute~0.6*" and "*compute~0.6*" That will match "*distributing*", "*distributive*", "*distribution*", "*distributel*", etc&#8230; Anything that requires four edits (I assume)
5) Compose search query back; "*on distribute~0.6 compute~0.6*"
6) Use your search engine to make a search.

You will get some garbage, like "on distributing computers" or "on distributed computers", but if you're using other strategies to narrow things down, you may find it working well.


----------



## Sanmayce

Thank you for the walkthrough.
Yes, you guessed well what I needed.
I'm sorry for the example with the actors, this one is more complicated because for the full coverage it takes searching into raw lines and ripped lines (x-grams) as well. Of course having the x-grams is a luxury not always available.

The feature that caught my attention is ability to specify fuzziness within the phrase for arbitrary word, this is hella good.

Also, the morphological parsing at Free NLP Online Services is very good and makes me think to "group" all morphologically related words and map this group onto each and every one of them, thus no dynamic analysis will be needed.
I liked this example:


Code:



Code:


Put your word here, e.g. internationalization

Morphologically realted words:
nations
national
nationals
nationhood
nationwide
nationally
nationalize
nationalist
nationalise
nationalism
nationality
nationalised
nationalized
nationalists
nationalises
nationalizes
nationalistic
nationalizing
denationalize
transnational
nationalising
nationalities
international
multinational
denationalise
denationalizes
internationale
internationals
denationalised
denationalises
denationalized
denationalizing
nationalisation
internationales
internationally
nationalization
denationalising
internationalise
transnationalism
ultranationalism
nationalizations
internationalize
internationalist
nationalisations
internationalised
internationalises
internationalized
internationalists
internationalizes
denationalization
internationalising
internationalizing
internationalization
internationalisation
internationalisations
internationalizations

Food for thought, thanks again.

In our case it failed to mark 'dis' as prefix, though. Yet it provided the 'group':

Code:



Code:


Morphologically realted words:
distributes
distributor
distributed
redistribute
distributing
distribution
distributive
distributors
redistributed
distributions
redistributes
redistribution
distributional
distributively
redistributing
redistributions

As I thought, it is the same for 'distributing' and 'distributive'.

Now, when I asked about your snippet exploiting inheritance I had in mind a potential simple graph-traversal mode where by starting with 'on' all words following it (being its children) can be searched for either 'distributing' or 'distributive' and at final stage for 'computing'.
In here I talk not only for searching but for the very nifty suggestion/prediction mode.
As in most modern crawlers when you e.g. start typing 'gwen' and add a space then the most highly ranked children word is 'stefani', enormous speed-up and assistance in case the user don't know the family name of the 'No doubt' singer.
My goal is tri-faceted:
#1 linear search, that is, line-by-line;
#2 complex (for now using 'Pagoda' files) search into previously ripped x-grams from the raw data (used in #1);
#3 predictive/suggestive type mode (as 'gwen stefani').

What is 'Pagoda' file?
It is a textual file with one key word used as a main pillar (stem) and all its adjacent (from left and right) words. This is how it looks like:


This pagoda is for the word 'on', it is 9+ million lines high!

Talking about #3, my latest idea to ease the huge calculations is to have for each and every English word a corresponding file with all words surrounding that word i.e. all their ancestors and successors. Currently I implemented depth up to 5 levels in both directions.
Discarding the scary part, the cumulative size of all 'Pagoda' files which is beyond 1,000,000 words x 4,000,000 bytes or > 4TB! The good thing is that it is easily compressible, I wrote a compressor achieving 8:1 (thus 512GB will house them) with 3rd fastest decompression.



If you are interested how 'Pagoda' files for 'distributing' and 'distributive' look like I attached them. The source used for their building is my old English texts corpus ~20GB long.

I am looking for a better way to find all major ancestors&successors of a given word, however I see no replacement, it would be great if anyone can point out an algorithm or just an approach allowing realtime suggestive typing.

Kazahana_distributive.PAGODA-order-5.zip 10k .zip file


Kazahana_distributing.PAGODA-order-5.zip 74k .zip file


----------



## geoxile

So in SQLite would it be more expensive to check if a tag exists in the database or more expensive to just try an insert every time even if it fails? I'm thinking it might be better to just fuse Tags and hasTag together.

Right now my tag systems is as such

Code:



Code:


CREATE TABLE Images
(IID int,
Path varchar(255) NOT NULL,
Filename varchar(255) NOT NULL,
ImgDate TIMESTAMP DEFAULT CURRENT_TIME,
PRIMARY KEY (IID),
UNIQUE (Path, Filename))

CREATE TABLE Type
(TypeName varchar(30),
TagColor varchar(30) DEFAULT 'Blue',
PRIMARY KEY (TypeName))

CREATE TABLE Tags
(TID int,
TagType varchar(30) DEFAULT 'Default',
TagName varchar(255) NOT NULL,
PRIMARY KEY(TID),
UNIQUE (TagType, TagName),
FOREIGN KEY (TagType) REFERENCES Types(TypeName) ON DELETE RESTRICT)

CREATE TABLE hasTag
(IID int,
TID int,
PRIMARY KEY (IID, TID),
FOREIGN KEY (IID) REFERENCES Images(IID) ON DELETE CASCADE,
FOREIGN KEY (TID) REFERENCES Tags(TID) ON DELETE CASCADE)

CREATE TABLE Family
(IID int,
FID int,
PRIMARY KEY (IID, FID),
FOREIGN KEY (IID) REFERENCES Images(IID) ON DELETE CASCADE)

CREATE TABLE Collection
(CID int,
ColDate TIMESTAMP DEFAULT CURRENT_TIME,
CName varchar(100) NOT NULL UNIQUE,
PRIMARY KEY (CID))

CREATE TABLE ColHasTag
(CID int,
TID int,
PRIMARY KEY (CID, TID),
FOREIGN KEY (CID) REFERENCES Collection(CID) ON DELETE CASCADE,
FOREIGN KEY (TID) REFERENCES Tags(TID) ON DELETE CASCADE)

CREATE TABLE CImages
(CID int,
Position int,
Path varchar(255),
Filename varchar(255),
UNIQUE (Position),
PRIMARY KEY (CID, Path, Filename),
FOREIGN KEY(CID) REFERENCES Collection(CID) ON DELETE CASCADE)

Just posting the rest of it. The problem with fusing Tag and hasTag would mean that I'm separating the tag tables for Images and Collections. A Collection would be a separate set of images, like a private album, while the Images would just contain all the images like on safebooru. A collection is tagged by the entire thing and not by its individual images, whereas an image would be tagged by itself. A single search for a tag should return both images and collections. Also, for a hypothetical autocomplete feature, it would be more convenient to pull results from one table.

Any advice?


----------



## geoxile

JavaFX's listview doesn't have wrap around functionality. Aaaahhhhhhhhhhh!


----------



## geoxile

I hate JavaFX. It's already obtuse and frustrating to use, and now for some reason my FXML reset back to the initial version I created a week back on the 8th. I don't even understand how. I really should've kept a git on this... At this point I'm just ready to toss this entire project in the bin. It's just been a frustrating exercise in reading obscure forum posts to find workarounds and hacks for what I want to do.


----------



## twerk

Anyone have any idea why this doesn't work? (Java)

This is in my start method:

Code:



Code:


File file = new File ("/resources/UserScores.txt");
OpenFile.openFile(file); //<------------------------------------------ error on this line

This is the OpenFile method being called:

Code:



Code:


class OpenFile extends Assignment2 {

    static void openFile(File file) {
        String str;
        FileInputStream myFis=null;
        try {
            myFis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        }
        BufferedReader myBr=new BufferedReader(new  InputStreamReader(myFis)); //<------------------------------------------ and error on this line

        try {
            Users.clear();
            while ( (str=myBr.readLine()) != null) {

                String [] strs = str.split(",");
                String name = strs[0];
                Integer score = Integer.parseInt(strs[1]);
                Users.add(new User(name, score));
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        System.out.println(Users.size());
    }
}

The exception I get is this:
_\resources\UserScores.txt (The system cannot find the path specified)_

This would imply that the path set is wrong but I've targeted other resources in that folder elsewhere in the program without issue ("/resources/18.png" for example).

Any help would be massively, massively appreciated.


----------



## Plan9

Any reason for the different angle of your slashes in the two paths you posted?


----------



## twerk

Quote:


> Originally Posted by *Plan9*
> 
> Any reason for the different angle of your slashes in the two paths you posted?


In my code they are forward slashes "/"

In the exception that pops up they change to back slashes for some reason "\"


----------



## KYKYLLIKA

Does your file get created and does it have the proper permissions?


----------



## twerk

Fixed it. For some reason it couldn't be accessed from within the resources folder, which I don't understand because the images could but oh well. I just moved it to the project root and it's now fine.

Thanks!


----------



## Microx256

Quote:


> Originally Posted by *twerk*
> 
> Anyone have any idea why this doesn't work? (Java)
> 
> This is in my start method:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> File file = new File ("/resources/UserScores.txt");
> OpenFile.openFile(file); //<------------------------------------------ error on this line


Did you try this:

Code:



Code:


File file = new File ("resources/UserScores.txt");
OpenFile.openFile(file); //<------------------------------------------ error on this line

You seem to be using Windows, so I am not entirely certain, but at least on Linux etc OS'es that would be an absolute path rather than relative (hence the leading slash), so it might refer to something like C:\resources\UserScores.txt instead of C:\something\morething\project123\resources\UserScore.txt on your Windows.

Also, for the reason the slashes changing to backslashes: slash ( / ) is the appropriate notation to use in the code, because the JVM will automatically translate that to environment specific directory separator, which is backslash on Windows.


----------



## Six-Strings

I've just finished the Introduction to Javascript on Khan Academy and I'm wondering where to go next.

Which would be a productive programming language to learn for a non-programmer, just for fun / as a brain teaser / as something to spice up the CV?


----------



## Plan9

Quote:


> Originally Posted by *Six-Strings*
> 
> I've just finished the Introduction to Javascript on Khan Academy and I'm wondering where to go next.
> 
> Which would be a productive programming language to learn for a non-programmer, just for fun / as a brain teaser / as something to spice up the CV?


Probably Python.


----------



## andyroo89

Ok, guys, I am running into a small problem, in my android app I am using alarm manager and calendar to execute a task for me.

It works... to a certain degree. Now, I do programming on, and off so I am considered noobish, but I put Log.d into any method I can so I know what is executing and what isn't.

I set my calendar to 1 minute later after I execute (I execute at 1:47, and have my calendar set to 1:48) I am in logcat watching the logs, and see main activity, and calendar logs, and it takes 3-6 minutes after my calendar time to execute my intent.

So, I have two main questions

1. What am I doing wrong with alarm manager, and Calendar Manager? What I am trying to achieve is to execute task everyday at certain time.
2. (wasn't discussed) but when I try to dim the screen I get "method getsystemservice cannot be resolved" from the piece of code to dim the screen.

The code to question number 2 is commented out on schedule service class.

MainActivity (I was too lazy to rename it so it's not actually main activity)
http://pastebin.com/QPHRwNwv

Schedule Service class
http://pastebin.com/ccpSALbB


----------



## twerk

Hi guys,

Quick one. How would I write this equation in Java?

10*(10/10)*(10/10)^2

I tried:

Math.pow(10*(10/10)*(10/10), 2);

but it gave me the complete wrong answer, it should come to 10.


----------



## tompsonn

No it shouldn't, if you write it like that.

This is really what it should be to make it come to 10:

Code:



Code:


10 * ( 10 / 10 ) * ( (10 / 10 ) ^ 2 )

So it should be in your code:

Code:



Code:


Math.pow( 10 / 10, 2 ) * 10 / 10 * 10

But why call a function:

Code:



Code:


( ( 10 / 10 ) * ( 10 / 10 ) ) * 10 / 10 * 10


----------



## twerk

Sorry. Using all 10's was a bad idea for an example. If I put in some random numbers...

195 * ( 1300 / 1058 ) * ( ( 1212 / 1175 ) ^ 2 )

I would expect that to equal 255 (rounded).

How should that be written?


----------



## Microx256

Quote:


> Originally Posted by *twerk*
> 
> Sorry. Using all 10's was a bad idea for an example. If I put in some random numbers...
> 
> 195 * ( 1300 / 1058 ) * ( ( 1212 / 1175 ) ^ 2 )
> 
> I would expect that to equal 255 (rounded).
> 
> How should that be written?


add a .0 to the numbers, otherwise you're performing integer-divisions. Eg. 2/3 would become 2.0/3.0


----------



## tompsonn

Quote:


> Originally Posted by *twerk*
> 
> Sorry. Using all 10's was a bad idea for an example. If I put in some random numbers...
> 
> 195 * ( 1300 / 1058 ) * ( ( 1212 / 1175 ) ^ 2 )
> 
> I would expect that to equal 255 (rounded).
> 
> How should that be written?


Write it exactly how I showed you. Then round it yourself as necessary. Or Microx256 should work too.


----------



## twerk

Sorted. When you have that d'oh moment.... thanks guys


----------



## andyroo89

Quote:


> Originally Posted by *andyroo89*
> 
> Ok, guys, I am running into a small problem, in my android app I am using alarm manager and calendar to execute a task for me.
> 
> It works... to a certain degree. Now, I do programming on, and off so I am considered noobish, but I put Log.d into any method I can so I know what is executing and what isn't.
> 
> I set my calendar to 1 minute later after I execute (I execute at 1:47, and have my calendar set to 1:48) I am in logcat watching the logs, and see main activity, and calendar logs, and it takes 3-6 minutes after my calendar time to execute my intent.
> 
> So, I have two main questions
> 
> 1. What am I doing wrong with alarm manager, and Calendar Manager? What I am trying to achieve is to execute task everyday at certain time.
> 2. (wasn't discussed) but when I try to dim the screen I get "method getsystemservice cannot be resolved" from the piece of code to dim the screen.
> 
> The code to question number 2 is commented out on schedule service class.
> 
> MainActivity (I was too lazy to rename it so it's not actually main activity)
> http://pastebin.com/QPHRwNwv
> 
> Schedule Service class
> http://pastebin.com/ccpSALbB


Got it figured out, on android's developer page they mention that alarm is inexact on kitkat and up (battery saving reasons), so I have to use setWindow, or setExact to make it exact, but then I have to fire a new alarm.


----------



## andyroo89

Ok, guys I think I finally have the question to the answer I am hoping to look for.

Ok, so after deleting my source code to my socket android app, I decided to revive it.

Now the obstacle I came across was how can I send command to certain socket when I have no way of identifying it (at this point I was using different words, thus not getting answer I was looking for.)

So my question is what method can I use to identify a socket so I can use that ID to send a command to that specific socket? in stack overflow question I saw this answer.
Quote:


> No, because you don't know what's in between. Most mobile providers use proxies, NAT and so on. The mobile device thinks it's on a LAN (10.0.0.x or 192.168.x.x addresses) which the provider provides. It's even possible for multiple clients to have the same remote address (seen from your server).
> 
> The easiest way would be to let either client or server generate some unique number, *for example using the device ID and some kind of timestamp*. Then after connecting (but that depends on the protocol you're using) you send a "Hello" message from or to the client with that ID.
> 
> This does mean however that you'll have more 'bookkeeping data' around your socket, but wrap it in your own ClientSocket class and you're good to go.


source: http://stackoverflow.com/questions/15130586/what-to-use-for-identifying-between-clients-that-connect-to-a-server-java-andr

now that brings follow up question(s) the words in bold would that be ok? If so, how can I use that ID to send command back through socket (or outputstream?)

like multiple devices is samsung S4 named andy, and I generate AndyS4 and S5 named phil and generates philS5

then I want my tablet (server) to be like AndyS4 I want you to vibrate (for example)

but not affect socket to philS5 cause sometime later in the day I want to have the phone's ringtone to go off.. so, my tablet is like PhilS5 set ringtone to high and ring.

Hopefully this helps so I can find the answer I am looking for.


----------



## alcal

Quote:


> Originally Posted by *andyroo89*
> 
> snip


Ok, so I probably am missing a bunch of background since I don't want to read backwards, but what I gather is that you are making an app for your phone which will act as a client, and you will have a tablet functioning as some sort of server (?).

As far as sockets programming goes, you will need your server-side code to listen for connections on a socket which you define, probably in the constructor for the listener (I don't remember what the native android implementation of this is since I've only used sockets in raw Java). Once that listener is there, any connection to that device's IP on that socket will trigger the listener and let you send whatever you want.

As far as a way to identify multiple devices connected to the server, you can do pretty much whatever you want as long as security isn't a massive concern. However you decide to generate an ID, you can send it across the network in some sort of payload formatted to suit your needs.

Again, I'm super unsure of the background/what you're asking still, so maybe I shouldn't have bothered replying, but I'm not exactly sure what the issue is.


----------



## andyroo89

Quote:


> Originally Posted by *alcal*
> 
> Ok, so I probably am missing a bunch of background since I don't want to read backwards, but what I gather is that you are making an app for your phone which will act as a client, and you will have a tablet functioning as some sort of server (?).
> 
> As far as sockets programming goes, you will need your server-side code to listen for connections on a socket which you define, probably in the constructor for the listener (I don't remember what the native android implementation of this is since I've only used sockets in raw Java). Once that listener is there, any connection to that device's IP on that socket will trigger the listener and let you send whatever you want.
> 
> As far as a way to identify multiple devices connected to the server, you can do pretty much whatever you want as long as security isn't a massive concern. However you decide to generate an ID, you can send it across the network in some sort of payload formatted to suit your needs.
> 
> Again, I'm super unsure of the background/what you're asking still, so maybe I shouldn't have bothered replying, but I'm not exactly sure what the issue is.


Essentially here is a summary, i had my server listen for connections, made a new thread when connection was made, obstacle was I had no idea how to identify each socket that connects so I can send commands to the client from the server. Problem was if I sent something from the server it will only send it to the newest connected device.


----------



## alcal

Quote:


> Originally Posted by *andyroo89*
> 
> Essentially here is a summary, i had my server listen for connections, made a new thread when connection was made, obstacle was I had no idea how to identify each socket that connects so I can send commands to the client from the server. Problem was if I sent something from the server it will only send it to the newest connected device.


Ok thanks for the clarification. You'll probably want to set it up so that your when your listener connects and sets up the connection, you spawn a new listener in another thread to handle the subsequent connection. You can't talk to more than one device on a single connection (as you stated) so you'll need to always have a listener ready to offer a new connection to each device.

Once you do that, you'll have some sort of threadpool of active connections, and I think that what I said earlier about identifying them however you want should work fine. Depending on how you have things set up/what you're doing, you might want to use a thread-safe data structure of some sort to pass information between threads, though Android has policies against blocking operations in the main thread (which most thread safe data structures need to be able to do to ensure that they are indeed thread safe) so I'm not 100% sure what your options are there.


----------



## andyroo89

Quote:


> Originally Posted by *alcal*
> 
> Ok thanks for the clarification. You'll probably want to set it up so that your when your listener connects and sets up the connection, you spawn a new listener in another thread to handle the subsequent connection. You can't talk to more than one device on a single connection (as you stated) so you'll need to always have a listener ready to offer a new connection to each device.
> 
> Once you do that, you'll have some sort of threadpool of active connections, and I think that what I said earlier about identifying them however you want should work fine. Depending on how you have things set up/what you're doing, you might want to use a thread-safe data structure of some sort to pass information between threads, though Android has policies against blocking operations in the main thread (which most thread safe data structures need to be able to do to ensure that they are indeed thread safe) so I'm not 100% sure what your options are there.


When I did some googling, I came across using hashtable to make identifier for each connections, someone else also mentioned GUID. I mean easier said than do when you say "identifying them however you want" I mean someone mentioned using device ID + timestamp but how would I implement that into the socket?

would it be something like...

socket.getoutputstream(randomgenerateID);
? idk


----------



## alcal

Quote:


> Originally Posted by *andyroo89*
> 
> When I did some googling, I came across using hashtable to make identifier for each connections, someone else also mentioned GUID. I mean easier said than do when you say "identifying them however you want" I mean someone mentioned using device ID + timestamp but how would I implement that into the socket?
> 
> would it be something like...
> 
> socket.getoutputstream(randomgenerateID);
> ? idk


um socket.getOutputStream() takes no parameters as I recall so that wouldn't be possible. There is probably a better way to do this, but here is what I might do:
On initial connection:
Server generates a random ID for new device. It tells the device its ID over the connection (i.e. you write a message to the outputstrem from the server to the device informing the device of its ID).

On subsequent connections:
Device sends a message (again by writing to the outputstream of its socket) to the server saying effectively "Hi, I'm device ########"

You will need to design a simple handshake procedure for this, and possibly something resembling a protocol for the rest of the communications between client and server. Pretty much all talking between devices will be done by writing a specially formatted message to the outputstream, waiting for a reply and then responding depending on what the reply contains. None of this has to do with the socket object itself once the connection is established.

Edit: once again, how you actually name the devices doesn't really matter so long as you are sure it will avoid collisions. You could use random numbers assigned by the server, and then make sure you aren't reusing them by linearly searching a list of used numbers [this is obviously easy to implement] or you could use GUIDs or timestamps or whatever else you think suits the needs of your app.

Edit 2: if security is a concern, most of this advice is terrible and you'll have a whole new set of problems.


----------



## andyroo89

Quote:


> Originally Posted by *alcal*
> 
> um socket.getOutputStream() takes no parameters as I recall so that wouldn't be possible. There is probably a better way to do this, but here is what I might do:
> On initial connection:
> Server generates a random ID for new device. It tells the device its ID over the connection (i.e. you write a message to the outputstrem from the server to the device informing the device of its ID).
> 
> On subsequent connections:
> Device sends a message (again by writing to the outputstream of its socket) to the server saying effectively "Hi, I'm device ########"
> 
> You will need to design a simple handshake procedure for this, and possibly something resembling a protocol for the rest of the communications between client and server. Pretty much all talking between devices will be done by writing a specially formatted message to the outputstream, waiting for a reply and then responding depending on what the reply contains. None of this has to do with the socket object itself once the connection is established.
> 
> Edit: once again, how you actually name the devices doesn't really matter so long as you are sure it will avoid collisions. You could use random numbers assigned by the server, and then make sure you aren't reusing them by linearly searching a list of used numbers [this is obviously easy to implement] or you could use GUIDs or timestamps or whatever else you think suits the needs of your app.
> 
> Edit 2: if security is a concern, most of this advice is terrible and you'll have a whole new set of problems.


I figured it didn't. hmm idk this may take a couple of days/weeks to do since I am still trying to figure this out.


----------



## alcal

Quote:


> Originally Posted by *andyroo89*
> 
> I figured it didn't. hmm idk this may take a couple of days/weeks to do since I am still trying to figure this out.


I'm still somewhat new to Android myself and am always looking to learn, so if you want to talk about something in more detail /want me to actually research my suggestions before I make them, feel free to PM me. In principle though, this shouldn't be too difficult. You just need to come up with a simple, clear way to format messages and write yourself a document establishing the protocol so you can follow it clearly when writing the client and serverside implementations.

Anyways, yeah feel free to PM me as you work through it.


----------



## NameUnknown

Is there any logic in moving from VB to C# outside of platform support for C# being much greater? Is one more prevalent than the other? etc...

I ask because I was thinking of creating a few apps to make my life at work easier since I can't find anything that does what I am looking for and since I only know VB well enough to do it was going to use that. But when I saw the Android & iOS support for C# I thought it may be beneficial to use it despite having to learn it from the ground up.


----------



## GamerFamalam

I know im late to the party but my main language is Java but i will have to get into Delphi possibly for A level compsci, for my IDE i use NetBeans8.2 or Eclipse. At the moment I am working on a project for a GCSE qualification. Im slightly struggling with a problem with it. Using file handling i have created a text file containing multiple lines split by a straight line. I need to sort the data in a seperate program. the aim is to sort the first part of each line (name) by alphabetical order, then the second part of the data (score) by score amount ascending / descending. Im hoping to use the split function to split the lines on the center line. This then provides me with two strings i need to sort. Can i then sort these strings maybe in arrays? long and convuloted i know but any help appreciated


----------



## alltheGHz

Hello everyone, what is the best way to learn how to code in MSDOS?


----------



## patriotaki

Quote:


> Originally Posted by *alltheGHz*
> 
> Hello everyone, what is the best way to learn how to code in MSDOS?


You can get this book for the basics
http://www.amazon.com/DOS-Dummies-Dan-Gookin/dp/0764503618?SubscriptionId=1ECM10QMJC4BZXXP0W02&tag=bimecom2-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=0764503618

but msdos is really dead...have you considered pascal?

also have a look at this

http://aetos.it.teithe.gr/~vassik/downloads/cn/LearningMSDOS.pdf


----------



## alltheGHz

Quote:


> Originally Posted by *patriotaki*
> 
> You can get this book for the basics
> http://www.amazon.com/DOS-Dummies-Dan-Gookin/dp/0764503618?SubscriptionId=1ECM10QMJC4BZXXP0W02&tag=bimecom2-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=0764503618
> 
> but msdos is really dead...have you considered pascal?
> 
> also have a look at this
> 
> http://aetos.it.teithe.gr/~vassik/downloads/cn/LearningMSDOS.pdf


I'll check out pascal, thank you!


----------



## andyroo89

For some reason when ever a client connects my listview updates, BUT it updates on the same line as the previous connection

like

Client A

then when a new client joins it will remove client A and add client B

Client B

but I want it like this

Client A
Client B
Client C
etc...

Here is my SO question, with piece of code.
http://stackoverflow.com/questions/36739500/listview-updates-but-not-on-a-new-row


----------



## andyroo89

Quote:


> Originally Posted by *andyroo89*
> 
> For some reason when ever a client connects my listview updates, BUT it updates on the same line as the previous connection
> 
> like
> 
> Client A
> 
> then when a new client joins it will remove client A and add client B
> 
> Client B
> 
> but I want it like this
> 
> Client A
> Client B
> Client C
> etc...
> 
> Here is my SO question, with piece of code.
> http://stackoverflow.com/questions/36739500/listview-updates-but-not-on-a-new-row


Nevermind, figured it out, my code kept "resetting" my hasmap/listview values. Works like a charm now.


----------



## patriotaki

why doesnt this work?
it always goes to the s2!=key situation

Code:



Code:


BufferedReader br2 = null;
        String s2;
        String key="XYJC6SQ1Y4RC";
        try{
        br2 = new BufferedReader(new FileReader("C:\\license.txt"));
        s2 = br2.readLine();

            if(s2==key)
            {
                JOptionPane.showMessageDialog(null, "Validation Succeed Starting the proccess...");
                System.out.println(s2);
            }
            else if(s2!=key){
                JOptionPane.showMessageDialog(null, "Validation Failed! Program will exit");
                System.out.println(s2);
                  System.exit(0);

            }

        }

        catch(FileNotFoundException x){ JOptionPane.showMessageDialog(null, "File not found");
        System.exit(0);
        }


----------



## tom.slick

Quote:


> Originally Posted by *patriotaki*
> 
> why doesnt this work?
> it always goes to the s2!=key situation
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> BufferedReader br2 = null;
> String s2;
> String key="XYJC6SQ1Y4RC";
> try{
> br2 = new BufferedReader(new FileReader("C:\\license.txt"));
> s2 = br2.readLine();
> 
> if(s2==key)
> {
> JOptionPane.showMessageDialog(null, "Validation Succeed Starting the proccess...");
> System.out.println(s2);
> }
> else if(s2!=key){
> JOptionPane.showMessageDialog(null, "Validation Failed! Program will exit");
> System.out.println(s2);
> System.exit(0);
> 
> }
> 
> }
> 
> catch(FileNotFoundException x){ JOptionPane.showMessageDialog(null, "File not found");
> System.exit(0);
> }


== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they are logically "equal").


----------



## patriotaki

Quote:


> Originally Posted by *tom.slick*
> 
> == tests for reference equality (whether they are the same object).
> 
> .equals() tests for value equality (whether they are logically "equal").


any ideas how can i protect my program (jar) ? i mean i dont want others to send it to other people because i will be charging the program.
i dont want anything special like connection to servers etc.. something simple


----------



## tom.slick

Quote:


> Originally Posted by *patriotaki*
> 
> any ideas how can i protect my program (jar) ? i mean i dont want others to send it to other people because i will be charging the program.
> i dont want anything special like connection to servers etc.. something simple


Don't know, I never tried. I'm more the open source type. You can try some kind of obfuscator


----------



## patriotaki

Quote:


> Originally Posted by *tom.slick*
> 
> Don't know, I never tried. I'm more the open source type. You can try some kind of obfuscator


one last question.. is there any way i can create an installation package (.msi for example) and select for each file where it should be extracted?


----------



## tom.slick

Quote:


> Originally Posted by *patriotaki*
> 
> one last question.. is there any way i can create an installation package (.msi for example) and select for each file where it should be extracted?


All kinds. Google around for something that suites your needs.


----------



## Dimaggio1103

Sorry had to clean it up, im OCD with code. lol != is strict, and sometimes if the string read case letters it will expect the same or fall into the else if. You can create a method for converting everything to upper case, and may solve your issue. Im not to familiar with this anguage though so pardon me if you are already aware of that.

Code:



Code:


BufferedReader br2 = null;
        String s2;
        String key="XYJC6SQ1Y4RC";
        try
        {
        br2 = new BufferedReader(new FileReader("C:\\license.txt"));
        s2 = br2.readLine();

            if(s2==key)
            {
                JOptionPane.showMessageDialog(null, "Validation Succeed Starting the proccess...");
                System.out.println(s2);
            }
            else if(s2!=key)
                        {
                JOptionPane.showMessageDialog(null, "Validation Failed! Program will exit");
                System.out.println(s2);
                  System.exit(0);

            }

        }

        catch(FileNotFoundException x){ JOptionPane.showMessageDialog(null, "File not found");
        System.exit(0);
        }


----------



## Microx256

Quote:


> Originally Posted by *Dimaggio1103*
> 
> Sorry had to clean it up, im OCD with code. lol != is strict, and sometimes if the string read case letters it will expect the same or fall into the else if. You can create a method for converting everything to upper case, and may solve your issue. Im not to familiar with this anguage though so pardon me if you are already aware of that.
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> BufferedReader br2 = null;
> String s2;
> String key="XYJC6SQ1Y4RC";
> try
> {
> br2 = new BufferedReader(new FileReader("C:\\license.txt"));
> s2 = br2.readLine();
> 
> if(s2==key)
> {
> JOptionPane.showMessageDialog(null, "Validation Succeed Starting the proccess...");
> System.out.println(s2);
> }
> else if(s2!=key)
> {
> JOptionPane.showMessageDialog(null, "Validation Failed! Program will exit");
> System.out.println(s2);
> System.exit(0);
> 
> }
> 
> }
> 
> catch(FileNotFoundException x){ JOptionPane.showMessageDialog(null, "File not found");
> System.exit(0);
> }


In Java, the != and == operators test for references when dealing with objects like String, like pointed out by tom.slick a few posts back. When dealing with primitives like int and float, the != and == operators test with the equality more or less. So the only way to properly test if two strings "contain the same text" is by using the .equals() method, or alternatively the .equalsIgnoreCase() method if you want to perform a case-insensitive check for equality. So for example, instead of:

Code:



Code:


if(s2==key)

you should use:

Code:



Code:


if(s2.equals(key))

or

Code:



Code:


if(s2.equalsIgnoreCase(key))


----------



## Dimaggio1103

Ah gotcha. I know in python and c++ we have to be specific about lowercase so you specify or convert method to take all input and make it caps. Thought maybe that might be an issue.


----------



## subassy

I was debating if I should start a separate thread for this, but I think I'll ask here first instead.

I wanted to know if anybody had an opinion of _Electron_?

Here's the shorter description from the web site:
Quote:


> Electron is an open source library developed by GitHub for building cross-platform desktop applications with HTML, CSS, and JavaScript.


I've been wanting to find more motivation for learning JavaScript and I already wrote a HTML/CSS/VBScript utility using _Windows Script Host_. So naturally a fully capable (what? HTML 5? A JS engine made _after_ IE 8? Crazy talk) alternative appeals to me. Also JavaScript over VBScript probably not a bad idea.
And Electron is pretty new by the way. It's only about 18 months old and the 1.0 release was just in May of this year.

The first and/or most famous example of an Electron application is the ATOM text editor. From little I've used of it it seems really good/special. Only disadvantage, at least of ATOM anyway, is the file size: 90 MBs for a text editor? Is that really entirely necessary? How many text editors are 90MBs? I think it's because they have to include the native UI elements of different operating systems inside the installed package.
The other thing I would call a disadvantage (at least of atom) is the default install locaiton:
C:\Users\[name]\AppData\Local\atom\app-1.10.2
Is making my user profile that much larger _really_ necessary (this folder is 266MBs)? Sure it's common on Linux/etc and Mac OS X, but it's annoying-as-well just annoying in Windows.

I do have a few programs I have in mind that would be best written in via Electron. Hopefully to come in under 90MBs.

On what may or may not be a related note, I just published my first real working utility (albeit a batch file) to github. I'm kind of excited about this. And it practically works!


----------



## patriotaki

Does anyone know imacros language for firefox in here?

i need some help asap


----------



## andyroo89

Will anyone be able to explain to me how to handle second activity when using back button? I am working on remote directory app for couple of old android phones I have. Whenever I open second activity to certain phone, it will populate the folders/files in the listview just fine (the way I want it to), but If i have the back button and go to re open second activity it will be blank. I know I am receiving the file/folder names since thats what my log is showing me. Here is the source code, sorry for the mess, i was adding one liners here, and there to make sure I didn't overlook anything.

http://stackoverflow.com/questions/40188573/listview-does-not-populate-when-opening-activity-for-second-time


----------

