synthesize conductor action code from composition
422002
function synthesize ({ name, composition, ast, version: composer, annotations = [] }) {
  const code = `// generated by composer v${composer} and conductor v${version}\n\nconst composition = ${JSON.stringify(composition, null, 4)}\n\n// do not edit below this point\n\n` +
    minify(`const main=(${main})(composition)`, { output: { max_line_len: 127 } }).code
  annotations = annotations.concat([{ key: 'conductor', value: ast }, { key: 'composerVersion', value: composer }, { key: 'conductorVersion', value: version }])
  return { name, action: { exec: { kind: 'nodejs:default', code }, annotations } }
}
41308
function run_wiring(wiring, req, res, format) {
	
	 var filteredParams = req.query;
	// TODO
    /*filteredParams = params.dup
    filteredParams.delete("id")
    filteredParams.delete("action")
    filteredParams.delete("controller")
    filteredParams.delete("callback")
    filteredParams.delete("format")*/
	
	
	mySimpleflowRunWithActivity(wiring, req.current_user._id, format, "web", 
			filteredParams, false, req.wiring_collection, function(results) {
		
				if(format == "html") {
					// Reder the template
					if( !!wiring.template && !req.param("notemplate") ) {
						res.header('Content-Type', wiring.template_content_type);
						var output;
						try {
							output = ejs.render(wiring.template, {
								locals: {
									results: results,
									params: filteredParams
								}
							});
						} catch(ex) {
							output = "Error in your template: "+ex.message;
						}
						res.send(output);

					} 
					// Render the result of the "outputField" variable as a html document
					else if( req.param('outputField') ) {
						res.header('Content-Type', "text/html");
						if(results.hasOwnProperty(req.param('outputField'))) {
							res.send( results[req.param('outputField')] );
						}
						else {
							res.send( "No field called "+req.param('outputField') );
						}
			       }
				    else {
						// render run.ejs
						res.render('wirings/run', {
					        locals: {
									title: "Wiring "+wiring.name,
									action: "wirings",
									wiring: wiring,
									params: filteredParams,
									results: results
					        }
					    });
					}
				}
				/*else if(format == "xml") {
				}*/
				else if(format == "json") {
					
					if(req.param("callback")) {
						res.header('Content-Type', 'text/javascript');
						
						res.send("if(typeof "+req.param("callback")+" == 'function') {"+
									req.param("callback")+"("+JSON.stringify(results)+");} else {\n"+
									"if (typeof console!== 'undefined' && typeof console.log !== 'undefined'){\n"+
									"console.log('Error: Callback method not defined');}	}");
					}
					else {
						res.header('Content-Type', 'application/json');
						res.send(JSON.stringify(results));
					}
				}
				/*else if(format == "txt") {
					if results.keys.size == 1
						if results.values[0].is_a?(String)
							render :text => results.values[0]
							return
						end
					else
						# TODO: check if param outputField
					end

					render :text => "blabla"
				}*/		
				
	});
		
}
1340181
def plugitInclude(parser, token):
    
    bits = token.split_contents()

    if len(bits) != 2:
        raise TemplateSyntaxError("'plugitInclude' tag takes one argument: the tempalte's action to use")

    action = parser.compile_filter(bits[1])

    return PlugItIncludeNode(action)
751361
def mulexp_action(self, text, loc, mul):
        """"""
        exshared.setpos(loc, text)
        if DEBUG > 0:
            print("MUL_EXP:",mul)
            if DEBUG == 2: self.symtab.display()
            if DEBUG > 2: return
        #iterate through all multiplications/divisions
        m = list(mul)
        while len(m) > 1:
            if not self.symtab.same_types(m[0], m[2]):
                raise SemanticException("Invalid opernads to binary '%s'" % m[1])
            reg = self.codegen.arithmetic(m[1], m[0], m[2])
            #replace first calculation with it's result
            m[0:3] = [reg]
        return m[0]
956052
def makebranchcomponents(data, commdct, anode="epnode"):
    """"""
    alledges = []

    objkey = 'BRANCH'
    cnamefield = "Component %s Name"
    inletfield = "Component %s Inlet Node Name"
    outletfield = "Component %s Outlet Node Name"

    numobjects = len(data.dt[objkey])
    cnamefields = loops.repeatingfields(data, commdct, objkey, cnamefield)
    inletfields = loops.repeatingfields(data, commdct, objkey, inletfield)
    outletfields = loops.repeatingfields(data, commdct, objkey, outletfield)

    inlts = loops.extractfields(data, commdct, 
        objkey, [inletfields] * numobjects)
    cmps = loops.extractfields(data, commdct, 
        objkey, [cnamefields] * numobjects)
    otlts = loops.extractfields(data, commdct, 
        objkey, [outletfields] * numobjects)

    zipped = list(zip(inlts, cmps, otlts))
    tzipped = [transpose2d(item) for item in zipped]
    for i in range(len(data.dt[objkey])):
        tt = tzipped[i]
        # branchname = data.dt[objkey][i][1]
        edges = []
        for t0 in tt:
            edges = edges + [((t0[0], anode), t0[1]), (t0[1], (t0[2], anode))]
        alledges = alledges + edges
    return alledges
1333140
def _decompose(net, wv_map, mems, block_out):
    

    def arg(x, i):
        # return the mapped wire vector for argument x, wire number i
        return wv_map[(net.args[x], i)]

    def destlen():
        # return iterator over length of the destination in bits
        return range(len(net.dests[0]))

    def assign_dest(i, v):
        # assign v to the wiremap for dest[0], wire i
        wv_map[(net.dests[0], i)] <<= v

    one_var_ops = {
        'w': lambda w: w,
        '~': lambda w: ~w,
    }
    c_two_var_ops = {
        '&': lambda l, r: l & r,
        '|': lambda l, r: l | r,
        '^': lambda l, r: l ^ r,
        'n': lambda l, r: l.nand(r),
    }

    if net.op in one_var_ops:
        for i in destlen():
            assign_dest(i, one_var_ops[net.op](arg(0, i)))
    elif net.op in c_two_var_ops:
        for i in destlen():
            assign_dest(i, c_two_var_ops[net.op](arg(0, i), arg(1, i)))
    elif net.op == 's':
        for i in destlen():
            selected_bit = arg(0, net.op_param[i])
            assign_dest(i, selected_bit)
    elif net.op == 'c':
        arg_wirelist = []
        # generate list of wires for vectors being concatenated
        for arg_vector in net.args:
            arg_vector_as_list = [wv_map[(arg_vector, i)] for i in range(len(arg_vector))]
            arg_wirelist = arg_vector_as_list + arg_wirelist
        for i in destlen():
            assign_dest(i, arg_wirelist[i])
    elif net.op == 'r':
        for i in destlen():
            args = (arg(0, i),)
            dests = (wv_map[(net.dests[0], i)],)
            new_net = LogicNet('r', None, args=args, dests=dests)
            block_out.add_net(new_net)
    elif net.op == 'm':
        arg0list = [arg(0, i) for i in range(len(net.args[0]))]
        addr = concat_list(arg0list)
        new_mem = _get_new_block_mem_instance(net.op_param, mems, block_out)[1]
        data = as_wires(new_mem[addr])
        for i in destlen():
            assign_dest(i, data[i])
    elif net.op == '@':
        addrlist = [arg(0, i) for i in range(len(net.args[0]))]
        addr = concat_list(addrlist)
        datalist = [arg(1, i) for i in range(len(net.args[1]))]
        data = concat_list(datalist)
        enable = arg(2, 0)
        new_mem = _get_new_block_mem_instance(net.op_param, mems, block_out)[1]
        new_mem[addr] <<= MemBlock.EnabledWrite(data=data, enable=enable)
    else:
        raise PyrtlInternalError('Unable to synthesize the following net '
                                 'due to unimplemented op :\n%s' % str(net))
    return
488448
def _gen_mods(self, action, records, existing_rrsets):
        '''
        
        '''
        return [r.mod(action, existing_rrsets) for r in records]
956892
def create_action_from_dict(name, spec, base_class=ActionsAction, metaclass=type, pop_keys=False):
    
    actions = load_grouped_actions(spec, pop_keys=pop_keys)
    attrs = {"actions": actions, "name": name}
    if "as" in spec:
        attrs["as_"] = spec["as"]
        if pop_keys:
            del spec["as"]
    for k in ("requires", "methods", "defaults", "default_option"):
        if k in spec:
            attrs[k] = spec[k]
            if pop_keys:
                del spec[k]
    return metaclass(name, (base_class,), attrs)
869070
def convertAndMake(converter, handler):
  """"""
  def convertAction(loc, value):
    return handler(loc, converter(value))
  return convertAction
9452
def __make_innermsg(resource, rtype, ref, action=None, payload=None, limit=None):
        
        if action is not None and not isinstance(action, (tuple, list)):
            raise TypeError('action must be None/tuple/list')
        p = {M_RESOURCE: resource,
             M_TYPE: int(rtype),
             M_CLIENTREF: ref,
             # Ensure action path consists only of strings
             M_ACTION: tuple(u(element) for element in action) if action else None,
             M_PAYLOAD: payload}
        if limit is not None:  # Note: fmtted like "0/15" where 0 = offset, 15 = limit
            p[M_RANGE] = limit
        return p
637659
def generate(self, more_content=None, all_members=False):
        # type: (Any, str, bool, bool) -> None
        
        directive = getattr(self, 'directivetype', self.objtype)

        # parse components out of name
        (file, _, namepath) = self.name.rpartition(':')
        (contract_name, _, fullname) = namepath.partition('.')
        (name, _, paramtypes) = fullname.partition('(')

        # normalize components
        name = name.strip() or None

        if directive in ('contract', 'interface', 'library') and name is None:
            name = contract_name
            contract_name = None

        paramtypes = ','.join(ptype.strip() for ptype in paramtypes.split(','))
        paramtypes = re.sub(r'\s+', ' ', paramtypes)
        if paramtypes.endswith(')'):
            paramtypes = paramtypes[:-1]

        # build query
        expressions = [
            SolidityObject.objtype == directive,
            SolidityObject.name == name,
        ]

        if file:
            expressions.append(SolidityObject.file == file)
        if contract_name:
            expressions.append(SolidityObject.contract_name == contract_name)
        if paramtypes:
            expressions.append(SolidityObject.paramtypes == paramtypes)

        # get associated object
        query = SolidityObject.select().where(*expressions)
        sol_objects = tuple(query)
        if len(sol_objects) == 0:
            logger.warning('{} {} could not be found via query:\n{}'.format(
                directive, self.name, ',\n'.join(
                    '  ' + str(expr.lhs.column_name) +
                    str(expr.op) + ('' if expr.rhs is None else expr.rhs)
                    for expr in expressions
                )))
            return
        elif len(sol_objects) > 1:
            logger.warning('multiple candidates for {} {} found:\n{}'.format(
                directive, self.name,
                '\n'.join('  ' + obj.signature for obj in sol_objects)))

        self.object = sol_objects[0]

        # begin rendering output
        sourcename = self.get_sourcename()

        # make sure that the result starts with an empty line.  This is
        # necessary for some situations where another directive preprocesses
        # reST and no starting newline is present
        self.add_line('', sourcename)

        # generate the directive header and options, if applicable
        self.add_directive_header()

        # make sure content is indented
        # TODO: consider adding a source unit directive
        self.indent += self.content_indent

        # add all content (from docstrings, attribute docs etc.)
        self.add_content(more_content)

        # document members, if possible
        if directive in ('contract', 'interface', 'library'):
            self.add_line('', sourcename)
            self.document_members(all_members)
1689
def prepare(c):
    
    # Print dry-run/status/actions-to-take data & grab programmatic result
    # TODO: maybe expand the enum-based stuff to have values that split up
    # textual description, command string, etc. See the TODO up by their
    # definition too, re: just making them non-enum classes period.
    # TODO: otherwise, we at least want derived eg changelog/version/etc paths
    # transmitted from status() into here...
    actions, state = status(c)
    # TODO: unless nothing-to-do in which case just say that & exit 0
    if not confirm("Take the above actions?"):
        sys.exit("Aborting.")

    # TODO: factor out what it means to edit a file:
    # - $EDITOR or explicit expansion of it in case no shell involved
    # - pty=True and hide=False, because otherwise things can be bad
    # - what else?

    # Changelog! (pty for non shite editing, eg vim sure won't like non-pty)
    if actions.changelog is Changelog.NEEDS_RELEASE:
        # TODO: identify top of list and inject a ready-made line? Requires vim
        # assumption...GREAT opportunity for class/method based tasks!
        cmd = "$EDITOR {0.packaging.changelog_file}".format(c)
        c.run(cmd, pty=True, hide=False)
    # TODO: add a step for checking reqs.txt / setup.py vs virtualenv contents
    # Version file!
    if actions.version == VersionFile.NEEDS_BUMP:
        # TODO: suggest the bump and/or overwrite the entire file? Assumes a
        # specific file format. Could be bad for users which expose __version__
        # but have other contents as well.
        version_file = os.path.join(
            _find_package(c),
            c.packaging.get("version_module", "_version") + ".py",
        )
        cmd = "$EDITOR {0}".format(version_file)
        c.run(cmd, pty=True, hide=False)
    if actions.tag == Tag.NEEDS_CUTTING:
        # Commit, if necessary, so the tag includes everything.
        # NOTE: this strips out untracked files. effort.
        cmd = 'git status --porcelain | egrep -v "^\\?"'
        if c.run(cmd, hide=True, warn=True).ok:
            c.run(
                'git commit -am "Cut {0}"'.format(state.expected_version),
                hide=False,
            )
        # Tag!
        c.run("git tag {0}".format(state.expected_version), hide=False)
581880
def template_for_action(self, action):
        
        return "%s/%s_%s.html" % (self.module_name.lower(), self.model_name.lower(), action)
615886
def Builder(**kw):
    """"""
    composite = None
    if 'generator' in kw:
        if 'action' in kw:
            raise UserError("You must not specify both an action and a generator.")
        kw['action'] = SCons.Action.CommandGeneratorAction(kw['generator'], {})
        del kw['generator']
    elif 'action' in kw:
        source_ext_match = kw.get('source_ext_match', 1)
        if 'source_ext_match' in kw:
            del kw['source_ext_match']
        if SCons.Util.is_Dict(kw['action']):
            composite = DictCmdGenerator(kw['action'], source_ext_match)
            kw['action'] = SCons.Action.CommandGeneratorAction(composite, {})
            kw['src_suffix'] = composite.src_suffixes()
        else:
            kw['action'] = SCons.Action.Action(kw['action'])

    if 'emitter' in kw:
        emitter = kw['emitter']
        if SCons.Util.is_String(emitter):
            # This allows users to pass in an Environment
            # variable reference (like "$FOO") as an emitter.
            # We will look in that Environment variable for
            # a callable to use as the actual emitter.
            var = SCons.Util.get_environment_var(emitter)
            if not var:
                raise UserError("Supplied emitter '%s' does not appear to refer to an Environment variable" % emitter)
            kw['emitter'] = EmitterProxy(var)
        elif SCons.Util.is_Dict(emitter):
            kw['emitter'] = DictEmitter(emitter)
        elif SCons.Util.is_List(emitter):
            kw['emitter'] = ListEmitter(emitter)

    result = BuilderBase(**kw)

    if not composite is None:
        result = CompositeBuilder(result, composite)

    return result
1340707
protected void _generate(SarlAction action, PyAppendable it, IExtraLanguageGeneratorContext context) {
		final String feature = getFeatureNameConverter(context).convertDeclarationName(action.getName(), action);
		generateExecutable(feature, action, !action.isStatic(), action.isAbstract(),
				action.getReturnType(),
				getTypeBuilder().getDocumentation(action),
				it, context);
	}
465417
def __createInspectorActionGroup(self, parent):
        
        actionGroup = QtWidgets.QActionGroup(parent)
        actionGroup.setExclusive(True)

        sortedItems = sorted(self.argosApplication.inspectorRegistry.items,
                             key=lambda item: item.identifier)
        shortCutNr = 1
        for item in sortedItems:
            logger.debug("item: {}".format(item.identifier))
            setAndDrawFn = partial(self.setAndDrawInspectorById, item.identifier)
            action = QtWidgets.QAction(item.name, self, triggered=setAndDrawFn, checkable=True)
            action.setData(item.identifier)
            if shortCutNr <= 9 and "debug" not in item.identifier: # TODO: make configurable by the user
                action.setShortcut(QtGui.QKeySequence("Ctrl+{}".format(shortCutNr)))
                shortCutNr += 1

            actionGroup.addAction(action)

        return actionGroup
160676
def to_wire
      content = ''
      @avps.each { |a| content += a.to_wire }
      length_8, length_16 = Internals::UInt24.to_u8_and_u16(content.length + 20)
      code_8, code_16 = Internals::UInt24.to_u8_and_u16(@command_code)
      request_flag = @request ? '1' : '0'
      proxy_flag = @proxyable ? '1' : '0'
      flags_str = "#{request_flag}#{proxy_flag}000000"

      header = [@version, length_8, length_16, flags_str, code_8, code_16, @app_id, @hbh, @ete].pack('CCnB8CnNNN')
      header + content
    end