Figure out which utmp file to use when determining runlevel.
    Sometimes /var/run/utmp doesn't exist, /run/utmp is the new hotness.
975197
def _find_utmp():
    '''
    
    '''
    result = {}
    # These are the likely locations for the file on Ubuntu
    for utmp in '/var/run/utmp', '/run/utmp':
        try:
            result[os.stat(utmp).st_mtime] = utmp
        except Exception:
            pass
    if result:
        return result[sorted(result).pop()]
    else:
        return False
168712
function findAssertionSourceInTrace(trace) {

    var found = null;

    for (var i = 0, l = trace.length; i < l; ++i) {
      if (
        trace[i].file === stSkipStart.file &&
        trace[i].line >= stSkipStart.line &&
        trace[i].line <= stSkipEnd.line
      ) {
        break;
      }
      found = trace[i];
    }

    return found;

  }
169844
protected function run()
    {
        $pack = $this->rec->getResourcePack();
        $this->version = $this->get(VersionAnalyzer::class);
        $version = $this->version;

        $players = $this->get(PlayerMetaAnalyzer::class);

        // The player number is used for chat messages.
        $playersByNumber = [];
        // The player index is used for game actions.
        $playersByIndex = [];
        foreach ($players as $player) {
            $playersByNumber[$player->number] = $player;
            $playersByIndex[$player->index] = $player;
        }

        $this->playersByNumber = $playersByNumber;

        $size = strlen($this->body);

        $this->position = 0;
        if ($version->isMgl) {
            $this->processGameStart();
        }

        while ($this->position < $size - 3) {
            $operationType = $this->readBody('l', 4);

            if ($operationType === self::OP_CHAT) {
                // AoC and up store the game start message with the same ID
                // as a CHAT message, but chat messages are prefixed with 0xFFFF_FFFF
                $syncChecksumInterval = $this->readBody('l', 4);
                if ($syncChecksumInterval === -1) {
                    $this->processChatMessage();
                } else {
                    $this->position -= 4;
                    $this->processGameStart();
                }
            } else if ($operationType === self::OP_SYNC) {
                $this->syncIndex++;
                // There are a lot of sync packets, so we get a significant
                // speedup just from doing this inline (and not in a separate
                // method), and by using `unpack` and manual position increments
                // instead of `readBody`.
                $data = unpack('l2', substr($this->body, $this->position, 8));
                $this->currentTime += $data[1]; // $this->readBody('l', 4);
                if ($this->syncIndex === $this->syncChecksumInterval) {
                    // no need to parse checksums
                    $this->position += 28;
                }
            } else if ($operationType === self::OP_VIEWLOCK) {
                // just skip for now
                $this->position += 12;
            } else if ($operationType === self::OP_COMMAND) {
                $length = $this->readBody('l', 4);
                $next = $this->position + $length;
                $command = ord($this->body[$this->position]);
                $this->position++;

                switch ($command) {
                    // player resign
                    case self::COMMAND_RESIGN:
                        $playerIndex = ord($this->body[$this->position]);
                        $playerNumber = ord($this->body[$this->position + 1]);
                        $disconnected = ord($this->body[$this->position + 2]);
                        $this->position += 3;
                        $player = $playersByIndex[$playerIndex];
                        if ($player && $player->resignTime === 0) {
                            $player->resignTime = $this->currentTime;
                            $message = sprintf('%s resigned', $player->name);
                            $this->chatMessages[] = new ChatMessage($this->currentTime, null, $message);
                        }
                        break;
                    // researches
                    case self::COMMAND_RESEARCH:
                        $this->position += 3;
                        $buildingId = $this->readBody('l', 4);
                        $playerId = $this->readBody('v', 2);
                        $researchId = $this->readBody('v', 2);
                        $player = $playersByIndex[$playerId];
                        if (!$player) {
                            break;
                        }

                        switch ($researchId) {
                            case self::RESEARCH_FEUDAL:
                                $researchDuration = 130000;
                                $player->feudalTime = $this->currentTime + $researchDuration;
                                break;
                            case self::RESEARCH_CASTLE:
                                // persians have faster research time
                                $researchDuration = 160000;
                                if ($player->civId === Civilization::PERSIANS) {
                                    $researchDuration /= 1.10;
                                }
                                $player->castleTime = $this->currentTime + round($researchDuration);
                                break;
                            case self::RESEARCH_IMPERIAL:
                                $researchDuration = 190000;
                                if ($player->civId === Civilization::PERSIANS) {
                                    $researchDuration /= 1.15;
                                }
                                $player->imperialTime = $this->currentTime + round($researchDuration);
                                break;
                        }
                        $player->addResearch($researchId, $this->currentTime);
                        break;
                    // training unit
                    case self::COMMAND_TRAIN:
                        $this->position += 3;
                        $buildingId = $this->readBody('l', 4);
                        $unitType = $this->readBody('v', 2);
                        $amount = $this->readBody('v', 2);

                        if (!isset($this->units[$unitType])) {
                            $this->units[$unitType] = $amount;
                        } else {
                            $this->units[$unitType] += $amount;
                        }
                        break;
                    // AI trains unit
                    case self::COMMAND_TRAIN_SINGLE:
                        $this->position += 9;
                        $unitType = $this->readBody('v', 2);
                        if (!isset($this->units[$unitType])) {
                            $this->units[$unitType] = 1;
                        } else {
                            $this->units[$unitType] += 1;
                        }
                        break;
                    // building
                    case self::COMMAND_BUILD:
                        $this->position += 1;
                        $playerId = $this->readBody('v', 2);
                        $this->position += 8;
                        $buildingType = $this->readBody('v', 2);

                        $buildingType = $pack->normalizeUnit($buildingType);

                        if (!isset($this->buildings[$playerId][$buildingType])) {
                            $this->buildings[$playerId][$buildingType] = 1;
                        } else {
                            $this->buildings[$playerId][$buildingType]++;
                        }
                        break;
                    // tributing
                    case self::COMMAND_TRIBUTE:
                        $playerIdFrom = ord($this->body[$this->position++]);
                        $playerIdTo = ord($this->body[$this->position++]);
                        $resourceId = ord($this->body[$this->position++]);

                        $playerFrom = $playersByIndex[$playerIdFrom];
                        $playerTo = $playersByIndex[$playerIdTo];

                        if ($playerFrom && $playerTo) {
                            $amount = $this->readBody('f', 4);
                            $marketFee = $this->readBody('f', 4);

                            $tribute = new Tribute();
                            $tribute->time = $this->currentTime;
                            $tribute->playerFrom = $playerFrom;
                            $tribute->playerTo = $playerTo;
                            $tribute->resourceId = $resourceId;
                            $tribute->amount = floor($amount);
                            $tribute->fee = $marketFee;
                            $this->tributes[] = $tribute;
                        } else {
                            $this->position += 8;
                        }
                        break;
                    // multiplayer postgame data in UP1.4 RC2+
                    case self::COMMAND_POSTGAME:
                        $this->postGameData = $this->read(PostgameDataAnalyzer::class);
                        break;
                    default:
                        break;
                }

                $this->position = $next;
            }
        }

        if (!empty($this->chatMessages)) {
            usort($this->chatMessages, function ($a, $b) {
                return $a->time - $b->time;
            });
        }

        if (!empty($this->buildings)) {
            ksort($this->buildings);
        }

        $analysis = new \StdClass;
        $analysis->duration = $this->currentTime;
        $analysis->tributes = $this->tributes;
        $analysis->chatMessages = $this->chatMessages;
        $analysis->units = $this->units;
        $analysis->buildings = $this->buildings;
        $analysis->postGameData = $this->postGameData;

        return $analysis;
    }
884188
public org.tensorflow.framework.RunOptions.TraceLevel getTraceLevel() {
    org.tensorflow.framework.RunOptions.TraceLevel result = org.tensorflow.framework.RunOptions.TraceLevel.valueOf(traceLevel_);
    return result == null ? org.tensorflow.framework.RunOptions.TraceLevel.UNRECOGNIZED : result;
  }
461766
def fast_compare(self, dir_path):
        
        if self.latest_backup is None:
            # No old backup run was found
            return

        if self.latest_mtime_ns is None:
            # No timestamp from old backup run was found
            return

        # There was a completed old backup run
        # Check if we can made a 'fast compare'
        mtime_ns = dir_path.stat.st_mtime_ns
        if mtime_ns > self.latest_mtime_ns:
            # The current source file is newer than
            # the latest file from last completed backup
            log.info("Fast compare: source file is newer than latest backuped file.")
            return

        # Look into database and compare mtime and size

        try:
            old_backup_entry = BackupEntry.objects.get(
                backup_run=self.latest_backup,
                directory__directory=self.path_helper.sub_path,
                filename__filename=self.path_helper.filename,
                no_link_source=False,
            )
        except BackupEntry.DoesNotExist:
            log.debug("No old backup entry found")
            return

        content_info = old_backup_entry.content_info

        file_size = content_info.file_size
        if file_size != dir_path.stat.st_size:
            log.info("Fast compare: File size is different: %i != %i" % (file_size, dir_path.stat.st_size))
            return

        old_backup_filepath = old_backup_entry.get_backup_path()
        try:
            old_file_mtime_ns = old_backup_filepath.stat().st_mtime_ns
        except FileNotFoundError as err:
            log.error("Old backup file not found: %s" % err)
            old_backup_entry.no_link_source = True
            old_backup_entry.save()
            return

        if old_file_mtime_ns != old_backup_entry.file_mtime_ns:
            log.error("ERROR: mtime from database is different to the file!")
            log.error(" * File: %s" % old_backup_filepath)
            log.error(" * Database mtime: %s" % old_backup_entry.file_mtime_ns)
            log.error(" * File mtime: %s" % old_file_mtime_ns)

        if old_file_mtime_ns != dir_path.stat.st_mtime_ns:
            log.info("Fast compare mtime is different between:")
            log.info(" * %s" % old_backup_entry)
            log.info(" * %s" % dir_path)
            log.info(" * mtime: %i != %i" % (old_file_mtime_ns, dir_path.stat.st_mtime_ns))
            return

        # We found a old entry with same size and mtime
        return old_backup_entry
1288210
private static void run(final String pServerURL, final String pDestinationFile, final String pTempFolder, final int pThreadCount, final String pFileAppendix, final int pMinZoom, final int pMaxZoom, final double pNorth, final double pSouth, final double pEast, final double pWest) {

          new File(pTempFolder).mkdirs();

          System.out.println("---------------------------");
          runFileExpecterWithAbort(pMinZoom, pMaxZoom, pNorth, pSouth, pEast, pWest);
          execute(pServerURL, pDestinationFile, pTempFolder, pThreadCount, pFileAppendix, pMinZoom, pMaxZoom, pNorth, pSouth, pEast, pWest, null);
           if (pServerURL != null) {
               runCleanup(pTempFolder, true);
          }

     }
643017
private File getTmpDir(ProbeTestRun testRun) {
		File tmpDir = new File(configuration.getWorkspace() + "/tmp/" + testRun.getVersion());
		
		if (!tmpDir.exists()) {
			tmpDir.mkdirs();
		}
		
		return tmpDir;
	}
563697
def main():
    
    logging.basicConfig(level=logging.INFO)

    run_metrics = py_interop_run_metrics.run_metrics()
    summary = py_interop_summary.run_summary()

    valid_to_load = py_interop_run.uchar_vector(py_interop_run.MetricCount, 0)
    py_interop_run_metrics.list_summary_metrics_to_load(valid_to_load)

    for run_folder_path in sys.argv[1:]:
        run_folder = os.path.basename(run_folder_path)
        try:
            run_metrics.read(run_folder_path, valid_to_load)
        except Exception, ex:
            logging.warn("Skipping - cannot read RunInfo.xml: %s - %s"%(run_folder, str(ex)))
            continue
        py_interop_summary.summarize_run_metrics(run_metrics, summary)
        error_rate_read_lane_surface = numpy.zeros((summary.size(), summary.lane_count(), summary.surface_count()))
        for read_index in xrange(summary.size()):
            for lane_index in xrange(summary.lane_count()):
                for surface_index in xrange(summary.surface_count()):
                    error_rate_read_lane_surface[read_index, lane_index, surface_index] = \
                        summary.at(read_index).at(lane_index).at(surface_index).error_rate().mean()
        logging.info("Run Folder: "+run_folder)
        for read_index in xrange(summary.size()):
            read_summary = summary.at(read_index)
            logging.info("Read "+str(read_summary.read().number())+" - Top Surface Mean Error: "+str(error_rate_read_lane_surface[read_index, :, 0].mean()))
1114720
def RunMetadata(self, tag):
    
    if tag not in self._tagged_metadata:
      raise ValueError('There is no run metadata with this tag name')

    run_metadata = config_pb2.RunMetadata()
    run_metadata.ParseFromString(self._tagged_metadata[tag])
    return run_metadata
823017
def _default_runlevel():
    '''
    
    '''
    # Try to get the "main" default.  If this fails, throw up our
    # hands and just guess "2", because things are horribly broken
    try:
        with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_:
            for line in fp_:
                line = salt.utils.stringutils.to_unicode(line)
                if line.startswith('env DEFAULT_RUNLEVEL'):
                    runlevel = line.split('=')[-1].strip()
    except Exception:
        return '2'

    # Look for an optional "legacy" override in /etc/inittab
    try:
        with salt.utils.files.fopen('/etc/inittab') as fp_:
            for line in fp_:
                line = salt.utils.stringutils.to_unicode(line)
                if not line.startswith('#') and 'initdefault' in line:
                    runlevel = line.split(':')[1]
    except Exception:
        pass

    # The default runlevel can also be set via the kernel command-line.
    # Kinky.
    try:
        valid_strings = set(
            ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single'))
        with salt.utils.files.fopen('/proc/cmdline') as fp_:
            for line in fp_:
                line = salt.utils.stringutils.to_unicode(line)
                for arg in line.strip().split():
                    if arg in valid_strings:
                        runlevel = arg
                        break
    except Exception:
        pass

    return runlevel
394712
def run!
      trace = @always_trace || false
      require_program :version, :description
      trap('INT') { abort program(:int_message) } if program(:int_message)
      trap('INT') { program(:int_block).call } if program(:int_block)
      global_option('-h', '--help', 'Display help documentation') do
        args = @args - %w(-h --help)
        command(:help).run(*args)
        return
      end
      global_option('-v', '--version', 'Display version information') do
        say version
        return
      end
      global_option('-t', '--trace', 'Display backtrace when an error occurs') { trace = true } unless @never_trace || @always_trace
      parse_global_options
      remove_global_options options, @args
      if trace
        run_active_command
      else
        begin
          run_active_command
        rescue InvalidCommandError => e
          abort "#{e}. Use --help for more information"
        rescue \
          OptionParser::InvalidOption,
          OptionParser::InvalidArgument,
          OptionParser::MissingArgument => e
          abort e.to_s
        rescue => e
          if @never_trace
            abort "error: #{e}."
          else
            abort "error: #{e}. Use --trace to view backtrace"
          end
        end
      end
    end
132005
def display_motd
      if ::File.exists?("/var/run/motd.dynamic")
        # Ubuntu 14.04+ motd location
        puts ::File.read("/var/run/motd.dynamic")
      elsif ::File.exists?("/var/run/motd")
        # Ubuntu 12.04 motd location
        puts ::File.read("/var/run/motd")
      elsif ::File.exists?("/etc/motd")
        # Legacy (CentOS 6 style)
        puts ::File.read("/etc/motd")
      end
    rescue 
      nil
    end
869295
private TrackType findTrackType() {
        TrackType result = TRACK_TYPE_MAP.get(packetBytes[42]);
        if (result == null) {
            return TrackType.UNKNOWN;
        }
        return result;
    }
1166844
def temp_filename(self):
        
        # TODO: it would be nice to get this to behave more like a
        # context so we can make sure these temporary files are
        # removed, regardless of whether an error occurs or the
        # program is terminated.
        handle, filename = tempfile.mkstemp()
        os.close(handle)
        return filename
1196013
def CheckForUnknownFiles(self):
		""""""
		unknown_files = self.GetUnknownFiles()
		if unknown_files:
			print "The following files are not added to version control:"
			for line in unknown_files:
				print line
			prompt = "Are you sure to continue?(y/N) "
			answer = raw_input(prompt).strip()
			if answer != "y":
				ErrorExit("User aborted")
725128
def find_runner(program):
    
    if os.path.isfile(program) and not os.access(program, os.X_OK):
        # program is a path to a non-executable file
        try:
            opened = open(program)
        except PermissionError:
            return None
        first_line = opened.readline().strip()
        if first_line.startswith('#!'):
            return shlex.split(first_line[2:])
        if program.endswith('.py'):
            return [sys.executable]
    return None
447251
def _runlevel():
    '''
    
    '''
    contextkey = 'systemd._runlevel'
    if contextkey in __context__:
        return __context__[contextkey]
    out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True)
    try:
        ret = out.split()[1]
    except IndexError:
        # The runlevel is unknown, return the default
        ret = _default_runlevel()
    __context__[contextkey] = ret
    return ret