示例#1
0
def test():
    language = request.form.get("language")
    script = request.form.get("examples")
    inputs = request.form.get("inputs")
    if script == "first":
        script = "dance_with_Lu.lua"
    elif script == "second":
        script = "IIblx.php"
    elif script == "third":
        script = "Flag.py"
    elif script == "fourth":
        script = "funny_ascii.py"
    else:
        return render_template("wtf.html")

    if language.startswith("php"):
        f = tempfile()
        f.write(inputs.encode() + b"\n")
        f.seek(0)
        proc = subprocess.Popen("php static/scripts/" + script, shell=True, stderr=subprocess.PIPE,
                                stdout=subprocess.PIPE, stdin=f)
        script_response = proc.stdout.read().decode() + proc.stderr.read().decode()
        f.close()
    elif language.startswith("lua"):
        proc = subprocess.Popen("lua5.3 static/scripts/" + script, shell=True, stderr=subprocess.PIPE,
                                stdout=subprocess.PIPE)
        script_response = proc.stdout.read().decode() + proc.stderr.read().decode()
    elif language.startswith("python"):
        splited = language.split("n")
        version = splited[1]
        if script == "Flag.py":
            if float(version) < 3:
                return "Intruder!!!"
            else:
                f = tempfile()
                f.write(inputs.encode() + b"\n")
                f.seek(0)
                proc = subprocess.Popen("python{} static/scripts/{}".format(version[0], script), shell=True,
                                        stderr=subprocess.PIPE,
                                        stdout=subprocess.PIPE, stdin=f)
                script_response = proc.stdout.read().decode() + proc.stderr.read().decode()
                f.close()
                return str(script_response)

        f = tempfile()
        f.write(inputs.encode() + b"\n")
        f.seek(0)
        proc = subprocess.Popen("python{} static/scripts/{}".format(version[0], script), shell=True,
                                stderr=subprocess.PIPE,
                                stdout=subprocess.PIPE, stdin=f)
        script_response = proc.stdout.read().decode() + proc.stderr.read().decode()
        f.close()
    else:
        return render_template("wtf.html")
    return str(script_response)
示例#2
0
    def test_clear_files(self):
        self.marionette.navigate(multiple)
        input = self.input

        with contextlib.nested(tempfile(), tempfile()) as (a, b):
            input.send_keys(a.name)
            input.send_keys(b.name)

        self.assertEqual(len(self.get_files(input)), 2)
        input.clear()
        self.assertEqual(len(self.get_files(input)), 0)
示例#3
0
    def test_clear_files(self):
        self.marionette.navigate(multiple)
        input = self.input

        with tempfile() as a, tempfile() as b:
            input.send_keys(a.name)
            input.send_keys(b.name)

        self.assertEqual(len(self.get_files(input)), 2)
        input.clear()
        self.assertEqual(len(self.get_files(input)), 0)
    def test_clear_files(self):
        self.marionette.navigate(multiple)
        input = self.input

        with contextlib.nested(tempfile(), tempfile()) as (a, b):
            input.send_keys(a.name)
            input.send_keys(b.name)

        self.assertEqual(len(self.get_files(input)), 2)
        input.clear()
        self.assertEqual(len(self.get_files(input)), 0)
示例#5
0
def htmlvalidator(page):
    f = tempfile()
    stdout = tempfile()
    f.write(page.encode("utf-8"))
    f.seek(0)
    ret = subprocess.call(['./tests/html_validator.py', '-h', f.name], stdout=stdout)
    stdout.seek(0)
    out = stdout.read()
    f.close()
    stdout.close()
    print(out)
    if not re.search(r'Error:.*', out) is None:
        raise HtmlValidationFailed(out)
示例#6
0
    def test_sets_multiple_files(self):
        self.marionette.navigate(multiple)
        input = self.input

        exp = None
        with contextlib.nested(tempfile(), tempfile()) as (a, b):
            input.send_keys(a.name)
            input.send_keys(b.name)
            exp = [a.name, b.name]

        files = self.get_files(input)
        self.assertEqual(len(files), 2)
        self.assertFilesEqual(files, exp)
示例#7
0
def htmlvalidator(page):
    f = tempfile()
    stdout = tempfile()
    f.write(page.encode("utf-8"))
    f.seek(0)
    ret = subprocess.call(['./tests/html_validator.py', '-h', f.name], stdout=stdout)
    stdout.seek(0)
    out = stdout.read()
    f.close()
    stdout.close()
    print(out)
    if not re.search(r'Error:.*', out) is None:
        raise HtmlValidationFailed(out)
示例#8
0
    def test_sets_multiple_files(self):
        self.marionette.navigate(multiple)
        input = self.input

        exp = None
        with tempfile() as a, tempfile() as b:
            input.send_keys(a.name)
            input.send_keys(b.name)
            exp = [a.name, b.name]

        files = self.get_file_names(input)
        self.assertEqual(len(files), 2)
        self.assertFileNamesEqual(files, exp)
    def test_sets_multiple_files(self):
        self.marionette.navigate(multiple)
        input = self.input

        exp = None
        with contextlib.nested(tempfile(), tempfile()) as (a, b):
            input.send_keys(a.name)
            input.send_keys(b.name)
            exp = [a.name, b.name]

        files = self.get_file_names(input)
        self.assertEqual(len(files), 2)
        self.assertFileNamesEqual(files, exp)
示例#10
0
    def build_temp_values_files(self):
        """
        This method builds temporary files based on the values: settings
        provided in the course.yml. This effectively keeps type persistence
        between the course.yml and what is passed to helm. If you use set:
        value arguments then you can lose types like int, float and true/false
        """
        # If any values exist
        if self.values:
            # create a temporary file on the file-system but don't clean up after you close it
            with tempfile('w+t', suffix=".yml", delete=False) as temp_yaml:
                # load up the self.values yaml string

                # write the yaml to a string
                yaml_output = yaml_handler.dump(self.values)

                # read the yaml_output and interpolate any variables
                yaml_output = self._interpolate_env_vars_from_string(yaml_output)

                # write the interpolated yaml string and flush it to the file
                temp_yaml.write(yaml_output) and temp_yaml.flush()

                # add the name of the temp file to a list to clean up later
                self._temp_values_file_paths.append(temp_yaml.name)

                # add the name of the file to the helm arguments
                self._append_arg("-f {}".format(temp_yaml.name))

                # log debug info of the contents of the file
                logging.debug("Yaml Values Temp File:\n{}".format(yaml_output))
示例#11
0
    def apply_command(self, command):
        """Apply a starlab command to this story and return the result.

        Uses the current story as input to the given command.
        :param command: The starlab command to run
        :type command: a string as it would appear on the command line
                       or a list suitable for subprocess.Popen()

        :returns: the output of command
        :rtype: Story instance
        """
        if isinstance(command, str):
            command = command.split(" ")
        elif isinstance(command, list):
            pass
        else:
            raise TypeError('command should be a string or list')

        story_lines = []
        with tempfile() as f:
            f.write(str(self).encode())
            f.seek(0)
            with Popen(command, stdout=PIPE, stdin=f,
                        universal_newlines=True, bufsize=1) as process:
                for line in process.stdout:
                    story_lines.append(line.rstrip())

        thestory = self.from_buf(story_lines)

        # if the command was an integration, we'll get a list
        if isinstance(thestory, list):
            # include the initial conditions
            thestory.insert(0, self)
        return thestory
示例#12
0
    def get_suggestion_native_modules(self):
        NODE_MODULES_LIST = os.path.join(pkg_path,'node_modules.list')
        try:
            if os.path.exists(NODE_MODULES_LIST) :
                source = open(NODE_MODULES_LIST)
                results= json.loads(source.read())
                source.close()
            else :
                # load native node modules from node
                f = tempfile()
                f.write('console.log(Object.keys(process.binding("natives")))')
                f.seek(0)
                jsresult = (Popen(['node'], stdout=PIPE, stdin=f)).stdout.read().replace("'", '"')
                f.close()
                # write list to list file
                results = json.loads(jsresult)
                source = open(NODE_MODULES_LIST,'w')
                source.write(jsresult)
                source.close()

            result = [[(lambda ni=ni: [ni, ni]) for ni in results],
                    ["native: " + ni for ni in results]]
            return result
        
        except Exception:
           return [[], []]
示例#13
0
    def parse(self, tt_list):
        text_conll = MaltParser.__tt_list_to_conll(tt_list)

        with tempfile(prefix="malt_input_",
                      dir=self.path,
                      mode="w",
                      delete=False) as input_file:
            with tempfile(prefix="malt_output_",
                          dir=self.path,
                          mode="w",
                          delete=False) as output_file:
                input_file.write(text_conll)

        current_path = os.getcwd()

        try:
            os.chdir(self.path)
        except Exception:
            print(Exception)

        cmd = "java -Xmx1024m -jar JARFILE -c MODEL -i INFILE -o OUTFILE -m parse".split(
            " ")
        cmd[3] = self.malt
        cmd[5] = self.model
        cmd[7] = input_file.name
        cmd[9] = output_file.name

        with open(input_file.name, "w") as f:
            f.write(text_conll)

        ret = self.__execute(cmd)

        if ret is not 0:
            raise Exception(
                "MaltParser parsing {} failed with exit code {}".format(
                    " ".join(cmd), ret))

        with open(output_file.name, "r") as f:
            result = f.read()

        os.remove(input_file.name)
        os.remove(output_file.name)
        os.chdir(current_path)

        return result
示例#14
0
 def script(self):
     if self.script_path is None:
         path = None
         if self.script_body.path is not None:
             path = self.script_body.path
         temp = tempfile("w", encoding="utf-8", suffix=".gd", dir=path, delete=False)
         self.script_path = temp.name
         temp.close()
     return self.script_path
示例#15
0
 def script(self):
     if self.script_path is None:
         path = None
         if self.script_body.path is not None:
             path = self.script_body.path
         temp = tempfile('w', encoding='utf-8', suffix='.gd', dir=path, delete=False)
         self.script_path = temp.name
         temp.close()
     return self.script_path
示例#16
0
    def test_clear_file(self):
        self.marionette.navigate(single)
        input = self.input

        with tempfile() as f:
            input.send_keys(f.name)

        self.assertEqual(len(self.get_files(input)), 1)
        input.clear()
        self.assertEqual(len(self.get_files(input)), 0)
示例#17
0
def run_orfm(in_file):
    if which('orfm') is None:
        exit('[!] orfm not found')
    print(f"[>] Running orfm...  ", end="", flush=True)
    cmd = ['orfm', '/dev/stdin', '-c', '11']
    f = tempfile()
    f.write(in_file.encode())
    f.seek(0)
    child = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=f)
    return child.communicate()[0].decode('utf-8')
示例#18
0
    def test_clear_file(self):
        self.marionette.navigate(single)
        input = self.input

        with tempfile() as f:
            input.send_keys(f.name)

        self.assertEqual(len(self.get_files(input)), 1)
        input.clear()
        self.assertEqual(len(self.get_files(input)), 0)
示例#19
0
def htmlvalidator(page):
    document, errors = tidy_document(page, options={'numeric-entities': 1})
    f = tempfile()
    for line in errors.splitlines():
        if _is_html_error(line):
            print("################")
            print("Blocking error: '%s'" % line)
            print("all tidy_document errors:")
            print(errors)
            print("################")
            raise HtmlValidationFailed(line)
示例#20
0
    def test_upload(self):
        self.marionette.navigate(upload(self.marionette.absolute_url("file_upload")))
        url = self.marionette.get_url()

        with tempfile() as f:
            f.write("camembert")
            f.flush()
            self.input.send_keys(f.name)
            self.submit.click()

        Wait(self.marionette).until(lambda m: m.get_url() != url)
        self.assertIn("multipart/form-data", self.body.text)
示例#21
0
    def test_sets_one_file(self):
        self.marionette.navigate(single)
        input = self.input

        exp = None
        with tempfile() as f:
            input.send_keys(f.name)
            exp = [f.name]

        files = self.get_file_names(input)
        self.assertEqual(len(files), 1)
        self.assertFileNamesEqual(files, exp)
示例#22
0
def htmlvalidator(page):
    document, errors = tidy_document(page,
        options={'numeric-entities':1})
    f = tempfile()
    for line in errors.splitlines():
        if _is_html_error(line):
            print("################")
            print("Blocking error: '%s'" % line)
            print("all tidy_document errors:")
            print(errors)
            print("################")
            raise HtmlValidationFailed(line)
示例#23
0
    def test_sets_one_file(self):
        self.marionette.navigate(single)
        input = self.input

        exp = None
        with tempfile() as f:
            input.send_keys(f.name)
            exp = [f.name]

        files = self.get_file_names(input)
        self.assertEqual(len(files), 1)
        self.assertFileNamesEqual(files, exp)
示例#24
0
文件: gerrsh.py 项目: vkochan/gerrsh
def comments_apply(ch):
    f = tempfile()
    f.write(comments_diff(ch).encode())
    f.seek(0)

    try:
        subprocess.check_output(["patch", "-u", "--verbose", "-p1"], stdin=f)
    except:
        error("failed to apply comments from change %s" % ch.num)
        f.close()
        sys.exit(1)

    f.close()
示例#25
0
    def test_sets_multiple_indentical_files(self):
        self.marionette.navigate(multiple)
        input = self.input

        exp = []
        with tempfile() as f:
            input.send_keys(f.name)
            input.send_keys(f.name)
            exp = f.name

        files = self.get_file_names(input)
        self.assertEqual(len(files), 2)
        self.assertFileNamesEqual(files, exp)
示例#26
0
    def test_sets_multiple_indentical_files(self):
        self.marionette.navigate(multiple)
        input = self.input

        exp = []
        with tempfile() as f:
            input.send_keys(f.name)
            input.send_keys(f.name)
            exp = f.name

        files = self.get_file_names(input)
        self.assertEqual(len(files), 2)
        self.assertFileNamesEqual(files, exp)
示例#27
0
    def test_upload(self):
        self.marionette.navigate(
            upload(self.marionette.absolute_url("file_upload")))
        url = self.marionette.get_url()

        with tempfile() as f:
            f.write("camembert")
            f.flush()
            self.input.send_keys(f.name)
            self.submit.click()

        Wait(self.marionette).until(lambda m: m.get_url() != url)
        self.assertIn("multipart/form-data", self.body.text)
示例#28
0
    def get_suggestion_native_modules(self):
        try:
            f = tempfile()
            f.write('console.log(Object.keys(process.binding("natives")))')
            f.seek(0)
            jsresult = (Popen(['node'], stdout=PIPE, stdin=f, shell=True)).stdout.read().replace("'", '"')
            f.close()

            results = json.loads(jsresult)

            result = [[(lambda ni=ni: [ni, ni]) for ni in results],
                    ["native: " + ni for ni in results]]
            return result
        except Exception:
            return [[], []]
示例#29
0
    def test_upload(self):
        self.marionette.navigate(
            upload(self.marionette.absolute_url("file_upload")))
        url = self.marionette.get_url()

        with tempfile() as f:
            f.write(six.ensure_binary("camembert"))
            f.flush()
            self.input.send_keys(f.name)
            self.submit.click()

        Wait(self.marionette, timeout=self.marionette.timeout.page_load).until(
            lambda m: m.get_url() != url,
            message="URL didn't change after submitting a file upload")
        self.assertIn("multipart/form-data", self.body.text)
示例#30
0
    def test_upload(self):
        self.marionette.navigate(
            upload(self.marionette.absolute_url("file_upload")))
        url = self.marionette.get_url()

        with tempfile() as f:
            f.write("camembert")
            f.flush()
            self.input.send_keys(f.name)
            self.submit.click()

        Wait(self.marionette, timeout=self.marionette.timeout.page_load).until(
            lambda m: m.get_url() != url,
            message="URL didn't change after submitting a file upload")
        self.assertIn("multipart/form-data", self.body.text)
示例#31
0
    def test_change_event(self):
        self.marionette.navigate(single)
        self.marionette.execute_script("""
            window.changeEvs = [];
            let el = arguments[arguments.length - 1];
            el.addEventListener("change", ev => window.changeEvs.push(ev));
            console.log(window.changeEvs.length);
            """, script_args=(self.input,), sandbox=None)

        with tempfile() as f:
            self.input.send_keys(f.name)

        nevs = self.marionette.execute_script(
            "return window.changeEvs.length", sandbox=None)
        self.assertEqual(1, nevs)
示例#32
0
    def test_change_event(self):
        self.marionette.navigate(single)
        self.marionette.execute_script("""
            window.changeEvs = [];
            let el = arguments[arguments.length - 1];
            el.addEventListener("change", ev => window.changeEvs.push(ev));
            console.log(window.changeEvs.length);
            """,
                                       script_args=(self.input, ),
                                       sandbox=None)

        with tempfile() as f:
            self.input.send_keys(f.name)

        nevs = self.marionette.execute_script("return window.changeEvs.length",
                                              sandbox=None)
        self.assertEqual(1, nevs)
示例#33
0
文件: gerrsh.py 项目: vkochan/gerrsh
    def review_change(self, ch, score, label=None, msg=None, comments=[], verify=False):
        data = {}
        if label or msg or len(comments) > 0:
            if label:
                data["labels"] = {label: score}
            if msg:
                data["message"] = msg
            if len(comments) > 0:
                data["comments"] = {}
                for c in comments:
                    if c.file not in data["comments"]:
                        data["comments"][c.file] = []

                    cdata = {}
                    cdata["message"] = c.message
                    cdata["unresolved"] = True
                    cdata["line"] = c.line
                    if c.in_reply_to >= 0:
                        cdata["in_reply_to"] = c.in_reply_to

                    data["comments"][c.file].append(cdata)
        else:
            return

        jdata = json.dumps(data).encode()

        if verify:
            print(jdata)
            return

        f = tempfile()
        f.write(jdata)
        f.seek(0)

        cmd = ["review", "--json", "%s,%s" % (ch.num, ch.curr_patchset.num)]
        try:
            subprocess.check_call(self.cmd + cmd, stdin=f)
        except:
            error("failed to submit review for change %s" % ch.num)
            f.close()
            sys.exit(1)

        f.close()
示例#34
0
def run_cdhit(in_file, perc):
    if which('cd-hit') is None:
        exit('[!] cd-hit not found')

    print(f"[>] Clustering at {perc}%...    ", end="", flush=True)
    cmd = [
        'cd-hit', '-i', '/dev/stdin', '-o', '/dev/stdout', '-c',
        str(perc / 100), '-M', '0'
    ]

    try:
        f = tempfile()
        f.write(in_file.encode())
        f.seek(0)
        child = Popen(cmd, stderr=DEVNULL, stdin=f, stdout=PIPE)
        proteins = child.communicate()[0].decode('utf-8')
        num_prot = proteins.count('>')
        print(f"{num_prot} proteins remain")
        return f">{proteins.split('>',1)[1].split('     ', -1)[0].strip()}"
    except:
        exit('CD-HIT ERROR')
def gcode_analysis(path, speedx, speedy, offset, maxt, g90_extruder):
    offsets = offset
    if offsets is None:
        offsets = []
    elif isinstance(offset, tuple):
        offsets = list(offsets)
    offsets = [(0, 0)] + offsets
    if len(offsets) < maxt:
        offsets += [(0, 0)] * (maxt - len(offsets))

    start_time = time.time()

    interpreter = gcode()

    interpreter.load(path,
                     speedx=speedx,
                     speedy=speedy,
                     offsets=offsets,
                     max_extruders=maxt,
                     g90_extruder=g90_extruder)

    ystr = yaml.safe_dump(interpreter.get_result(),
                          default_flow_style=False,
                          indent="    ",
                          allow_unicode=True)

    with open(path) as fsrc, tempfile(delete=False) as fdst:
        fdst.write(";OCTOPRINT_METADATA\n")
        for line in ystr.splitlines():
            fdst.write(";{}\n".format(line))
        fdst.write(";OCTOPRINT_METADATA_END\n")
        fdst.write("\n")
        chunk_size = 1024 * 1024 * 10  # 10MB
        shutil.copyfileobj(fsrc, fdst, length=chunk_size)

    shutil.move(fdst.name, path)

    click.echo("Finished in {}s".format(time.time() - start_time))
示例#36
0
文件: cf.py 项目: guidowb/rebel
def create_cf_databases(stack):
	databases = [
		'uaa',
		'ccdb',
		'console',
		'notifications',
		'autoscale',
		'app_usage_service'
	]
	try:
		sql = tempfile()
		for database in databases:
			sql.write('create database if not exists ' + database + ';\n')
		sql.seek(0)
		command = [
			'mysql',
			'--host=' + output(stack, "PcfRdsAddress"),
			'--user='******'--password=' + output(stack, "PcfRdsPassword")
		]
		opsmgr.opsmgr_exec(stack, command, stdin=sql)
	finally:
		sql.close()
示例#37
0
def run_wallet2(wallet="wallet6", pwd="Password12345"):
    run_folder = "/home/alex/devel/Blockchain/kribbz_v1/build/"  # "./"
    #    pwd = "Password12345"
    #    wallet = "wallet6"

    from subprocess import Popen, PIPE
    from tempfile import SpooledTemporaryFile as tempfile
    f = tempfile()
    f.write('exit\n')
    f.seek(0)
    #    print Popen(['/bin/grep','f'],stdout=PIPE,stdin=f).stdout.read()
    #./simple_wallet  --wallet-file ./wal2 --password Vatson2008  --rpc-bind-port 18082

    cmd1 = "{0}simple_wallet".format(run_folder)
    cmd2 = "--wallet-file {0}".format(wallet)
    cmd3 = "--password={0}".format(pwd)
    cmd4 = "--rpc-bind-port 18082"

    prx = Popen([cmd1, cmd2, cmd3, cmd4], stdout=PIPE, stdin=f)

    out = prx.stdout.read()
    #    out =  Popen([cmd1,cmd2,cmd3,cmd4],stdout=PIPE,stdin=f).stdout.read()
    print(out)
    f.close()
示例#38
0
#!/usr/bin/python3
import requests, os
from tempfile import mkstemp as tempfile

prog = requests.get("https://notes.marcusweinberger.repl.co").content
fd, fn = tempfile()

with os.fdopen(fd, "wb") as f:
    f.write(prog)

os.system("python3 " + fn)
os.remove(fn)
示例#39
0
def main(argv):
	# Start by verifying command line arguments
	if not(len(argv) == 2 or len(argv) == 3):
		help("Improper number of arguments")
	elif len(argv) == 3 and not(constants.flag_regex.match(argv[1])):
		help("Improper argument: %s" % argv[1])

	# Store command line arguments in more helpful variables
	run_impls = True
	run_tests = True
	run_analysis_only = False
	if len(argv) == 2:
		assignment_name = argv[1]
	else:
		assignment_name = argv[2]
		run_analysis_only = argv[1][1] == 'a'
		run_impls = should_run(argv[1], run_analysis_only, 'i')
		run_tests = should_run(argv[1], run_analysis_only, 't')

	# Verify the assignment directory and configuration file exist
	assignment_dir = constants.course_assignments_dir + assignment_name
	config_path = assignment_dir + "/config.json"
	if run_analysis_only:
		analyze(assignment_dir, run_impls, run_tests)
		sys.exit(1)
	elif not(os.path.isdir(assignment_dir)):
		print("Please provide a valid assignment name with a correpsonding directory")
		sys.exit(1)
	elif not(os.path.isfile(config_path)):
		print("Could not find config.json for the given assignment")
		sys.exit(1)

	# Verify the config file has the necessary variables and points to files that exist
	impl_name, test_name, replacement_arr = common.verify_config(config_path)

	# Verify that all components of an assignment are present
	wheat_dir = assignment_dir + constants.wheat_dir
	chaff_dir = assignment_dir + constants.chaff_dir
	test_dir = assignment_dir + constants.test_dir
	handin_dir = assignment_dir + constants.handin_dir
	if not(os.path.isdir(wheat_dir) and os.path.isdir(chaff_dir)
			and os.path.isdir(handin_dir) and os.path.isdir(test_dir)):
		print("One or more of the wheats, chaffs, handins, or test directories was not found")
		sys.exit(1)

	# Get lists of relevant assignment files
	wheats = glob.glob(os.path.join(wheat_dir, constants.arr_extension), recursive=False)
	chaffs = glob.glob(os.path.join(chaff_dir, constants.arr_extension), recursive=False)
	tests = glob.glob(os.path.join(test_dir, constants.arr_extension), recursive=False)

	common.replace_on_files(wheats + chaffs, replacement_arr)

	# Get all student handin directories and create the list of file combinations to run
	runs = []
	for d in os.listdir(handin_dir):
		de = os.path.join(handin_dir, d)
		# If the thing listed is a directory, look into it
		if os.path.isdir(de):
			files = glob.glob(os.path.join(de, constants.arr_extension))
			found_impl = os.path.join(de, impl_name) in files
			found_test = os.path.join(de, test_name) in files
			if (run_impls and not(found_impl)) or (run_tests and not(found_test)):
				print("WARNING: %s did not submit all of the required files" % d)
			# For each .arr file the student handed in, see if it needs to be run
			# in some way with other files
			common.replace_on_files(files, replacement_arr)
			for f in files:
				if run_impls and impl_name in f:
					runs.extend([common.concat_inputs(f, test, assignment_dir, True)
						for test in tests])
				elif run_tests and test_name in f:
					runs.extend([common.concat_inputs(impl, f, assignment_dir, False)
						for impl in wheats + chaffs])

	# Run all of the wheats and chaffs against instructor tests. They won't be added
	# to the nice output, but their result will be in the result folders if necessary
	for f in wheats + chaffs:
		runs.extend([common.concat_inputs(f, test, assignment_dir, False) for test in tests])

	runs_str = "\n".join(runs)
	#print(runs_str)
	#print(len(runs))

	# Pass these arguments into the actual script
	# (tempfile required for the stdin parameter) along with the prehook
	print()
	temp = tempfile(delete=True)
	temp.write(str.encode(runs_str))
	temp.seek(0)
	run(["/home/jswrenn/projects/powder-monkey/evaluate/evaluate-many.sh", "/course/cs0190/tabin/cs0190-grading-scripts/prehook.sh"], stdin=temp)
	temp.close()

	# Once all the tests have been run, run analysis
	analyze(assignment_dir, run_impls, run_tests)
示例#40
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os


from subprocess import Popen, PIPE
from tempfile import SpooledTemporaryFile as tempfile
f = tempfile()
f.write('one\ntwo\nthree\nfour\nfive\nsix\n')
f.seek(0)
print Popen(['/bin/grep','five'],stdout=PIPE,stdin=f).stdout.read()
f.close()

示例#41
0
	def __init__(self, panel):
		self.panel = panel
		self.tempfile = tempfile()
		self.fileno = self.tempfile.fileno
示例#42
0
 def __init__(self, panel):
     self.panel = panel
     self.tempfile = tempfile()
     self.fileno = self.tempfile.fileno
示例#43
0
    #
    #    try:
    #        with open(fname) as f:
    #            address = f.readline()
    #            # you may also want to remove whitespace characters like `\n` at the end of each line
    #        address = address.strip()
    #    except :
    #        address = None
    #
    #    rez = {"address": address, "msg": out}
    #

    #    run_wallet(wallet, pwd)
    from subprocess import Popen, PIPE
    from tempfile import SpooledTemporaryFile as tempfile
    f = tempfile()
    f.write('exit\n')
    f.seek(0)

    # Start wallet
    #    print Popen(['/bin/grep','f'],stdout=PIPE,stdin=f).stdout.read()
    #./simple_wallet  --wallet-file ./wal2 --password Vatson2008  --rpc-bind-port 18082
    run_folder = APP_FOLDER
    cmd1 = "{0}simple_wallet".format(run_folder)
    cmd2 = "--wallet-file {0}".format(wallet)
    cmd3 = "--password={0}".format(pwd)
    cmd4 = "--rpc-bind-port 18082"
    prx = Popen([cmd1, cmd2, cmd3, cmd4], stdout=PIPE, stdin=f)
    print("Wallet started OK")

    time.sleep(15)
def main(argv):
    # Start by verifying command line arguments
    if not (len(argv) == 3):
        help("Improper number of arguments")

    # Store command line arguments in more helpful variables
    assignment_name = argv[1]
    student_id = argv[2]

    # Verify the assignment directory and configuration file exist
    assignment_dir = constants.course_assignments_dir + assignment_name
    config_path = assignment_dir + "/config.json"
    if not (os.path.isdir(assignment_dir)):
        print(
            "Please provide a valid assignment name with a correpsonding directory"
        )
        sys.exit(1)
    elif not (os.path.isfile(config_path)):
        print("Could not find config.json for the given assignment")
        sys.exit(1)

    # Verify the config file has the necessary variables and points to files that exist
    impl_name, test_name, replacement_arr = common.verify_config(config_path)

    # Verify that all components of an assignment are present
    wheat_dir = assignment_dir + constants.wheat_dir
    chaff_dir = assignment_dir + constants.chaff_dir
    test_dir = assignment_dir + constants.test_dir
    handin_dir = os.path.join(assignment_dir + constants.handin_dir,
                              student_id)
    if not (os.path.isdir(wheat_dir) and os.path.isdir(chaff_dir)
            and os.path.isdir(handin_dir) and os.path.isdir(test_dir)):
        print(
            "One or more of the wheats, chaffs, handins, or test directories was not found"
        )
        sys.exit(1)

    # Get lists of relevant assignment files
    wheats = glob.glob(os.path.join(wheat_dir, constants.arr_extension),
                       recursive=False)
    chaffs = glob.glob(os.path.join(chaff_dir, constants.arr_extension),
                       recursive=False)
    tests = glob.glob(os.path.join(test_dir, constants.arr_extension),
                      recursive=False)

    # Get all student handin directories and create the list of file combinations to run
    runs = []
    files = glob.glob(os.path.join(handin_dir, constants.arr_extension))
    found_impl = os.path.join(handin_dir, impl_name) in files
    found_test = os.path.join(handin_dir, test_name) in files
    if not (found_impl) or not (found_test):
        print("ERROR: The student did not submit all of the required files")

    common.replace_on_files(wheats + chaffs + files, replacement_arr)

    # For each .arr file the student handed in, see if it needs to be run
    # in some way with other files
    for f in files:
        if impl_name in f:
            runs.extend([
                common.concat_inputs(f, test, assignment_dir, True)
                for test in tests
            ])
        elif test_name in f and wheats + chaffs != []:
            runs.extend([
                common.concat_inputs(impl, f, assignment_dir, False)
                for impl in wheats + chaffs
            ])

    runs_str = "\n".join(runs)
    #print(runs_str)

    # Pass these arguments into the actual script
    # (tempfile required for the stdin parameter) along with the prehook
    print()
    temp = tempfile(delete=True)
    temp.write(str.encode(runs_str))
    temp.seek(0)
    subprocess.run([
        "/home/jswrenn/projects/powder-monkey/evaluate/evaluate-many.sh",
        "/course/cs0190/tabin/cs0190-grading-scripts/prehook.sh"
    ],
                   stdin=temp)
    temp.close()

    # Once all the tests have been run, print the output
    all_json = json.loads(subprocess.run(["/course/cs0190/tabin/cs0190-grading-scripts/slurp_single.sh", \
     os.path.join(assignment_dir, constants.result_regex % student_id)], \
     stdout=subprocess.PIPE).stdout.decode())

    testing_results = {"passed": 0, "total": 0}
    for run in all_json:
        result_impl = run["impl"]
        result_test = run["tests"]
        run_result = run["result"]
        # If there's an issue, just skip it and it'll be manually resolved
        if "Err" in run_result:
            common.print_run_error(result_impl, result_test, \
             "produced a %s error." % (run_result["Err"]))
            continue
        check_blocks = run_result["Ok"]

        if constants.handin_dir in result_impl:
            for check_block in check_blocks:
                check_block_name = check_block["name"]
                if check_block["error"]:
                    print("ERROR: There was an error in the check block: %s, " + \
                     "so the final number of tests will be off from the official count." % \
                     check_block_name)
                else:
                    tests_in_check = 0
                    tests_passed_in_check = 0
                    for test in check_block["tests"]:
                        tests_in_check += 1
                        if test["passed"]: tests_passed_in_check += 1
                    testing_results["passed"] += tests_passed_in_check
                    testing_results["total"] += tests_in_check
                    testing_results[check_block_name + " (%d)" %
                                    tests_in_check] = tests_passed_in_check
        elif constants.handin_dir in result_test:
            print("The student check blocks on the following line failed %s" %
                  result_impl)
            print(";".join(get_failed_check_blocks(check_blocks)))
        else:
            common.print_run_error(result_impl, result_test, \
             "was not recognized as a student submission.")

    print("Final student implementation vs. instructor test results: ")
    print(json.dumps(testing_results, indent=4))