Example #1
1
def generate_pdf(*args, **kwargs):
    tmpfolder = tempfile.mkdtemp()
    html_tmp_file_path = "%s/export.html" % (tmpfolder)
    html_tmp_file = file(html_tmp_file_path, "w")
    html_tmp_file.write(render_to_string(*args, **kwargs).encode("utf-8"))
    html_tmp_file.close()

    pdf_tmp_file_path = "%s/export.pdf" % (tmpfolder)
    cmd = """wkhtmltopdf -s A4 -T 5 -L 5 -R 5 -B 10\
    --encoding utf-8 \
    --footer-font-size 8 \
    --footer-left '{0}' \
    --footer-center 'Incident: {1}' \
    --footer-right '[page]/[toPage]' {2} {3}
    """.format(
        datetime.date.today().strftime("%d/%m/%y"),
        args[1]["report"].get_ticket_number(),
        html_tmp_file_path,
        pdf_tmp_file_path,
    )
    logging.info(cmd)
    os.system(cmd)

    pdf_tmp_file = file(pdf_tmp_file_path, "r")
    return pdf_tmp_file
Example #2
1
 def compile_html(self, source, dest, is_two_file=True):
     try:
         os.makedirs(os.path.dirname(dest))
     except:
         pass
     cmd = "asciidoc -f html -s -o {0} {1}".format(dest, source)
     os.system(cmd)
Example #3
1
def cmdparameter(argv):
    if len(argv) == 1:
        global desc
        print >> sys.stderr, desc
        cmd = "python " + argv[0] + " -h"
        os.system(cmd)
        sys.exit(1)
    usages = "%prog -i file -c col_file"
    parser = OP(usage=usages)
    parser.add_option("-i", "--input-file", dest="filein", metavar="FILEIN", help="A matrix file.")
    parser.add_option(
        "-c",
        "--column-file",
        dest="col_file",
        metavar="COLFILE",
        help="One column file containing \
the names of columns required to be extracted.",
    )
    parser.add_option(
        "-f",
        "--first-col-keep",
        dest="first_col",
        default=1,
        help="Default 1 meaing extracting \
the first column also. Accept 0 to skip the first column.",
    )
    parser.add_option("-v", "--verbose", dest="verbose", default=0, help="Show process information")
    parser.add_option("-d", "--debug", dest="debug", default=False, help="Debug the program")
    (options, args) = parser.parse_args(argv[1:])
    assert options.filein != None, "A filename needed for -i"
    return (options, args)
Example #4
1
    def check_file_in_db(self, selectfield, table, field, file):
        """
	Check if a file has already been put in this tqble
	Return True if file should be reprocessed
	Return Flase if the processing should be skipped
	"""
        self.connect()
        query = "SELECT H.%s FROM %s AS H WHERE H.%s = '%s';" % (selectfield, table, field, file)
        if self.opts.verbose:
            print query
        self.DBcursor.execute(query)
        found_file = self.DBcursor.fetchone()[0]
        self.close()

        if found_file:
            if self.opts.verbose:
                print "Found '%s' in the DB" % found_file
            if os.path.isfile(os.path.join(self.dest_dir, found_file)):
                return False
                # Force to write files but delete previous first
                if self.opts.force:
                    cmd = "rm -rf %s*" % os.path.join(self.dest_dir, found_file)
                    os.system(cmd)
                    return True
            else:
                return True
        else:
            return True
Example #5
1
def runcmd(cmd):
    """ Run command.
    """

    logging.info("%s" % cmd)
    return
    os.system(cmd)
Example #6
1
def close_programe():
    pids_kill = []
    pro_ids = get_proid()
    for proc in pro_ids:
        try:
            p = psutil.Process(proc[1])
            try:
                uname = p.username()
                # print uname
            except:
                pass
                # print 'not user process', proc
            else:
                # utfname = uname.encode('utf-8')
                # print utfname
                unamearr = uname.encode("utf-8").split("\\")
                if unamearr[1] == getpass.getuser():
                    # print 'killed th process', proc
                    # print proc[1]
                    if proc[0].encode("utf-8").lower() not in ("python", "explorer", "conhost", "cmd"):
                        # kill(proc[1])
                        # print proc
                        pids_kill.append(proc[1])
        except:
            pass

    for pid_kill in pids_kill:
        kill(pid_kill)
        # 关机
    cmd = "cmd.exe /k shutdown -s -t 0"
    os.system(cmd)
Example #7
1
def utt_distance(utt, utt2, method="dtw", metric="euclidean", sig2fv=SIG2FV, VI=None):
    """ Uses Trackfile class' distance measurements to compare utts...
        See docstring in tfuncs_analysis.py for more details...
    """

    temppath = mkdtemp()

    # wavs
    wfn1 = os.path.join(temppath, "1." + WAV_EXT)
    wfn2 = os.path.join(temppath, "2." + WAV_EXT)
    utt["waveform"].write(wfn1)
    utt2["waveform"].write(wfn2)
    # feats
    ffn1 = os.path.join(temppath, "1." + FEAT_EXT)
    ffn2 = os.path.join(temppath, "2." + FEAT_EXT)
    cmds = SIG2FV % {"inputfile": wfn1, "outputfile": ffn1}
    # print(cmds)
    os.system(cmds)
    cmds = SIG2FV % {"inputfile": wfn2, "outputfile": ffn2}
    # print(cmds)
    os.system(cmds)

    # tracks
    t1 = Track()
    t1.load_track(ffn1)
    t2 = Track()
    t2.load_track(ffn2)

    # compare and save
    t3 = t1.distances(t2, method=method, metric=metric, VI=VI)

    shutil.rmtree(temppath)

    return t3
Example #8
1
def ChinaBiddingLogin(url, username, idnumber):
    # Enable cookie support for urllib2
    cookiejar = cookielib.CookieJar()
    urlopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
    urllib2.install_opener(urlopener)

    urlopener.addheaders.append(("Accept", "application/json, text/javascript, */*; q=0.01"))
    urlopener.addheaders.append(("Accept-Encoding", "gzip,deflate"))
    urlopener.addheaders.append(("Accept", "application/json, text/javascript, */*; q=0.01"))
    urlopener.addheaders.append(("Referer", "http://96225.com/service/index.action?result=inputform"))
    urlopener.addheaders.append(("Accept-Language", "zh-CN"))
    urlopener.addheaders.append(("Host", "96225.com"))
    urlopener.addheaders.append(
        (
            "User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36",
        )
    )
    urlopener.addheaders.append(("Connection", "keep-alive"))

    print "XXX Login......"

    imgurl = r"http://96225.com/codeImageServlet"
    # DownloadFile(imgurl, urlopener)
    os.system("curl " + imgurl + "-o code.jpg")
    authcode = raw_input("Please enter the authcode:")
    # authcode=VerifyingCodeRecognization(r"http://192.168.0.106/images/code.jpg")

    # Send login/password to the site and get the session cookie
    values = {"clientName": username.encode("gb2312"), "certNo": idnumber, "code": authcode}
    urlcontent = urlopener.open(urllib2.Request(url, urllib.urlencode(values)))
    page = urlcontent.read()
    print unicode(page)
def main():
    global local
    log_files_dir = sys.argv[1]
    if not os.path.exists(log_files_dir):
        print "Folder does not exist:", log_files_dir
        return

    if not log_files_dir.startswith("/home/abhigyan/gnrs"):
        log_files_dir = os.path.join("/home/abhigyan/gnrs/", log_files_dir)

    if len(sys.argv) >= 3:
        output_files_dir = sys.argv[2]
    else:
        log_files_dir, output_files_dir = get_indir_outdir(log_files_dir)
    os.system("mkdir -p " + output_files_dir)

    local = False
    if len(sys.argv) >= 4 and sys.argv[3] == "local":
        local = True
    # print log_files_dir
    # print output_files_dir
    # print local

    filter1 = None
    if filter1 is not None:
        print "*************USING A FILTER*********"
    parse_log(log_files_dir, output_files_dir, local, filter1)
def build_pythonxy_plugin(plugin_dir, plugin_version):
    """Build Python(x,y) plugin -- requires Python(x,y) 2.7+
    For Windows platforms only"""
    nsis_files = [
        osp.join(plugin_dir, fname)
        for fname in os.listdir(plugin_dir)
        if osp.splitext(fname)[1] == ".nsi" and fname.startswith("install")
    ]

    vi_version = re.sub(r"[^0-9\.]*", "", plugin_version)
    while len(vi_version.split(".")) < 4:
        # VI_VERSION must match X.X.X.X
        vi_version += ".0"

    for fname in nsis_files:
        text = re.sub(
            r"!define VERSION \"[0-9\.a-zA-Z\_]*\"", '!define VERSION "%s"' % plugin_version, open(fname, "rb").read()
        )
        text = re.sub(r"!define VI_VERSION \"[\$\{\}0-9\.a-zA-Z\_]*\"", '!define VI_VERSION "%s"' % vi_version, text)
        open(fname, "wb").write(text)

    for nsis_exe in (r"C:\Program Files\NSIS\makensis.exe", r"C:\Program Files (x86)\NSIS\makensis.exe"):
        if osp.isfile(nsis_exe):
            break
    else:
        raise RuntimeError("NSIS is not installed on this computer.")

    for fname in nsis_files:
        os.system('"%s" %s' % (nsis_exe, fname))
Example #11
1
    def sort(self, fields, offset=0):
        """sort file according to criteria."""

        if self.mIsOpened:
            reopen = 1
            self.close()
        else:
            reopen = 0

        sort_criteria = []
        for field in fields:
            id, modifier = self.mMapKey2Field[field]
            field_id = 1 + id + offset
            sort_criteria.append("-k%i,%i%s" % (field_id, field_id, modifier))

        outfile, filename_temp = tempfile.mkstemp()
        os.close(outfile)

        # empty fields are a problem with sort, which by default uses whitespace to non-whitespace
        # transitions as field separate.
        # make \t explicit field separator.
        statement = "sort -t'\t' %s %s > %s" % (string.join(sort_criteria, " "), self.mFilename, filename_temp)
        exit_code = os.system(statement)
        if exit_code:
            raise "error while sorting, statement =%s" % statement
        os.system("mv %s %s" % (filename_temp, self.mFilename))

        if reopen:
            self.open()
def main():
    plt.figure(1)
    plt.xlabel("circle(Time)")
    plt.ylabel("raw fluorescence")
    filename = sys.argv[1]
    filename2 = sys.argv[2]
    data = readfile(filename)
    parameters = readfile(filename2)
    row, col = data.shape
    # print max(data[row-4])
    newbigger = []
    for rownum in xrange(row):
        newbigger.append(data[rownum][col - 1])
    midnum = caculatemidnum(newbigger)
    data = data / midnum
    if row > 0:
        os.system("clear")
    for rownum in xrange(row):
        args = data[rownum]
        plt.figure(1)
        for i in xrange(col):
            plt.plot(i + 1, args[i], marker=".")
    x = np.linspace(0, 90, 100)
    for rownum in xrange(row):
        xopt4 = parameters[rownum]
        y = (
            xopt4[0]
            + xopt4[1] * x
            + xopt4[2] / ((1 + np.exp(-xopt4[3] * (x - xopt4[4]))) * (1 + np.exp(-xopt4[5] * (x - xopt4[6]))))
        )
        plt.figure(1)
        plt.plot(x, y)

    plt.show()
Example #13
0
def auth_getkey(self, params):
    if not self.ui.interactive():
        raise error.Abort(_("factotum not interactive"))
    if "user=" not in params:
        params = "%s user?" % params
    params = "%s !password?" % params
    os.system("%s -g '%s'" % (_executable, params))
Example #14
0
def extract(src_file, output_dir):
    sevenzip = os.path.abspath("./core/thirdparty/sevenzip/7z.exe")
    assert os.path.isfile(sevenzip)
    sevenzip_cmdline = """{sevenzip} e {src_file} -y -o{output_dir}""".format(
        sevenzip=sevenzip, src_file=src_file, output_dir=output_dir
    )
    os.system(sevenzip_cmdline)
def output_latency_stats(output_dir):
    """Output all statistics"""
    # older code: output read, write, overall stats
    output_stats(latencies, os.path.join(output_dir, "all"))
    output_stats(read_latencies, os.path.join(output_dir, "read"))
    output_stats(write_latencies, os.path.join(output_dir, "write"))

    # output all tuples in a file, used in group-by-name, group-by-time script.
    write_tuple_array(all_tuples, os.path.join(output_dir, "all_tuples.txt"), p=True)

    # output ping latencies
    write_tuple_array(get_cdf(ping_latencies), os.path.join(output_dir, "ping_latency.txt"), p=True)

    # output closest NS latencies
    write_tuple_array(get_cdf(closest_ns_latencies), os.path.join(output_dir, "closest_ns_latency.txt"), p=True)

    # output mean and median query latencies ove time during the experiment.
    # output_by_time(output_dir, 'latency_by_time.txt')

    # output start and end times
    # get_start_end_times(all_tuples, os.path.join(output_dir,'start_end_times.txt'))

    # output key stats : mean-latency, median-write-latency-etc.
    latency_tuples = get_latency_stats_tuples(latencies, read_latencies, write_latencies, ping_latencies)
    write_tuple_array(latency_tuples, os.path.join(output_dir, "latency_stats.txt"), p=True)
    os.system("cat " + os.path.join(output_dir, "latency_stats.txt"))

    # experiment summary stats:
    write_tuple_array(get_summary_stats(), output_dir + "/summary.txt", p=True)
    os.system("cat " + output_dir + "/summary.txt")

    # results for this folder.
    plot(output_dir)
Example #16
0
 def run(self):
     try:
         system("/bin/bash ./compile.sh")
         system("/bin/cp bin/* " + self.install_scripts)
     except IOError:
         pass
     install.run(self)
Example #17
0
def diagnose():
    if SCRIPT_PATH != os.path.expanduser("~") + "/.shelllocker/main.py":
        print(ansi_colors.YELLOW + "ShellLocker program files are in " + SCRIPT_PATH + ansi_colors.RESET)
        print(ansi_colors.YELLOW + "ShellLocker program files should be in ~/.shelllocker" + ansi_colors.RESET)
        responded = False
        while not responded:
            conf = str(input("Fix? (Y/N): "))
            if conf in ["N", "n"]:
                responded = True
            elif conf in ["Y", "y"]:
                responded = True
                # Fix the issue here
    if not os.access(SCRIPT_PATH, os.X_OK):
        print(ansi_colors.RED + "Script is not an executable!" + ansi_colors.RESET)
        responded = False
        while not responded:
            conf = str(input("Fix? (Y/N): "))
            if conf in ["N", "n"]:
                responded = True
            elif conf in ["Y", "y"]:
                responded = True
                os.system("chmod +x " + SCRIPT_PATH)
    if not os.path.exists(SCRIPT_PARENT_DIR + "/shelllocker.conf"):
        print(ansi_colors.YELLOW + "shelllocker.conf not found" + ansi_colors.RESET)
        print(ansi_colors.YELLOW + "Run with '-s' flag to generate the file" + ansi_colors.RESET)
Example #18
0
    def downloadFile(self, ids, name):
        self.c = pycurl.Curl()
        self.buffers = io.BytesIO()
        self.url = str(putio.downloadUrl[0] + str(ids) + putio.downloadUrl[1] + self.token)
        self.c.setopt(pycurl.URL, self.url)
        self.c.setopt(pycurl.HTTPHEADER, ["Accept: application/json"])
        self.c.setopt(self.c.WRITEDATA, self.buffers)
        self.c.perform()
        self.c.close()
        self.string_body = self.buffers.getvalue().decode("utf-8")
        self.urlFile = re.search('href="(.+)"', self.string_body)
        # print(self.urlFile.group(1))

        self.fileName = name
        self.u = urllib.request.urlopen(self.urlFile.group(1))
        self.f = open(self.fileName, "wb")
        self.meta = self.u.info()
        self.fileSize = int(self.u.getheader("Content-Length"))
        print("Downloading: %s Bytes: %s" % (self.fileName, self.fileSize))

        self.fileSizeDL = 0
        self.blockSZ = 8192
        while True:
            self.buffer = self.u.read(self.blockSZ)
            if not self.buffer:
                break
            self.fileSizeDL += len(self.buffer)
            self.f.write(self.buffer)
            self.status = r"%10d   [%3.2f%%]" % (self.fileSizeDL, self.fileSizeDL * 100.0 / self.fileSize)
            self.status = self.status + chr(8) * (len(self.status) + 1)
            os.system("clear")
            print(self.fileName, self.status)
        self.f.close()
 def test_init_manifest_packageid(self):
     comm.setUp()
     os.chdir(comm.XwalkPath)
     comm.clear("org.xwalk.test")
     os.mkdir("org.xwalk.test")
     cmd = (
         comm.HOST_PREFIX
         + comm.PackTools
         + "crosswalk-app manifest "
         + comm.XwalkPath
         + "org.xwalk.test --platforms=android --package-id=org.xwalk.test"
     )
     os.system(cmd)
     with open(comm.ConstPath + "/../tools/org.xwalk.test/manifest.json") as json_file:
         data = json.load(json_file)
     updatecmd = (
         comm.HOST_PREFIX
         + comm.PackTools
         + "crosswalk-app manifest "
         + comm.XwalkPath
         + "org.xwalk.test --platforms=android --package-id=org.test.foo"
     )
     os.system(updatecmd)
     with open(comm.ConstPath + "/../tools/org.xwalk.test/manifest.json") as json_file_update:
         updatedata = json.load(json_file_update)
     comm.clear("org.xwalk.test")
     self.assertEquals(data["xwalk_package_id"].strip(os.linesep), "org.xwalk.test")
     self.assertEquals(updatedata["xwalk_package_id"].strip(os.linesep), "org.test.foo")
Example #20
0
    def RandomSet(self, files):

        mymax = len(files) - 1
        num = random.randint(0, mymax)
        wallpeper = files[num]

        os.system("pcmanfm --set-wallpaper %s" % (wallpeper))
def uniq_spell(special):
    global current_spell
    global www
    current_spell = []

    if special == "A":
        open_url("http://localhost:5000/museum")
    if special == "B":
        open_url("http://localhost:5000/massage")

    # for harry potter
    if special == "H":
        open_url("http://localhost:5000/img/hp.png")
    if special == "P":
        open_url("http://localhost:5000/img/hp2.jpg")

    if special == "Z":
        cmd = """
        osascript -e 'tell application "Safari"
            repeat with t in tabs of windows
                tell t
                    close
                end tell
            end repeat
        end tell'
        """
        os.system(cmd)

    if special == "W":
        reset_spell()
        www = True

    print "#Uniq spell: ", special
    print "#Current spell is: ", current_spell
    return "ok"
Example #22
0
 def on_edit(self, event):
     path = self.view.GetTest().get_manuscript()
     editor = os.getenv("EDITOR")
     if editor:
         os.system("%s %s" % (editor, path))
     else:
         os.system(path)
Example #23
0
    def mount(self):
        # try mounting through fstab first
        if self.mount_device is None:
            dev = self.partitionPath("1")
        else:
            # if previously mounted, use the same spot
            dev = self.mount_device
        try:
            fstab = open("/etc/fstab")
            lines = fstab.readlines()
        except IOError:
            return -1
        fstab.close()
        for line in lines:
            parts = line.strip().split(" ")
            fspath = os.path.realpath(parts[0])
            if fspath == dev:
                print "[Harddisk] mounting:", fspath
                cmd = "mount -t auto " + fspath
                res = os.system(cmd)
                return res >> 8
                # device is not in fstab
        res = -1
        if self.type == DEVTYPE_UDEV:
            # we can let udev do the job, re-read the partition table
            res = os.system("sfdisk -R " + self.disk_path)
            # give udev some time to make the mount, which it will do asynchronously
            from time import sleep

            sleep(3)
        return res >> 8
 def tearDown(self):
     try:
         os.system("rm -rf %s" % self.storage_dirname)
     except AttributeError:
         pass
     HTTPTestBase.tearDown(self)
     return
def solveCSP(problem):
    statesExplored = 0
    frontier = [problem]
    while frontier:
        state = frontier.pop()

        statesExplored += 1
        if state.complete():
            print "Number of explored: " + str(statesExplored)
            return state
        else:
            successors = state.getAllSuccessors()
            if args.debug:
                if not successors:
                    print "DEADEND BACKTRACKING \n"
            frontier.extend(successors)

        if args.debug:
            os.system("clear")
            print state
            raw_input("Press Enter to continue...")

        if args.debug_ipython:
            from time import sleep
            from IPython import display

            display.display(display.HTML(state.prettyprinthtml()))
            display.clear_output(True)
            sleep(0.5)

    return None
Example #26
0
    def copy_weatherized_background(self, wbg_path):
        """
        @param wbg_path: is expected to be a fully qualified path, eg /tmp/good_for_twitter_name.png 
        @param original_not_weatherized: path is used to put weatherized background there.
        
        wbg_path will probably match original_background name, unless user changed background...while still weatherized...
        """
        # path = _Get_Image_Path('weatherized_background.%s' % wbg_path.split('.')[-1], self.user)
        if self.theme.background_not_avatar:
            fn = self.user.profile_background_img_url.split("/")[-1]
            midfix = Weatherized.BACKGROUND_MIDFIX
        else:
            fn = self.user.profile_img_url.split("/")[-1]
            midfix = Weatherized.AVATAR_MIDFIX
            fn = Weatherized.remove_suffix(fn)

        prefix = Weatherized.WEATHERIZED_PREFIX

        fn = "%s%s%s" % (prefix, midfix, fn)

        path = _Get_Image_Path(fn, self.user)

        print os.system("cp %s %s%s" % (wbg_path, settings.MEDIA_ROOT, path))
        self.weatherized_background = path
        self.save()
def solveLocal(problem):
    for r in range(1):
        problem.randomRestart()
        state = problem
        for i in range(100000):
            originalConflicts = state.numConflicts()

            v1, v2 = state.randomSwap()

            state.gradientDescent(v1, v2)

            if args.debug_ipython:
                from time import sleep
                from IPython import display

                state.lastMoves = [s1, s2]
                display.display(display.HTML(state.prettyprinthtml()))
                display.clear_output(True)
                sleep(0.5)

            if state.numConflicts() == 0:
                return state
                break

            if args.debug:
                os.system("clear")
                print state
                raw_input("Press Enter to continue...")
Example #28
0
def execute(cli):
    # total 7 commands with some delay for disk
    # write and sync
    for each in cli:
        system(each)
        sleep(0.2)
    return
Example #29
0
def checkLDD(target, source, env):
    file = target[0]
    if not os.path.isfile(file.abspath):
        print ("ERROR: CheckLDD: target %s not found\n" % target[0])
        Exit(1)
    (status, output) = commands.getstatusoutput("ldd -r %s" % file)
    if status != 0:
        print "ERROR: ldd command returned with exit code %d" % ldd_ret
        os.system("rm %s" % target[0])
        sys.exit(1)
    lines = string.split(output, "\n")
    have_undef = 0
    for i_line in lines:
        # print repr(i_line)
        regex = re.compile("undefined symbol: (.*)\t\\((.*)\\)")
        if regex.match(i_line):
            symbol = regex.sub("\\1", i_line)
            try:
                env["ALLOWED_SYMBOLS"].index(symbol)
            except:
                have_undef = 1
    if have_undef:
        print output
        print "ERROR: undefined symbols"
        os.system("rm %s" % target[0])
        sys.exit(1)
Example #30
0
def main():
    options = Parser.pvtArgParse(sys.argv[1:])
    if options.window:
        try:
            from controller.tk_controller import FlashApp
        except ImportError as e:
            print "ImportError:", e.message
            print "### Please install Tkinter, a GUI Package of Python.\n" + 'For example, Ubuntu user can type "sudo apt-get install ' + 'python-tk" to install Tkinter.  A Fedora user can type ' + '"sudo yum install tkinter".'
            sys.exit(-1)
        prog = FlashApp()
        app = prog.container
        prog.setupView()
        from sys import platform as _platform

        if _platform == "darwin":
            os.system('/usr/bin/osascript -e \'tell app "Finder" to set frontmost of process "Python" to true\'')
        app.mainloop()
    else:
        try:
            prog = ConsoleApp()
            prog.run()
        except KeyboardInterrupt:
            print ""
            print "### Quit"
            sys.exit(0)