• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

D4Danger

Unconfirmed Member
Well, never is a long time. It'll diminish a lot once it's no longer the only show in town, but it'll be a long, long time before it dies out entirely.

I eventually see Javascript being used as a gimmick, toy language for small projects. Sort of a curiosity, "they used to code with this?!"

Always bet on JS

JS isn't going anywhere. The four biggest tech companies are pouring enormous resources into its continued development.
 
Always bet on JS

JS isn't going anywhere. The four biggest tech companies are pouring enormous resources into its continued development.
Well, this touches on my point (I see he goes off into the ES6 weeds later). WebAssembly is the endgame.

"enormous resources" into not breaking backwards compatibility with a bad programming language. I'm not a believer, as you may have gathered.

I don't have any problems with JS, it was necessary to have a cross platform browser language for the web to take off. And its shittiness means that even though it's entrenched, there's enormous demand to ditch it! In that way, it's wonderful.
 

Godslay

Banned
On the frontend I don't see JS waning any time soon, especially with Google and Facebook backing it with Angular and React respectively. Then you have Ember 2.0 that's suppose to finally get itself together.

I just want Node and the whole JS on server side to die out and I'll be happy or at least the "hot new tech" appeal to go away.

Agree with the server side sentiments.

JS on the server side is really only a thing because JS on the client side is the only show in town. Lots of developers => "we should use the same language on the server" => node.

JS on the client side will be on the downturn in 5 years, IMO. I want it to go faster, but it's going to take some time for WebAssembly to stabilize. We need a consistent (non-JS) way of accessing the DOM as well. Once we're there, JS loses its captive audience.

None of Angular/React/Ember are particularly good. But it's not their fault, they're trying to make a language that was designed in two weeks (and has never really been redesigned!) do some crazy things.

I don't mind Ember, I've had to maintain an app written in it. Just an MVC basically. Still JS though.

JS server side makes sense to unify your talent pool, but it sucks. Especially when you have vastly better alternatives.
 

Ke0

Member
Always bet on JS

JS isn't going anywhere. The four biggest tech companies are pouring enormous resources into its continued development.

What is Apple's contribution to JS? Honestly can't imagine what they could contribute to it. I know MS is putting it's money behind Typescript, Google with Angular 2.0, Facebook with React.
 

hateradio

The Most Dangerous Yes Man
Java on the rise means that a lot of schools are still teaching it. :p




Other than that, the graph looks about right. JS forever.
 
Python is an excellent language. Very well thought out, restrictive yet not cumbersome. Very few landmines to step on, too, which is nice for a restrictive language.

Until you try to refactor some code and end up fixing bugs for the next week because there's no concept of a compiler helipng you find errors.

Or until you try to write multi-threaded code and you realize it's not as well thought out as you first thought.

Or until you get an Architecture Astronaut on your team and end up with so many levels of dynamic indirection it makes Boost.Spirit look like Hello World in comparison.

Or until you try to upgrade to 3.0 and commit suicide because it's less painful.

It's good as a replacement for shell scripts. Anything beyond that I find highly dubious.
 

phoenixyz

Member
Until you try to refactor some code and end up fixing bugs for the next week because there's no concept of a compiler helipng you find errors.

Or until you try to write multi-threaded code and you realize it's not as well thought out as you first thought.

Or until you get an Architecture Astronaut on your team and end up with so many levels of dynamic indirection it makes Boost.Spirit look like Hello World in comparison.

Or until you try to upgrade to 3.0 and commit suicide because it's less painful.

It's good as a replacement for shell scripts. Anything beyond that I find highly dubious.

cpp_is_king
Member
(Today, 10:04 AM)

;)
 

vypek

Member
Hi guys/gals, I'm currently applying to some big companies for jobs/internships depending on when I graduate.

I've been studying cracking the coding interview, practicing some problems on hacker rank, and going through them with a whiteboard at home. I'm doing this roughly six hours a day and then working on my projects in the mean time to get everything wrapped up (resume/projects/interview question practice/linked-in) and start sending out my resume by 8/30.

Anyways, I was wondering if any of you have gone through the process at larger companies and have any insight or comments on what I might be missing, thanks!

I recently wound up at a large company. I was also studying cracking the coding interview as well but never finished going through it. What I did was helpful though. Being able to think about how you'd go about solving different problems seemed to be the most important thing when I was interviewing. I personally don't think you are missing anything but maybe more experienced people will disagree.
 

injurai

Banned
You are correct, PHP being #4 is another bad omen. Thankfully the cavalry is coming.

Java -> Go
Javascript -> (your favorite language thanks to WebAssembly)
PHP -> PHP, it will never die

Backend Java -> Scala
Application Java -> C#
Ruby/Python -> Go
Javascript -> Ask a Magic 8 Ball.
Fortran -> Julia (Though Physics still resists.)
5 Figure Cobal -> 6 Figure Cobal
Common Lisp -> Clojure
Scheme -> Racket
Erlang -> Elixir
Systems Obj-C -> Systems Obj-C
Applications Obj-C -> Swift
C/C++ -> Rust
SML -> F#
Haskell -> OCaml
OCaml -> Haskell
Delphi -> Delphi (What don't they want us to know...)
 
https://www.reinterpretcast.com/writing-a-game-boy-advance-game

Just read this article yesterday, pretty awesome. It's actually really easy to set up a toolchain for the GBA and cross-compile for it if you use the devkitARM Perl script for installing (at least on Linux, have not tried it on Windows). The four steps described in the article create a .gba file that you can open with VisualBoyAdvance for example. Pretty neat.

It would be pretty sweet if I could cross-compile Rust for the GBA, but that's probably pretty difficult still.
 

Onemic

Member
Currently in a bit of a dilemma for my coming fall semester.

I'm in my last(or second last depending on how I wanna go about things) semester for my computer programming and analysis program Im taking. This is my co-op semester, so out of the 5 courses I can take, one course must be the co-op prep course. On top of that if I do want to graduate as soon as I'm done my co-op with a company(co-op would last 8 months and begins in the winter semester) I also have to take an additional two courses, one being a literature course and one being a business writing course(basically a careers course). This would leave me with only 2 options for actual programming related courses.

Im most interested in specializing in game development or graphics and there are 3 courses I would want to take that I feel would help me reach that. They are:

Game Engine Foundations
Game Development Fundamentals
Data Structures and Algorithms in C++


If I didnt have 3 required courses out of my possible 5 this wouldnt be a problem as I could just take all three, but since that isn't the case, I have to choose 2 and drop one. I just don't know what it should be. OR I could take the other option and simply do another semester after my co-op term, but at 26 I sorta wanna get out into the field ASAP as I'm not getting any younger and enough people are already wayyyyy ahead of me and are a whole lot younger too. Graduating after the co-op term is over would net me a regular diploma, but doing another semester would net me an advanced diploma....and I'm not sure how useful that even is, especially when my plan would ultimately be to go back to school after a few years and get a masters in Computer Science. Any help would be greatly appreciated.

Other courses of interest:

Parallel Programming Fundamentals
Introduction to Data Warehousing
Everything else
 
Currently in a bit of a dilemma for my coming fall semester.

I'm in my last(or second last depending on how I wanna go about things) semester for my computer programming and analysis program Im taking. This is my co-op semester, so out of the 5 courses I can take, one course must be the co-op prep course. On top of that if I do want to graduate as soon as I'm done my co-op with a company(co-op would last 8 months and begins in the winter semester) I also have to take an additional two courses, one being a literature course and one being a business writing course(basically a careers course). This would leave me with only 2 options for actual programming related courses.

Im most interested in specializing in game development or graphics and there are 3 courses I would want to take that I feel would help me reach that. They are:

Game Engine Foundations
Game Development Fundamentals
Data Structures and Algorithms in C++


If I didnt have 3 required courses out of my possible 5 this wouldnt be a problem as I could just take all three, but since that isn't the case, I have to choose 2 and drop one. I just don't know what it should be. OR I could take the other option and simply do another semester after my co-op term, but at 26 I sorta wanna get out into the field ASAP as I'm not getting any younger and enough people are already wayyyyy ahead of me and are a whole lot younger too. Graduating after the co-op term is over would net me a regular diploma, but doing another semester would net me an advanced diploma....and I'm not sure how useful that even is, especially when my plan would ultimately be to go back to school after a few years and get a masters in Computer Science. Any help would be greatly appreciated.

Other courses of interest:

Parallel Programming Fundamentals
Introduction to Data Warehousing
Everything else

Drop Game Dev Fundamentals and take the other 2
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Looking at the description, it's no more than you'd learn just fooling around with Unity on your own. In that sense, DirectX and graphics programming or Data Structures and Algorithms are much better topics to study in an academic environment.
 

Onemic

Member
Looking at the description, it's no more than you'd learn just fooling around with Unity on your own. In that sense, DirectX and graphics programming or Data Structures and Algorithms are much better topics to study in an academic environment.

This is what I was initially thinking, just needed confirmation. I'm already messing around in UE4 myself.
 

HelloMeow

Member
Looking at the description, it's no more than you'd learn just fooling around with Unity on your own. In that sense, DirectX and graphics programming or Data Structures and Algorithms are much better topics to study.

Yup, that's what it looks like. It seems like an introduction to just one specific engine. Probably Unreal or Unity. You'll learn to use the editor and how to do some AI, pathfinding, game logic, etc. for one specific engine.
 

Slo

Member
Can anyone give me a good description of why someone would use Scala or Groovy instead of Java? If I'm working in a shop with a lot of Java code, why would I want to switch to another JVM language?
 

Nelo Ice

Banned
So I'm just now learning about hackerspaces and I'm at one right now. Looked at their site and they've had a front end web dev class aimed right at beginners for the past month. I know what I'm doing from now on. And I need to catch up or do the best I can before the next class on Monday.
 
Can anyone give me a good description of why someone would use Scala or Groovy instead of Java? If I'm working in a shop with a lot of Java code, why would I want to switch to another JVM language?
Why would you want to switch to another language in general?

Because there are many, many other languages that are not Java that have their own advantages and disadvantages, and many of those advantages strongly outweigh the disadvantages. Java has been evolving over the years but is routinely adopting language features that have been commonplace in languages like Scala.

Switching languages has a very high cost, however. You lose the a) runtime of the JVM, b) the libraries for Java, and c) the developer knowledge of those libraries. By using an alternative JVM language, you keep the hotspot tracing JIT bytecode virtual machine, you can use any library you want via the languages foreign function interface, and your developers can keep using the libraries they are familiar with and slowly wean yourself off of those libraries in favor of libraries written for idiomatic use in your new language. That is why Clojure, Scala, and Groovy have such low cost of adoption.
 
Why would you pick the other 2 over game dev fundamentals?

Data Structures is a straight up requirement, it's the foundation of everything. Every serious engineer, game dev or not, needs to know about data structures.

So it comes down to which of the two game dev courses to eliminate. It wasn't a clear cut decision, but i chose to keep Game Engine Development since it looks like it contains practical experience with important APIs like DirectX and OpenGL
 

Haly

One day I realized that sadness is just another word for not enough coffee.
More practically, you'll be tested on data structures no matter where you go. You're a stronger candidate if you know them well than if you have some existence tinkering in this one specific game dev engine, which is usually just a bonus.
 
Why would you pick the other 2 over game dev fundamentals?

Adding to my other post, if you do decide to extend another semester, take Game Dev Fundamentals, Game Engine Techniques, and Game Content Creation. But I don't think it's necessary, just get out there.
 
Backend Java -> Scala
Application Java -> C#
Ruby/Python -> Go
Javascript -> Ask a Magic 8 Ball.
Fortran -> Julia (Though Physics still resists.)
5 Figure Cobal -> 6 Figure Cobal
Common Lisp -> Clojure
Scheme -> Racket
Erlang -> Elixir
Systems Obj-C -> Systems Obj-C
Applications Obj-C -> Swift
C/C++ -> Rust
SML -> F#
Haskell -> OCaml
OCaml -> Haskell
Delphi -> Delphi (What don't they want us to know...)
The bolded definitely aren't happening, BTW. :)

edit: Does application java still exist? Please tell me it doesn't. :(

Until you try to refactor some code and end up fixing bugs for the next week because there's no concept of a compiler helipng you find errors.
Do you not have a linter + comprehensive unit tests? JIT languages, weakly typed languages require it. If you're fixing bugs for a week, that's a you problem.

Or until you try to write multi-threaded code and you realize it's not as well thought out as you first thought.
Each language has its strengths and weaknesses. I wouldn't try to write multithreaded code in python, I'd use something else. I also wouldn't write a web app in C++, I'd use something else. (probably python. maybe go if I'm feeling frisky)

It seems reasonable to note that shared-state multithreaded code is not a very performant way to scale to multiple CPUs. Even with the coolest threadsafe data structures you can find, when you start benchmarking, NUMA and synchronization kill you every time.

Or until you get an Architecture Astronaut on your team and end up with so many levels of dynamic indirection it makes Boost.Spirit look like Hello World in comparison.
This can happen in any language.

Or until you try to upgrade to 3.0 and commit suicide because it's less painful.
The full-break between 2.x and 3.x is one of the better things about the language. It makes the transition painful, but it'll keep python in a great place going forward.

Also, pip is excellent.
 

Onemic

Member
Data Structures is a straight up requirement, it's the foundation of everything. Every serious engineer, game dev or not, needs to know about data structures.

So it comes down to which of the two game dev courses to eliminate. It wasn't a clear cut decision, but i chose to keep Game Engine Development since it looks like it contains practical experience with important APIs like DirectX and OpenGL

More practically, you'll be tested on data structures no matter where you go. You're a stronger candidate if you know them well than if you have some existence tinkering in this one specific game dev engine, which is usually just a bonus.

Adding to my other post, if you do decide to extend another semester, take Game Dev Fundamentals, Game Engine Techniques, and Game Content Creation. But I don't think it's necessary, just get out there.

Thanks for the advice. Im definitely looking to graduate as soon as I'm done co-op, so I'll just stick to those two classes.

Guess I should start practicing my math again early to get ready for the game engine class.
 

Big Chungus

Member
First time working with Web API, trying to pull data into a Windows Form Application in Visual Studio, gets lots of errors...

Using Giant Bomb's API, for now trying to get the games name to pop up in a messagebox but I have no idea how to pull the name

It's also giving me an error when I try to run it, it shows "UnsupportedMediaTypeException was unhandled by user code", it seems to happen when it reaches:

Product product = await response.Content.ReadAsAsync<Product>();

Anyone have any idea whats going on or maybe some advice?

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Net.Http.Headers;


namespace RetroCollection
{

    class Product
    {
        public int id { get; set; }
        public string name { get; set; }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void btnSubmit_Click(object sender, EventArgs e)
        {
            await RunAsync();
            
        }

        static async Task RunAsync()
        {
            using(var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://www.giantbomb.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync("api/game/3030-4725/?api_key={bunch of numbers]");

                MessageBox.Show((response.StatusCode).ToString());

                if(response.IsSuccessStatusCode)
                {
                    MessageBox.Show("inside");
                    Product product = await response.Content.ReadAsAsync<Product>();
                    MessageBox.Show("{0}", product.name);
                    
                }
            }
        }
    }

}
 
Why would you pick the other 2 over game dev fundamentals?

If you don't understand Data Structures you'll be laughed out of most game dev job interviews anyhow.

I minored in game development and only two classes I took in the entire minor that were specifically on game development ended up being relevant to getting work in the games industry: a class on game engine architecture and a project class. The project class was important because it gave me experience working on a team and a completed game to show, but I could've done had that without a class. Game engines was useful because it taught me which concepts from computer science were most important. Everything else I learned was just bonus knowledge that didn't help me land a job in any way.

Things you will need to know:

Data structures
Algorithm analysis
Debugging
3d Math
Pointers
Object Oriented Programming (especially virtual functions/classes)
Data Oriented Design

Bonus things that might come up in interviews:
Assembly
Shaders
Networking
Scripting Languages
Data Synchronization/Concurrency

Things that have never come up:
My ability to create assets beyond programmer art.

In general I've found a lot of older lead programmers don't particularly value the stuff most diploma mill game dev programs (re digipen/full sail) provide and prefer strong computer science fundamentals above all else. Now, sketchy mobile startups will hire anyone with half a brain and a bit of Unity knowledge, but that's another story.
 
First time working with Web API, trying to pull data into a Windows Form Application in Visual Studio, gets lots of errors...

Using Giant Bomb's API, for now trying to get the games name to pop up in a messagebox but I have no idea how to pull the name

It's also giving me an error when I try to run it, it shows "UnsupportedMediaTypeException was unhandled by user code", it seems to happen when it reaches:

Product product = await response.Content.ReadAsAsync<Product>();

Anyone have any idea whats going on or maybe some advice?

Code:
code
It looks like deserializing the response from the server into a Product doesn't work. Look at the JSON that the API sends back to you, you can use the ReadAsStringAsync method on the content of the response.
 

injurai

Banned
The bolded definitely aren't happening, BTW. :)

edit: Does application java still exist? Please tell me it doesn't. :(

It's funny that you mentioned those specifically, because those were the two I felt were I was mostly projecting wishful thinking and bullshiting on. Python/Ruby usecase is too broad, some people are moving onto other things while others are flocking to them.

Now I expect C will always be the linux systems language, C++ will always be the Windows sys language. C++ will also always be the graphical application language.

I see Rust primarily used as parallel backend application, and FFI/Library language. If Rust ever does take off it will be twenty years from now after it's fought the same uphill battle has haskell. But then all of Rust will probably be incorporated as a proper subset and coding discipline of C++ by then...

edit: oh and application Java, that's unfortunately a thing on Android. Luckily it's been on it's way out on most other platforms for a while now. It's really nothing but corporate backends from my experience.
 

Gattsu25

Banned
Taking part in the current reddit /r/dailyprogrammer Intermediate challenge and I actually found most of the base challenge to be a piece of cake...but wasted several hours trying to figure out how to optimize my code.

It's single threaded/process and the slow response times from the server on HTTP 404s are severely slowing everything down. I figured that multi-threading this would be able to give me some improvement in total time but after looking around for several hours I couldn't figure out exactly what is needed to get multiple threads to consume items from my API list in a thread-safe manner.

In the end, I stripped out all of that code and submitted what you see below:

Python3
Code:
from urllib import request
from datetime import datetime
import itertools
import logging


logging.basicConfig(level=logging.DEBUG,
                    format='(%(asctime)s [%(levelname)s] -%(threadName)-10s-) '
                    + '%(message)s')
markets = ['bitfinex', 'bitstamp', 'btce', 'itbit', 'anxhk', 'hitbtc',
           'kraken', 'bitkonan', 'bitbay', 'rock', 'cbx', 'cotr', 'vcx']
currencies = ['KRW', 'NMC', 'IDR', 'RON', 'ARS', 'AUD', 'BGN', 'BRL', 'BTC',
              'CAD', 'CHF', 'CLP', 'CNY', 'CZK', 'DKK', 'EUR', 'GAU', 'GBP',
              'HKD', 'HUF', 'ILS', 'INR', 'JPY', 'LTC', 'MXN', 'NOK', 'NZD',
              'PEN', 'PLN', 'RUB', 'SAR', 'SEK', 'SGD', 'SLL', 'THB', 'UAH',
              'USD', 'XRP', 'ZAR']
url = []


def generate_api_list(var1, var2):
    """
    Takes both a list of markets and a list of currencies as input
    Outputs combined values in a format needed for the bitcoincharts API
    """
    logging.debug('Ingested %s Markets and %s different Currencies.' %
                  (len(var1), len(var2)))
    for i in itertools.product(var1, var2):
        url.append(i[0] + i[1])
    logging.debug('Merged Markets and Currencies into %s permutations.' %
                  (len(url)))


def return_values(input_value):
    """
    Takes combination of market and currency as input.
    Returns tab-delimited transactions if available, otherwise returns error.
    """
    try:
        req = request.Request(
            'http://api.bitcoincharts.com/v1/trades.csv?symbol=' + n)
        resp = request.urlopen(req).read().decode('utf-8').split('\n')
        for x in resp:
            if len(x) == 0:
                logging.warn('No Data for %s!' % n)
            elif x:
                di = dict([(n, [int(x.split(',')[0]), float(x.split(',')[1]),
                          float(x.split(',')[2])])])
                logging.info(
                    'For %s: The value of the transaction at %s was %.2f' %
                    (n, di[n][0], di[n][1]))
    except Exception as e:
        logging.error('Symbol %s resulted in "%s"' % (n, str(e)))


if __name__ == '__main__':
    generate_api_list(markets, currencies)
    for n in url:
        return_values(n)
    logging.info('All done!')


This is the second program* I've ever written. No formal training but I'm almost through learn Python The Hard Way and reading O'Rielly's Learning Python book while on the train to/from work.

Err...I guess this is my way of saying "Hi".


*That actually does something..
 
Taking part in the current reddit /r/dailyprogrammer Intermediate challenge and I actually found most of the base challenge to be a piece of cake...but wasted several hours trying to figure out how to optimize my code.

It's single threaded/process and the slow response times from the server on HTTP 404s are severely slowing everything down. I figured that multi-threading this would be able to give me some improvement in total time but after looking around for several hours I couldn't figure out exactly what is needed to get multiple threads to consume items from my API list in a thread-safe manner.

In the end, I stripped out all of that code and submitted what you see below:

Python3
Code:


This is the second program* I've ever written. No formal training but I'm almost through learn Python The Hard Way and reading O'Rielly's Learning Python book while on the train to/from work.

Err...I guess this is my way of saying "Hi".


*That actually does something..

Looks good! The CSV parsing looks a little inefficient, since you're splitting each line multiple times:
Code:
di = dict([(n, [int([B]x.split[/B](',')[0]), float([B]x.split[/B](',')[1]), float([B]x.split[/B](',')[2])])])
You want to store x.split(',') in some temporary variable (say row_values) and then create the dictionary from those values.

In general, I'd recommend using a CSV parser library, because CSV can be deceptively tricky to parse (since there's not really a standard format for it that every application uses).
 
It's funny that you mentioned those specifically, because those were the two I felt were I was mostly projecting wishful thinking and bullshiting on. Python/Ruby usecase is too broad, some people are moving onto other things while others are flocking to them.

Now I expect C will always be the linux systems language, C++ will always be the Windows sys language. C++ will also always be the graphical application language.

I see Rust primarily used as parallel backend application, and FFI/Library language. If Rust ever does take off it will be twenty years from now after it's fought the same uphill battle has haskell. But then all of Rust will probably be incorporated as a proper subset and coding discipline of C++ by then...

edit: oh and application Java, that's unfortunately a thing on Android. Luckily it's been on it's way out on most other platforms for a while now. It's really nothing but corporate backends from my experience.
Oh, Android. Duh.

Yeah, I'm not sure what Google's plans are for Android apps, they could keep Java around indefinitely I guess. (then again, with Oracle extorting them for re-implementing the APIs, there might be enough motivation to take the plunge and switch to something else)

re: the bolded, that's what I expect to happen too. I'm really glad Rust exists, and wish them the best. But as long as the C++ committee continues to be forward looking, all the good features are going to end up in C++ as well. (I'm hoping/waiting for C++ to adopt an equivalent of unsafe, for example)
 

0xCA2

Member
Hey guys. I'm writing a forum application in Rails and I'm stuck on limiting nested quotes.

I'm try to use regex and recursion, going down to each matching tag, counting the levels and if the current level is > max, deleting everything inside of it. Problem is that my regex is only matching the first [ quote ] with the first seen [ /quote ], and not the last as intended.

The regex is just a slight tweak of what was given in the docs of the custom bbcode library I'm using (I know very little about regex, I've tried to learn as much as I can in the past couple days but I'm still stuck). I changed it so it'd include
,
name said:
and
. Could someone examine my code and let me know what the problem could be? I'd appreciate it lots.

Code:
  def remove_nested_quotes(post_string, max_quotes, count)
    result = post_string.match(/\[quote(:.*)?(?:)?(.*?)(?:)?\](.*?)\[\/quote\1?\]/mi)

    if result.nil?
      return false
    elsif  (count = count+1) > max_quotes
      full_str = result[0]
      offset_beg = result.begin(3)
      offset_end = result.end(3)
      excess_quotes = full_str[offset_beg ..offset_end ]
      new_string = full_str.slice(excess_quotes )
      return new_string
    else
      offset_beg = result.begin(3)
      offset_end = result.end(3)
      full_str = result[0]
      inner_string = full_str[offset_beg..offset_end]
      return remove_nested_quotes(inner_string , max, count)
    end
 end
 

Big Chungus

Member
It looks like deserializing the response from the server into a Product doesn't work. Look at the JSON that the API sends back to you, you can use the ReadAsStringAsync method on the content of the response.

Looks like it uses XML, when I use ReadAsStringAsync it gives me a huge string which is the entire XML structure.

Not sure how to parse out the data that I want, I looked online but it says I have to use XMLDocument.

Anyone know of a simpler way?
 
Looks like it uses XML, when I use ReadAsStringAsync it gives me a huge string which is the entire XML structure.

Not sure how to parse out the data that I want, I looked online but it says I have to use XMLDocument.

Anyone know of a simpler way?

Try passing the &format=json argument with your API call. I think the API ignores the HTTP Accept header. It'll result in a big JSON result. You can however control which fields you want to have in your response by passing the field_list argument (see here).
 

Bollocks

Member
I have a little logic/design problem, given I have the following html

Code:
<div1><span1>foo</span1><div1>
<div2><span2>foo</span2><div2>
<div3><span3>foo</span3><div3>

I want to iterate through it recursively, however I want to process div1, then div2 and then div3, then I want to go back up and go INTO div 1 and examine span 1.
Then I want to go INTO div 2 and examine span 2 and so on.

I have a hard time expressing that recursive behaviour in code.
If it would be top to bottom like div1>span1>div2>span2>div3>span3 it would be easy but I cant use that approach
 

phoenixyz

Member
I have a little logic/design problem, given I have the following html

Code:
<div1><span1>foo</span1><div1>
<div2><span2>foo</span2><div2>
<div3><span3>foo</span3><div3>

I want to iterate through it recursively, however I want to process div1, then div2 and then div3, then I want to go back up and go INTO div 1 and examine span 1.
Then I want to go INTO div 2 and examine span 2 and so on.

I have a hard time expressing that recursive behaviour in code.
If it would be top to bottom like div1>span1>div2>span2>div3>span3 it would be easy but I cant use that approach

Well, you can simulate an iteration via recursion

Code:
function doStuff1(list, index):
    // do some stuff with list[index]
    doStuff1(list, index+1)

But why do you even want to do it recursively?
 

Bollocks

Member
Well, you can simulate an iteration via recursion

Code:
function doStuff1(list, index):
    // do some stuff with list[index]
    doStuff1(list, index+1)

But why do you even want to do it recursively?

Because in my humble beginnings with micro controllers I was taught that recursion is bad so I subsequently never used it, even on modern platforms/languages but recently used it to rewrite a parser because why the fuck not and holy shit was it less code and therefore easier to understand. kinda my aha moment :D

But no real reason to use recursion.

Seems like Level Order Traversal is the algorithm I'm looking for
e: actually not, but at least I have a direction
 

Somnid

Member
The basic structure would be something like:

Code:
function getChildren(element){
   var children = [].concat(element.children);
   for(var i = 0; i < element.children.length; i++){
      children = children.concat(getChildren(element.children[i]));
   }
   return children;
}

var children = getChildren(element);

//doStuff
 
Because in my humble beginnings with micro controllers I was taught that recursion is bad so I subsequently never used it, even on modern platforms/languages but recently used it to rewrite a parser because why the fuck not and holy shit was it less code and therefore easier to understand. kinda my aha moment :D

But no real reason to use recursion.

Seems like Level Order Traversal is the algorithm I'm looking for
e: actually not, but at least I have a direction
You've got a real reason not to use recursion. Recursion is good for recursive data structures and complicated algorithms with obvious base cases. Using recursion where the only thing changing is an incrementing index is going to blow your stack for no good reason.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
That's just a breadth first search isn't it?

@Somnid: I think your skeleton still goes down by depth, only you're adding an entire level before moving down the first element of that level.
 

wolfmat

Confirmed Asshole
0xCA2 said:
Hey guys. I'm writing a forum application in Rails and I'm stuck on limiting nested quotes.

I'm try to use regex and recursion, going down to each matching tag, counting the levels and if the current level is > max, deleting everything inside of it. Problem is that my regex is only matching the first [ quote ] with the first seen [ /quote ], and not the last as intended.

The regex is just a slight tweak of what was given in the docs of the custom bbcode library I'm using (I know very little about regex, I've tried to learn as much as I can in the past couple days but I'm still stuck). I changed it so it'd include
,
name said:
and
. Could someone examine my code and let me know what the problem could be? I'd appreciate it lots.

Code:
  def remove_nested_quotes(post_string, max_quotes, count)
    result = post_string.match(/\[quote(:.*)?(?:)?(.*?)(?:)?\](.*?)\[\/quote\1?\]/mi)

    if result.nil?
      return false
    elsif  (count = count+1) > max_quotes
      full_str = result[0]
      offset_beg = result.begin(3)
      offset_end = result.end(3)
      excess_quotes = full_str[offset_beg ..offset_end ]
      new_string = full_str.slice(excess_quotes )
      return new_string
    else
      offset_beg = result.begin(3)
      offset_end = result.end(3)
      full_str = result[0]
      inner_string = full_str[offset_beg..offset_end]
      return remove_nested_quotes(inner_string , max, count)
    end
 end

Not gonna comment on your specific issue, but generally, I recommend http://www.regexr.com/ to people who want to get in touch with regular expressions. Direct visual feedback helps a lot.
 
Top Bottom