Create project for each image

@return list of projects for all docker images
347236
public Collection<AgentProjectInfo> resolveDockerImages() {

        // TODO: Read this before changing RemoteDockersManager location
        // Remote Docker pulling should be enable only if docker.scanImages==true && docker.pull.enable==true
        // Before calling resolveDockerImages() there is a check for isScanDockerImages()
        // If we create RemoteDockersManager outside of resolveDockerImages then we have to check isScanDockerImages()
        RemoteDockersManager remoteDockersManager = new RemoteDockersManager(config.getRemoteDocker());
        remoteDockersManager.pullRemoteDockerImages();

        String line = null;
        Collection<DockerImage> dockerImages = new LinkedList<>();
        Collection<DockerImage> dockerImagesToScan;
        Process process = null;
        try {
            // docker get list of images, use wait to get the whole list
            boolean isTarImages = config.isScanImagesTar();
            if (!isTarImages) {
                process = Runtime.getRuntime().exec(DOCKER_IMAGES);
                InputStream inputStream = process.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                logger.debug("Docker images list from BufferedReader");
                while ((line = br.readLine()) != null) {
                    logger.debug(line);
                    // read all docker images data, skip the first line
                    if (!line.startsWith(REPOSITORY)) {
                        String[] dockerImageString = line.split(SPACES_REGEX);
                        if (dockerImageString.length > 2) {
                            dockerImages.add(new DockerImage(dockerImageString[0], dockerImageString[1], dockerImageString[2]));
                        } else {
                            logger.info("Docker line content is ignored: {}", line);
                        }
                    }
                }
                process.waitFor();
                if (!dockerImages.isEmpty()) {
                    // filter docker images using includes & excludes parameter
                    dockerImagesToScan = filterDockerImagesToScan(dockerImages, config.getAgent().getDockerIncludes(), config.getAgent().getDockerExcludes());
                    if (!dockerImagesToScan.isEmpty()) {
                        saveDockerImages(dockerImagesToScan, projects);
                    }
                }
                br.close();
            } else {
                Collection<File> tarFiles = new HashSet<>();
                FilenameFilter filenameFilter = new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        if (name.endsWith(TAR_SUFFIX)) {
                            return true;
                        }
                        return false;
                    }
                };
                for(String dir: config.getDependencyDirs()) {
                    File tarDir = new File(dir);
                    if (tarDir.isDirectory()) {
                        for (File tarFile: tarDir.listFiles(filenameFilter)) {
                            tarFiles.add(tarFile);
                        }
                    }
                }
                Collection<File> tarImagesToScan = filterTarImagesToScan(tarFiles, config.getAgent().getDockerIncludes(), config.getAgent().getDockerExcludes());
                scanTarList(tarImagesToScan, projects);
            }
        } catch (IOException e) {
            logger.error("IO exception : {}", e.getMessage());
            logger.debug("IO exception : {}", e.getStackTrace());
        } catch (InterruptedException e) {
            logger.error("Interrupted exception : {}", e.getMessage());
            logger.debug("Interrupted exception : {}", e.getStackTrace());
        } catch (Exception e) {
            logger.error("Exception : {}", e.getMessage());
            logger.debug("Resolve Docker Images Exception : {}", e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        remoteDockersManager.removePulledRemoteDockerImages();
        return projects;
    }
604166
def list_projects(self):
        
        data = self._run(
            url_path="projects/list"
        )
        projects = data['result'].get('projects', [])
        return [self._project_formatter(item) for item in projects]
1214426
private String createMultiProjectCSV() {

        String csvData = null;
        List<IProject> projects = null;
        IProject project = null;

        if (isProjectKeyProvided()) {

            project = getExtractor().getProject(getProjectKey());
            projects = new ArrayList<IProject>();
            projects.add(project);

        } else if (isProjectKeyPatternProvided()) {

            projects = getExtractor().getProjects(getProjectKeyPattern());

        } else {

            projects = getExtractor().getAllProjects();
        }

        csvData = getConverter().getCSVData(projects, getMeasureObjects(), isCleanValues(), isSurroundFields());
        LOG_INFO.info("Retrieved projects and generated CSV data.");

        return csvData;
    }
1177894
public Project.Storepoints.Storepoint.Calendars.Calendar createProjectStorepointsStorepointCalendarsCalendar()
   {
      return new Project.Storepoints.Storepoint.Calendars.Calendar();
   }
560004
function dockerContainers(all, callback) {

  function inContainers(containers, id) {
    let filtered = containers.filter(obj => {
      /**
       * @namespace
       * @property {string}  Id
       */
      return (obj.Id && (obj.Id === id));
    });
    return (filtered.length > 0);
  }

  // fallback - if only callback is given
  if (util.isFunction(all) && !callback) {
    callback = all;
    all = false;
  }

  all = all || false;
  let result = [];
  return new Promise((resolve) => {
    process.nextTick(() => {
      if (!_docker_socket) {
        _docker_socket = new DockerSocket();
      }

      _docker_socket.listContainers(all, data => {
        let docker_containers = {};
        try {
          docker_containers = data;
          if (docker_containers && Object.prototype.toString.call(docker_containers) === '[object Array]' && docker_containers.length > 0) {
            docker_containers.forEach(function (element) {
              /**
               * @namespace
               * @property {string}  Id
               * @property {string}  Name
               * @property {string}  Image
               * @property {string}  ImageID
               * @property {string}  Command
               * @property {number}  Created
               * @property {string}  State
               * @property {Array}  Names
               * @property {Array}  Ports
               * @property {Array}  Mounts
               */

              if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) {
                element.Name = element.Names[0].replace(/^\/|\/$/g, '');
              }
              result.push({
                id: element.Id,
                name: element.Name,
                image: element.Image,
                imageID: element.ImageID,
                command: element.Command,
                created: element.Created,
                state: element.State,
                ports: element.Ports,
                mounts: element.Mounts,
                // hostconfig: element.HostConfig,
                // network: element.NetworkSettings
              });
            });
          }
        } catch (err) {
          util.noop();
        }
        // }

        // GC in _docker_container_stats
        for (let key in _docker_container_stats) {
          if (_docker_container_stats.hasOwnProperty(key)) {
            if (!inContainers(docker_containers, key)) delete _docker_container_stats[key];
          }
        }
        if (callback) { callback(result); }
        resolve(result);
      });
    });
  });
}
1149877
def _export_project_file(project, path, z, include_images, keep_compute_id, allow_all_nodes, temporary_dir):
    

    # Image file that we need to include in the exported archive
    images = []

    with open(path) as f:
        topology = json.load(f)

    if "topology" in topology:
        if "nodes" in topology["topology"]:
            for node in topology["topology"]["nodes"]:
                compute_id = node.get('compute_id', 'local')

                if node["node_type"] == "virtualbox" and node.get("properties", {}).get("linked_clone"):
                    raise aiohttp.web.HTTPConflict(text="Topology with a linked {} clone could not be exported. Use qemu instead.".format(node["node_type"]))
                if not allow_all_nodes and node["node_type"] in ["virtualbox", "vmware", "cloud"]:
                    raise aiohttp.web.HTTPConflict(text="Topology with a {} could not be exported".format(node["node_type"]))

                if not keep_compute_id:
                    node["compute_id"] = "local"  # To make project portable all node by default run on local

                if "properties" in node and node["node_type"] != "docker":
                    for prop, value in node["properties"].items():

                        if node["node_type"] == "iou":
                            if not prop == "path":
                                continue
                        elif not prop.endswith("image"):
                            continue
                        if value is None or value.strip() == '':
                            continue

                        if not keep_compute_id:  # If we keep the original compute we can keep the image path
                            node["properties"][prop] = os.path.basename(value)

                        if include_images is True:
                            images.append({
                                'compute_id': compute_id,
                                'image': value,
                                'image_type': node['node_type']
                            })

        if not keep_compute_id:
            topology["topology"]["computes"] = []  # Strip compute information because could contain secret info like password

    local_images = set([i['image'] for i in images if i['compute_id'] == 'local'])

    for image in local_images:
        _export_local_images(project, image, z)

    remote_images = set([
        (i['compute_id'], i['image_type'], i['image'])
        for i in images if i['compute_id'] != 'local'])

    for compute_id, image_type, image in remote_images:
        yield from _export_remote_images(project, compute_id, image_type, image, z, temporary_dir)

    z.writestr("project.gns3", json.dumps(topology).encode())

    return images
832165
def create_dependencies task
      project_name = "minke#{SecureRandom.urlsafe_base64(12)}".downcase.gsub(/[^0-9a-z ]/i, '')
      network_name = ENV['DOCKER_NETWORK'] ||= "#{project_name}_default"
      ENV['DOCKER_PROJECT'] = project_name
      ENV['DOCKER_NETWORK'] = network_name

      logger = Minke::Logging.create_logger(STDOUT, self.verbose)
      shell = Minke::Helpers::Shell.new(logger)

      task_runner = Minke::Tasks::TaskRunner.new ({
        :ruby_helper       => Minke::Helpers::Ruby.new,
        :copy_helper       => Minke::Helpers::Copy.new,
        :service_discovery => Minke::Docker::ServiceDiscovery.new(project_name, Minke::Docker::DockerRunner.new(logger), network_name),
        :logger_helper     => logger
      })

      consul = Minke::Docker::Consul.new(
        {
          :health_check => Minke::Docker::HealthCheck.new(logger),
          :service_discovery => Minke::Docker::ServiceDiscovery.new( project_name, Minke::Docker::DockerRunner.new(logger, network_name), network_name),
          :consul_loader => ConsulLoader::Loader.new(ConsulLoader::ConfigParser.new),
          :docker_runner => Minke::Docker::DockerRunner.new(logger, network_name),
          :network => network_name,
          :project_name => project_name,
          :logger_helper => logger
        }
      )

      network = Minke::Docker::Network.new(
        network_name,
        shell
      )

      return {
        :config                 => @config,
        :task_name              => task,
        :docker_runner          => Minke::Docker::DockerRunner.new(logger, network_name, project_name),
        :task_runner            => task_runner,
        :shell_helper           => shell,
        :logger_helper          => logger,
        :generator_config       => generator_config,
        :docker_compose_factory => Minke::Docker::DockerComposeFactory.new(shell, project_name, network_name),
        :consul                 => consul,
        :docker_network         => network,
        :health_check           => Minke::Docker::HealthCheck.new(logger),
        :service_discovery      => Minke::Docker::ServiceDiscovery.new(project_name, Minke::Docker::DockerRunner.new(logger), network_name)
      } 
    end
67815
public Project.Calendars.Calendar.WorkWeeks.WorkWeek createProjectCalendarsCalendarWorkWeeksWorkWeek()
   {
      return new Project.Calendars.Calendar.WorkWeeks.WorkWeek();
   }
192538
def all(self):
        
        project_list = self.fetch('projects.json').get("projects")
        obj_list = []
        for proj in project_list:
            proj['_connection'] = self._connection
            proj = Project(proj)
            obj_list.append(proj)
        return obj_list
1209227
public DistributerMap createMap() {
    final DistributerMap map = new DistributerMap();
    map.setProject(getProject());
    this.maps.addElement(map);
    return map;
  }
711242
public java.util.List<Image> getImages() {
        if (images == null) {
            images = new com.amazonaws.internal.SdkInternalList<Image>();
        }
        return images;
    }
144460
protected function copyDockerServiceFiles()
    {
        $root = ProjectX::projectRoot() . "/docker/services";
        $configs = $this->getProjectServiceConfigs();
        $project_type = $this->getProjectType();

        foreach ($this->getServices() as $name => $info) {
            if (!isset($info['type'])) {
                continue;
            }
            $type = $info['type'];

            /** @var DockerService $instance */
            $instance = self::loadService($this, $type, $name);

            if (isset($info['version'])) {
                $instance->setVersion($info['version']);
            }

            if (isset($configs[$type])) {
                $instance->setConfigs($configs[$type]);
            }

            foreach ($instance->templateFiles() as $template => $temp_info) {
                $paths = [
                    "{$type}/{$project_type}/{$template}",
                    "{$type}/{$template}"
                ];
                foreach ($paths as $path) {
                    $filepath = $this->getTemplateFilePath($path);

                    if (false !== $filepath) {
                        $filesystem = $this->taskFilesystemStack();
                        $destination = "{$root}/{$type}";

                        if (!file_exists($destination)) {
                            $filesystem->mkdir($destination);
                        }
                        $filename = basename($filepath);
                        $destination = "{$destination}/{$filename}";

                        $overwrite = isset($temp_info['overwrite'])
                            ? $temp_info['overwrite']
                            : false;

                        $status = $filesystem
                            ->copy($filepath, $destination, $overwrite)
                            ->run();

                        if ($status->wasSuccessful()
                            && !empty($temp_info['variables'])) {
                            $file_task = $this
                                ->taskWriteToFile($destination)
                                ->append();

                            foreach ($temp_info['variables'] as $name => $value) {
                                $file_task->place($name, $value);
                            }

                            $file_task->run();
                        }

                        break;
                    }
                }
            }
        }

        return $this;
    }
867372
public List<Resource> buildResources() {
        List<Resource> resources = new ArrayList<Resource>();
        for (ResourceBuilder builder : _resourceBuilders) {
            Resource resource = builder.build();
            if (resource != null) {
                resources.add(resource);
            }
        }
        return resources;
    }
784235
def projects(self, task, params={}, **options): 
        
        path = "/tasks/%s/projects" % (task)
        return self.client.get_collection(path, params, **options)
1343666
public Iterator<?> downstreamProjects() {
        List<Run<?, ?>> downstreamList = new ArrayList<Run<?, ?>>();

        downstreamList.add(build);

        return downstreamList.iterator();
    }
540247
def applet_list_projects(object_id, input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/%s/listProjects' % object_id, input_params, always_retry=always_retry, **kwargs)
576757
protected File[] listRepositoryFiles() {
        //return AccessHelper.listFiles(repositoryLocation, filter);
        File[] directories = listRepositoryDirs();
        ArrayList<File> allFilesArray = new ArrayList<File>();
        File[] allFiles = new File[allFilesArray.size()];

        //get all the files in each server instance directory
        for (int i = 0; i < directories.length; i++) {

            //for each server instance directory, list the files, filtering out subdirectories
            File[] files = AccessHelper.listFiles(directories[i], filter);
            if (files != null && files.length > 0) {
                allFilesArray.addAll(Arrays.asList(files));
            }
            // F017049-22453 ... now look for files in child processes
            files = AccessHelper.listFiles(directories[i], subprocFilter);
            for (File curFile : files) {
                File[] subFiles = AccessHelper.listFiles(curFile, filter);
                if (subFiles != null && subFiles.length > 0) {
                    allFilesArray.addAll(Arrays.asList(subFiles));
                }
            }
        }

        //if there are files to sort, then sort
        if (!allFilesArray.isEmpty()) {
            allFiles = allFilesArray.toArray(allFiles);
        }

        return allFiles;
    }