Open Side Menu Go to the Top
Register
Programming homework and newbie help thread Programming homework and newbie help thread

05-08-2018 , 02:32 AM
I'm using document.write but having weird problems with functions I've declared inside the HTML i'm writing.

particularly anything that gets called by "onclick" events that i declare in the tag. I probably should not do that in the tag and add an eventlistener but I'm not sure if that's what the real problem is.
Programming homework and newbie help thread Quote
05-08-2018 , 02:35 AM
but thanks so much guys. I'm so bad at JS. it's so frustrating debugging php/JS.

one last thing if you wanna be super duper helpful, by tomorrow morning for 25% of the grade I have to come up with 2 "non trivial" uses of AJAX. What would be some easy to implement things that just use vanilla JS and look cool?

i have basic forms to submit and some product info but that's about the whole website. It's ecommerce related.
Programming homework and newbie help thread Quote
05-08-2018 , 05:46 AM
Quote:
Originally Posted by jmakin
I'm using document.write but having weird problems with functions I've declared inside the HTML i'm writing.

particularly anything that gets called by "onclick" events that i declare in the tag. I probably should not do that in the tag and add an eventlistener but I'm not sure if that's what the real problem is.
*disclaimer - it's been ages since I've used document.write so this may be wrong...

This is a situation where you'll be wanting to target an existing DIV tag to output your results. Calling a document.write from an onClick handler (so, after the document has finished loading) will emit the output after the closing </body></html> tags, so it probably won't be shown or it seems in Firefox it starts a new document (replacing what's already there entirely)

Try this:

Code:
<html>

<body>
  <script>
    document.write('<h1>A Simple Demo</h1>');
  </script>
  <a href="" onClick="document.getElementById('resultarea').innerHTML = '<h2>You clicked link A</h2>'; return false;">Link A</a>
  <br/>
  <a href="" onClick="document.getElementById('resultarea').innerHTML = '<h2>You clicked link B</h2>'; return false;">Link B</a>
  <br/>
  <a href="" onClick="document.write('<h2>You clicked link C</h2>'); return false;">Link C</a>
  <br/>
  <div id="resultarea"></div>
</body>

</html>
Hopefully demonstrates how things work.
Programming homework and newbie help thread Quote
05-08-2018 , 05:51 AM
Ideas for non-trivial AJAX ecommerce related...

An auto-suggesting search? that would be 2 ajaxes, one for the autocomplete and one for the results. Probably way too "non-trivial"...
Programming homework and newbie help thread Quote
05-08-2018 , 10:22 AM
Yea that makes sense.

They suggested auto complete But I already have auto complete implemented in my HTML and didn’t really want to rewrite it. I have a few hours and I can afford to tank this assignment, but I was thinking of sending an email of the form information to the user. Not sure how complicated this would be, it seems like PHP has good support for it
Programming homework and newbie help thread Quote
05-08-2018 , 03:23 PM
Programmer tendencies in a nutshell:
https://github.com/urigoren/ssh_decorator/issues/11

Someone points out a backdoor installed in a python package. Someone else comes along to show how to write the backdoor more efficiently.
Programming homework and newbie help thread Quote
05-12-2018 , 08:46 PM
python pros:

This is a wrapper that typechecks an argument passed into a function.

I need to write another wrapper @ReturnTypes that checks the return value. How would i go about this?

Code:
class AcceptTypes():
    def __init__(self, *args):
        self._args = args

    def __call__(self, f):
        def wrapped_f(*args):
            for i in range(len(self._args)):
                if type(args[i]) <> self._args[i]:
                    raise TypeError("Expecting %s got %s" % (str(self._args[i]), str(type(args[i]))))
            return f(*args)
        return wrapped_f
#
# The functions
#
@AcceptTypes(str)
def extract_words(path_to_file):
    with open(path_to_file) as f:
        str_data = f.read()
    pattern = re.compile('[\W_]+')
    word_list = pattern.sub(' ', str_data).lower().split()
    with open('./stop_words.txt') as f:
        stop_words = f.read().split(',')
    stop_words.extend(list(string.ascii_lowercase))
    return [w for w in word_list if not w in stop_words]
Programming homework and newbie help thread Quote
05-12-2018 , 09:19 PM
I figured it out, but have no idea why it works:

Code:
class ReturnTypes():
        def __init__(self,*args):
                self._args = args
        def __call__(self, f):
                def wrapped(*args):
                        r = f(*args)

                        if type(r) <> self._args[0]:
                                raise TypeError("Expected %s got %s" % (str(self._args[0]), str(type(r))))
                        return r
                return wrapped
and put @ReturnTypes(<desired type>) in front of @AcceptTypes


particularly confused why if i remove "return r" the program no longer works. AcceptTypes calls and returns the function - why does return types "wrapped" have to?
Programming homework and newbie help thread Quote
05-13-2018 , 01:59 AM
It's important to remember that

Code:
@mywrapper
def foo():
   something
is the same as

Code:
def foo():
    something

foo = mywrapper(foo)
And in your particular case, consider that your first wrapper does
return f(*args)

and your seconds does the same thing, but has to store and check the return value before returning, so it does
r = f(*args)
... check r
return r

So they're both returning the result of f(*args), the 2nd version just does an extra step with it.
Programming homework and newbie help thread Quote
05-13-2018 , 01:59 PM
I tried removing the return f(*args) from accept types, and it no longer works if I do that either. They both have to return for this to work. That's what I'm a little confused about, why the original function seems to have to be returned twice, once in each of my __call__ methods
Programming homework and newbie help thread Quote
05-13-2018 , 03:10 PM
I really don't like this example of yours - I hope it's not your introduction to wrappers. It's a case that is more complex than is usual, because the wrapper takes arguments so there's an extra layer of indirection. Let's try a simpler example.

Let's say I wanted to make a wrapper that catches any exceptions in a function and prints the error. Let's called it "printexc"

Code:
def printexc(f):
    def wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception as e:
            print("An error occurred: {}".format(e))

    return wrapper

@printexc
def test1():
    return 1

@printexc
def test2():
    raise Exception("foo")


print("test1")
test1()

print()
print("test2")
test2()
This outputs
Code:
test1

test2
An error occurred: foo

See what's happening here? Wrapping test1 with printexc is the same as saying
test1 = printexc(test1)
printexc() is a function that returns the function "wrapper" right now. The code in "wrapper" doesn't run until you try to invoke test1(). When you do, it runs wrapper instead.

wrapper needs to return f(*args, **kwargs) because otherwise whatever has called test1 won't get it's return value.

If you had another wrapper called, like, printexc2 and you used both, like
Code:
@printexc
@prntexc2
def foo():
   ... do somethnig
Then this is the equivalent of
Code:
foo = printexc(printexc2(foo))
So when you invoke foo, its going to call the wrapper() returned by printexc, then it's going to call the wrapper() returned by printexc2, which is then going to call foo.

It's layered, so each layer has to call the function it wraps, and return the return value back up the stack.

Last edited by RustyBrooks; 05-13-2018 at 03:23 PM.
Programming homework and newbie help thread Quote
05-17-2018 , 01:04 PM
Anyone here familiar with DAX? Trying to work out the most efficient way to code some stuff
Programming homework and newbie help thread Quote
05-17-2018 , 02:54 PM
Quote:
Originally Posted by RustyBrooks
I really don't like this example of yours - I hope it's not your introduction to wrappers. It's a case that is more complex than is usual, because the wrapper takes arguments so there's an extra layer of indirection. Let's try a simpler example.

Let's say I wanted to make a wrapper that catches any exceptions in a function and prints the error. Let's called it "printexc"

Code:
def printexc(f):
    def wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception as e:
            print("An error occurred: {}".format(e))

    return wrapper

@printexc
def test1():
    return 1

@printexc
def test2():
    raise Exception("foo")


print("test1")
test1()

print()
print("test2")
test2()
This outputs
Code:
test1

test2
An error occurred: foo

See what's happening here? Wrapping test1 with printexc is the same as saying
test1 = printexc(test1)
printexc() is a function that returns the function "wrapper" right now. The code in "wrapper" doesn't run until you try to invoke test1(). When you do, it runs wrapper instead.

wrapper needs to return f(*args, **kwargs) because otherwise whatever has called test1 won't get it's return value.

If you had another wrapper called, like, printexc2 and you used both, like
Code:
@printexc
@prntexc2
def foo():
   ... do somethnig
Then this is the equivalent of
Code:
foo = printexc(printexc2(foo))
So when you invoke foo, its going to call the wrapper() returned by printexc, then it's going to call the wrapper() returned by printexc2, which is then going to call foo.

It's layered, so each layer has to call the function it wraps, and return the return value back up the stack.
That makes sense. Thank you.
Programming homework and newbie help thread Quote
05-18-2018 , 06:18 PM
I dunno if this would be solvable via knapsack problem solutions or what, but I’m interested in figuring out a solution that’s basically the opposite of grep -c. Meaning, instead of entering a string and seeing how many times it’s in a file, I want to enter a number and see how many patterns are in a file that many times exactly and what those patterns are. This would be for about 10mb files or so.

Does this make sense? Would it take eternity to process a single file?
Programming homework and newbie help thread Quote
05-18-2018 , 10:28 PM
You'd need a minimum length of the pattern and the algorithm might be a little tricky to write, but for 10MB files it shouldn't be too bad.
Programming homework and newbie help thread Quote
05-19-2018 , 01:54 PM
Probably going to need a maximum length pattern as well, but it or something similar to it has probably been done by some cryptanalyst somewhere...

Like here: https://www.dcode.fr/frequency-analysis Well, the first step anyway, it will find all the times a pattern is in a file.

Here are the 4 letter patterns that show up in your post Loki:
Code:
↑↓	↑↓
WHAT	2
WOUL	2
UTIO	2
THIS	2
TMAN	1
ETHA	1
AFIL	1
YTIM	1
ESEX	1
EPAT	1
THOS	1
YAND	1
ACTL	1
REIN	1
RNSA	1
ERAN	1
NUMB	1
TERA	1
TOEN	1
DSEE	1
HOWM	1
TERN	1
ATTE	1
ANYP	1
WANT	1
ORAB	1
ERNI	1
KEET	1
ITTA	1
OULD	1
TYTO	1
PROC	1
LEFI	1
SING	1
ESSA	1
NSEW	1
KESE	1
OUTM	1
ILEI	1
DBEF	1
BFIL	1
ESOR	1
ISMA	1
ESTH	1
SODO	1
SARE	1
TIME	1
TEDI	1
ERES	1
MINT	1
BUTI	1
NFIG	1
URIN	1
NTHA	1
ASOL	1
GOUT	1
NSOR	1
MSOL	1
OLVA	1
DBES	1
NOIF	1
BLEV	1
IAKN	1
OBLE	1
CKPR	1
APSA	1
TSBA	1
SICA	1
ANDS	1
RING	1
GAST	1
ERIN	1
EEIN	1
GHOW	1
SITS	1
IDUN	1
MANY	1
FENT	1
EADO	1
POSI	1
HEOP	1
LLYT	1
TEOF	1
GREP	1
INST	1
NING	1
CMEA	1
INAF	1
Programming homework and newbie help thread Quote
05-19-2018 , 04:17 PM
i think i actually used that once at a capture-the-flag competition, hehe

The only problem is that I don't know the size of string i'm looking for. If I could build on what they've got and move from a given minimum to a maximum (with some exclusions) that would be pretty helpful... maybe.

appreciate the responses on this
Programming homework and newbie help thread Quote
05-20-2018 , 12:36 AM
you need to know the max len, but just keep some type of hashmap and then iterate through it and output all the patterns where their freq = your N.

it's girthy, but for 10MB it's not that hard of a brute force solution. just set max len to like 100bytes or something.
Programming homework and newbie help thread Quote
05-20-2018 , 12:39 AM
idk why but your problem reminds me of one i'm working on, the lempel ziv sliding window algorithm for file compression:

Lempel-Ziv Sliding Window
Programming homework and newbie help thread Quote
05-23-2018 , 02:20 AM
Noob javascript question.

I have a function:

Code:
foo () { ... calls another webserver to do some computation .. }
foo() needs to return a value from that webserver. So obviously it has to be a synchronous request right? I can't change how foo() gets called here. I'm using XMLHttpRequest and everyone on the internet is saying it's deprecated. Even Google says the same.

How do fulfill foo() when it requires a synchronous return?

I'm doing a company coding challenge and rather than do the computation in javascript, I neglected to write my code in python and have this javascript code call my python server.
Programming homework and newbie help thread Quote
05-23-2018 , 02:43 AM
Need a bit more information. It's not clear from what you said why the request has to be synchronous. Why can't you use a callback?
Programming homework and newbie help thread Quote
05-23-2018 , 03:08 AM
Not sure how I can make it work with a callback. Correct me if I'm wrong, but generally callbacks are used to call another function or mutate some state.

foo() --> async call --> (what does foo() return??)

If foo() blocks then it's no longer async anymore.

I'm not the one calling foo() so I can't modify that person's code.
Programming homework and newbie help thread Quote
05-23-2018 , 03:25 AM
Instead of XMLHttpRequest, I would point you towards fetch as a first step (https://developers.google.com/web/up...ction-to-fetch).

Then I think you'll want to look into async/await (https://javascript.info/async-await, https://medium.com/@kvosswinkel/is-j...e-7aa9dd8f3bfb funfunfunction video at the end is solid too). Adding async out in front of the function declaration will allow you to use await, which makes it act like synchronous request.

Code:
// fetch
function foo() {
    return fetch('https://api.twoplustwo.com/')
        .then(response => return response.json())
}

// async/await
async function foo() {
    const response = await fetch('https://api.twoplustwo.com/')
    const data = await response.json()
    return data
}
Programming homework and newbie help thread Quote
05-23-2018 , 07:06 AM
so do you want to wait for foo to finish and return a value before you execute your code?
Programming homework and newbie help thread Quote
05-23-2018 , 11:17 AM
Quote:
Originally Posted by Victor
so do you want to wait for foo to finish and return a value before you execute your code?
Sounds like he has to, because the consumer/called of foo is expecting a value, not a promise etc.
Programming homework and newbie help thread Quote

      
m