def generate(data): sf = 2 # Matrix shape M = 3 myNumber = 2.148233 # Generating the orthogonal matrix U # (numbers rounded with 2 decimal digits) X = np.random.rand(M, M) Q,R = sla.qr(X) U = np.around(Q, sf + 1) b = np.random.rand(M) bc = b.reshape((M, 1)) br = b.reshape(1, M) data['params']['sf'] = sf data['params']['M'] = M data['params']['U'] = pl.to_json(U) data['params']['myNumber'] = pl.to_json(myNumber) data['params']['b'] = pl.to_json(br) data['params']['c'] = pl.to_json(bc) return data
def generate(data): sf = 2 # Matrix shape M = 3 myNumber = 2.148233 # Generating the orthogonal matrix U # (numbers rounded with 2 decimal digits) X = np.random.rand(M, M) Q, R = sla.qr(X) U = np.around(Q, sf + 1) b = np.random.rand(M) bc = b.reshape((M, 1)) br = b.reshape(1, M) data['params']['sf'] = sf data['params']['M'] = M data['params']['U'] = pl.to_json(U) data['params']['myNumber'] = pl.to_json(myNumber) data['params']['b'] = pl.to_json(br) data['params']['c'] = pl.to_json(bc) return data
def generate(data): # Dimensions nInnerMin = 2 nMax = 5 nRows = np.random.randint(1,nMax+1) nInner = np.random.randint(nInnerMin,nMax+1) nCols = np.random.randint(1,nMax+1) # Number of digits after the decimal nDigits = 1 # Range of entries numMax = 10 # The two matrices to be multiplied A = np.random.random_integers(-numMax,numMax,(nRows,nInner))/(10**nDigits) B = np.random.random_integers(-numMax,numMax,(nInner,nCols))/(10**nDigits) # Product of these two matrices C = A.dot(B) # Modify data and return data["params"]["A"] = pl.to_json(A) data["params"]["B"] = pl.to_json(B) data["correct_answers"]["C"] = pl.to_json(C)
def generate(data): df = pd.io.parsers.read_csv("breast-cancer-train.dat", header=None) data['params']['df'] = pl.to_json(df.head(15)) data['params']['matrix'] = pl.to_json(np.random.random((3, 3))) data['params']['my_dictionary'] = {'a': 1, 'b': 2, 'c': 3} return data
def parse(element_html, data): element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') # Get true answer a_tru = pl.from_json(data['correct_answers'].get(name, None)) if a_tru is None: return a_tru = np.array(a_tru) if a_tru.ndim != 2: raise ValueError('true answer must be a 2D array') else: m, n = np.shape(a_tru) A = np.empty([m, n]) # Create an array for the submitted answer to be stored in data['submitted_answer'][name] # used for display in the answer and submission panels # Also creates invalid error messages invalid_format = False for i in range(m): for j in range(n): each_entry_name = name + str(n * i + j + 1) a_sub = data['submitted_answers'].get(each_entry_name, None) if a_sub is None: data['submitted_answers'][each_entry_name] = None data['format_errors'][ each_entry_name] = '(No submitted answer)' invalid_format = True elif not a_sub: data['submitted_answers'][each_entry_name] = None data['format_errors'][ each_entry_name] = '(Invalid blank entry)' invalid_format = True else: a_sub_parsed = pl.string_to_number(a_sub, allow_complex=False) if a_sub_parsed is None: data['submitted_answers'][each_entry_name] = None data['format_errors'][each_entry_name] = '(Invalid format)' invalid_format = True elif not np.isfinite(a_sub_parsed): data['submitted_answers'][each_entry_name] = None data['format_errors'][ each_entry_name] = '(Invalid format - not finite)' invalid_format = True else: data['submitted_answers'][each_entry_name] = pl.to_json( a_sub_parsed) A[i, j] = a_sub_parsed if invalid_format: with open('pl-matrix-component-input.mustache', 'r', encoding='utf-8') as f: data['format_errors'][name] = chevron.render( f, { 'format_error': True }).strip() data['submitted_answers'][name] = None else: data['submitted_answers'][name] = pl.to_json(A)
def generate(data): sympy.var('y b a m') x = (y - b) / a z = m * (sympy.cos(a) + sympy.I * sympy.sin(a)) c = a + sympy.I * b data['correct_answers']['x'] = pl.to_json(x) data['correct_answers']['z'] = pl.to_json(z) data['correct_answers']['I'] = 'V / R' data['correct_answers']['c'] = pl.to_json(c)
def parse(element_html, data): element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') # Get true answer a_tru = pl.from_json(data['correct_answers'].get(name, None)) if a_tru is None: return a_tru = np.array(a_tru) if a_tru.ndim != 2: raise ValueError('true answer must be a 2D array') else: m, n = np.shape(a_tru) A = np.empty([m, n]) # Create an array for the submitted answer to be stored in data['submitted_answer'][name] # used for display in the answer and submission panels # Also creates invalid error messages invalid_format = False for i in range(m): for j in range(n): each_entry_name = name + str(n * i + j + 1) a_sub = data['submitted_answers'].get(each_entry_name, None) if a_sub is None: data['submitted_answers'][each_entry_name] = None data['format_errors'][ each_entry_name] = '(No submitted answer)' invalid_format = True elif not a_sub: data['submitted_answers'][each_entry_name] = None data['format_errors'][ each_entry_name] = '(Invalid blank entry)' invalid_format = True else: a_sub_parsed = pl.string_to_number(a_sub, allow_complex=False) if a_sub_parsed is None: data['submitted_answers'][each_entry_name] = None data['format_errors'][each_entry_name] = '(Invalid format)' invalid_format = True elif not np.isfinite(a_sub_parsed): data['submitted_answers'][each_entry_name] = None data['format_errors'][ each_entry_name] = '(Invalid format - not finite)' invalid_format = True else: data['submitted_answers'][each_entry_name] = pl.to_json( a_sub_parsed) A[i, j] = a_sub_parsed if invalid_format: data['format_errors'][ name] = 'At least one of the entries has invalid format (empty entries or not a double precision floating point number)' data['submitted_answers'][name] = None else: data['submitted_answers'][name] = pl.to_json(A)
def generate(data): data['params']['weight1'] = random.randint(1, 10) data['params']['weight2'] = random.randint(1, 10) mat = np.random.random((3, 3)) mat = mat / la.norm(mat, 1, axis=0) data['params']['labels'] = pl.to_json(['A', 'B', 'C']) data['params']['matrix'] = pl.to_json(mat) mat2 = np.random.binomial(1, 0.5, (3, 3)) data['params']['matrix2'] = pl.to_json(mat2)
def generate(data): N = random.choice([2, 3]) data["params"]["N"] = N for i in range(2): X = np.random.rand(N, N) name = "N" + str(i + 1) data["params"][name] = pl.to_json(X) for i in range(4): M = random.choice([j for j in range(2, 5) if j not in [N]]) X = np.random.rand(M, M) name = "M" + str(i + 1) data["params"][name] = pl.to_json(X) return data
def generate(data): N = random.choice([2,3]) data["params"]["N"] = N for i in range(2): X = np.random.rand(N,N) name = "N" + str(i+1) data["params"][name] = pl.to_json(X) for i in range(4): M = random.choice([j for j in range(2,5) if j not in [N]]) X = np.random.rand(M,M) name = "M" + str(i+1) data["params"][name] = pl.to_json(X) return data
def parse(element_html, data): element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') # Get true answer a_tru = pl.from_json(data['correct_answers'].get(name, None)) if a_tru is None: return a_tru = np.array(a_tru) if a_tru.ndim != 2: raise ValueError('true answer must be a 2D array') else: m, n = np.shape(a_tru) A = np.empty([m, n]) # Create an array for the submitted answer to be stored in data['submitted_answer'][name] # used for display in the answer and submission panels # Also creates invalid error messages invalid_format = False for i in range(m): for j in range(n): each_entry_name = name + str(n * i + j + 1) a_sub = data['submitted_answers'].get(each_entry_name, None) if a_sub is None: data['submitted_answers'][each_entry_name] = None data['format_errors'][each_entry_name] = '(No submitted answer)' invalid_format = True elif not a_sub: data['submitted_answers'][each_entry_name] = None data['format_errors'][each_entry_name] = '(Invalid blank entry)' invalid_format = True else: a_sub_parsed = pl.string_to_number(a_sub, allow_complex=False) if a_sub_parsed is None: data['submitted_answers'][each_entry_name] = None data['format_errors'][each_entry_name] = '(Invalid format)' invalid_format = True elif not np.isfinite(a_sub_parsed): data['submitted_answers'][each_entry_name] = None data['format_errors'][each_entry_name] = '(Invalid format - not finite)' invalid_format = True else: data['submitted_answers'][each_entry_name] = pl.to_json(a_sub_parsed) A[i, j] = a_sub_parsed if invalid_format: data['format_errors'][name] = 'At least one of the entries has invalid format (empty entries or not a double precision floating point number)' data['submitted_answers'][name] = None else: data['submitted_answers'][name] = pl.to_json(A)
def generate(data): # Number of digits after the decimal nDigits = 1 # Dimension n = np.random.randint(2,4) # Matrix A = np.round( np.random.rand(n,n), nDigits) # Product B = [email protected] # Return data data["params"]["nDigits"] = nDigits data["params"]["sigfigs"] = nDigits + 1 data["params"]["A"] = pl.to_json(A) data["correct_answers"]["B"] = pl.to_json(B)
def parse(element_html, data): element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') # Get submitted answer or return parse_error if it does not exist a_sub = data['submitted_answers'].get(name, None) if a_sub is None: data['format_errors'][name] = 'No submitted answer.' data['submitted_answers'][name] = None return if a_sub.strip() == '': opts = { 'format_error': True, 'format_error_message': 'the submitted answer was blank.' } with open('pl-integer-input.mustache', 'r', encoding='utf-8') as f: format_str = chevron.render(f, opts).strip() data['format_errors'][name] = format_str data['submitted_answers'][name] = None return # Convert to integer try: a_sub_parsed = pl.string_to_integer(a_sub) if a_sub_parsed is None: raise ValueError('invalid submitted answer (wrong type)') data['submitted_answers'][name] = pl.to_json(a_sub_parsed) except Exception: with open('pl-integer-input.mustache', 'r', encoding='utf-8') as f: format_str = chevron.render(f, {'format_error': True}).strip() data['format_errors'][name] = format_str data['submitted_answers'][name] = None
def generate(data): df = pd.read_csv("clientFilesQuestion/properties.csv") selected_columns = [ "Designation", "Depth (in)", 'Width (in)', 'Moment of Inertia - Ix (in^4)', 'Moment of Inertia - Iy (in^4)' ] m = len(df) pos1 = np.random.randint(0, m - 10) # note that in general, you will need to do a check if m > 10. # for simplicity, I am not doing any safety check because I know the length of my table is greater than 10 pos2 = pos1 + 10 df = df[selected_columns].iloc[pos1:pos2] m = len(df) select = random.sample(range(1, m), 4) name_list = df['Designation'].iloc[select] for i, name in enumerate(name_list): data["params"]["name" + str(i + 1)] = name Ix = df['Moment of Inertia - Ix (in^4)'].iloc[select].values h = df['Depth (in)'].iloc[select].values M = np.random.randint(2, 8) data["params"]["M"] = M data["params"]["df"] = pl.to_json(df) for i in range(len(h)): sigma = M * (h[i] / 2) / Ix[i] data["correct_answers"]["sigma" + str(i + 1)] = sigma * 100
def generate(data): # Generates number of events. x_events = random.randint(4, 7) # Control rounding n_digits = 2 # Generate random integers up to a number r = [float(random.randint(1, 100)) for i in range(x_events)] # Sum events s = sum(r) # Divide each value by sum to bring into [0, 1] # Round events a = [ round(i/s, n_digits) for i in r ] # Enforce probability summation constraint prob_sum = sum(a) capped_sum = round(1 - prob_sum, n_digits) # Truncate if not capped_sum.is_integer(): max_val = max(a) max_ind = a.index(max_val) a[max_ind] += capped_sum d = {'P(X)': a} df = pd.DataFrame(data = d) data['params']['df'] = pl.to_json(df) data['correct_answers']['p_sum'] = sum(a) data['correct_answers']['big_event'] = a.index(max(a))
def generate(data): website_list = [ "Google", "Wikipedia", "YouTube", "Instagram", "Stackoverflow", "Twitter", "NYTimes", "The Guardian", "taobao", "Amazon", "Reddit", "Netflix", "Linkedin", "Ebay", "GitHub" ] npages = 4 max_n_links = 3 min_n_links = 1 # Getting the Markov matrix M, page_names = create_markov_matrix(website_list, npages, max_n_links, min_n_links) data["params"]["M"] = pl.to_json(M) data["params"]["page_names"] = page_names # Getting the eigenvector G = 0.85 * M + (0.15 / npages) * np.ones((npages, npages)) xstar = power_iteration(G, 1e-8) probs = np.sort(xstar)[::-1] x_index_sorted = np.argsort(xstar)[::-1] first = page_names[x_index_sorted[0]] # Setting up the dropdown list dropdown_list = [] for name in page_names: if name != first: dropdown_list.append({'tag': 'false', 'ans': name}) else: dropdown_list.append({'tag': 'true', 'ans': name}) data["params"]["sites"] = dropdown_list
def parse(element_html, data): element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') allow_complex = pl.get_boolean_attrib(element, 'allow-complex', ALLOW_COMPLEX_DEFAULT) # Get submitted answer or return parse_error if it does not exist a_sub = data['submitted_answers'].get(name, None) if a_sub is None: data['format_errors'][name] = 'No submitted answer.' data['submitted_answers'][name] = None return # Convert to float or complex try: a_sub_parsed = pl.string_to_number(a_sub, allow_complex=allow_complex) if a_sub_parsed is None: raise ValueError('invalid submitted answer (wrong type)') if not np.isfinite(a_sub_parsed): raise ValueError('invalid submitted answer (not finite)') data['submitted_answers'][name] = pl.to_json(a_sub_parsed) except Exception: if allow_complex: data['format_errors'][ name] = 'Invalid format. The submitted answer could not be interpreted as a double-precision floating-point or complex number.' else: data['format_errors'][ name] = 'Invalid format. The submitted answer could not be interpreted as a double-precision floating-point number.' data['submitted_answers'][name] = None
def generate(data): df = pd.read_csv("clientFilesQuestion/properties.csv") selected_columns = [ "Designation", "Depth (in)", 'Width (in)', 'Moment of Inertia - Ix (in^4)', 'Moment of Inertia - Iy (in^4)' ] m = len(df) pos1 = np.random.randint(0, m - 10) # note that in general, you will need to do a check if m > 10. # for simplicity, I am not doing any safety check because I know the length of my table is greater than 10 pos2 = pos1 + 10 df = df[selected_columns].iloc[pos1:pos2] data["params"]["df"] = pl.to_json(df) m = len(df) select = np.random.randint(0, m) name = df['Designation'].iloc[select] data["params"]["name"] = name Ix = df['Moment of Inertia - Ix (in^4)'].iloc[select] h = df['Depth (in)'].iloc[select] M = np.random.randint(2, 8) data["params"]["M"] = M sigma = M * (h / 2) / Ix data["correct_answers"]["sigma"] = sigma * 100
def parse(element_html, data): element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') # Get allow-blank option allow_blank = pl.get_string_attrib(element, 'allow-blank', ALLOW_BLANK_DEFAULT) normalize_to_ascii = pl.get_boolean_attrib(element, 'normalize-to-ascii', NORMALIZE_TO_ASCII_DEFAULT) # Get submitted answer or return parse_error if it does not exist a_sub = data['submitted_answers'].get(name, None) if a_sub is None: data['format_errors'][name] = 'No submitted answer.' data['submitted_answers'][name] = None return if normalize_to_ascii: a_sub = unidecode(a_sub) data['submitted_answers'][name] = a_sub if not a_sub and not allow_blank: data['format_errors'][ name] = 'Invalid format. The submitted answer was left blank.' data['submitted_answers'][name] = None else: data['submitted_answers'][name] = pl.to_json(a_sub)
def parse(element_html, data): # By convention, this function returns at the first error found element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') allow_complex = pl.get_boolean_attrib(element, 'allow-complex', ALLOW_COMPLEX_DEFAULT) # Get submitted answer or return parse_error if it does not exist a_sub = data['submitted_answers'].get(name, None) if a_sub is None: data['format_errors'][name] = get_format_string('No submitted answer.') data['submitted_answers'][name] = None return # Convert submitted answer to numpy array (return parse_error on failure) (a_sub_parsed, info) = pl.string_to_2darray(a_sub, allow_complex=allow_complex) if a_sub_parsed is None: data['format_errors'][name] = get_format_string(info['format_error']) data['submitted_answers'][name] = None return # Replace submitted answer with numpy array data['submitted_answers'][name] = pl.to_json(a_sub_parsed) # Store format type if '_pl_matrix_input_format' not in data['submitted_answers']: data['submitted_answers']['_pl_matrix_input_format'] = {} data['submitted_answers']['_pl_matrix_input_format'][name] = info[ 'format_type']
def parse(element_html, data): # By convention, this function returns at the first error found element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') allow_complex = pl.get_boolean_attrib(element, 'allow-complex', False) # Get submitted answer or return parse_error if it does not exist a_sub = data['submitted_answers'].get(name, None) if a_sub is None: data['format_errors'][name] = 'No submitted answer.' data['submitted_answers'][name] = None return # Convert submitted answer to numpy array (return parse_error on failure) (a_sub_parsed, info) = pl.string_to_2darray(a_sub, allow_complex=allow_complex) if a_sub_parsed is None: data['format_errors'][name] = info['format_error'] data['submitted_answers'][name] = None return # Replace submitted answer with numpy array data['submitted_answers'][name] = pl.to_json(a_sub_parsed) # Store format type if '_pl_matrix_input_format' not in data['submitted_answers']: data['submitted_answers']['_pl_matrix_input_format'] = {} data['submitted_answers']['_pl_matrix_input_format'][name] = info['format_type']
def generate(data): data['params']['weight1'] = random.randint(1, 10) data['params']['weight2'] = random.randint(1, 10) mat = np.random.random((3, 3)) mat = mat / la.norm(mat, 1, axis=0) data['params']['labels'] = pl.to_json(['A', 'B', 'C']) data['params']['matrix'] = pl.to_json(mat) mat2 = np.random.binomial(1, 0.5, (3, 3)) data['params']['matrix2'] = pl.to_json(mat2) # chosen by dice roll, guaranteed to be random edge_mat = np.array([[-1, 0, 1, 0], [0, -1, 1, 0], [1, 0, 0, -1], [0, 1, -1, 0]]) data['params']['edge-inc-mat'] = pl.to_json(edge_mat)
def generate(data): # Dimensions n = np.random.randint(3, 5) m = np.random.randint(2, 4) A = np.round(np.random.rand(m, n), 2) b = np.round(np.random.rand(n), 2) # Product of these two matrices C = A @ b # # Modify data and return data["params"]["A"] = pl.to_json(A) data["params"]["b"] = pl.to_json(b.reshape(n, 1)) data["correct_answers"]["C"] = pl.to_json(C.reshape(m, 1))
def generate(data): N = 2 A = np.random.rand(N,N) sf = 2 B = np.round(A,sf) x = np.array([[1,2,3,4]]) data["params"]["sf"] = sf data["params"]["in"] = pl.to_json(B) data["params"]["x"] = pl.to_json(x) data["correct_answers"]["out1"] = pl.to_json(B) data["correct_answers"]["out2"] = pl.to_json(B) data["correct_answers"]["out3"] = pl.to_json(x) return data
def generate(data): mu_o = random.choice([19.7, 19.8, 19.9, 20, 20.1, 20.2]) std_gen = random.choice([1.3, 1.4, 1.5]) sample_size = random.randint(8, 11) # dataset sample_data = np.round(np.random.normal(mu_o, std_gen, sample_size), 1) data['params']['array'] = pl.to_json(sample_data) # computing the correct answer data['correct_answers']['std'] = sample_data.std()
def generate(data): # Number of digits after the decimal point to display d = 3 # Generate random vectors u = np.round(np.random.random(4), d) v = np.round(np.random.random(4), d) a = np.random.randint(1, 10) b = np.random.randint(1, 10) w = np.outer(a * u, b * v) # Release parameters data["params"]["u"] = pl.to_json(u) data["params"]["v"] = pl.to_json(v) data["params"]["a"] = a data["params"]["b"] = b data["params"]["d"] = d data["params"]["d2"] = d + 1 data["correct_answers"]["w"] = pl.to_json(w)
def generate(data): data["params"]["names_for_user"] = [] data["params"]["names_from_user"] = [{ "name": "df", "description": "dataframe as described above.", "type": "Pandas DataFrame" }] data['params']['df'] = pl.to_json( pd.DataFrame(data={ 'a': [1, 2], 'b': [3, 4] }))
def generate(data): # Generate a random value x = random.uniform(1, 2) # Fill in the Blank Inputs data["correct_answers"]["ans_rtol"] = x data["correct_answers"]["ans_sig"] = round(x, 2) data["correct_answers"]["int_value"] = 42 data["correct_answers"]["string_value"] = "Learn" # Symbolic x, y = sympy.symbols('x y') data['correct_answers']['symbolic_math'] = pl.to_json(x + y + 1) # Matrix Fill in the Blank data['correct_answers']['matrixA'] = pl.to_json(np.matrix('1 2; 3 4')) # Programming Variant of Supplying a Matrix data['correct_answers']['matrixB'] = pl.to_json(np.matrix('1 2; 3 4')) # Threejs data['correct_answers']['robotC'] = [[1, 0, 0], [0, 45, 0]] # Output elements data['params']['matrixC'] = pl.to_json(np.matrix('5 6; 7 8')) data['params']['matrixD'] = pl.to_json(np.matrix('-1 4; 3 2')) # Display python variable contents data_dictionary = { 'a': 1, 'b': 2, 'c': 3 } data['params']['data_dictionary'] = pl.to_json(data_dictionary) # Display a pandas data frame d = {'col1': [1, 2], 'col2': [3, 4]} df = pd.DataFrame(data=d) data['params']['df'] = pl.to_json(df) # Display a dynamically generated graph mat = np.random.random((3, 3)) mat = mat / np.linalg.norm(mat, 1, axis=0) data['params']['labels'] = pl.to_json(['A', 'B', 'C']) data['params']['matrix'] = pl.to_json(mat) # Overlay data['correct_answers']['c'] = (2 * (3 ** 2)) ** 0.5
def parse(element_html, data): element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') base = pl.get_integer_attrib(element, 'base', BASE_DEFAULT) # Get submitted answer or return parse_error if it does not exist a_sub = data['submitted_answers'].get(name, None) if a_sub is None: data['format_errors'][name] = 'No submitted answer.' data['submitted_answers'][name] = None return if a_sub.strip() == '': if pl.get_boolean_attrib(element, 'allow-blank', ALLOW_BLANK_DEFAULT): a_sub = pl.get_integer_attrib(element, 'blank-value', BLANK_VALUE_DEFAULT) else: opts = { 'format_error': True, 'format_error_message': 'the submitted answer was blank.', 'base': base, 'default_base': base == BASE_DEFAULT or base == 0, 'zero_base': base == 0 } with open('pl-integer-input.mustache', 'r', encoding='utf-8') as f: format_str = chevron.render(f, opts).strip() data['format_errors'][name] = format_str data['submitted_answers'][name] = None return # Convert to integer try: a_sub_parsed = pl.string_to_integer(str(a_sub), base) if a_sub_parsed is None: raise ValueError('invalid submitted answer (wrong type)') if a_sub_parsed > 2**53 - 1 or a_sub_parsed < -((2**53) - 1): data['format_errors'][ name] = 'correct answer must be between -9007199254740991 and +9007199254740991 (that is, between -(2^53 - 1) and +(2^53 - 1)).' data['submitted_answers'][name] = pl.to_json(a_sub_parsed) except Exception: with open('pl-integer-input.mustache', 'r', encoding='utf-8') as f: format_str = chevron.render( f, { 'format_error': True, 'base': base, 'default_base': base == BASE_DEFAULT or base == 0, 'zero_base': base == 0 }).strip() data['format_errors'][name] = format_str data['submitted_answers'][name] = None
def generate(data): n = 4 choice = np.random.choice(np.arange(2, dtype='int'), p=[.7, .3]) if choice == 0: # random graph correct = np.random.choice([0, 1], size=(n, n), p=[0.5, 0.5]) elif choice == 1: # ring shift = np.random.choice([1, -1]) * np.random.randint(1, n - 2) correct = np.roll(np.diag(np.ones(n)), shift) data["correct_answers"]["mat"] = pl.to_json(correct.T) data["params"]["mat"] = data["correct_answers"]["mat"] return data
def generate(data): # Fill in the Blank Inputs data["correct_answers"]["numericvalue"] = 3.14 data["correct_answers"]["integervalue"] = 42 data["correct_answers"]["stringvalue"] = "PrairieLearn" # Symbolic sympy.var('x y') data['correct_answers']['mathexpvalue'] = pl.to_json(x + y + 1) # Matrix Fill in the Blank data['correct_answers']['matrixA'] = pl.to_json(np.matrix('1 2; 3 4')) # Programming Variant of Supplying a Matrix data['correct_answers']['matrixB'] = pl.to_json(np.matrix('1 2; 3 4')) # Threejs data['correct_answers']['robotC'] = [[1, 0, 0], [0, 45, 0]] # Output elements data['params']['matrixC'] = pl.to_json(np.matrix('5 6; 7 8')) data['params']['matrixD'] = pl.to_json(np.matrix('-1 4; 3 2'))
def parse(element_html, data): element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') allow_fractions = pl.get_boolean_attrib(element, 'allow-fractions', ALLOW_FRACTIONS_DEFAULT) # Get true answer a_tru = pl.from_json(data['correct_answers'].get(name, None)) if a_tru is None: return a_tru = np.array(a_tru) if a_tru.ndim != 2: raise ValueError('true answer must be a 2D array') else: m, n = np.shape(a_tru) A = np.empty([m, n]) # Create an array for the submitted answer to be stored in data['submitted_answer'][name] # used for display in the answer and submission panels # Also creates invalid error messages invalid_format = False for i in range(m): for j in range(n): each_entry_name = name + str(n * i + j + 1) a_sub = data['submitted_answers'].get(each_entry_name, None) value, newdata = pl.string_fraction_to_number(a_sub, allow_fractions, allow_complex=False) if value is not None: A[i, j] = value data['submitted_answers'][each_entry_name] = newdata[ 'submitted_answers'] else: invalid_format = True data['format_errors'][each_entry_name] = newdata[ 'format_errors'] data['submitted_answers'][each_entry_name] = None if invalid_format: with open('pl-matrix-component-input.mustache', 'r', encoding='utf-8') as f: data['format_errors'][name] = chevron.render( f, { 'format_error': True, 'allow_fractions': allow_fractions }).strip() data['submitted_answers'][name] = None else: data['submitted_answers'][name] = pl.to_json(A)
def generate(data): mu_o = random.choice([19.7, 19.8, 19.9, 20, 20.1, 20.2]) std_gen = random.choice([1.3, 1.4, 1.5]) sample_size = random.randint(8, 11) # dataset sample_data = np.round(np.random.normal(mu_o, std_gen, sample_size), 1) # providing the dataset as pandas frame df = pd.DataFrame(data=sample_data) df.columns = ['Volume (oz)'] data['params']['df'] = pl.to_json(df) # computing the correct answer data['correct_answers']['average'] = sample_data.mean()
def generate(data): # Sample two complex numbers with real and imaginary parts that are # random integers between -5 and 5 (inclusive) a = random.randint(-5, 5) + random.randint(-5, 5)*1j b = random.randint(-5, 5) + random.randint(-5, 5)*1j # Put string representations of these two complex numbers into data['params'] data['params']['a'] = '{:.0f}'.format(a) data['params']['b'] = '{:.0f}'.format(b) # Compute the sum of these two complex numbers c = a + b # Put the sum into data['correct_answers'] data['correct_answers']['c'] = pl.to_json(c)
def parse(element_html, data): element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') # Get allow-blank option allow_blank = pl.get_string_attrib(element, 'allow-blank', False) # Get submitted answer or return parse_error if it does not exist a_sub = data['submitted_answers'].get(name, None) if a_sub is None: data['format_errors'][name] = 'No submitted answer.' data['submitted_answers'][name] = None return if not a_sub and not allow_blank: data['format_errors'][name] = 'Invalid format. The submitted answer was left blank.' data['submitted_answers'][name] = None else: data['submitted_answers'][name] = pl.to_json(a_sub)
def parse(element_html, data): element = lxml.html.fragment_fromstring(element_html) name = pl.get_string_attrib(element, 'answers-name') # Get submitted answer or return parse_error if it does not exist a_sub = data['submitted_answers'].get(name, None) if a_sub is None: data['format_errors'][name] = 'No submitted answer.' data['submitted_answers'][name] = None return # Convert to integer try: a_sub_parsed = pl.string_to_integer(a_sub) if a_sub_parsed is None: raise ValueError('invalid submitted answer (wrong type)') if not np.isfinite(a_sub_parsed): raise ValueError('invalid submitted answer (not finite)') data['submitted_answers'][name] = pl.to_json(a_sub_parsed) except Exception: data['format_errors'][name] = 'Invalid format. The submitted answer was not an integer.' data['submitted_answers'][name] = None
def generate(data): N = 2 A = np.random.rand(N,N) sf = 2 B = np.round(A,sf) x = np.array([[1,2,3,4]]) long_matrix = np.array([[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]) data["params"]["sf"] = sf data["params"]["in"] = pl.to_json(B) data["params"]["x"] = pl.to_json(x) data["correct_answers"]["out1"] = pl.to_json(B) data["correct_answers"]["out2"] = pl.to_json(B) data["correct_answers"]["out3"] = pl.to_json(x) data["correct_answers"]["out4"] = pl.to_json(long_matrix) return data