Run an operation on a set of meshes
544408
def boolean(meshes, operation='difference'):
    
    script = operation + '(){'
    for i in range(len(meshes)):
        script += 'import(\"$mesh_' + str(i) + '\");'
    script += '}'
    return interface_scad(meshes, script)
831827
def _run_grid_multithread(self, func, iterables):
        ''' 
        '''
        
        f = lambda x: threading.Thread(target = func,args = (x,))
        threads = map(f, iterables)
        for thread in threads:
            thread.setDaemon(True)
            thread.start()
            thread.join()
545143
function (meshes, applyWorldTransform) {

        if (! meshes.length) {
            return;
        }

        var templateMesh = meshes[0];
        var templateGeo = templateMesh.geometry;
        var material = templateMesh.material;

        var geometry = new Geometry({
            dynamic: false
        });
        geometry.boundingBox = new BoundingBox();

        var attributeNames = templateGeo.getEnabledAttributes();

        for (var i = 0; i < attributeNames.length; i++) {
            var name = attributeNames[i];
            var attr = templateGeo.attributes[name];
            // Extend custom attributes
            if (!geometry.attributes[name]) {
                geometry.attributes[name] = attr.clone(false);
            }
        }

        var inverseTransposeMatrix = mat4.create();
        // Initialize the array data and merge bounding box
        var nVertex = 0;
        var nFace = 0;
        for (var k = 0; k < meshes.length; k++) {
            var currentGeo = meshes[k].geometry;
            if (currentGeo.boundingBox) {
                currentGeo.boundingBox.applyTransform(applyWorldTransform ? meshes[k].worldTransform : meshes[k].localTransform);
                geometry.boundingBox.union(currentGeo.boundingBox);
            }
            nVertex += currentGeo.vertexCount;
            nFace += currentGeo.triangleCount;
        }
        for (var n = 0; n < attributeNames.length; n++) {
            var name = attributeNames[n];
            var attrib = geometry.attributes[name];
            attrib.init(nVertex);
        }
        if (nVertex >= 0xffff) {
            geometry.indices = new Uint32Array(nFace * 3);
        }
        else {
            geometry.indices = new Uint16Array(nFace * 3);
        }

        var vertexOffset = 0;
        var indicesOffset = 0;
        var useIndices = templateGeo.isUseIndices();

        for (var mm = 0; mm < meshes.length; mm++) {
            var mesh = meshes[mm];
            var currentGeo = mesh.geometry;

            var nVertex = currentGeo.vertexCount;

            var matrix = applyWorldTransform ? mesh.worldTransform.array : mesh.localTransform.array;
            mat4.invert(inverseTransposeMatrix, matrix);
            mat4.transpose(inverseTransposeMatrix, inverseTransposeMatrix);

            for (var nn = 0; nn < attributeNames.length; nn++) {
                var name = attributeNames[nn];
                var currentAttr = currentGeo.attributes[name];
                var targetAttr = geometry.attributes[name];
                // Skip the unused attributes;
                if (!currentAttr.value.length) {
                    continue;
                }
                var len = currentAttr.value.length;
                var size = currentAttr.size;
                var offset = vertexOffset * size;
                var count = len / size;
                for (var i = 0; i < len; i++) {
                    targetAttr.value[offset + i] = currentAttr.value[i];
                }
                // Transform position, normal and tangent
                if (name === 'position') {
                    vec3.forEach(targetAttr.value, size, offset, count, vec3.transformMat4, matrix);
                }
                else if (name === 'normal' || name === 'tangent') {
                    vec3.forEach(targetAttr.value, size, offset, count, vec3.transformMat4, inverseTransposeMatrix);
                }
            }

            if (useIndices) {
                var len = currentGeo.indices.length;
                for (var i = 0; i < len; i++) {
                    geometry.indices[i + indicesOffset] = currentGeo.indices[i] + vertexOffset;
                }
                indicesOffset += len;
            }

            vertexOffset += nVertex;
        }

        return new Mesh({
            material: material,
            geometry: geometry
        });
    }
942811
def _call(self, func, out=None, **kwargs):
        """"""
        mesh = self.grid.meshgrid
        if out is None:
            out = func(mesh, **kwargs)
        else:
            with writable_array(out) as out_arr:
                func(mesh, out=out_arr, **kwargs)
        return out
1318397
def run(self, mod):
        """"""
        if not mod.body:
            # Nothing to do.
            return
        # Insert some special imports at the top of the module but after any
        # docstrings and __future__ imports.
        aliases = [ast.alias(py.builtin.builtins.__name__, "@py_builtins"),
                   ast.alias("dessert.rewrite", "@dessert_ar")]
        expect_docstring = True
        pos = 0
        lineno = 0
        for item in mod.body:
            if (expect_docstring and isinstance(item, ast.Expr) and
                    isinstance(item.value, ast.Str)):
                doc = item.value.s
                if "PYTEST_DONT_REWRITE" in doc:
                    # The module has disabled assertion rewriting.
                    return
                lineno += len(doc) - 1
                expect_docstring = False
            elif (not isinstance(item, ast.ImportFrom) or item.level > 0 or
                  item.module != "__future__"):
                lineno = item.lineno
                break
            pos += 1
        imports = [ast.Import([alias], lineno=lineno, col_offset=0)
                   for alias in aliases]
        mod.body[pos:pos] = imports
        # Collect asserts.
        nodes = [mod]
        while nodes:
            node = nodes.pop()
            for name, field in ast.iter_fields(node):
                if isinstance(field, list):
                    new = []
                    for i, child in enumerate(field):
                        if isinstance(child, ast.Assert):
                            # Transform assert.
                            new.extend(self.visit(child))
                        else:
                            new.append(child)
                            if isinstance(child, ast.AST):
                                nodes.append(child)
                    setattr(node, name, new)
                elif (isinstance(field, ast.AST) and
                      # Don't recurse into expressions as they can't contain
                      # asserts.
                      not isinstance(field, ast.expr)):
                    nodes.append(field)
1024457
def mesh(faces, coordinates, meta_data=None, properties=None):
    '''
    
    '''
    return Mesh(faces, coordinates, meta_data=meta_data, properties=properties)
327561
private void execute(MultiPolygon multiPolygon) {
		if (index.getGeometryIndex() >= multiPolygon.getNumGeometries()) {
			Polygon[] polygons = new Polygon[multiPolygon.getNumGeometries() + 1];
			for (int i = 0; i < multiPolygon.getNumGeometries(); i++) {
				polygons[i] = (Polygon) multiPolygon.getGeometryN(i);
			}
			LinearRing exteriorRing = multiPolygon.getGeometryFactory().createLinearRing(
					new Coordinate[] { coordinate });
			polygons[multiPolygon.getNumGeometries()] = multiPolygon.getGeometryFactory().createPolygon(exteriorRing,
					null);
			setPolygons(multiPolygon, polygons);
		} else {
			execute((Polygon) multiPolygon.getGeometryN(index.getGeometryIndex()));
		}
	}
1205156
def run():
    """"""
    
    # Grab server args
    args = client_helper.grab_server_args()

    # Start up workbench connection
    workbench = zerorpc.Client(timeout=300, heartbeat=60)
    workbench.connect('tcp://'+args['server']+':'+args['port'])

    # Test out zip data
    data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data/zip')
    file_list = [os.path.join(data_path, child) for child in os.listdir(data_path)]
    for filename in file_list:
        with open(filename,'rb') as f:
            base_name = os.path.basename(filename)
            md5 = workbench.store_sample(f.read(), base_name, 'zip')
            results = workbench.work_request('view', md5)
            print 'Filename: %s ' % (base_name)
            pprint.pprint(results)

            # The unzip worker gives you a list of md5s back
            # Run meta on all the unzipped files.
            results = workbench.work_request('unzip', md5)
            print '\n*** Filename: %s ***' % (base_name)
            for child_md5 in results['unzip']['payload_md5s']:
                pprint.pprint(workbench.work_request('meta', child_md5))
1330373
function run() {
	var len = series.length,
		ctx = context(),
		i = 0;

	series[ i ].call( ctx, next );

	function next() {
		i += 1;
		if ( i < len ) {
			series[ i ].call( ctx, next );
		}
	}
}
1126983
@Override
	public DataSet<Result<K>> runInternal(Graph<K, VV, EV> input)
			throws Exception {
		// u, v, w, bitmask
		DataSet<TriangleListing.Result<K>> triangles = input
			.run(new TriangleListing<K, VV, EV>()
				.setParallelism(parallelism));

		// u, edge count
		DataSet<Tuple2<K, LongValue>> triangleVertices = triangles
			.flatMap(new SplitTriangles<>())
				.name("Split triangle vertices");

		// u, triangle count
		DataSet<Tuple2<K, LongValue>> vertexTriangleCount = triangleVertices
			.groupBy(0)
			.reduce(new CountTriangles<>())
			.setCombineHint(CombineHint.HASH)
				.name("Count triangles")
				.setParallelism(parallelism);

		// u, deg(u)
		DataSet<Vertex<K, Degrees>> vertexDegree = input
			.run(new VertexDegrees<K, VV, EV>()
				.setIncludeZeroDegreeVertices(includeZeroDegreeVertices.get())
				.setParallelism(parallelism));

		// u, deg(u), triangle count
		return vertexDegree
			.leftOuterJoin(vertexTriangleCount)
			.where(0)
			.equalTo(0)
			.with(new JoinVertexDegreeWithTriangleCount<>())
				.setParallelism(parallelism)
				.name("Clustering coefficient");
	}
986429
def run(configObj=None, input_dict={}, loadOnly=False):
    
    # If called from interactive user-interface, configObj will not be
    # defined yet, so get defaults using EPAR/TEAL.
    #
    # Also insure that the input_dict (user-specified values) are folded in
    # with a fully populated configObj instance.
    configObj = util.getDefaultConfigObj(__taskname__,configObj,input_dict,loadOnly=loadOnly)
    if configObj is None:
        return
    # Define list of imageObject instances and output WCSObject instance
    # based on input paramters
    imgObjList,outwcs = processInput.setCommonInput(configObj)

    # Build DQ masks for all input images.
    buildMask(imgObjList,configObj)
879624
def run(items):
    
    assert len(items) == 1, "Expect one input to MetaSV ensemble calling"
    data = items[0]
    work_dir = _sv_workdir(data)
    out_file = os.path.join(work_dir, "variants.vcf.gz")
    cmd = _get_cmd() + ["--sample", dd.get_sample_name(data), "--reference", dd.get_ref_file(data),
                        "--bam", dd.get_align_bam(data), "--outdir", work_dir]
    methods = []
    for call in data.get("sv", []):
        vcf_file = call.get("vcf_file", call.get("vrn_file", None))
        if call["variantcaller"] in SUPPORTED and call["variantcaller"] not in methods and vcf_file is not None:
            methods.append(call["variantcaller"])
            cmd += ["--%s_vcf" % call["variantcaller"], vcf_file]
    if len(methods) >= MIN_CALLERS:
        if not utils.file_exists(out_file):
            tx_work_dir = utils.safe_makedir(os.path.join(work_dir, "raw"))
            ins_stats = shared.calc_paired_insert_stats_save(dd.get_align_bam(data),
                                                             os.path.join(tx_work_dir, "insert-stats.yaml"))
            cmd += ["--workdir", tx_work_dir, "--num_threads", str(dd.get_num_cores(data))]
            cmd += ["--spades", utils.which("spades.py"), "--age", utils.which("age_align")]
            cmd += ["--assembly_max_tools=1", "--assembly_pad=500"]
            cmd += ["--boost_sc", "--isize_mean", ins_stats["mean"], "--isize_sd", ins_stats["std"]]
            do.run(cmd, "Combine variant calls with MetaSV")
        filters = ("(NUM_SVTOOLS = 1 && ABS(SVLEN)>50000) || "
                   "(NUM_SVTOOLS = 1 && ABS(SVLEN)<4000 && BA_FLANK_PERCENT>80) || "
                   "(NUM_SVTOOLS = 1 && ABS(SVLEN)<4000 && BA_NUM_GOOD_REC=0) || "
                   "(ABS(SVLEN)<4000 && BA_NUM_GOOD_REC>2)")
        filter_file = vfilter.cutoff_w_expression(out_file, filters,
                                                  data, name="ReassemblyStats", limit_regions=None)
        effects_vcf, _ = effects.add_to_vcf(filter_file, data, "snpeff")
        data["sv"].append({"variantcaller": "metasv",
                           "vrn_file": effects_vcf or filter_file})
    return [data]
545658
def autostack(self):
    """"""
    num_slices = 0
    for v in self.graph.all_variables:
      num_slices += self.mesh_to_impl[v.mesh].size
    if num_slices >= 2 ** 16:
      # Startup times are slow with lots of variable slices.
      # Perform more aggressive stacking
      max_combined_slice_size = 2 ** 27
    else:
      # Stacking hurts memory utilization - only stack small variables.
      max_combined_slice_size = 2 ** 16
    self.graph.rewrite_stack_variables(
        mesh_to_impl=self.mesh_to_impl,
        max_combined_slice_size=max_combined_slice_size)
569468
def _run_workflow(items, paired, workflow_file, work_dir):
    
    utils.remove_safe(os.path.join(work_dir, "workspace"))
    data = paired.tumor_data if paired else items[0]
    cmd = [utils.get_program_python("configManta.py"), workflow_file, "-m", "local", "-j", dd.get_num_cores(data)]
    do.run(cmd, "Run manta SV analysis")
    utils.remove_safe(os.path.join(work_dir, "workspace"))
661978
def run(self, lines):
        """"""
        ret = []

        for block in self.blocks(lines):
            ret.extend(self.convert_table(block))

        return ret
1033922
def merge_mesh( x1, ngroups1, conns1, x2, ngroups2, conns2, cmap, eps = 1e-8 ):
    """"""
    n1 = x1.shape[0]
    n2 = x2.shape[0]

    err = nm.sum( nm.sum( nm.abs( x1[cmap[:,0],:-1] - x2[cmap[:,1],:-1] ) ) )
    if abs( err ) > (10.0 * eps):
        print 'nonmatching meshes!', err
        raise ValueError

    mask = nm.ones( (n2,), dtype = nm.int32 )
    mask[cmap[:,1]] = 0
#    print mask, nm.cumsum( mask )
    remap = nm.cumsum( mask ) + n1 - 1
    remap[cmap[:,1]] = cmap[:,0]
#    print remap

    i2 = nm.setdiff1d( nm.arange(  n2, dtype = nm.int32 ),
                       cmap[:,1] )
    xx = nm.r_[x1, x2[i2]]
    ngroups = nm.r_[ngroups1, ngroups2[i2]]

    conns = []
    for ii in xrange( len( conns1 ) ):
        conn = nm.vstack( (conns1[ii], remap[conns2[ii]]) )
        conns.append( conn )
    
    return xx, ngroups, conns
131291
def run(self):
        
        self._runtime_initialize()

        if len(self._flattened_nodes) == 0:
            logger.warning("WARNING: Nothing to do. Try checking your model "
                           "configs and model specification args")
            return []
        else:
            logger.info("")

        selected_uids = frozenset(n.unique_id for n in self._flattened_nodes)
        result = self.execute_with_hooks(selected_uids)

        result.write(self.result_path())

        self.task_end_messages(result.results)
        return result.results