Generates a map of parent process and child processes. This method
 will currently only work on unix.
167556
def process_map
      output    = `ps -eo ppid,pid`
      processes = {}

      output.split("\n").each do |line|
        if result = line.match(/(\d+)\s(\d+)/)
          parent = result[1].to_i
          child  = result[2].to_i

          processes[parent] ||= []
          processes[parent] << child
        end
      end

      processes
    end
187338
def get_shell(pid=None, max_depth=6):
    
    if not pid:
        pid = os.getpid()
    processes = dict(_iter_process())

    def check_parent(pid, lvl=0):
        ppid = processes[pid].get('parent_pid')
        shell_name = _get_executable(processes.get(ppid))
        if shell_name in SHELL_NAMES:
            return (shell_name, processes[ppid]['executable'])
        if lvl >= max_depth:
            return None
        return check_parent(ppid, lvl=lvl + 1)

    shell_name = _get_executable(processes.get(pid))
    if shell_name in SHELL_NAMES:
        return (shell_name, processes[pid]['executable'])
    try:
        return check_parent(pid)
    except KeyError:
        return None
1346567
private function getAllChildKeys($data, $maps, $parent_keys, $parent_types, & $result, & $keys, $current_key = [], $current_type = null) {
		if ($current_type == '11') {
			$data = ['__11__' => $data];
		}
		foreach ($data as $k => $v) {
			$new_key = $current_key;
			if ($current_type != '11') {
				$new_key[] = $k;
			}
			if (count($parent_keys) == 1) {
				$new_key[] = $parent_keys[0];
				// put values into result
				$result[] = $new_key;
				// generate keys
				$temp = [];
				foreach ($maps[0] as $k3 => $v3) {
					$temp[] = $v[$k3];
				}
				// we need to preserve a data type if its just one column key
				if (count($temp) == 1) {
					$keys[] = $temp[0];
				} else {
					$keys[] = implode('::', $temp);
				}
			} else {
				// remove extra level
				$parent_keys_temp = $parent_keys;
				$v2 = array_shift($parent_keys_temp);
				$parent_types_temp = $parent_types;
				array_shift($parent_types_temp);
				$maps_temp = $maps;
				array_shift($maps_temp);
				// generate key
				$new_key[] = $v2;
				$this->getAllChildKeys($v[$v2], $maps_temp, $parent_keys_temp, $parent_types_temp, $result, $keys, $new_key, $parent_types[0]);
			}
		}
	}
501019
private Map<String, Scope> getSubMap(Map<String, Map<String, Scope>> parent, String key) {

	Map<String, Scope> context = parent.get(key);
	if (context != null) return context;

	context = MapFactory.<String, Scope>getConcurrentMap();
	parent.put(key, context);
	return context;

    }
903202
def output(results_dir, config, parent='../../'):
    
    start = time.time()
    print("Compiling results...")
    results_dir = os.path.abspath(results_dir)
    results = ReportResults(config['run_time'], config['results_ts_interval'])
    results.compile_results()
    print("Results compiled in {} seconds\n".format(time.time() - start))

    if results.total_transactions == 0:
        print("No results, cannot create report")
        return False

    print_infos(results)

    data = {
        'report': results,
        'run_time': config['run_time'],
        'ts_interval': config['results_ts_interval'],
        'turrets_config': results.turrets,
        'results': {"all": results.main_results, "timers": results.timers_results}
    }

    print("Generating graphs...")
    partial = time.time()
    generate_graphs(results.main_results, 'All_Transactions', results_dir)

    for key, value in results.timers_results.items():
        generate_graphs(value, key, results_dir)
    print("All graphs generated in {} seconds\n".format(time.time() - partial))

    write_template(data, results_dir, parent)
    print("Full report generated in {} seconds".format(time.time() - start))
    return True
948875
def process_children(self, node, parent, pmod):
        
        for ch in node.i_children:
            if ch.keyword in ["rpc", "notification"]: continue
            if ch.keyword in ["choice", "case"]:
                self.process_children(ch, parent, pmod)
                continue
            if ch.i_module.i_modulename == pmod:
                nmod = pmod
                nodename = ch.arg
            else:
                nmod = ch.i_module.i_modulename
                nodename = "%s:%s" % (nmod, ch.arg)
            ndata = [ch.keyword]
            if ch.keyword == "container":
                ndata.append({})
                self.process_children(ch, ndata[1], nmod)
            elif ch.keyword == "list":
                ndata.append({})
                self.process_children(ch, ndata[1], nmod)
                ndata.append([(k.i_module.i_modulename, k.arg)
                              for k in ch.i_key])
            elif ch.keyword in ["leaf", "leaf-list"]:
                ndata.append(self.base_type(ch.search_one("type")))
            modname = ch.i_module.i_modulename
            parent[nodename] = ndata
1160032
def fork_many(n)
      pids = []
      n.times do |i|
        pids << fork do
          yield i
          Kernel.exit!
        end
      end

      pids.each { |pid| ::Process.wait(pid) }
    end
1037569
def process_memory_map(attrs=None, where=None):
    '''
    
    '''
    if __grains__['os_family'] in ['RedHat', 'Debian']:
        return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where)
    return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'}
292947
def _map_parallel(function, args, n_jobs):
    """"""
    # Following the error checking found in joblib
    multiprocessing = int(os.environ.get('JOBLIB_MULTIPROCESSING', 1)) or None
    if multiprocessing:
        try:
            import multiprocessing
            import multiprocessing.pool
        except ImportError:
            multiprocessing = None
        if sys.platform.startswith("win") and PY2:
            msg = "Multiprocessing is not supported on Windows with Python 2.X. Setting n_jobs=1"
            logger.warning(msg)
            n_jobs = 1
    # 2nd stage: validate that locking is available on the system and
    #            issue a warning if not
    if multiprocessing:
        try:
            _sem = multiprocessing.Semaphore()
            del _sem  # cleanup
        except (ImportError, OSError) as e:
            multiprocessing = None
            logger.warning('{}. _map_parallel will operate in serial mode'.format(e))
    if multiprocessing and int(n_jobs) not in (0, 1):
        if n_jobs == -1:
            n_jobs = None
        try:
            pool = multiprocessing.Pool(processes=n_jobs)
            map_result = pool.map(function, args)
        finally:
            pool.close()
            pool.join()
    else:
        map_result = list(map(function, args))
    return map_result
290808
def _mapped_std_streams(lookup_paths, streams=('stdin', 'stdout', 'stderr')):
    """"""
    # FIXME add device number too
    standard_inos = {}
    for stream in streams:
        try:
            stream_stat = os.fstat(getattr(sys, stream).fileno())
            key = stream_stat.st_dev, stream_stat.st_ino
            standard_inos[key] = stream
        except Exception:  # FIXME UnsupportedOperation
            pass
        # FIXME if not getattr(sys, stream).istty()

    def stream_inos(paths):
        """Yield tuples with stats and path."""
        for path in paths:
            try:
                stat = os.stat(path)
                key = (stat.st_dev, stat.st_ino)
                if key in standard_inos:
                    yield standard_inos[key], path
            except FileNotFoundError:  # pragma: no cover
                pass

    return dict(stream_inos(lookup_paths)) if standard_inos else {}
451319
def create_process(cmd, root_helper=None, addl_env=None, log_output=True):
    
    if root_helper:
        cmd = shlex.split(root_helper) + cmd
    cmd = map(str, cmd)

    log_output and LOG.info("Running command: %s", cmd)
    env = os.environ.copy()
    if addl_env:
        env.update(addl_env)

    obj = subprocess_popen(cmd, shell=False, stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                           env=env)
    return obj, cmd
573575
Map<Integer, Integer> initParentMap() {
        Map<Integer, Integer> parentMap = new LinkedHashMap<>(numWorkers);
        for(int r = 0; r < numWorkers; r++) {
            parentMap.put(r, ((r + 1) / 2 - 1) );
        }
        return parentMap;
    }
965628
def post_fork_child(self):
    """"""
    entry_point = '{}:launch'.format(__name__)
    exec_env = combined_dict(os.environ, dict(PANTS_ENTRYPOINT=entry_point))
    # Pass all of sys.argv so that we can proxy arg flags e.g. `-ldebug`.
    cmd = [sys.executable] + sys.argv
    self._logger.debug('cmd is: PANTS_ENTRYPOINT={} {}'.format(entry_point, ' '.join(cmd)))
    # TODO: Improve error handling on launch failures.
    os.spawnve(os.P_NOWAIT, sys.executable, cmd, env=exec_env)
569852
def _get_process_mapping():
    
    for impl in (proc, ps):
        try:
            mapping = impl.get_process_mapping()
        except EnvironmentError:
            continue
        return mapping
    raise ShellDetectionFailure('compatible proc fs or ps utility is required')
490522
def main():
    

    logging.captureWarnings(True)
    logging.basicConfig(format=('%(asctime)s - %(name)s - %(levelname)s - ' +
                                '%(message)s'), level=logging.INFO)

    args = [3, 5, 10, 20]

    # The default queue used by grid_map is all.q. You must specify
    # the `queue` keyword argument if that is not the name of your queue.
    intermediate_results = grid_map(computeFactorial, args, quiet=False,
                                    max_processes=4, queue='all.q')

    # Just print the items instead of really reducing. We could always sum them.
    print("reducing result")
    for i, ret in enumerate(intermediate_results):
        print("f({0}) = {1}".format(args[i], ret))
993920
def cpmap(cores=1):
    
    if int(cores) == 1:
        yield itertools.imap
    else:
        if futures is None:
            raise ImportError("concurrent.futures not available")
        pool = futures.ProcessPoolExecutor(cores)
        yield pool.map
        pool.shutdown()
297261
def prepareSystem(cls):
        
        try:
            resourceRootDirPath = os.environ[cls.rootDirPathEnvName]
        except KeyError:
            # Create directory holding local copies of requested resources ...
            resourceRootDirPath = mkdtemp()
            # .. and register its location in an environment variable such that child processes
            # can find it.
            os.environ[cls.rootDirPathEnvName] = resourceRootDirPath
        assert os.path.isdir(resourceRootDirPath)