コード例 #1
0
ファイル: SoundPlayer.py プロジェクト: aziagiles/papagayo
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0 # current audio position in frames
        self.audio = pyaudio.PyAudio()
        if AudioSegment:
            if which("ffmpeg") != None:
                AudioSegment.converter = which("ffmpeg")
            elif which("avconv") != None:
                AudioSegment.converter = which("avconv")
            else:
                if platform.system() == "Windows":
                    AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe"
                else:
                    # TODO: Check if we have ffmpeg or avconv installed
                    AudioSegment.converter = "ffmpeg"

        try:
            if AudioSegment:
                tempsound = AudioSegment.from_file(self.soundfile, format = os.path.splitext(self.soundfile)[1][1:])
                tempsound.export(os.path.dirname(os.path.realpath(__file__)) +"\\temp.wav", format = "wav")
                self.wave_reference = wave.open(os.path.dirname(os.path.realpath(__file__)) + "\\temp.wav")
            else:
                self.wave_reference = wave.open(self.soundfile)

            self.isvalid = True

        except:
            traceback.print_exc()
            self.wave_reference = None
            self.isvalid = False
コード例 #2
0
ファイル: buildmetageta.py プロジェクト: pegaucher/metageta
def main(vers=None):
    try:
        if vers:pause=False
        else:pause=True

        svn=which('svn')
        makensis=which('makensis')

        if not svn:
            print 'Install an SVN command line client (e.g. http://www.sliksvn.com) or ensure that it is on your PATH'
            if pause:raw_input('Press enter to exit.')
            sys.exit(1)

        if not makensis:
            print 'Install NSIS (http://nsis.sourceforge.net) or ensure that it is on your PATH'
            if pause:raw_input('Press enter to exit.')
            sys.exit(1)

        if not vers:
            try:vers = raw_input('Enter the version to build, options are: \n1.N (eg. 1.1 release) \ncurr (latest release) \nbranches/<branch> \ntrunk (unstable development) \nVersion:  ')
            except:sys.exit(0)#vers = 'trunk'

        repo=''
        if vers in ['curr','']:
            cmd='svn ls http://metageta.googlecode.com/svn/tags'
            exit_code,stdout,stderr=runcmd(cmd)
            if exit_code != 0:
                if stderr:    print stderr
                elif stdout:  print stdout
                else :        print 'SVN command failed'
                if pause:raw_input('Press enter to exit.')
                sys.exit(exit_code)
            else:
コード例 #3
0
def check_requirements():
    if which("adb") is None:
        print(t.red("This program requires adb executable to be in path."))
        sys.exit(-3)

    ffmpeg_path = which("ffmpeg")
    if ffmpeg_path is None:
        print(t.red("This program requires ffmpeg in path."))
        sys.exit(-4)

    # Check if ffmpeg supports all capabilities we need
    try:
        ffmpeg_p = subprocess.Popen([ffmpeg_path, "-codecs"],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
        output = ffmpeg_p.stdout.read().decode("utf-8")
        ffmpeg_p.communicate()

        if ffmpeg_p.returncode != 0:
            print(
                t.red(
                    "Incompatible ffmpeg version detected, please update to newest ffmpeg."
                ))
            sys.exit(-4)

        if "gif" not in output:
            print(
                t.red(
                    "Missing GIF encoder in your installed ffmpeg, cannot create gifs."
                ))
            sys.exit(-4)

        if "libx264" not in output:
            print(
                t.yellow(
                    "Missing libx264 encoder in your installed ffmpeg, will not be able to create videos."
                ))

        ffmpeg_p = subprocess.Popen([ffmpeg_path, "-filters"],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
        output = ffmpeg_p.stdout.read().decode("utf-8")
        ffmpeg_p.communicate()
        if ffmpeg_p.returncode != 0:
            print(
                t.red(
                    "Incompatible ffmpeg version detected, please update to newest ffmpeg."
                ))
            sys.exit(-4)

        if not ("format" in output and "scale" in output and "palettegen"
                in output and "paletteuse" in output and "fps" in output):
            print(t.red("Missing required filters in installed ffmpeg, installed ffmpeg requires"), \
                  t.green("format, fps, scale, palettegen and paletteuse"), t.red("filters."))
            sys.exit(-4)
    except OSError:
        print(t.red("This program requires a newish ffmpeg in path."))
        sys.exit(-4)
コード例 #4
0
    def submit_ask(self, print_result=True, after_job=None):
        """ Submits the job, but prints the jobfile and asks first """
        import utilities
        qsub = utilities.which('qsub')
        qstat = utilities.which('qstat')

        if not qsub: raise PBSMissingError('Cannot find qsub!')

        sub_script = self._get_sub_script()

        # Determine if we have to submit this with a dependency
        if after_job:
            # Make sure we have qstat, since that's how we check that the job
            # we're depending on exists in the first place
            if not qstat:
                raise PBSMissingError('Cannot find qstat!')
            process = Popen([qstat, after_job],
                            stdin=PIPE,
                            stdout=PIPE,
                            stderr=PIPE)
            (output, error) = process.communicate('')
            # If we get a non-zero exit status, that job doesn't exist!
            if process.wait():
                raise PBSDependError('Job %s does not exist. Bad dependency!' %
                                     after_job)
        # If it does exist,

        ending_prompt = 'OK?  > '
        if after_job:
            ending_prompt = 'with "qsub -W depend=afterok:%s", OK? > ' % after_job
        stdout.write('Going to submit the following script:' + linesep)
        stdout.write('=============' + linesep + sub_script + linesep +
                     '=============' + linesep + ending_prompt)
        response = stdin.readline()

        if response.strip().lower() == 'yes' or response.strip().lower(
        ) == 'y':
            if after_job:
                process = Popen(
                    [qsub, '-W', 'depend=afterok:%s' % after_job],
                    stdin=PIPE,
                    stdout=PIPE,
                    stderr=PIPE)
            else:
                process = Popen([qsub], stdin=PIPE, stdout=PIPE, stderr=PIPE)

            (output, error) = process.communicate(sub_script)

            if process.wait():
                raise QsubError('problem submitting job: %s' % error)

            if print_result: print output

            return output

        return None
コード例 #5
0
 def _check_member_accnt(self, user):
     if which('getent'):
         xcmd = ['getent', 'passwd', user]
     elif which('pwget'):
         xcmd = ['pwget', '-n', user]
     else:
         return 0
     xp = Popen(xcmd, stdout=PIPE, stderr=PIPE, close_fds=True)
     xout, xerr = xp.communicate()
     return xp.returncode
コード例 #6
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = QMediaPlayer()
        self.is_loaded = False
        self.volume = 100
        self.isplaying = False
        self.max_bits = 32768
        # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works
        self.audio.durationChanged.connect(self.on_durationChanged)
        # self.decoder.finished.connect(self.decode_finished_signal)
        self.audio.setMedia(QUrl.fromLocalFile(soundfile))
        # self.decoder.setSourceFilename(soundfile)  # strangely inconsistent file-handling
        # It will hang here forever if we don't process the events.
        while not self.is_loaded:
            QCoreApplication.processEvents()
            time.sleep(0.1)

        self.isvalid = True
        self.pydubfile = None
        if AudioSegment:
            if which("ffmpeg") is not None:
                AudioSegment.converter = which("ffmpeg")
            elif which("avconv") is not None:
                AudioSegment.converter = which("avconv")
            else:
                if platform.system() == "Windows":
                    AudioSegment.converter = os.path.join(
                        get_main_dir(), "ffmpeg.exe")
                    # AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe"
                else:
                    # TODO: Check if we have ffmpeg or avconv installed
                    AudioSegment.converter = "ffmpeg"

        try:
            if AudioSegment:
                print(self.soundfile)
                self.pydubfile = AudioSegment.from_file(
                    self.soundfile,
                    format=os.path.splitext(self.soundfile)[1][1:])
            else:
                self.wave_reference = wave.open(self.soundfile)

            self.isvalid = True

        except:
            traceback.print_exc()
            self.wave_reference = None
            self.isvalid = False
コード例 #7
0
ファイル: recorder.py プロジェクト: wangmingdong102/RoboGif
def check_requirements():
    if which("adb") is None:
        print(t.red("This program requires adb executable to be in path."))
        sys.exit(-3)

    ffmpeg_path = which("ffmpeg")
    if ffmpeg_path is None:
        print(t.red("This program requires ffmpeg in path."))
        sys.exit(-4)

    # Check if ffmpeg supports all capabilities we need
    try:
        ffmpeg_p = subprocess.Popen([ffmpeg_path, "-codecs"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output = ffmpeg_p.stdout.read().decode("utf-8")
        ffmpeg_p.communicate()

        if ffmpeg_p.returncode != 0:
            print(t.red("Incompatible ffmpeg version detected, please update to newest ffmpeg."))
            sys.exit(-4)

        if "gif" not in output:
            print(t.red("Missing GIF encoder in your installed ffmpeg, cannot create gifs."))
            sys.exit(-4)

        if "libx264" not in output:
            print(t.yellow("Missing libx264 encoder in your installed ffmpeg, will not be able to create videos."))

        ffmpeg_p = subprocess.Popen([ffmpeg_path, "-filters"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output = ffmpeg_p.stdout.read().decode("utf-8")
        ffmpeg_p.communicate()
        if ffmpeg_p.returncode != 0:
            print(t.red("Incompatible ffmpeg version detected, please update to newest ffmpeg."))
            sys.exit(-4)

        if not (
            "format" in output
            and "scale" in output
            and "palettegen" in output
            and "paletteuse" in output
            and "fps" in output
        ):
            print(
                t.red("Missing required filters in installed ffmpeg, installed ffmpeg requires"),
                t.green("format, fps, scale, palettegen and paletteuse"),
                t.red("filters."),
            )
            sys.exit(-4)
    except OSError:
        print(t.red("This program requires a newish ffmpeg in path."))
        sys.exit(-4)
コード例 #8
0
ファイル: pbsjob.py プロジェクト: swails/JmsScripts
    def submit_ask(self, print_result=True, after_job=None):
        """ Submits the job, but prints the jobfile and asks first """
        import utilities

        qsub = utilities.which("qsub")
        qstat = utilities.which("qstat")

        if not qsub:
            raise PBSMissingError("Cannot find qsub!")

        sub_script = self._get_sub_script()

        # Determine if we have to submit this with a dependency
        if after_job:
            # Make sure we have qstat, since that's how we check that the job
            # we're depending on exists in the first place
            if not qstat:
                raise PBSMissingError("Cannot find qstat!")
            process = Popen([qstat, after_job], stdin=PIPE, stdout=PIPE, stderr=PIPE)
            (output, error) = process.communicate("")
            # If we get a non-zero exit status, that job doesn't exist!
            if process.wait():
                raise PBSDependError("Job %s does not exist. Bad dependency!" % after_job)
        # If it does exist,

        ending_prompt = "OK?  > "
        if after_job:
            ending_prompt = 'with "qsub -W depend=afterok:%s", OK? > ' % after_job
        stdout.write("Going to submit the following script:" + linesep)
        stdout.write("=============" + linesep + sub_script + linesep + "=============" + linesep + ending_prompt)
        response = stdin.readline()

        if response.strip().lower() == "yes" or response.strip().lower() == "y":
            if after_job:
                process = Popen([qsub, "-W", "depend=afterok:%s" % after_job], stdin=PIPE, stdout=PIPE, stderr=PIPE)
            else:
                process = Popen([qsub], stdin=PIPE, stdout=PIPE, stderr=PIPE)

            (output, error) = process.communicate(sub_script)

            if process.wait():
                raise QsubError("problem submitting job: %s" % error)

            if print_result:
                print output

            return output

        return None
コード例 #9
0
ファイル: recorder.py プロジェクト: GcsSloop/RoboGif
def create_optimized_gif(in_file, out_file, size, fps):
    print(t.green("Converting video to GIF..."))
    tmp_pal_file = get_new_temp_file_path("png")
    gifsicle_path = which("gifsicle")

    if gifsicle_path is not None:
        convert_output_path = get_new_temp_file_path("gif")
    else:
        convert_output_path = out_file

    FFMPEG_FILTERS = "fps={fps},scale=w='if(gt(iw,ih),-1,{size})':h='if(gt(iw,ih),{size},-1)':flags=lanczos".format(fps=fps, size=size)
    FFMPEG_PALLETE = ["ffmpeg", "-v", "warning", "-i", in_file, "-vf", FFMPEG_FILTERS + ",palettegen", "-y", tmp_pal_file]
    FFMPEG_CONVERT = ["ffmpeg", "-v", "warning", "-i", in_file, "-i", tmp_pal_file, "-lavfi", FFMPEG_FILTERS + "[x];[x][1:v]paletteuse=dither=floyd_steinberg", "-y", "-f", "gif", convert_output_path]
    GIFSICLE_OPTIMIZE = ["gifsicle", "-O3", convert_output_path, "-o", out_file]

    try:
        subprocess.check_call(FFMPEG_PALLETE)
        subprocess.check_call(FFMPEG_CONVERT)

        if gifsicle_path is not None:
            subprocess.check_call(GIFSICLE_OPTIMIZE)

        print(t.green("Done!"))
    except:
        print(t.red("Could not convert downloaded recording to GIF!"))
        raise
    finally:
        try:
            os.remove(tmp_pal_file)
            if gifsicle_path is not None:
                os.remove(convert_output_path)
        except:
            pass

    print(t.yellow("Created " + out_file))
コード例 #10
0
 def pwconv(self):
     if not cap_shadow or not os.path.exists('/etc/shadow'):
         return
     if not which('pwconv'):
         return
     p = Popen(['pwconv'])
     p.communicate()
コード例 #11
0
def main(vers=None):
    try:
        if vers: pause = False
        else: pause = True

        svn = which('svn')

        if not svn:
            print 'Install an SVN command line client (e.g. http://www.sliksvn.com) or ensure that it is on your PATH'
            if pause: raw_input('Press enter to exit.')
            sys.exit(1)

        if not vers:
            try:
                vers = raw_input(
                    'Enter the version to build, options are: \n1.N (eg. 1.1 release) \ncurr (latest release) \nbranches/<branch> \ntrunk (unstable development) \nVersion:  '
                )
            except:
                sys.exit(0)  #vers = 'trunk'

        repo = ''
        if vers in ['curr', '']:
            cmd = 'svn ls http://metageta.googlecode.com/svn/tags'
            exit_code, stdout, stderr = runcmd(cmd)
            if exit_code != 0:
                if stderr: print stderr
                elif stdout: print stdout
                else: print 'SVN command failed'
                if pause: raw_input('Press enter to exit.')
                sys.exit(exit_code)
            else:
コード例 #12
0
    def set_radii(self, igb=0, radius_set='mbondi'):
        """ Sets the radius set to a new one using parmed """

        # If someone sets an igb, change to the appropriate radius set

        if igb:
            if igb == 1: radius_set = 'mbondi'
            elif igb == 2: radius_set = 'mbondi2'
            elif igb == 5: radius_set = 'mbondi2'
            elif igb == 7: radius_set = 'bondi'
            elif igb == 8: radius_set = 'mbondi3'

        if not radius_set in [
                'mbondi', 'mbondi2', 'mbondi3', 'bondi', 'amber6'
        ]:
            raise InputError('Bad radius set! Choose from ' +
                             'mbondi, mbondi2, mbondi3, bondi, and amber6')

        parmed = which('parmed.py')
        change_str = ("setOverwrite True\n" + "changeRadii %s\n" % radius_set +
                      "parmout %s\n" % self.prmtop + "go\n")

        process = Popen(
            [parmed, '-q', '-n', str(self.prmtop)],
            stdin=PIPE,
            stderr=PIPE,
            stdout=PIPE)

        (output, error) = process.communicate(change_str)

        if process.wait():
            raise ProgramError('parmed.py failed to change radii!')

        # Reload our topology file now that we've changed radius sets
        self.prmtop = AmberParm(str(self.prmtop))
コード例 #13
0
ファイル: recorder.py プロジェクト: wklin8607/RoboGif
def create_optimized_gif(in_file, out_file, size, fps):
    print(t.green("Converting video to GIF..."))
    tmp_pal_file = get_new_temp_file_path("png")
    gifsicle_path = which("gifsicle")

    if gifsicle_path is not None:
        convert_output_path = get_new_temp_file_path("gif")
    else:
        convert_output_path = out_file

    FFMPEG_FILTERS = "fps={fps},scale=w='if(gt(iw,ih),-1,{size})':h='if(gt(iw,ih),{size},-1)':flags=lanczos".format(fps=fps, size=size)
    FFMPEG_PALLETE = ["ffmpeg", "-v", "warning", "-i", in_file, "-vf", FFMPEG_FILTERS + ",palettegen", "-y", tmp_pal_file]
    FFMPEG_CONVERT = ["ffmpeg", "-v", "warning", "-i", in_file, "-i", tmp_pal_file, "-lavfi", FFMPEG_FILTERS + "[x];[x][1:v]paletteuse=dither=floyd_steinberg", "-y", "-f", "gif", convert_output_path]
    GIFSICLE_OPTIMIZE = ["gifsicle", "-O3", convert_output_path, "-o", out_file]

    try:
        subprocess.check_call(FFMPEG_PALLETE)
        subprocess.check_call(FFMPEG_CONVERT)

        if gifsicle_path is not None:
            subprocess.check_call(GIFSICLE_OPTIMIZE)

        print(t.green("Done!"))
    except:
        print(t.red("Could not convert downloaded recording to GIF!"))
        raise
    finally:
        try:
            os.remove(tmp_pal_file)
            if gifsicle_path is not None:
                os.remove(convert_output_path)
        except:
            pass

    print(t.yellow("Created " + out_file))
コード例 #14
0
   def set_radii(self, igb=0, radius_set='mbondi'):
      """ Sets the radius set to a new one using parmed """

      # If someone sets an igb, change to the appropriate radius set

      if igb:
         if igb == 1: radius_set = 'mbondi'
         elif igb == 2: radius_set = 'mbondi2'
         elif igb == 5: radius_set = 'mbondi2'
         elif igb == 7: radius_set = 'bondi'
         elif igb == 8: radius_set = 'mbondi3'

      if not radius_set in ['mbondi', 'mbondi2', 'mbondi3', 'bondi', 'amber6']:
         raise InputError('Bad radius set! Choose from ' +
                          'mbondi, mbondi2, mbondi3, bondi, and amber6')

      parmed = which('parmed.py')
      change_str = ("setOverwrite True\n" +
                    "changeRadii %s\n" % radius_set +
                    "parmout %s\n" % self.prmtop +
                    "go\n")

      process = Popen([parmed, '-q', '-n', str(self.prmtop)], stdin=PIPE,
                      stderr=PIPE, stdout=PIPE)

      (output, error) = process.communicate(change_str)

      if process.wait():
         raise ProgramError('parmed.py failed to change radii!')

      # Reload our topology file now that we've changed radius sets
      self.prmtop = AmberParm(str(self.prmtop))
コード例 #15
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = QMediaPlayer()
        self.is_loaded = False
        self.volume = 100
        self.isplaying = False
        self.max_bits = 32768
        # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works
        self.audio.durationChanged.connect(self.on_durationChanged)
        # self.decoder.finished.connect(self.decode_finished_signal)
        self.audio.setMedia(QUrl.fromLocalFile(soundfile))
        # self.decoder.setSourceFilename(soundfile)  # strangely inconsistent file-handling
        # It will hang here forever if we don't process the events.
        self.audio_file = audioread.audio_open(self.soundfile)
        self.audio_data = []
        for buf in self.audio_file:
            self.audio_data.extend(
                struct.unpack("<{}H".format(int(len(list(buf)) / 2)), buf))
        print(self.audio_data)
        print(len(self.audio_data))
        print(len(self.audio_data) / self.audio_file.samplerate)
        print(self.audio_file.duration)
        print(self.audio_file.channels)
        print("DATAEND")
        while not self.is_loaded:
            QCoreApplication.processEvents()
            time.sleep(0.1)

        self.isvalid = True
        self.pydubfile = None
        if AudioSegment:
            if which("ffmpeg") is not None:
                AudioSegment.converter = which("ffmpeg")
            elif which("avconv") is not None:
                AudioSegment.converter = which("avconv")
            else:
                if platform.system() == "Windows":
                    AudioSegment.converter = os.path.join(
                        get_main_dir(), "ffmpeg.exe")
                    # AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe"
                else:
                    # TODO: Check if we have ffmpeg or avconv installed
                    AudioSegment.converter = "ffmpeg"

        self.isvalid = True
コード例 #16
0
ファイル: vuln.py プロジェクト: sherlant/opensvc
 def pushpkg(self):
     bin = 'nodemgr'
     if which(bin) is None:
         return
     cmd = [bin, 'pushpkg']
     pinfo(' '.join(cmd))
     p = Popen(cmd)
     p.communicate()
コード例 #17
0
    def __init__(self,
                 parm,
                 traj_list,
                 start=1,
                 stride=1,
                 end=99999999,
                 logfile=None,
                 overwrite=False):
        # Get cpptraj
        self.cpptraj = which('cpptraj')
        if not self.cpptraj:
            raise TrajError('Could not find cpptraj!')

        # Load instance data
        self.parm = str(parm)

        # Order matters
        self.traj_name_list = []

        # Start, end, stride
        self.start, self.stride, self.end = [], [], []

        # traj_list is a dictionary that matches the trajectory name to the
        # number of frames in that trajectory
        self.traj_list = {}
        if type(traj_list).__name__ in ['list', 'tuple']:
            for item in traj_list:
                self.traj_list[item] = -1
                self.traj_name_list.append(item)
                self.start.append(start)
                self.stride.append(stride)
                self.end.append(end)
        elif type(traj_list).__name__ == 'str':
            self.traj_list[traj_list] = -1
            self.traj_name_list.append(traj_list)
            self.start.append(start)
            self.stride.append(stride)
            self.end.append(end)
        else:
            raise TypeError(
                'AmberTraj: trajectory(s) must be a list/tuple or str')

        # Now set up num_frames
        self._query()

        # Can we overwrite files?
        self.overwrite = overwrite

        # what is our logfile?
        if type(logfile).__name__ == 'str':
            if os.path.exists(logfile) and not self.overwrite:
                raise TrajError('Cannot overwrite %s' % logfile)
            self.logfile = open(logfile, 'w', 0)
        else:
            self.logfile = sys.stdout

        # Start keeping track of the commands we want to run
        self._cpptraj_commands = ''
コード例 #18
0
    def submit(self, print_result=True, after_job=None):
        """ Submits the job """
        import utilities
        qsub = utilities.which('qsub')
        qstat = utilities.which('qstat')

        if not qsub: raise PBSMissingError('Cannot find qsub!')

        sub_script = self._get_sub_script()

        # Determine if we have to submit this with a dependency
        if after_job:
            # Make sure we have qstat, since that's how we check that the job
            # we're depending on exists in the first place
            if not qstat:
                raise PBSMissingError('Cannot find qstat!')
            process = Popen([qstat, after_job],
                            stdin=PIPE,
                            stdout=PIPE,
                            stderr=PIPE)
            (output, error) = process.communicate('')
            # If we get a non-zero exit status, that job doesn't exist!
            if process.wait():
                raise PBSDependError('Job %s does not exist. Bad dependency!' %
                                     after_job)
        # If it does exist,

        if after_job:
            process = Popen(
                [qsub, '-W', 'depend=afterok:%s' % after_job],
                stdin=PIPE,
                stdout=PIPE,
                stderr=PIPE)
        else:
            process = Popen([qsub], stdin=PIPE, stdout=PIPE, stderr=PIPE)

        (output, error) = process.communicate(sub_script)

        if process.wait():
            raise QsubError('problem submitting job: %s' % error)

        if print_result: print output

        return output
コード例 #19
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = sd
        self.pydubfile = None
        self.volume = 100

        if AudioSegment:
            if which("ffmpeg") is not None:
                AudioSegment.converter = which("ffmpeg")
            elif which("avconv") is not None:
                AudioSegment.converter = which("avconv")
            else:
                if platform.system() == "Windows":
                    AudioSegment.converter = os.path.join(
                        get_main_dir(), "ffmpeg.exe")
                    #AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe"
                else:
                    # TODO: Check if we have ffmpeg or avconv installed
                    AudioSegment.converter = "ffmpeg"

        try:
            if AudioSegment:
                print(self.soundfile)
                self.pydubfile = AudioSegment.from_file(
                    self.soundfile,
                    format=os.path.splitext(self.soundfile)[1][1:])
            else:
                self.wave_reference = wave.open(self.soundfile)

            self.isvalid = True

        except:
            traceback.print_exc()
            self.wave_reference = None
            self.isvalid = False
        if AudioSegment:
            self.pydubfile = self.pydubfile.set_sample_width(2)
            self.audio.default.samplerate = self.pydubfile.frame_rate * self.pydubfile.channels

        else:
            self.audio.default.samplerate = self.wave_reference.getframerate()
コード例 #20
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = pyaudio.PyAudio()
        self.pydubfile = None
        self.volume = 100

        if which("ffmpeg") is not None:
            self.converter = which("ffmpeg")
        elif which("avconv") is not None:
            self.converter = which("avconv")
        else:
            if platform.system() == "Windows":
                self.converter = os.path.join(get_main_dir(), "ffmpeg.exe")
                #AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe"
            else:
                # TODO: Check if we have ffmpeg or avconv installed
                self.converter = "ffmpeg"

        if AudioSegment:
            AudioSegment.converter = self.converter

        try:
            format = os.path.splitext(self.soundfile)[1][1:]

            if AudioSegment:
                self.pydubfile = AudioSegment.from_file(self.soundfile, format=format)
            else:
                wave_file = self.soundfile

                if format != "wav":
                    wave_file = tempfile._get_default_tempdir() + "/" + next(tempfile._get_candidate_names()) + ".wav"
                    subprocess.call([self.converter, '-i', self.soundfile, wave_file])

                self.wave_reference = wave.open(wave_file)

            self.isvalid = True

        except:
            traceback.print_exc()
            self.wave_reference = None
            self.isvalid = False
コード例 #21
0
 def vglist_Linux(self):
     if not which("vgs"):
         perror('vgs command not found')
         raise ComplianceError()
     cmd = ['vgs', '-o', 'vg_name', '--noheadings']
     p = Popen(cmd, stdout=PIPE, stderr=PIPE)
     out, err = p.communicate()
     if p.returncode != 0:
         perror('failed to list volume groups')
         raise ComplianceError()
     out = bdecode(out)
     self.vg = out.split()
コード例 #22
0
ファイル: pbsjob.py プロジェクト: swails/JmsScripts
    def submit(self, print_result=True, after_job=None):
        """ Submits the job """
        import utilities

        qsub = utilities.which("qsub")
        qstat = utilities.which("qstat")

        if not qsub:
            raise PBSMissingError("Cannot find qsub!")

        sub_script = self._get_sub_script()

        # Determine if we have to submit this with a dependency
        if after_job:
            # Make sure we have qstat, since that's how we check that the job
            # we're depending on exists in the first place
            if not qstat:
                raise PBSMissingError("Cannot find qstat!")
            process = Popen([qstat, after_job], stdin=PIPE, stdout=PIPE, stderr=PIPE)
            (output, error) = process.communicate("")
            # If we get a non-zero exit status, that job doesn't exist!
            if process.wait():
                raise PBSDependError("Job %s does not exist. Bad dependency!" % after_job)
        # If it does exist,

        if after_job:
            process = Popen([qsub, "-W", "depend=afterok:%s" % after_job], stdin=PIPE, stdout=PIPE, stderr=PIPE)
        else:
            process = Popen([qsub], stdin=PIPE, stdout=PIPE, stderr=PIPE)

        (output, error) = process.communicate(sub_script)

        if process.wait():
            raise QsubError("problem submitting job: %s" % error)

        if print_result:
            print output

        return output
コード例 #23
0
ファイル: mdcrd.py プロジェクト: jeiros/JmsScripts
   def __init__(self, parm, traj_list, start=1, stride=1, end=99999999,
                logfile=None, overwrite=False):
      # Get cpptraj
      self.cpptraj = which('cpptraj')
      if not self.cpptraj:
         raise TrajError('Could not find cpptraj!')

      # Load instance data
      self.parm = str(parm)

      # Order matters
      self.traj_name_list = []

      # Start, end, stride
      self.start, self.stride, self.end = [], [], []

      # traj_list is a dictionary that matches the trajectory name to the
      # number of frames in that trajectory
      self.traj_list = {}
      if type(traj_list).__name__ in ['list', 'tuple']:
         for item in traj_list:
            self.traj_list[item] = -1
            self.traj_name_list.append(item)
            self.start.append(start)
            self.stride.append(stride)
            self.end.append(end)
      elif type(traj_list).__name__ == 'str':
         self.traj_list[traj_list] = -1
         self.traj_name_list.append(traj_list)
         self.start.append(start)
         self.stride.append(stride)
         self.end.append(end)
      else:
         raise TypeError('AmberTraj: trajectory(s) must be a list/tuple or str')

      # Now set up num_frames
      self._query()

      # Can we overwrite files?
      self.overwrite = overwrite

      # what is our logfile?
      if type(logfile).__name__ == 'str':
         if os.path.exists(logfile) and not self.overwrite:
            raise TrajError('Cannot overwrite %s' % logfile)
         self.logfile = open(logfile, 'w', 0)
      else:
         self.logfile = sys.stdout

      # Start keeping track of the commands we want to run
      self._cpptraj_commands = ''
コード例 #24
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = sd
        self.pydubfile = None
        self.volume = 100

        if AudioSegment:
            if which("ffmpeg") is not None:
                AudioSegment.converter = which("ffmpeg")
            elif which("avconv") is not None:
                AudioSegment.converter = which("avconv")
            else:
                if platform.system() == "Windows":
                    AudioSegment.converter = os.path.join(get_main_dir(), "ffmpeg.exe")
                    #AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe"
                else:
                    # TODO: Check if we have ffmpeg or avconv installed
                    AudioSegment.converter = "ffmpeg"

        try:
            if AudioSegment:
                print(self.soundfile)
                self.pydubfile = AudioSegment.from_file(self.soundfile, format=os.path.splitext(self.soundfile)[1][1:])
            else:
                self.wave_reference = wave.open(self.soundfile)

            self.isvalid = True

        except:
            traceback.print_exc()
            self.wave_reference = None
            self.isvalid = False
        if AudioSegment:
            self.audio.default.samplerate = self.pydubfile.frame_rate
        else:
            self.audio.default.samplerate = self.wave_reference.getframerate()
コード例 #25
0
ファイル: SoundPlayer.py プロジェクト: aziagiles/papagayo
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = pyaudio.PyAudio()
        if AudioSegment:
            if which("ffmpeg") != None:
                AudioSegment.converter = which("ffmpeg")
            elif which("avconv") != None:
                AudioSegment.converter = which("avconv")
            else:
                if platform.system() == "Windows":
                    AudioSegment.converter = os.path.dirname(
                        os.path.realpath(__file__)) + "\\ffmpeg.exe"
                else:
                    # TODO: Check if we have ffmpeg or avconv installed
                    AudioSegment.converter = "ffmpeg"

        try:
            if AudioSegment:
                tempsound = AudioSegment.from_file(self.soundfile,
                                                   format=os.path.splitext(
                                                       self.soundfile)[1][1:])
                tempsound.export(os.path.dirname(os.path.realpath(__file__)) +
                                 "\\temp.wav",
                                 format="wav")
                self.wave_reference = wave.open(
                    os.path.dirname(os.path.realpath(__file__)) + "\\temp.wav")
            else:
                self.wave_reference = wave.open(self.soundfile)

            self.isvalid = True

        except:
            traceback.print_exc()
            self.wave_reference = None
            self.isvalid = False
コード例 #26
0
def submit_jobfiles(job_list, dependent=True, previous_job=None):
    """ Submits multiple job files one after another """
    import utilities
    qsub = utilities.which('qsub')
    if not qsub: raise PBSMissingError('Cannot find qsub!')

    for job in job_list:
        cl_array = [qsub]
        if dependent and previous_job:
            cl_array.extend(['-W', 'depend=afterok:%s' % previous_job])
        cl_array.append(job)
        process = Popen(cl_array, stdout=PIPE, stderr=PIPE)
        (previous_job, error) = process.communicate('')
        if process.wait():
            raise QsubError('Problem submitting job file %s:\n%s' %
                            (job, error))
        print previous_job
コード例 #27
0
ファイル: pbsjob.py プロジェクト: swails/JmsScripts
def submit_jobfiles(job_list, dependent=True, previous_job=None):
    """ Submits multiple job files one after another """
    import utilities

    qsub = utilities.which("qsub")
    if not qsub:
        raise PBSMissingError("Cannot find qsub!")

    for job in job_list:
        cl_array = [qsub]
        if dependent and previous_job:
            cl_array.extend(["-W", "depend=afterok:%s" % previous_job])
        cl_array.append(job)
        process = Popen(cl_array, stdout=PIPE, stderr=PIPE)
        (previous_job, error) = process.communicate("")
        if process.wait():
            raise QsubError("Problem submitting job file %s:\n%s" % (job, error))
        print previous_job
コード例 #28
0
 def grpconv(self):
     if not cap_shadow or not os.path.exists('/etc/gshadow'):
         return
     if not which('grpconv'):
         return
     with open('/etc/group', 'r') as f:
         buff = f.read()
     l = []
     for line in buff.split('\n'):
         u = line.split(':')[0]
         if u in l:
             perror(
                 "duplicate group %s in /etc/group. skip grpconv (grpconv bug workaround)"
                 % u)
             return
         l.append(u)
     p = Popen(['grpconv'])
     p.communicate()
コード例 #29
0
ファイル: config.py プロジェクト: symek/harm-sge
 def select_optional_executable(self, field):
     """ We try to choose amount avaible tools specified
         optianally in a class like image_viewer or file_manager.
     """
     # self.config['image_viewer'] is a list of a number of viewers
     # [('rv', ""), ...], second tuple element is optional path.
     # If None, it is to be found in PATH,
     
     for candidate in self[field]:
         assert(len(candidate) == 2)
         exec_, path = candidate
         if not path:
             exec_ = utilities.which(exec_)
             if exec_:
                 return exec_
         else:
             path = self.convert_platform_path(path)
             if os.path.isfile(path):
                 return path
     return None
コード例 #30
0
    def select_optional_executable(self, field):
        """ We try to choose amount avaible tools specified
            optianally in a class like image_viewer or file_manager.
        """
        # self.config['image_viewer'] is a list of a number of viewers
        # [('rv', ""), ...], second tuple element is optional path.
        # If None, it is to be found in PATH,

        for candidate in self[field]:
            assert (len(candidate) == 2)
            exec_, path = candidate
            if not path:
                exec_ = utilities.which(exec_)
                if exec_:
                    return exec_
            else:
                path = self.convert_platform_path(path)
                if os.path.isfile(path):
                    return path
        return None
コード例 #31
0
ファイル: ansible_playbook.py プロジェクト: sherlant/opensvc
    def init(self):
        self.rules = []
        if not which('ansible-playbook'):
            perror('ansible-playbook binary not found')
            raise NotApplicable()

        self.inventory = os.path.join(os.environ["OSVC_PATH_COMP"],
                                      ".ansible-inventory")

        for rule in self.get_rules():
            try:
                self.rules += self.add_rule(rule)
            except InitError:
                continue
            except ValueError:
                perror('ansible_playbook: failed to parse variable',
                       os.environ[k])

        if len(self.rules) == 0:
            raise NotApplicable()
コード例 #32
0
	def __init__(self):
		"""Load up the applications and connect to the X Server"""

		# The list of .desktop files' relevant details. A list of dicts with keys "FullPath", "StartupWMClass", "Exec"
		self.applications = []

		## Load up all the .desktop files
		for fullPath in self._get_xdg_application_files():

			# Make sure this is a .desktop file
			if not os.path.isfile(fullPath) or os.path.splitext(fullPath)[1].lower() != ".desktop":
				continue

			# Try to parse the desktop file; catching any exceptions
			try:
				entry = DesktopEntry.DesktopEntry(fullPath)
			except xdg.Exceptions.Error:
				continue

			# Make sure this is an application and isn't hidden (which is equivalent to not existing at all), 
			if entry.getType() != "Application" or entry.getHidden():
				continue

			# Test the `TryExec` key, if it exists
			if entry.getTryExec() != "" and which(entry.getTryExec()) == None:
				continue

			# Add the relevant details to the list of applications
			self.applications.append({
				"FullPath": fullPath,
				"StartupWMClass": entry.getStartupWMClass(),
				"Exec": entry.getExec()
				})

		# Connect to the X server, re-raising any Xerror.DisplayError
		try:
			self.display = Xdisplay.Display()
		except Xerror.DisplayError as exception:
			raise XServerError from exception
コード例 #33
0
ファイル: process.py プロジェクト: sherlant/opensvc
    def fix_process(self, process):
        if process['state'] == 'on':
            if self.check_present(process, verbose=False) == RET_OK:
                if ('uid' in process and self.check_uid(process, process['uid'], verbose=False) == RET_ERR) or \
                   ('user' in process and self.check_user(process, process['user'], verbose=False) == RET_ERR):
                    perror(process, "runs with the wrong user. can't fix.")
                    return RET_ERR
                return RET_OK
        elif process['state'] == 'off':
            if self.check_not_present(process, verbose=False) == RET_OK:
                return RET_OK

        if 'start' not in process or len(process['start'].strip()) == 0:
            perror("undefined fix method for process", process['comm'])
            return RET_ERR

        v = process['start'].split(' ')
        if not which(v[0]):
            perror("fix command", v[0], "is not present or not executable")
            return RET_ERR
        pinfo('exec:', process['start'])
        try:
            p = Popen(v, stdout=PIPE, stderr=PIPE)
            out, err = p.communicate()
        except Exception as e:
            perror(e)
            return RET_ERR
        out = bdecode(out)
        err = bdecode(err)
        if len(out) > 0:
            pinfo(out)
        if len(err) > 0:
            perror(err)
        if p.returncode != 0:
            perror("fix up command returned with error code", p.returncode)
            return RET_ERR
        return RET_OK
コード例 #34
0
 def get_ogm(self):
     if not which(self.ogm_script):
         r = files.CompFiles(prefix="OSVC_COMP_OGM_SCRIPT").fix()
         if r != 0:
             raise Exception()
コード例 #35
0
ファイル: get_rmsds.py プロジェクト: swails/JmsScripts
                  default=None,
                  help='Reference file for RMSDs')
parser.add_option('-m',
                  '--mask',
                  dest='mask',
                  default='@CA',
                  help='Mask to calculate RMSd for. Default [%default]')
opt, args = parser.parse_args()

if not args or not opt.rmsfile or not os.path.exists(opt.prmtop):
    print >> sys.stderr, 'Error: Missing key CL arguments or missing topology!'
    parser.print_help()
    sys.exit(1)

if opt.rmsbin:
    binner = which('1Dbinning.py')
    if not binner:
        print >> sys.stderr, 'Error: Binning requires 1Dbinning.py!'
        sys.exit(1)

trajs = AmberTraj(opt.prmtop, args)

trajs.rmsd(mask=opt.mask, outfile=opt.rmsfile, ref=opt.reffile)
trajs.run()

if opt.rmsbin:
    process = Popen(
        [binner, '-f', opt.rmsfile, '-o', opt.rmsbin, '-n', '-c', 2])
    if process.wait():
        print >> sys.stderr, 'Error: Binning program (%s) failed!' % binner
        sys.exit(1)
コード例 #36
0
ファイル: self_signed_cert.py プロジェクト: sherlant/opensvc
 def init(self):
     self.rules = self.get_rules()
     if which("openssl") is None:
         raise NotApplicable("openssl command not found")
コード例 #37
0
ファイル: FindSaltbridge.py プロジェクト: jeiros/JmsScripts
         x += 1
         while x < len(sys.argv) and not sys.argv[x].startswith('-'):
            mdcrds.append(sys.argv[x])
            x += 1
except IndexError:
   print 'Error: Improper command!'
   printusage()
except ValueError:
   print 'Error: "percent" must be a floating point decimal!'
   printusage()

parm = amberParm(prmtop)
if len(mdcrds) == 0: # if no mdcrd supplied, give default
   mdcrds.append('mdcrd')

ptraj = utilities.which('cpptraj') # look for ptraj

if ptraj is None:
   print 'Error: cpptraj needed for FindSaltbridge.py!'
   sys.exit() # quit if not found

if not parm.valid:
   printusage()

for x in range(len(mdcrds)): # check for mdcrd existences
   if utilities.fileexists(mdcrds[x]) == -1:
      printusage()

residues = parm.parm_data['RESIDUE_LABEL']

for x in range(len(residues)): # build acceptor list and donor list
コード例 #38
0
ファイル: RefRemTitrate.py プロジェクト: jeiros/JmsScripts
                 help='MPI Command to run MPI programs on your machine. ('
                 'Default "%default")', default='mpiexec -n 6')
group.add_option('-d', '--intdiel', dest='intdiel', type='float', default=1.0,
                 metavar='FLOAT', help='Internal dielectric to use. Default is '
                 '1.0')
parser.add_option_group(group)

(options, args) = parser.parse_args()

# Make sure we have enough arguments
if options.res is None or options.pKa is None:
   parser.print_help()
   sys.exit(1)

# Now determine where required programs are
sander = which('sander')
sanderMPI = which('sander.MPI')
tleap = which('tleap')
cpinutil = which('cpinutil.py')
converter = which('parmed.py')

if options.nreps % 2 != 0:
   print >> sys.stderr, 'Error: Even number of replicas required!'
   sys.exit(1)

if None in [sander, sanderMPI, tleap, cpinutil]:
   print >> sys.stderr, 'sander, tleap, and cpinutil.py are all necessary!'
   sys.exit(1)

if options.igb == 8 and converter is None:
   print >> sys.stderr, 'parmed.py is needed for igb = 8!'
コード例 #39
0
ファイル: chi1chi2gen.py プロジェクト: swails/JmsScripts
    print "Error: Invalid topology file " + topname + "!"
    sys.exit()

for x in range(len(residues)):
    if residues[x] < 1:
        print "Error: You chose a nonsensical residue (residue 0 or less)"
        sys.exit()
    elif residues[x] > residue_number:
        print "Error: The residue you chose is out of range!"
        sys.exit()

for x in range(len(mdcrds)):
    if utilities.fileexists(mdcrds[x]) == -1:
        sys.exit()

ptraj = utilities.which("ptraj")

if ptraj == "none":
    print "Error: ptraj needed for phipsigen.py!"
    sys.exit()
else:
    print "ptraj Found! Using " + ptraj

os.system("rm -f _CHI1CHI2_*")
ptrajin = open("_CHI1CHI2_ptraj.in", "w")
for x in range(len(mdcrds)):
    ptrajin.write("trajin " + mdcrds[x] + "\n")

ptrajin.write("\n")

for x in range(len(residues)):
コード例 #40
0
ファイル: ConstpH_TI.py プロジェクト: jeiros/JmsScripts
   intdiel={1},
/
""".format(igb, intdiel)


# Groupfiles -- 1 is for the first run, 2 is for each one after
TI_groupfile1 = """-O -i mdin -p {0}0.prmtop -c {0}0.inpcrd -o 0_0.mdout -r 0_0.restrt -x 0_0.mdcrd
-O -i mdin -p {0}1.prmtop -c {0}1.inpcrd -o 0_1.mdout -r 0_1.restrt -x 0_1.mdcrd
""".format(resname.lower())

TI_groupfile2 = """-O -i mdin -p {0}0.prmtop -c {1}_0.restrt -o {2}_0.mdout -r {2}_0.restrt -x {2}_0.mdcrd
-O -i mdin -p {0}1.prmtop -c {1}_1.restrt -o {2}_1.mdout -r {2}_1.restrt -x {2}_1.mdcrd
"""

# Find sander and tleap or quit
sander = which("sander.MPI")
sandermin = which("sander")
tleap = which("tleap")

if sander is None or tleap is None or sandermin is None:
   sys.exit("Error: You need sander.MPI and tleap to run this program!")

# Make tleap script and build the residue
extras = ''
if opt.off:
   extras += 'loadOFF %s\n' % opt.off
if opt.frcmod:
   extras += 'loadAmberParams %s\n' % opt.frcmod

if isolated:
   prev_str, next_str = '', ''
コード例 #41
0
ファイル: phipsigen.py プロジェクト: jeiros/JmsScripts
for x in range(len(residues)):
   if residues[x] == 1 or residues[x] == residue_number:
      print 'Error: You cannot get phi/psi dihedrals for either terminus!'
      sys.exit()
   elif residues[x] < 1:
      print 'Error: You chose a nonsensical residue (residue 0 or less)'
      sys.exit()
   elif residues[x] > residue_number:
      print 'Error: The residue you chose is out of range!'
      sys.exit()

for x in range(len(mdcrds)):
   if utilities.fileexists(mdcrds[x]) == -1:
      sys.exit()

ptraj = utilities.which('cpptraj')

if ptraj == 'none':
   print 'Error: ptraj needed for phipsigen.py!'
   sys.exit()
else:
   print 'ptraj Found! Using ' + ptraj

os.system('rm -f _PHIPSI_*')
ptrajin = open('_PHIPSI_ptraj.in','w')
for x in range(len(mdcrds)):
   ptrajin.write('trajin ' + mdcrds[x] + '\n')

ptrajin.write('\n')

for x in range(len(residues)):
コード例 #42
0
ファイル: RefTitrate.py プロジェクト: jeiros/JmsScripts
parser.add_option('-i', '--right-residue', dest='rightres', default=None,
                  help='Which residue to cap with on the right terminus')
parser.add_option('--frcmod', dest='frcmod', metavar='FILE', default=None,
                  help='File with additional parameters for the compound')
parser.add_option('--lib', dest='lib', metavar='FILE', default=None,
                  help='File with the residue definition (OFF file)')

(options, args) = parser.parse_args()

# Make sure we have enough arguments
if options.res == None or options.pH == None:
   parser.print_help()
   commworld.Abort()

# Now determine where required programs are
sander = which('sander')
pmemd = which('pmemd.cuda')
tleap = which('tleap')
cpinutil = which('cpinutil.py')

if None in [sander, pmemd, tleap, cpinutil]:
   print('sander, pmemd.cuda, tleap, cpinutil.py, and parmed.py are all '
         'necessary!')
   commworld.Abort()

print(" Found necessary programs!")

# Keep a log of all stdout
log = open('%s.log' % os.path.split(sys.argv[0])[1].strip('.py'), 'w')

md_mdin = """Mdin file for titrating stuff
コード例 #43
0
pmemd_input.write('pmemd_pH.mdin')

pmemd_energy.minimization(maxcyc=1)
pmemd_energy.change('cntrl', 'ntpr', 1)
pmemd_energy.write('pmemd_min.mdin')

# Now it's time to enter the actual MD loop
numsteps = int(total_time / dt)

try:
    mpi_cmd = os.environ['DO_PARALLEL']
except KeyError:
    mpi_cmd = 'none'

if mpi_cmd == 'none':
    pmemd = which('pmemd')
    exe = '%s' % pmemd
else:
    pmemd = which('pmemd.MPI')
    exe = '%s %s' % (mpi_cmd, pmemd)

if pmemd == 'none':
    print >> sys.stderr, 'Error: PMEMD cannot be found! It must be in your PATH for cph_pmemd.py to work.'
    sys.exit()

cpout_file = open(cpout, 'w')
cpout_file.write("""Solvent pH: %8.5f
Monte Carlo step size: %8i
Time step: %8i
Time: %10.3f
""" % (pH, dt, 0, 0))
コード例 #44
0
ファイル: RefTitrate.py プロジェクト: swails/JmsScripts
                  help='File with additional parameters for the compound')
parser.add_option('--lib',
                  dest='lib',
                  metavar='FILE',
                  default=None,
                  help='File with the residue definition (OFF file)')

(options, args) = parser.parse_args()

# Make sure we have enough arguments
if options.res == None or options.pH == None:
    parser.print_help()
    commworld.Abort()

# Now determine where required programs are
sander = which('sander')
pmemd = which('pmemd.cuda')
tleap = which('tleap')
cpinutil = which('cpinutil.py')

if None in [sander, pmemd, tleap, cpinutil]:
    print(
        'sander, pmemd.cuda, tleap, cpinutil.py, and parmed.py are all '
        'necessary!')
    commworld.Abort()

print(" Found necessary programs!")

# Keep a log of all stdout
log = open('%s.log' % os.path.split(sys.argv[0])[1].strip('.py'), 'w')
コード例 #45
0
(options, args) = parser.parse_args()

# Make sure we have enough arguments
if options.res is None or options.pKa is None:
   parser.print_help()
   sys.exit(1)

if options.dielc != 1 and options.dielc != 2:
   sys.exit('--intdiel must be 1 or 2!')

if options.mccycles <= 0:
   sys.exit('--mccycles must be a positive integer!')

# Now determine where required programs are
sander = which('sander.MPI')
pmemd = which('pmemd.MPI')
pmemd_cuda = which('pmemd.cuda')
tleap = which('tleap')
cpinutil = which('cpinutil.py')
converter = which('parmed.py')

if options.nreps % 2 != 0:
   print >> sys.stderr, 'Error: Even number of replicas required!'
   sys.exit(1)

if 'none' in [sander, tleap, cpinutil]:
   print >> sys.stderr, 'sander, tleap, and cpinutil.py are all necessary!'
   sys.exit(1)

if options.igb == 8 and converter == 'none':
コード例 #46
0
opt, args = clparser.parse_args()

if not opt.mdout or not opt.prmtop or not opt.mdcrd:
   clparser.print_help()
   sys.exit()

try:
   mdout = open(opt.mdout,'r')
   if not os.path.exists(opt.mdcrd): raise IOError('mdcrd doesn\'t exist')
   if not os.path.exists(opt.prmtop): raise IOError('mdcrd doesn\'t exist')
except IOError:
   print >> sys.stderr, "Error: mdout, prmtop, and/or mdcrd files don't exist!"
   clparser.print_help()
   sys.exit(1)

ptraj = utilities.which('ptraj')

if ptraj == "none":
   print "Error: ptraj is needed to analyze coordinate files!"
   sys.exit(1)

mdoutlines = mdout.readlines()
mdout.close()

# parse this block:
# NSTEP =   100000   TIME(PS) =     200.000  TEMP(K) =   308.77  PRESS =     0.0
# Etot   =    -18650.7357  EKtot   =      4532.3000  EPtot      =    -23183.0357
# BOND   =        11.0060  ANGLE   =        19.7379  DIHED      =        12.5913
# 1-4 NB =         5.9918  1-4 EEL =      -372.1093  VDWAALS    =      3276.9971
# EELEC  =    -26139.9559  EHBOND  =         0.0000  RESTRAINT  =         2.7054
# EAMBER (non-restraint)  =    -23185.7411
コード例 #47
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = QMediaPlayer()
        self.decoder = QAudioDecoder()
        self.is_loaded = False
        self.volume = 100
        self.isplaying = False
        self.decoded_audio = {}
        self.only_samples = []
        self.decoding_is_finished = False
        self.max_bits = 32768
        # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works
        self.audio.durationChanged.connect(self.on_durationChanged)
        #self.decoder.finished.connect(self.decode_finished_signal)
        self.audio.setMedia(QUrl.fromLocalFile(soundfile))
        #self.decoder.setSourceFilename(soundfile)  # strangely inconsistent file-handling
        # It will hang here forever if we don't process the events.
        while not self.is_loaded:
            QCoreApplication.processEvents()
            time.sleep(0.1)

        #self.decode_audio()
        #self.np_data = np.array(self.only_samples)
        #self.np_data = np.abs(self.np_data / self.max_bits)
        # A simple normalisation, with this the samples should all be between 0 and 1
        # for i in self.decoded_audio.items():
        #     self.only_samples.extend(i[1][0])
        # t = []
        # for i in self.only_samples:
        #     if i != []:
        #         t.append(i + -(min(self.only_samples)))
        #
        # t2 = []
        # for i in t:
        #     t2.append(i / max(t))
        # self.only_samples = t2
        #print(len(self.only_samples))
        #print(self.max_bits)


        self.isvalid = True
        self.pydubfile = None
        if AudioSegment:
            if which("ffmpeg") is not None:
                AudioSegment.converter = which("ffmpeg")
            elif which("avconv") is not None:
                AudioSegment.converter = which("avconv")
            else:
                if platform.system() == "Windows":
                    AudioSegment.converter = os.path.join(get_main_dir(), "ffmpeg.exe")
                    #AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe"
                else:
                    # TODO: Check if we have ffmpeg or avconv installed
                    AudioSegment.converter = "ffmpeg"

        try:
            if AudioSegment:
                print(self.soundfile)
                self.pydubfile = AudioSegment.from_file(self.soundfile, format=os.path.splitext(self.soundfile)[1][1:])
            else:
                self.wave_reference = wave.open(self.soundfile)

            self.isvalid = True

        except:
            traceback.print_exc()
            self.wave_reference = None
            self.isvalid = False
コード例 #48
0
ファイル: get_rmsds.py プロジェクト: jeiros/JmsScripts
                  default=None, help='Data file to dump RMSDs to')
parser.add_option('-b', '--rmsd-bin-file', dest='rmsbin', metavar='FILE',
                  default=None, help='Data file to dump RMSD bins to')
parser.add_option('-f', '--reference', dest='reffile', metavar='FILE',
                  default=None, help='Reference file for RMSDs')
parser.add_option('-m', '--mask', dest='mask', default='@CA',
                  help='Mask to calculate RMSd for. Default [%default]')
opt, args = parser.parse_args()

if not args or not opt.rmsfile or not os.path.exists(opt.prmtop):
   print >> sys.stderr, 'Error: Missing key CL arguments or missing topology!'
   parser.print_help()
   sys.exit(1)

if opt.rmsbin:
   binner = which('1Dbinning.py')
   if not binner:
      print >> sys.stderr, 'Error: Binning requires 1Dbinning.py!'
      sys.exit(1)

trajs = AmberTraj(opt.prmtop, args)

trajs.rmsd(mask=opt.mask, outfile=opt.rmsfile, ref=opt.reffile)
trajs.run()

if opt.rmsbin:
   process = Popen([binner, '-f', opt.rmsfile, '-o', opt.rmsbin, '-n', '-c', 2])
   if process.wait():
      print >> sys.stderr, 'Error: Binning program (%s) failed!' % binner
      sys.exit(1)
   else:
コード例 #49
0
(options, args) = parser.parse_args()

# Make sure we have enough arguments
if options.res is None or options.pKa is None:
    parser.print_help()
    sys.exit(1)

if options.dielc != 1 and options.dielc != 2:
    sys.exit('--intdiel must be 1 or 2!')

if options.mccycles <= 0:
    sys.exit('--mccycles must be a positive integer!')

# Now determine where required programs are
sander = which('sander.MPI')
pmemd = which('pmemd.MPI')
pmemd_cuda = which('pmemd.cuda')
tleap = which('tleap')
cpinutil = which('cpinutil.py')
converter = which('parmed.py')

if options.nreps % 2 != 0:
    print >> sys.stderr, 'Error: Even number of replicas required!'
    sys.exit(1)

if 'none' in [sander, tleap, cpinutil]:
    print >> sys.stderr, 'sander, tleap, and cpinutil.py are all necessary!'
    sys.exit(1)

if options.igb == 8 and converter == 'none':
コード例 #50
0
   print 'Error: Invalid topology file ' + topname + '!'
   sys.exit()

for x in range(len(residues)):
   if residues[x] < 1:
      print 'Error: You chose a nonsensical residue (residue 0 or less)'
      sys.exit()
   elif residues[x] > residue_number:
      print 'Error: The residue you chose is out of range!'
      sys.exit()

for x in range(len(mdcrds)):
   if utilities.fileexists(mdcrds[x]) == -1:
      sys.exit()

ptraj = utilities.which('ptraj')

if ptraj == 'none':
   print 'Error: ptraj needed for phipsigen.py!'
   sys.exit()
else:
   print 'ptraj Found! Using ' + ptraj

os.system('rm -f _CHI1CHI2_*')
ptrajin = open('_CHI1CHI2_ptraj.in','w')
for x in range(len(mdcrds)):
   ptrajin.write('trajin ' + mdcrds[x] + '\n')

ptrajin.write('\n')

for x in range(len(residues)):
コード例 #51
0
ファイル: FindSaltbridge.py プロジェクト: swails/JmsScripts
            x += 1
            while x < len(sys.argv) and not sys.argv[x].startswith('-'):
                mdcrds.append(sys.argv[x])
                x += 1
except IndexError:
    print 'Error: Improper command!'
    printusage()
except ValueError:
    print 'Error: "percent" must be a floating point decimal!'
    printusage()

parm = amberParm(prmtop)
if len(mdcrds) == 0:  # if no mdcrd supplied, give default
    mdcrds.append('mdcrd')

ptraj = utilities.which('cpptraj')  # look for ptraj

if ptraj is None:
    print 'Error: cpptraj needed for FindSaltbridge.py!'
    sys.exit()  # quit if not found

if not parm.valid:
    printusage()

for x in range(len(mdcrds)):  # check for mdcrd existences
    if utilities.fileexists(mdcrds[x]) == -1:
        printusage()

residues = parm.parm_data['RESIDUE_LABEL']

for x in range(len(residues)):  # build acceptor list and donor list
コード例 #52
0
ファイル: astropng.py プロジェクト: kapadia/astropng
    def to_png(self, out_file, bit_depth = 16, clip_on_percentiles = False, crush = False):
        """
        Converts the FITS file to a PNG.
        
        :param out_file:            User specified filename for the PNG
        :param clip_on_percentiles: Clips flux values to a lower and upper percentile
        :param crush:               Call pngcrush on the output image
        
        .. warning:: Setting bit_depth to 8 may reduce the dynamic range of the image.        
        .. warning:: Setting clip_on_percentiles to True reduces the dynamic range of the image.
        """
        if not self.fits:
            raise ValueError, "AstroPNG was not initialized with a FITS image"
        
        hdu = pyfits.open(self.fits)
        header, fluxes = hdu[0].header, hdu[0].data
        
        height, width = fluxes.shape
        
        # Prepare data
        fluxes = numpy.flipud(fluxes)
        fluxes = fluxes.flatten()
        
        if header['BITPIX'] == 16:
            fluxes = fluxes.astype(numpy.uint16)
        
        # Determine the minimum pixel and maximum pixel value
        min_pix, max_pix = numpy.nanmin(fluxes), numpy.nanmax(fluxes)
        
        # Clip data
        if clip_on_percentiles:
            min_pix, max_pix = self.__compute_percentile(fluxes)
            fluxes = self.__clip(fluxes, min_pix, max_pix)
        
        # Scale down to zero
        if header['BITPIX'] == -64:
            fluxes = fluxes - min_pix
        
        # Scale image to 8 bit integer space
        if bit_depth == 8:
            range_of_pixels = max_pix - min_pix
            fluxes = 255 * ( (data - min_pix) / range_of_pixels )
            min_pix, max_pix = 0, 255
        
        # Reshape the data to its original dimensions
        fluxes = fluxes.reshape(height, width)
        
        # If non-integer data type then quantize pixels
        if header['BITPIX'] in (-32, -64):
            nan_indices = self.__find_nans(fluxes)
            z_zeros, z_scales, fluxes = self.__quantize(fluxes)
            fluxes[nan_indices] = 0
        
        # Create a PNG writer object with the appropriate settings
        png_writer = AstroPNGWriter(
            width = width,
            height = height,
            greyscale = True,
            alpha = False,
            bitdepth = bit_depth,
        )

        # Set various metadata in PNG
        png_writer.set_header(header)
        if self.quantized:
            png_writer.set_quantization_parameters(z_zeros, z_scales)
            png_writer.set_nans(nan_indices)
        
        f = open(out_file, 'wb')
        png_writer.write(f, fluxes)
        f.close()
        
        # Crush
        if crush:
            pngcrush = which('pngcrush')
            if pngcrush:
                path, extension = os.path.splitext(out_file)
                filename = "%s_crushed%s" % (path, extension)
                os.system("%s -save %s %s" % (pngcrush, out_file, filename))
                shutil.move(filename, out_file)