task that will link the given object files to a static lib
963380
def convert_to_rake()
      object_multitask = prepare_tasks_for_objects()
      archiver = @tcs[:ARCHIVER]

      res = typed_file_task Rake::Task::LIBRARY, get_task_name => object_multitask do
        cmd = calc_command_line
        aname = calc_archive_name
        Dir.chdir(@project_dir) do
          FileUtils.rm(aname) if File.exists?(aname)
#          cmd.map! {|c| c.include?(' ') ? "\"#{c}\"" : c }
          rd, wr = IO.pipe
          cmd << {
            :err => wr,
            :out => wr
          }
          sp = spawn(*cmd)
          cmd.pop

          consoleOutput = ProcessHelper.readOutput(sp, rd, wr)

          process_result(cmd, consoleOutput, @tcs[:ARCHIVER][:ERROR_PARSER], "Creating #{aname}")

          check_config_file()
        end
      end
      res.tags = tags
      enhance_with_additional_files(res)
      add_output_dir_dependency(get_task_name, res, true)

      add_grouping_tasks(get_task_name)

      setup_rake_dependencies(res, object_multitask)
      return res
    end
360510
def load(filename: str, format: str = None):
    """"""

    path = Path(filename).resolve()

    with path.open() as file:
        data = file.read()

    if format is None:
        loader, error_class = _load_autodetect, InvalidMofileFormat
    else:
        try:
            loader, error_class = formats[format]
        except KeyError:
            raise InvalidMofileFormat(f'Unknown file format: {format}')

    try:
        config = loader(data)
    except error_class as e:
        raise InvalidMofileFormat(f'Unable to load task file: {e}')

    return Project(config, path.parent)
752546
def main():
    """"""
    desc = 'Generate files to benchmark'
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument(
        '--src',
        dest='src_dir',
        default='src',
        help='The directory containing the templates'
    )
    parser.add_argument(
        '--out',
        dest='out_dir',
        default='generated',
        help='The output directory'
    )
    parser.add_argument(
        '--seed',
        dest='seed',
        default='13',
        help='The random seed (to ensure consistent regeneration)'
    )

    args = parser.parse_args()

    random.seed(int(args.seed))

    mkdir_p(args.out_dir)

    for template in templates_in(args.src_dir):
        modes = template.modes()

        n_range = template.range()
        for n_value in n_range:
            base = template.instantiate(n_value)
            for mode in modes:
                write_file(
                    os.path.join(
                        args.out_dir,
                        out_filename(template, n_value, mode)
                    ),
                    mode.convert_from(base)
                )
        write_file(
            os.path.join(args.out_dir, '{0}.json'.format(template.name)),
            json.dumps({
                'files': {
                    n: {
                        m.identifier: out_filename(template, n, m)
                        for m in modes
                    } for n in n_range
                },
                'name': template.name,
                'x_axis_label': template.property('x_axis_label'),
                'desc': template.property('desc'),
                'modes': {m.identifier: m.description() for m in modes}
            })
        )
398237
def obj2bunch(data, commdct, obj):
    """"""
    dtls = data.dtls
    key = obj[0].upper()
    key_i = dtls.index(key)
    abunch = makeabunch(commdct, obj, key_i)
    return abunch
732458
def build_object(self, obj):
        """"""
        if not obj.exclude_from_static:
            super(ShowPage, self).build_object(obj)
1181380
def load_objects(self, dirs=[], callwith={}):
        '''
        
        '''
        for d in dirs:
            contents = ls(d)
            for t in contents:
                first = join(d, t)
                if t.startswith('.') or os.path.isfile(first):
                    continue
                t_l = t.lower()
                for fl in ls(first):
                    full = join(first, fl)
                    if fl.startswith('.') or os.path.isdir(full):
                        continue
                    fl_n = fl.lower().rsplit('.', 1)[0]
                    ty = guess_type(full)
                    if ty == T_IMAGE:
                        self.load_image(full, fl_n, t)
                    elif ty == T_SOUND:
                        self.load_sound(full, fl_n, t)
                    elif ty == T_MUSIC:
                        self.load_music(full, fl_n, t)
                    elif ty == T_CODE and fl_n == '__init__':
                        self.load_code(d, t, callwith)
                    elif ty == T_PLAYLIST:
                        self.load_playlist(full, fl_n)
662754
def static(cls):
  
  """
  for attr in dir(cls):
      im_func = getattr(getattr(cls, attr), 'im_func', None)
      if im_func:
        setattr(cls, attr, staticmethod(im_func))

  return cls
177132
def find_static_library(library_name, library_path):
    """"""

    variants = ["lib{0}.a", "{0}.a", "{0}.lib", "lib{0}.lib"]
    if is_unix_like():
        extra_libdirs = ["/usr/local/lib64", "/usr/local/lib",
                "/usr/lib64", "/usr/lib", "/lib64", "/lib"]
    else:
        extra_libdirs = []

    for path in extra_libdirs:
        if path not in library_path and os.path.isdir(path):
            library_path.append(path)

    for path in library_path:
        for variant in variants:
            full_path = os.path.join(path, variant.format(library_name))
            if os.path.isfile(full_path):
                return full_path
677662
def load(cls, filename):
        
        jobject = javabridge.static_call(
            "weka/experiment/Experiment", "read", "(Ljava/lang/String;)Lweka/experiment/Experiment;",
            filename)
        return Experiment(jobject=jobject)
1218757
function template(files, staticPath) {
			return files ? files.map(function(filepath){
				paths = filepath.split(staticPath)[1].split('/')
				jsonpart = buildJsonPath(paths, filepath);
				return jsonpart;
			}) : ''
		}
401740
def define_ui_tasks
      @ui_files.each do | ui_file |
        ui_header = ui_header_path( ui_file )
        file ui_header => [ @objects_path, ui_file ] do |t|
          command = "uic #{ ui_file } -o #{ ui_header }"
          shell command
        end
      end
    end
784534
def _build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_typ: Type[T],
                                                     logger: Logger = None) -> Dict[Type, Parser]:
        

        parsers = OrderedDict()
        errors = OrderedDict()
        try:
            p = self.__build_parser_for_fileobject_and_desiredtype(obj_on_filesystem,
                                                                   object_typ=object_typ,
                                                                   logger=logger)
            parsers[object_typ] = p
        except NoParserFoundForObjectExt as e:
            logger.warning("{} - {}".format(type(e).__name__, e))
            errors[e] = e
        except NoParserFoundForObjectType as f:
            logger.warning("{} - {}".format(type(f).__name__, f))
            errors[f] = f

        # do not explore subclasses for collections
        if is_collection(object_typ, strict=True):
            if len(errors) > 0:
                raise next(iter(errors.values()))
            else:
                return parsers

        # Finally create one such parser for each subclass
        subclasses = get_all_subclasses(object_typ)

        # Then for each subclass also try (with a configurable limit in nb of subclasses)
        for subclass in subclasses[0:GLOBAL_CONFIG.dict_to_object_subclass_limit]:
            try:
                parsers[subclass] = self.__build_parser_for_fileobject_and_desiredtype(obj_on_filesystem,
                                                                                       object_typ=subclass,
                                                                                       logger=logger)
            except NoParserFoundForObjectExt as e:
                logger.warning("{} - {}".format(type(e).__name__, e))
                errors[e] = e
            except NoParserFoundForObjectType as f:
                logger.warning("{} - {}".format(type(f).__name__, f))
                errors[f] = f

        if len(subclasses) > GLOBAL_CONFIG.dict_to_object_subclass_limit:
            warn('Type {} has more than {} subclasses, only {} were tried to convert it, with no success. You '
                 'can raise this limit by setting the appropriate option with `parsyfiles_global_config()`'
                 ''.format(object_typ, len(subclasses), GLOBAL_CONFIG.dict_to_object_subclass_limit))

        return parsers
1232383
function mapObjects(root, list, callback) {
	var ret = {};
	var sent = false;
	var count = list.length;
	if (count === 0) {
		callback(null, ret);
	}
	list.forEach(function (pointer) {
		var name = path.join(root._path, pointer);
		fp.define({filePath: name, parent: root}, function (err, obj) {
			if (err) {
				if (!sent) {
					callback(err);
					sent = true;
				}
				return;
			}
			ret[name] = obj;
			if (ret[name]._type === 'directory') {
				addMaping(ret[name]);
			}
			if (--count === 0) {
				callback(null, ret);
			}
		});
	});

}
127996
def output(file_like_object, path, verbose=False):
    """"""
    if not path:
        for line in file_like_object:
            if verbose:
                print_info(line.rstrip())
            else:
                print(line.rstrip())
    else:
        try:
            object_file = open(os.path.expanduser(path), "w", encoding="utf-8")
            shutil.copyfileobj(file_like_object, object_file)
            object_file.close()
        except EnvironmentError as xxx_todo_changeme:
            (errno, strerror) = xxx_todo_changeme.args
            error_line_list = [
                "Could not write to object_file: {}".format(path),
                "I/O error({}): {}".format(errno, strerror),
            ]
            error_message = "\n".join(error_line_list)
            raise d1_cli.impl.exceptions.CLIError(error_message)
427306
@Override
  public void execute() throws BuildException {
    //
    // if link type allowed objdir to be defaulted
    // provide it from outfile
    if (this._objDir == null) {
      if (this._outfile != null) {
        this._objDir = new File(this._outfile.getParent());
      } else {
        this._objDir = new File(".");
      }
    }

    //
    // if the object directory does not exist
    //
    if (!this._objDir.exists()) {
      throw new BuildException("Object directory does not exist");
    }
    final TargetHistoryTable objHistory = new TargetHistoryTable(this, this._objDir);

    //
    // get the first active version info
    //
    VersionInfo versionInfo = null;
    final Enumeration<VersionInfo> versionEnum = this.versionInfos.elements();
    while (versionEnum.hasMoreElements()) {
      versionInfo = versionEnum.nextElement();
      versionInfo = versionInfo.merge();
      if (versionInfo.isActive()) {
        break;
      } else {
        versionInfo = null;
      }
    }

    //
    // determine the eventual linker configuration
    // (may be null) and collect any explicit
    // object files or libraries
    final Vector<File> objectFiles = new Vector<>();
    final Vector<File> sysObjectFiles = new Vector<>();
    final LinkerConfiguration linkerConfig = collectExplicitObjectFiles(objectFiles, sysObjectFiles, versionInfo);

    //
    // Assemble hashtable of all files
    // that we know how to compile (keyed by output file name)
    //
    final Map<String, TargetInfo> targets = getTargets(linkerConfig, objectFiles, versionInfo, this._outfile);
    TargetInfo linkTarget = null;
    //
    // if output file is not specified,
    // then skip link step
    //
    if (this._outfile != null) {
      linkTarget = getLinkTarget(linkerConfig, objectFiles, sysObjectFiles, targets, versionInfo);
    }

    if (this.projects.size() > 0) {
      final List<File> files = new ArrayList<>();
      final ProjectFileCollector matcher = new ProjectFileCollector(files);
      for (int i = 0; i < this._compilers.size(); i++) {
    	  final CompilerDef currentCompilerDef = this._compilers.elementAt(i);
    	  if (currentCompilerDef.isActive() && currentCompilerDef.hasFileSets()) {
    		  currentCompilerDef.visitFiles(matcher);
    	  }
      }
      this.compilerDef.visitFiles(matcher);

      final Enumeration<ProjectDef> iter = this.projects.elements();
      while (iter.hasMoreElements()) {
        final ProjectDef projectDef = iter.nextElement();
        if (projectDef.isActive()) {
          projectDef.execute(this, files, targets, linkTarget);
        }
      }
    }
    if (this.projectsOnly) {
      return;
    }

    //
    // mark targets that don't have a history record or
    // whose source last modification time is not
    // the same as the history to be rebuilt
    //
    objHistory.markForRebuild(targets);
    final CCTaskProgressMonitor monitor = new CCTaskProgressMonitor(objHistory, versionInfo);
    //
    // check for changed include files
    //
    final int rebuildCount = checkForChangedIncludeFiles(targets);
    if (rebuildCount > 0) {
      BuildException compileException = null;
      //
      // compile all targets with getRebuild() == true
      //
      final Map<CompilerConfiguration, Vector<TargetInfo>> targetsByConfig = getTargetsToBuildByConfiguration(targets);
      //
      // build array containing Vectors with precompiled generation
      // steps going first
      //
      final ArrayList<Vector<TargetInfo>> targetVectorsPreComp = new ArrayList<>();
      final ArrayList<Vector<TargetInfo>> targetVectors = new ArrayList<>();

      int index = 0;
      for (final Map.Entry<CompilerConfiguration, Vector<TargetInfo>> targetsForConfig : targetsByConfig.entrySet()) {
        //
        // get the configuration from the first entry
        //
        final CompilerConfiguration config = targetsForConfig.getKey();
        if (config.isPrecompileGeneration()) {
          targetVectorsPreComp.add(targetsForConfig.getValue());
        } else {
          targetVectors.add(targetsForConfig.getValue());
        }
      }

      // BEGINFREEHEP
      final Progress progress = new Progress(getObjdir(), rebuildCount);
      progress.start();
      // ENDFREEHEP

      compileException = runTargetPool(monitor, compileException, targetVectorsPreComp);
      if (compileException == null || this.relentless)
        compileException = runTargetPool(monitor, compileException, targetVectors);

      // BEGINFREEHEP
      progress.exit();
      try {
        progress.join();
      } catch (final InterruptedException ex) {
      }
      // ENDFREEHEP

      //
      // save the details of the object file compilation
      // settings to disk for dependency analysis
      //
      try {
        objHistory.commit();
      } catch (final IOException ex) {
        this.log("Error writing history.xml: " + ex.toString());
      }
      //
      // if we threw a compile exception and
      // didn't throw it at the time because
      // we were relentless then
      // save the history and
      // throw the exception
      //
      if (compileException != null) {
        if (this.failOnError) {
          throw compileException;
        } else {
          log(compileException.getMessage(), Project.MSG_ERR);
          return;
        }
      }
    }
    //
    // if the dependency tree was not fully
    // evaluated, then throw an exception
    // since we really didn't do what we
    // should have done
    //
    //
    if (this.dependencyDepth >= 0) {
      throw new BuildException("All files at depth " + Integer.toString(this.dependencyDepth)
          + " from changes successfully compiled.\n"
          + "Remove or change dependencyDepth to -1 to perform full compilation.");
    }
    //
    // if no link target then
    // commit the history for the object files
    // and leave the task
    if (linkTarget != null) {
      //
      // get the history for the link target (may be the same
      // as the object history)
      final TargetHistoryTable linkHistory = getLinkHistory(objHistory);
      //
      // see if it needs to be rebuilt
      //
      linkHistory.markForRebuild(linkTarget);
      //
      // if it needs to be rebuilt, rebuild it
      //
      final File output = linkTarget.getOutput();
      if (linkTarget.getRebuild()) {
        final LinkerConfiguration linkConfig = (LinkerConfiguration) linkTarget.getConfiguration();
        // BEGINFREEHEP
        log("Linking...");
        log("Starting link {" + linkConfig.getIdentifier() + "}");
        // ENDFREEHEP
        if (this.failOnError) {
          linkConfig.link(this, linkTarget);
        } else {
          try {
            linkConfig.link(this, linkTarget);
          } catch (final BuildException ex) {
            log(ex.getMessage(), Project.MSG_ERR);
            return;
          }
        }
        if (this.outputFileProperty != null) {
          getProject().setProperty(this.outputFileProperty, output.getAbsolutePath());
        }
        linkHistory.update(linkTarget);
        try {
          linkHistory.commit();
        } catch (final IOException ex) {
          log("Error writing link history.xml: " + ex.toString());
        }
      } else {
        if (this.outputFileProperty != null) {
          getProject().setProperty(this.outputFileProperty, output.getAbsolutePath());
        }
      }

      // If sharedObjectName was specified, add the shared object to an archive, then delete the shared object.
      if (sharedObjectName != null && !sharedObjectName.isEmpty()) {
        File workingDirectory = new File(this._outfile.getParent());
        String[] archiveCommand = new String[4];
        archiveCommand[0] = "ar";
        archiveCommand[1] = "r";
        archiveCommand[2] = linkerConfig.getOutputFileNames(this._outfile.getName(), versionInfo)[0];
        archiveCommand[3] = sharedObjectName;
        CUtil.runCommand(this, workingDirectory, archiveCommand, false, null);

        String[] removeCommand = new String[2];
        removeCommand[0] = "rm";
        removeCommand[1] = sharedObjectName;
        CUtil.runCommand(this, workingDirectory, removeCommand, false, null);
      }
    }
  }
1122016
def _make_exe(linklibs, identifier, verbose):
    """"""
    linktxt = "$(LIBS) " if linklibs else ""
    redirect = "" if verbose else " > /dev/null"
    base = """
$(EXENAME): $(OBJSF90)
	-rm $(EXENAME) 2> /dev/null
	echo -n "Linking... "{2}
	-$(F90) $(LDFLAGS) -o $(EXENAME) $(OBJSF90) {0}>> $(LOG) 2>> $(LOG)
	echo "done."{2}
	if test -e $(EXENAME); then echo "Produced executable: $(EXENAME)"{2}; else $(SHOW_LOG); echo "Error."; fi

$(OBJSF90): %.o: %.f90
	echo -n "Compiling: $^... "{2}
	-$(F90) -c $(FFLAGS) $^ >> $(LOG) 2>> $(LOG)
	echo "done."{2}

{1}.so: $(SLIBF90)
	-rm {1}.so 2> /dev/null
	echo -n "Creating shared library..."{2}
	-$(F90) -shared -fPIC $(FFLAGS) -o {1}.so {0}$(SLIBF90) >> $(LOG) 2>> $(LOG)
	echo "done."{2}

{1}.a: $(SLIBF90)
	echo -n "Creating linked library..."{2}
	ar ru $@ $?
	ranlib $@
	echo "done."{2}

clean:
	-mv fpy_auxiliary.mod fpy_auxiliary.modt 2> /dev/null
	-mv fpy_auxiliary.o fpy_auxiliary.ot 2> /dev/null
	-mv fortpy.o fortpy.ot
	-mv fortpy.mod fortpy.modt
	-rm *.o *.mod *.i90 $(EXENAME) initializeTree.so 2> /dev/null
	-mv fpy_auxiliary.modt fpy_auxiliary.mod 2> /dev/null
	-mv fpy_auxiliary.ot fpy_auxiliary.o 2> /dev/null
	-mv fortpy.ot fortpy.o
	-mv fortpy.modt fortpy.mod
remake: clean
	-rm *.o *.mod *.i90 $(EXENAME) {1}.so
"""
    return base.format(linktxt, identifier, redirect)
197192
def main(directories):
    ''''''
    msg = 'Checking module "{}" from directory "{}" for coding errors.'
    api_checker = ApiChecker()
    resource_checker = ResourceChecker()
    errors = []
    modules = []
    for loader, mname, _ in pkgutil.walk_packages(directories):
        sys.path.append(os.path.abspath(loader.path))
        log.info(msg.format(mname, loader.path))
        modules.append(mname)
        import_module(mname)
    for api in Api:
        if api.__module__.split('.')[-1] not in modules:
            continue
        log.debug('Anlysing Api class: {}'.format(api.__name__))
        errors.extend(api_checker(api))
    for res in Resource:
        if res.__module__.split('.')[-1] not in modules:
            continue
        log.debug('Anlysing Resource class: {}'.format(res.__name__))
        errors.extend(resource_checker(res))
    else:
        log.info('All modules tested, no problem detected.')
    return errors