Question:
Calculates the taxonomy after classification.

@return

public void buildTaxonomy() {

        // Determine if a full or incremental calculation is required
        if(!hasBeenIncrementallyClassified) {
            buildTaxonomyConcurrent();
            //buildTaxonomySequential();
        } else {
            final IConceptMap<IConceptSet> newConceptSubs = getNewSubsumptions();
            final IConceptMap<IConceptSet> affectedConceptSubs = getAffectedSubsumptions();

            // 1. Keep only the subsumptions that involve real atomic concepts
            IConceptMap<IConceptSet> allNew = new SparseConceptMap<IConceptSet>(newConceptSubs.size());

            IConceptMap<IConceptSet> allAffected = new SparseConceptMap<IConceptSet>(newConceptSubs.size());

            for (IntIterator itr = newConceptSubs.keyIterator(); itr.hasNext();) {
                final int x = itr.next();
                if (!factory.isVirtualConcept(x)) {
                    IConceptSet set = new SparseConceptHashSet();
                    allNew.put(x, set);
                    for (IntIterator it = newConceptSubs.get(x).iterator(); it.hasNext();) {
                        int next = it.next();
                        if (!factory.isVirtualConcept(next)) {
                            set.add(next);
                        }
                    }
                }
            }

            for (IntIterator itr = affectedConceptSubs.keyIterator(); itr.hasNext();) {
                final int x = itr.next();
                if (!factory.isVirtualConcept(x)) {
                    IConceptSet set = new SparseConceptHashSet();
                    allAffected.put(x, set);
                    for (IntIterator it = affectedConceptSubs.get(x).iterator(); it.hasNext();) {
                        int next = it.next();
                        if (!factory.isVirtualConcept(next)) {
                            set.add(next);
                        }
                    }
                }
            }

            // 2. Create nodes for new concepts and connect to node hierarchy
            // a. First create the nodes and add to index
            for (IntIterator itr = allNew.keyIterator(); itr.hasNext();) {
                final String key = factory.lookupConceptId(itr.next()).toString();
                Node cn = new Node();
                cn.getEquivalentConcepts().add(key);
                conceptNodeIndex.put(key, cn);
            }

            // b. Now connect the nodes disregarding redundant connections
            Node bottomNode = conceptNodeIndex.get(au.csiro.ontology.model.NamedConcept.BOTTOM);
            for (IntIterator itr = allNew.keyIterator(); itr.hasNext();) {
                int id = itr.next();
                final String key = factory.lookupConceptId(id).toString();
                Node cn = conceptNodeIndex.get(key);
                IConceptSet parents = allNew.get(id);
                for (IntIterator itr2 = parents.iterator(); itr2.hasNext();) {
                    // Create a connection to each parent
                    int parentId = itr2.next();
                    if (parentId == id)
                        continue;
                    Node parent = conceptNodeIndex.get(factory.lookupConceptId(parentId));
                    cn.getParents().add(parent);
                    parent.getChildren().add(cn);
                    // All nodes that get new children and are connected to BOTTOM
                    // must be disconnected
                    if (parent.getChildren().contains(bottomNode)) {
                        parent.getChildren().remove(bottomNode);
                        bottomNode.getParents().remove(parent);
                    }
                }
            }

            Set<Integer> toRemoveFromAffected = new HashSet<Integer>();
            for (IntIterator itr = allAffected.keyIterator(); itr.hasNext();) {
                final int id = itr.next();
                final String key = factory.lookupConceptId(id).toString();
                Node cn = conceptNodeIndex.get(key);
                IConceptSet parents = allAffected.get(id);

                if(parents.contains(IFactory.BOTTOM_CONCEPT)) {
                    // Special case - bottom is parent

                    // a. add equivalents to bottom node
                    bottomNode.getEquivalentConcepts().addAll(cn.getEquivalentConcepts());

                    Set<Node> tempParents = cn.getParents();
                    Set<Node> tempChildren = cn.getChildren();

                    // b. reconnect parents to children
                    for(Node parent : tempParents) {
                        parent.getChildren().remove(cn);
                        parent.getChildren().addAll(tempChildren);
                    }

                    for(Node child : tempChildren) {
                        child.getParents().remove(cn);
                        child.getParents().addAll(tempParents);
                    }

                    for(String k : cn.getEquivalentConcepts()) {
                        conceptNodeIndex.remove(k);
                        conceptNodeIndex.put(key, bottomNode);
                    }
                    toRemoveFromAffected.add(id);
                } else {
                    for (IntIterator itr2 = parents.iterator(); itr2.hasNext();) {
                        // Create a connection to each parent
                        int parentId = itr2.next();
                        if (parentId == id)
                            continue;
                        Node parent = conceptNodeIndex.get(factory.lookupConceptId(parentId));
                        cn.getParents().add(parent);
                        parent.getChildren().add(cn);
                        // All nodes that get new children and are connected to BOTTOM must be disconnected
                        if (parent.getChildren().contains(bottomNode)) {
                            parent.getChildren().remove(bottomNode);
                            bottomNode.getParents().remove(parent);
                        }
                    }
                }
            }

            for(Integer i : toRemoveFromAffected) {
                allAffected.remove(i.intValue());
                allNew.remove(i.intValue());
            }

            // 3. Connect new nodes without parents to TOP
            Node topNode = conceptNodeIndex.get(au.csiro.ontology.model.NamedConcept.TOP);

            for (IntIterator itr = allNew.keyIterator(); itr.hasNext();) {
                final String key = factory.lookupConceptId(itr.next()).toString();
                Node cn = conceptNodeIndex.get(key);
                if (cn.getParents().isEmpty()) {
                    cn.getParents().add(topNode);
                    topNode.getChildren().add(cn);
                }
            }

            // 4. Fix connections for new and affected concepts
            // a. Check for equivalents
            Set<Pair> pairsToMerge = new HashSet<Pair>();
            for (IntIterator itr = allNew.keyIterator(); itr.hasNext();) {
                final String key = factory.lookupConceptId(itr.next()).toString();
                Node cn = conceptNodeIndex.get(key);
                for (Node parent : cn.getParents()) {
                    if (parent.getParents().contains(cn)) {
                        pairsToMerge.add(new Pair(cn, parent));
                    }
                }
            }
            for (IntIterator itr = allAffected.keyIterator(); itr.hasNext();) {
                final String key = factory.lookupConceptId(itr.next()).toString();
                Node cn = conceptNodeIndex.get(key);
                for (Node parent : cn.getParents()) {
                    if (parent.getParents().contains(cn)) {
                        pairsToMerge.add(new Pair(cn, parent));
                    }
                }
            }

            Set<Node> affectedByMerge = new HashSet<Node>();

            // Merge equivalents
            for (Pair p : pairsToMerge) {
                Node cn1 = p.getA();
                Node cn2 = p.getB();

                affectedByMerge.addAll(cn1.getChildren());
                affectedByMerge.addAll(cn2.getChildren());

                // Merge into cn1 - remove cn2 from index and replace with cn1
                for (String n : cn2.getEquivalentConcepts()) {
                    conceptNodeIndex.put(n, cn1);
                }

                cn1.getEquivalentConcepts().addAll(cn2.getEquivalentConcepts());

                // Remove relationships between merged concepts
                cn1.getParents().remove(cn2);
                cn2.getChildren().remove(cn1);
                cn2.getParents().remove(cn1);
                cn1.getChildren().remove(cn2);

                // Taxonomy is bidirectional
                cn1.getParents().addAll(cn2.getParents());
                for (Node parent : cn2.getParents()) {
                    parent.getChildren().remove(cn2);
                    parent.getChildren().add(cn1);
                }
                cn1.getChildren().addAll(cn2.getChildren());
                for (Node child : cn2.getChildren()) {
                    child.getParents().remove(cn2);
                    child.getParents().add(cn1);
                }

                cn2 = null; // nothing should reference cn2 now
            }

            // b. Fix all new and affected nodes
            Set<Node> all = new HashSet<Node>();
            for (IntIterator it = allNew.keyIterator(); it.hasNext();) {
                all.add(conceptNodeIndex.get(factory.lookupConceptId(it.next())));
            }

            for (IntIterator it = allAffected.keyIterator(); it.hasNext();) {
                all.add(conceptNodeIndex.get(factory.lookupConceptId(it.next())));
            }

            for (Node cn : affectedByMerge) {
                all.add(cn);
            }

            // Add also the children of the affected nodes
            Set<Node> childrenToAdd = new HashSet<Node>();
            for (Node cn : all) {
                for (Node ccn : cn.getChildren()) {
                    if (ccn.equals(bottomNode))
                        continue;
                    childrenToAdd.add(ccn);
                }
            }
            all.addAll(childrenToAdd);

            // Find redundant relationships
            for (Node cn : all) {
                Set<Node> ps = cn.getParents();

                Object[] parents = ps.toArray(new Object[ps.size()]);
                Set<Node> toRemove = new HashSet<Node>();
                for (int i = 0; i < parents.length; i++) {
                    for (int j = i + 1; j < parents.length; j++) {
                        if (isChild((Node)parents[j], (Node)parents[i])) {
                            toRemove.add((Node)parents[i]);
                            continue;
                        }
                        if (isChild((Node)parents[i], (Node)parents[j])) {
                            toRemove.add((Node)parents[j]);
                            continue;
                        }
                    }
                }
                for (Node tr : toRemove) {
                    cn.getParents().remove(tr);
                    tr.getChildren().remove(cn);
                }
            }

            // 5. Connect bottom to new and affected concepts with no children
            for (IntIterator itr = allNew.keyIterator(); itr.hasNext();) {
                final int key = itr.next();
                Node cn = conceptNodeIndex.get(factory.lookupConceptId(key));
                if (cn.getChildren().isEmpty()) {
                    cn.getChildren().add(bottomNode);
                    bottomNode.getParents().add(cn);
                }
            }
            for (IntIterator itr = allAffected.keyIterator(); itr.hasNext();) {
                final int key = itr.next();
                Node cn = conceptNodeIndex.get(factory.lookupConceptId(key));
                if (cn.getChildren().isEmpty()) {
                    cn.getChildren().add(bottomNode);
                    bottomNode.getParents().add(cn);
                }
            }

            // 6. Connect the top node to new and affected concepts with no parents
            for (IntIterator itr = allNew.keyIterator(); itr.hasNext();) {
                final int key = itr.next();
                Node cn = conceptNodeIndex.get(factory.lookupConceptId(key));
                if (cn.getParents().isEmpty()) {
                    cn.getParents().add(topNode);
                    topNode.getChildren().add(cn);
                }
            }
            for (IntIterator itr = allAffected.keyIterator(); itr.hasNext();) {
                final int key = itr.next();
                Node cn = conceptNodeIndex.get(factory.lookupConceptId(key));
                if (cn.getParents().isEmpty()) {
                    cn.getParents().add(topNode);
                    topNode.getChildren().add(cn);
                }
            }
        }
    }

public function on_gradebook_end() {

        $this->open_xml_writer('gradebook.xml');
        $this->xmlwriter->begin_tag('gradebook');
        $this->write_grade_categories();
        $this->write_grade_items();
        $this->write_grade_letters();
        $this->xmlwriter->end_tag('gradebook');
        $this->close_xml_writer();
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
/* (non-Javadoc)
@see javax.servlet.ServletRequest#removeAttribute(java.lang.String)

public void removeAttribute(String arg0) {
        // 321485
        if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //306998.15
            logger.logp(Level.FINE, CLASS_NAME,"removeAttribute", "this->"+this+": "+" name --> " + arg0);
        }
        if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
            checkRequestObjectInUse();
        }
        Object oldValue = _srtRequestHelper._attributes.remove(arg0);
        if (oldValue != null) {
            this.attributeRemoved(arg0, oldValue);
        }
    }

public Set<HttpMethod> allAllowedMethods() {
		if (anyMethodRouter.size() > 0) {
			Set<HttpMethod> ret = new HashSet<HttpMethod>(9);
			ret.add(HttpMethod.CONNECT);
			ret.add(HttpMethod.DELETE);
			ret.add(HttpMethod.GET);
			ret.add(HttpMethod.HEAD);
			ret.add(HttpMethod.OPTIONS);
			ret.add(HttpMethod.PATCH);
			ret.add(HttpMethod.POST);
			ret.add(HttpMethod.PUT);
			ret.add(HttpMethod.TRACE);
			return ret;
		} else {
			return new HashSet<HttpMethod>(routers.keySet());
		}
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: // reads the integer based on its kind

func readInteger(typ byte, kind reflect.Kind, b []byte) interface{} {
	switch kind {
	case reflect.Uint8:
		return b[len(b)-1]
	case reflect.Uint16:
		return binary.BigEndian.Uint16(b[len(b)-2:])
	case reflect.Uint32:
		return binary.BigEndian.Uint32(b[len(b)-4:])
	case reflect.Uint64:
		return binary.BigEndian.Uint64(b[len(b)-8:])
	case reflect.Int8:
		return int8(b[len(b)-1])
	case reflect.Int16:
		return int16(binary.BigEndian.Uint16(b[len(b)-2:]))
	case reflect.Int32:
		return int32(binary.BigEndian.Uint32(b[len(b)-4:]))
	case reflect.Int64:
		return int64(binary.BigEndian.Uint64(b[len(b)-8:]))
	default:
		// the only case lefts for integer is int256/uint256.
		// big.SetBytes can't tell if a number is negative, positive on itself.
		// On EVM, if the returned number > max int256, it is negative.
		ret := new(big.Int).SetBytes(b)
		if typ == UintTy {
			return ret
		}

		if ret.Cmp(maxInt256) > 0 {
			ret.Add(maxUint256, big.NewInt(0).Neg(ret))
			ret.Add(ret, big.NewInt(1))
			ret.Neg(ret)
		}
		return ret
	}
}

func MustIntSlice(input interface{}) []int64 {
	output, err := IntSlice(input)
	if err != nil {
		panic(err)
	}
	return output
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns the available sub choices for a nested choice element.<p>

@return the available sub choices for a nested choice element as JSON array string

public String buildSubChoices() {

        String elementPath = getParamElementName();

        // we have to add a choice element, first check if the element to add itself is part of a choice or not
        boolean choiceType = Boolean.valueOf(getParamChoiceType()).booleanValue();
        I_CmsXmlSchemaType elemType = m_content.getContentDefinition().getSchemaType(elementPath);
        if (!choiceType || (elemType.isChoiceOption() && elemType.isChoiceType())) {
            // this is a choice option or a nested choice type to add, remove last element name from xpath
            elementPath = CmsXmlUtils.removeLastXpathElement(elementPath);
        }
        elementPath = CmsXmlUtils.concatXpath(elementPath, getParamChoiceElement());
        return buildElementChoices(elementPath, choiceType, false).toString();
    }

public function prepare_item_for_response( $post_type, $request ) {
		$data = array(
			'capabilities' => $post_type->cap,
			'description'  => $post_type->description,
			'hierarchical' => $post_type->hierarchical,
			'labels'       => $post_type->labels,
			'name'         => $post_type->label,
			'slug'         => $post_type->name,
		);
		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
		$data = $this->add_additional_fields_to_object( $data, $request );
		$data = $this->filter_response_by_context( $data, $context );

		// Wrap the data in a response object.
		$response = rest_ensure_response( $data );

		$base = ! empty( $post_type->rest_base ) ? $post_type->rest_base : $post_type->name;
		$response->add_links( array(
			'collection'              => array(
				'href'                => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
			),
			'https://api.w.org/items' => array(
				'href'                => rest_url( sprintf( 'wp/v2/%s', $base ) ),
			),
		) );

		/**
		 * Filter a post type returned from the API.
		 *
		 * Allows modification of the post type data right before it is returned.
		 *
		 * @param WP_REST_Response  $response   The response object.
		 * @param object            $item       The original post type object.
		 * @param WP_REST_Request   $request    Request used to generate the response.
		 */
		return apply_filters( 'rest_prepare_post_type', $response, $post_type, $request );
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Build an ASTMethod from the provided ExecutableElement

@param executableElement required input element
@return ASTMethod

public ASTMethod getMethod(ExecutableElement executableElement) {

        ImmutableList<ASTParameter> parameters = getParameters(executableElement.getParameters());
        ASTAccessModifier modifier = buildAccessModifier(executableElement);
        ImmutableSet<ASTType> throwsTypes = buildASTElementTypes(executableElement.getThrownTypes());

        return new ASTElementMethod(executableElement, astTypeBuilderVisitor, parameters, modifier, getAnnotations(executableElement), throwsTypes);
    }

public static ExecutionPath parse(String pathString) {
        pathString = pathString == null ? "" : pathString;
        pathString = pathString.trim();
        StringTokenizer st = new StringTokenizer(pathString, "/[]", true);
        ExecutionPath path = ExecutionPath.rootPath();
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if ("/".equals(token)) {
                assertTrue(st.hasMoreTokens(), mkErrMsg(), pathString);
                path = path.segment(st.nextToken());
            } else if ("[".equals(token)) {
                assertTrue(st.countTokens() >= 2, mkErrMsg(), pathString);
                path = path.segment(Integer.parseInt(st.nextToken()));
                String closingBrace = st.nextToken();
                assertTrue(closingBrace.equals("]"), mkErrMsg(), pathString);
            } else {
                throw new AssertException(format(mkErrMsg(), pathString));
            }
        }
        return path;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // check type-checks the package. The package must be OK to proceed.

func (pkg *Package) check(fs *token.FileSet, astFiles []*ast.File) {
	pkg.defs = make(map[*ast.Ident]types.Object)
	config := types.Config{Importer: importer.For("source", nil), FakeImportC: true}
	info := &types.Info{
		Defs: pkg.defs,
	}
	typesPkg, err := config.Check(pkg.dir, fs, astFiles, info)
	if err != nil {
		log.Fatalf("checking package: %s", err)
	}
	pkg.typesPkg = typesPkg
}

def _isvalid(self, datatype):
        ''''''
        if datatype in self.meta:
            return bool(Dap._meta_valid[datatype].match(self.meta[datatype]))
        else:
            return datatype in Dap._optional_meta

Instruction: Given a code description, retrieve the corresponding code.


Question:
Edits an existing MenuItem entity.

@Route("/item/{id}", name="admin_menu_item_update")
@Method("PUT")
@Template("FlowcodePageBundle:MenuItem:edit.html.twig")

public function updateMenuItemAction(Request $request, MenuItem $menuItem)
    {
        $em = $this->getDoctrine()->getManager();

        if (!$menuItem) {
            throw $this->createNotFoundException('Unable to find MenuItem entity.');
        }

        $editForm = $this->createMenuItemEditForm($menuItem);
        $editForm->handleRequest($request);
        if ($editForm->isValid()) {
            $this->get('amulen.page.service.menu')->reorder($menuItem->getMenu());
            if($menuItem->getPage()){
                $menuItem->setPageSlug($menuItem->getPage());
            }
            $em->flush();

            return $this->redirect($this->generateUrl('admin_menu_items', array('id' => $menuItem->getMenu()->getId())));
        }

        return array(
            'entity' => $menuItem,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

public function showAction($folderId)
    {
        $em = $this->getDoctrine()->getManager();

        /* @var Folder $folder */
        $folder = $em->getRepository('VictoireMediaBundle:Folder')->getFolder($folderId);
        $folders = $em->getRepository('VictoireMediaBundle:Folder')->getAllFolders();

        $sub = new Folder();
        $sub->setParent($folder);
        $subForm = $this->createForm(FolderType::class, $sub, ['folder' => $sub]);
        $editForm = $this->createForm(FolderType::class, $folder, ['folder' => $folder]);

        return $this->render('@VictoireMedia/Folder/show.html.twig', [
            'mediamanager' => $this->get('victoire_media.media_manager'),
            'subform'      => $subForm->createView(),
            'editform'     => $editForm->createView(),
            'folder'       => $folder,
            'folders'      => $folders,
        ]);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Finds a descriptor from a collection by the class name of the {@link Describable} it describes.
@param className should match {@link Class#getName} of a {@link #clazz}
@since 1.610

public static @CheckForNull <T extends Descriptor> T findByDescribableClassName(Collection<? extends T> list, String className) {
        for (T d : list) {
            if(d.clazz.getName().equals(className))
                return d;
        }
        return null;
    }

public Type[] getParameterTypes() {
        Type[] types = new Type[parameterNames.size()];
        for (int i = 0; i < types.length; i++) {
            types[i] = String.class;
        }

        return types;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Finds all enabled plugins, the result may include missing plugins.
@return array|null of enabled plugins $pluginname=>$pluginname, null means unknown

public static function get_enabled_plugins() {
        global $DB;

        $enabled = array();
        $rs = $DB->get_recordset('portfolio_instance', array('visible'=>1), 'plugin ASC', 'plugin');
        foreach ($rs as $repository) {
            $enabled[$repository->plugin] = $repository->plugin;
        }
        $rs->close();

        return $enabled;
    }

protected function validate()
    {
        if (empty($this->author)) {
            throw new \Exception('Author is empty!');
        }

        if (empty($this->classname)) {
            throw new \Exception('Class name is empty!');
        }

        if (empty($this->namespace)) {
            throw new \Exception('Namespace is empty!');
        }

        /*if (empty($this->dbConfig)) {
            throw new \Exception('Database config name is empty!');
        }*/

        if (empty($this->dbTable)) {
            throw new \Exception('Database table name is empty!');
        }

        if (empty($this->cacheName)) {
            throw new \Exception('Cache name is empty!');
        }

        if (empty($this->cachePrefix)) {
            throw new \Exception('Cache prefix is empty!');
        }

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a list of users specific to this site only.

@param auth
@return
@throws Exception

@GET
  public Response getConfigurableUsers(@HeaderParam("Authorization") @DefaultValue("no token") String auth) throws Exception {
    if(!this.isAuth(auth)) {
      throw new Exception("Unauthorized!");
    }
    if( realm != null ) {
      List<String> usernames = new ArrayList<String>();
      usernames = realm.listUsers();
      return Response.ok(new Gson().toJson(usernames), MediaType.APPLICATION_JSON).build();
    }
    return Response.status(Status.NOT_FOUND).build();
  }

public function execute($request)
    {
        $logger = $GLOBALS['logger'];

        try {
            parent::execute($request);
        } catch(AuthenticationException $ex) {
            $logger->error('Unauthorized attempt to access resource, being redirected to home page', array($ex->getMessage()));
            $this->_handleUnauthenticatedAccess();
            $this->_response->send();
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Handles preparing query.

Overrides ezcQuery->prepare()

Adds "FROM dual" to the select if no FROM clause specified
i.e. fixes queries like "SELECT 1+1" to work in Oracle.

@return PDOStatement

public function prepare()
    {
        if ( $this->fromString == null || $this->fromString == '' )
        {
            $this->from( $this->getDummyTableName() );
        }
        return parent::prepare();
    }

def get_element_spd_dos(self, el):

        el = get_el_sp(el)
        el_dos = {}
        for site, atom_dos in self.pdos.items():
            if site.specie == el:
                for orb, pdos in atom_dos.items():
                    orbital_type = _get_orb_type_lobster(orb)
                    if orbital_type not in el_dos:
                        el_dos[orbital_type] = pdos
                    else:
                        el_dos[orbital_type] = \
                            add_densities(el_dos[orbital_type], pdos)

        return {orb: Dos(self.efermi, self.energies, densities)
                for orb, densities in el_dos.items()}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sets active class to current slide.

@return {Void}

function activeClass() {
      var classes = Glide.settings.classes;
      var slide = Components.Html.slides[Glide.index];

      if (slide) {
        slide.classList.add(classes.activeSlide);

        siblings(slide).forEach(function (sibling) {
          sibling.classList.remove(classes.activeSlide);
        });
      }
    }

function (inst) {
    if (inst.$drawer.hasClass('mdui-drawer-open')) {
      inst.state = 'opened';
      componentEvent('opened', 'drawer', inst, inst.$drawer);
    } else {
      inst.state = 'closed';
      componentEvent('closed', 'drawer', inst, inst.$drawer);
    }
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: return installed board names.

def board_names(hwpack='arduino'):
    """"""
    ls = list(boards(hwpack).keys())
    ls.sort()
    return ls

function(finishedCallback){
      self.getHardwareModel(function(data,error){
        self.deviceData.hardwareModel = data;
        finishedCallback(error);
      });
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Create and populate the ~/.config/rapport directory tree if it's not existing.

    Doesn't interfere with already existing directories or configuration files.

def init_user():

    if not os.path.exists(USER_CONFIG_DIR):
        if rapport.config.get_int("rapport", "verbosity") >= 1:
            print("Create user directory {0}".format(USER_CONFIG_DIR))
        os.makedirs(USER_CONFIG_DIR)
    for subdir in ["plugins", "reports", "templates/plugin", "templates/email", "templates/web"]:
        user_conf_subdir = os.path.join(USER_CONFIG_DIR, subdir)
        if not os.path.exists(user_conf_subdir):
            if rapport.config.get_int("rapport", "verbosity") >= 1:
                print("Create user directory {0}".format(user_conf_subdir))
            os.makedirs(user_conf_subdir)
        if subdir == "reports" and not (os.stat(user_conf_subdir).st_mode & 0o777) == 0o700:
            if rapport.config.get_int("rapport", "verbosity") >= 1:
                print("Set secure directory permissions for {0}".format(user_conf_subdir))
            os.chmod(user_conf_subdir, 0o700)
    if not os.path.exists(USER_CONFIG_FILE):
        if rapport.config.get_int("rapport", "verbosity") >= 1:
            print("Create user configuration {0}".format(USER_CONFIG_FILE))
        default_config = os.path.abspath(os.path.join(os.path.splitext(__file__)[0], "rapport.conf"))
        shutil.copyfile(default_config, USER_CONFIG_FILE)

    if not (os.stat(USER_CONFIG_FILE).st_mode & 0o777) == 0o600:
        if rapport.config.get_int("rapport", "verbosity") >= 1:
            print("Set secure file permissions for {0}".format(USER_CONFIG_FILE))
        os.chmod(USER_CONFIG_FILE, 0o600)

func ensureDirectoryForFile(file string) error {
	baseDir := path.Dir(file)
	_, err := os.Stat(baseDir)
	if err != nil && !os.IsNotExist(err) {
		return err
	}

	return os.MkdirAll(baseDir, defaultDirectoryPermission)
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Assert that the response body matches some content

@param PyStringNode $content The content to match the response body against
@throws AssertionFailedException
@return void

@Then the response body is:

public function assertResponseBodyIs(PyStringNode $content) {
        $this->requireResponse();
        $content = (string) $content;

        try {
            Assertion::same($body = (string) $this->response->getBody(), $content, sprintf(
                'Expected response body "%s", got "%s".',
                $content,
                $body
            ));
        } catch (AssertionFailure $e) {
            throw new AssertionFailedException($e->getMessage());
        }
    }

def _parse_caps_cpu(node):
    '''

    '''
    result = {}
    for mode in node.findall('mode'):
        if not mode.get('supported') == 'yes':
            continue

        name = mode.get('name')
        if name == 'host-passthrough':
            result[name] = True

        elif name == 'host-model':
            host_model = {}
            model_node = mode.find('model')
            if model_node is not None:
                model = {
                    'name': model_node.text
                }

                vendor_id = model_node.get('vendor_id')
                if vendor_id:
                    model['vendor_id'] = vendor_id

                fallback = model_node.get('fallback')
                if fallback:
                    model['fallback'] = fallback
                host_model['model'] = model

            vendor = mode.find('vendor').text if mode.find('vendor') is not None else None
            if vendor:
                host_model['vendor'] = vendor

            features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')}
            if features:
                host_model['features'] = features

            result[name] = host_model

        elif name == 'custom':
            custom_model = {}
            models = {model.text: model.get('usable') for model in mode.findall('model')}
            if models:
                custom_model['models'] = models
            result[name] = custom_model

    return result

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get the parent of the element

        @rtype:     WebElementWrapper
        @return:    Parent of webelementwrapper on which this was invoked

def parent(self):

        def parent_element():
            """
            Wrapper to retrieve parent element
            """
            return WebElementWrapper(self.driver_wrapper, self.locator, self.element.parent)
        return self.execute_and_handle_webelement_exceptions(parent_element, 'get parent')

function( data, client ) {

    this.client = client;

    /**
     * @summary Linked channels
     *
     * @name Channel#links
     * @type Channel[]
     */
    this.links = [];

    /**
     * @summary Child channels
     *
     * @name Channel#children
     * @type Channel[]
     */
    this.children = [];

    /**
     * @summary Users in the channel
     *
     * @name Channel#users
     * @type User[]
     */
    this.users = [];

    this._checkParent( data ); // Needs to be done seperate
    this._applyProperties( data );

    // TODO: Description
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Runs the application.
This is the main entrance of an application.
@return int the exit status (0 means normal, non-zero values mean abnormal)

public function run()
    {
        if (YII_ENABLE_ERROR_HANDLER) {
            $this->get('errorHandler')->register();
        }

        try {
            $this->state = self::STATE_BEFORE_REQUEST;
            $this->trigger(RequestEvent::BEFORE);

            $this->state = self::STATE_HANDLING_REQUEST;
            $this->response = $this->handleRequest($this->getRequest());

            $this->state = self::STATE_AFTER_REQUEST;
            $this->trigger(RequestEvent::AFTER);

            $this->state = self::STATE_SENDING_RESPONSE;
            $this->response->send();

            $this->state = self::STATE_END;

            return $this->response->exitStatus;
        } catch (ExitException $e) {
            $this->end($e->statusCode, $this->response ?? null);
            return $e->statusCode;
        }
    }

func Login(login, password string) (*User, error) {
	var email *mail.Address
	var username string
	var id uint64
	var e error

	if email, e = mail.ParseAddress(login); e == nil { // is a mail
		if e = Db().Model(User{}).Select("username").Where(&User{Email: email.Address}).Scan(&username); e != nil {
			return nil, e
		}
	} else if id, e = strconv.ParseUint(login, 10, 64); e == nil { // if login the user ID
		if e = Db().Model(User{}).Select("username").Where(&User{Counter: id}).Scan(&username); e != nil {
			return nil, e
		}
	} else { // otherwise is the username
		username = login
	}

	var logged bool
	var counter uint64

	if e = Db().Model(User{}).Select("login(?, ?) AS logged, counter", username, password).Where("LOWER(username) = ?", username).Scan(&logged, &counter); e != nil {
		return nil, e
	}

	if !logged {
		return nil, errors.New("wrong username or password")
	}

	return NewUser(counter)
}

Instruction: Given a code description, retrieve the corresponding code.


Question: One of ways of creating builder. In most cases (considering all _functional_ builders) it requires to provide generic parameters (in most cases redundantly)

@Nonnull
	public static <T1, T2, R> LBiObjCharFunctionBuilder<T1, T2, R> biObjCharFunction() {
		return new LBiObjCharFunctionBuilder();
	}

public static <T extends Comparable<?>> TimeOperation<T> timeOperation(Class<? extends T> type,
            Operator operator, Expression<?>... args) {
        return new TimeOperation<T>(type, operator, args);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get a unique key to use as an index

@return string[]

public function getPrimaryKeyIndex()
    {
        $database = DatabaseLayer::getInstance();

        $columns = array();

        if ($this instanceof VersionedActiveRecord) {
            $schema = $this->getClassSchema();
            $firstColumn = reset($schema)['name'];
            $columns = [$firstColumn => $firstColumn, "sequence" => "sequence"];
        } else {
            foreach ($database->getTableIndexes($this->_table) as $key) {
                $columns[$key->Column_name] = $key->Column_name;
            }
        }

        return array_values($columns);
    }

public function validateResponseSignature(\Yubikey\Response $response)
    {
        $params = array();
        foreach ($response->getProperties() as $property) {
            $value = $response->$property;
            if ($value !== null) {
                $params[$property] = $value;
            }
        }
        ksort($params);

        $signature = $this->generateSignature($params);
        return $this->hash_equals($signature, $response->getHash(true));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Enforce clean slugs.

@param string $value

@return void

public function setSlugAttribute($value): void
    {
        $this->attributes['slug'] = str_slug($value, $this->getSlugOptions()->slugSeparator, $this->getSlugOptions()->slugLanguage);
    }

public function parseRoute($routeSpec)
    {
        $path           = isset($routeSpec['path']) ? $routeSpec['path'] : null;
        $methods        = isset($routeSpec['methods']) ? $routeSpec['methods'] : array();
        $controller     = isset($routeSpec['controller']) ? $routeSpec['controller'] : null;
        $calls          = isset($routeSpec['calls']) ? $routeSpec['calls'] : null;
        $requirements   = isset($routeSpec['requirements']) ? $routeSpec['requirements'] : array();
        $regex          = isset($routeSpec['path']) ? $routeSpec['path'] : null;

        $route = new Route($path, $methods, $controller, $calls, $requirements, $regex);

        return $route;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: A decorator to handle read timeouts from Twitter.

def catch_timeout(f):

    def new_f(self, *args, **kwargs):
        try:
            return f(self, *args, **kwargs)
        except (requests.exceptions.ReadTimeout,
                requests.packages.urllib3.exceptions.ReadTimeoutError) as e:
            log.warning("caught read timeout: %s", e)
            self.connect()
            return f(self, *args, **kwargs)
    return new_f

def consume(self, limit=None):
        """"""
        for total_message_count in count():
            if limit and total_message_count >= limit:
                raise StopIteration

            if not self.channel.is_open:
                raise StopIteration

            self.channel.conn.drain_events()
            yield True

Instruction: Given a code description, retrieve the corresponding code.


Question: // round rounds a float64

func round(a float64) float64 {
	if a < 0 {
		return math.Ceil(a - 0.5)
	}
	return math.Floor(a + 0.5)
}

func (p *Point) format() string {
	if p.X == nil && p.Y == nil {
		return "(inf,inf)"
	}
	return fmt.Sprintf("(%s,%s)", hex.EncodeToString(p.X.Bytes()), hex.EncodeToString(p.Y.Bytes()))
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
/* (non-Javadoc)
@see org.apache.hadoop.mapred.Reducer#reduce(java.lang.Object, java.util.Iterator, org.apache.hadoop.mapred.OutputCollector, org.apache.hadoop.mapred.Reporter)

public void reduce(Shard key, Iterator<IntermediateForm> values,
      OutputCollector<Shard, Text> output, Reporter reporter)
      throws IOException {

    LOG.info("Construct a shard writer for " + key);
    FileSystem fs = FileSystem.get(iconf.getConfiguration());
    String temp =
        mapredTempDir + Path.SEPARATOR + "shard_" + System.currentTimeMillis();
    final ShardWriter writer = new ShardWriter(fs, key, temp, iconf);

    // update the shard
    while (values.hasNext()) {
      IntermediateForm form = values.next();
      writer.process(form);
      reporter.progress();
    }

    // close the shard
    final Reporter fReporter = reporter;
    new Closeable() {
      volatile boolean closed = false;

      public void close() throws IOException {
        // spawn a thread to give progress heartbeats
        Thread prog = new Thread() {
          public void run() {
            while (!closed) {
              try {
                fReporter.setStatus("closing");
                Thread.sleep(1000);
              } catch (InterruptedException e) {
                continue;
              } catch (Throwable e) {
                return;
              }
            }
          }
        };

        try {
          prog.start();

          if (writer != null) {
            writer.close();
          }
        } finally {
          closed = true;
        }
      }
    }.close();
    LOG.info("Closed the shard writer for " + key + ", writer = " + writer);

    output.collect(key, DONE);
  }

Set<ProjectMethod> findProjectMethods(final List<Instruction> instructions) {
        final Set<ProjectMethod> projectMethods = new HashSet<>();

        addProjectMethods(instructions, projectMethods);

        return projectMethods;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
If not already created, a new flow-definition element will be created and returned.
Otherwise, the first existing flow-definition element will be returned.
@return the instance defined for the element flow-definition

public FacesConfigFlowDefinitionType<WebFacesConfigDescriptor> getOrCreateFlowDefinition()
   {
      List<Node> nodeList = model.get("flow-definition");
      if (nodeList != null &&  nodeList.size() > 0)
      {
         return new FacesConfigFlowDefinitionTypeImpl<WebFacesConfigDescriptor>(this, "flow-definition", model, nodeList.get(0));
      }
      return createFlowDefinition();
   }

def consume_at_rule(input = @tokens)
      rule = {}

      rule[:tokens] = input.collect do
        rule[:name]    = input.consume[:value]
        rule[:prelude] = []

        while token = input.consume
          node = token[:node]

          if node == :comment # Non-standard.
            next

          elsif node == :semicolon
            break

          elsif node === :'{'
            # Note: The spec says the block should _be_ the consumed simple
            # block, but Simon Sapin's CSS parsing tests and tinycss2 expect
            # only the _value_ of the consumed simple block here. I assume I'm
            # interpreting the spec too literally, so I'm going with the
            # tinycss2 behavior.
            rule[:block] = consume_simple_block(input)[:value]
            break

          elsif node == :simple_block && token[:start] == '{'
            # Note: The spec says the block should _be_ the simple block, but
            # Simon Sapin's CSS parsing tests and tinycss2 expect only the
            # _value_ of the simple block here. I assume I'm interpreting the
            # spec too literally, so I'm going with the tinycss2 behavior.
            rule[:block] = token[:value]
            break

          else
            input.reconsume
            rule[:prelude] << consume_component_value(input)
          end
        end
      end

      create_node(:at_rule, rule)
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
// checkUpdates checks if there's a torus update available. If so,
// it prints a message to the stdout with the download URL if so.

func checkUpdates(ctx *cli.Context) error {
	cfg, err := config.LoadConfig()
	if err != nil {
		return err
	}

	client := api.NewClient(cfg)
	c := context.Background()

	updateInfo, err := client.Updates.Check(c)
	if err != nil {
		return err
	}

	if updateInfo.NeedsUpdate {
		ui.Info("A new version of Torus is available (%s)! You can download it from %s.", updateInfo.Version, downloadURL)
	}

	return nil
}

def _worker(self):
        """"""
        while self.working:
            try:
                genome_id, genome, config = self.inqueue.get(
                    block=True,
                    timeout=0.2,
                    )
            except queue.Empty:
                continue
            f = self.eval_function(genome, config)
            self.outqueue.put((genome_id, genome, f))

Instruction: Given a code description, retrieve the corresponding code.


Question:
Waits for multiple handles. (Similar to 'select') Returns the handle which is ready.
    Returns `None` on timeout.

    http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx

def _wait_for_handles(handles, timeout=-1):

    arrtype = HANDLE * len(handles)
    handle_array = arrtype(*handles)

    ret = windll.kernel32.WaitForMultipleObjects(
        len(handle_array), handle_array, BOOL(False), DWORD(timeout))

    if ret == WAIT_TIMEOUT:
        return None
    else:
        h = handle_array[ret]
        return h

async def get_shade(self, shade_id, from_cache=True) -> BaseShade:
        """"""
        if not from_cache:
            await self.get_shades()
        for _shade in self.shades:
            if _shade.id == shade_id:
                return _shade
        raise ResourceNotFoundException("Shade not found. Id: {}".format(shade_id))

Instruction: Given a code description, retrieve the corresponding code.


Question: // NewEnvironment creates a plugin context from arguments and standard input.

func NewEnvironment() (env *Environment, err error) {
	env = &Environment{
		Invocation: os.Args[0],
		Response:   &Response{},
	}

	input := flag.String("input", "", "API description (in binary protocol buffer form)")
	output := flag.String("output", "-", "Output file or directory")
	plugin := flag.Bool("plugin", false, "Run as a gnostic plugin (other flags are ignored).")
	flag.Parse()

	env.RunningAsPlugin = *plugin
	programName := path.Base(os.Args[0])

	if (*input == "") && !*plugin {
		flag.Usage = func() {
			fmt.Fprintf(os.Stderr, "\n")
			fmt.Fprintf(os.Stderr, programName+" is a gnostic plugin.\n")
			fmt.Fprintf(os.Stderr, `
When it is run from gnostic, the -plugin option is specified and gnostic
writes a binary request to stdin and waits for a binary response on stdout.

This program can also be run standalone using the other flags listed below.
When the -plugin option is specified, these flags are ignored.`)
			fmt.Fprintf(os.Stderr, "\n\nUsage:\n")
			flag.PrintDefaults()
		}
		flag.Usage()
		os.Exit(0)
	}

	if env.RunningAsPlugin {
		// Handle invocation as a plugin.

		// Read the plugin input.
		pluginData, err := ioutil.ReadAll(os.Stdin)
		env.RespondAndExitIfError(err)
		if len(pluginData) == 0 {
			env.RespondAndExitIfError(fmt.Errorf("no input data"))
		}

		// Deserialize the request from the input.
		request := &Request{}
		err = proto.Unmarshal(pluginData, request)
		env.RespondAndExitIfError(err)

		// Collect parameters passed to the plugin.
		parameters := request.Parameters
		for _, parameter := range parameters {
			env.Invocation += " " + parameter.Name + "=" + parameter.Value
		}

		// Log the invocation.
		//log.Printf("Running plugin %s", env.Invocation)

		env.Request = request

	} else {
		// Handle invocation from the command line.

		// Read the input document.
		apiData, err := ioutil.ReadFile(*input)
		if len(apiData) == 0 {
			env.RespondAndExitIfError(fmt.Errorf("no input data"))
		}

		env.Request = &Request{}
		env.Request.OutputPath = *output
		env.Request.SourceName = path.Base(*input)

		// First try to unmarshal OpenAPI v2.
		documentv2 := &openapiv2.Document{}
		err = proto.Unmarshal(apiData, documentv2)
		if err == nil {
			env.Request.AddModel("openapi.v2.Document", documentv2)
			// include experimental API surface model
			surfaceModel, err := surface.NewModelFromOpenAPI2(documentv2)
			if err == nil {
				env.Request.AddModel("surface.v1.Model", surfaceModel)
			}
			return env, err
		}
		// If that failed, ignore deserialization errors and try to unmarshal OpenAPI v3.
		documentv3 := &openapiv3.Document{}
		err = proto.Unmarshal(apiData, documentv3)
		if err == nil {
			env.Request.AddModel("openapi.v3.Document", documentv3)
			// include experimental API surface model
			surfaceModel, err := surface.NewModelFromOpenAPI3(documentv3)
			if err == nil {
				env.Request.AddModel("surface.v1.Model", surfaceModel)
			}
			return env, err
		}
		// If that failed, ignore deserialization errors and try to unmarshal a Discovery document.
		discoveryDocument := &discovery.Document{}
		err = proto.Unmarshal(apiData, discoveryDocument)
		if err == nil {
			env.Request.AddModel("discovery.v1.Document", discoveryDocument)
			return env, err
		}
		// If we get here, we don't know what we got
		err = errors.New("Unrecognized format for input")
		return env, err
	}
	return env, err
}

def load_replace_candidate(self, filename=None, config=None):

        self.config_replace = True
        return_status, msg = self._load_candidate_wrapper(source_file=filename,
                                                          source_config=config,
                                                          dest_file=self.candidate_cfg,
                                                          file_system=self.dest_file_system)
        if not return_status:
            raise ReplaceConfigException(msg)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Map Exception into an response.

@param  Response $response
@param  Exception $e
@return Response

protected function toHttpResponse( $response, Exception $e )
	{
		$response = new Response( $response->getContent(), $response->getStatusCode(), $response->headers->all() );

		return $response->withException( $e );
	}

func (c *RolesController) List(ctx *app.ListRolesContext) error {
	if ctx.ResourceType == nil { // todo: check for empty string too?
		return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("resource_type", "nil"))
	}

	var roleScopes []role.RoleDescriptor

	_, err := c.app.ResourceTypeRepository().Lookup(ctx, *ctx.ResourceType)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting roles for the resource type")
		// if not found, then NotFoundError would be returned,
		// hence returning the error as is.
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	roleScopes, err = c.app.RoleManagementService().ListAvailableRolesByResourceType(ctx, *ctx.ResourceType)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting available roles for the resource")
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	respRoles := convertRoleScopeToAppRoles(roleScopes)
	res := &app.Roles{
		Data: respRoles,
	}
	return ctx.OK(res)
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Synchronous part of _new_job. Creates needed directories, copy files, and starts the container.

def __new_job_sync(self, message, future_results):

        course_id = message.course_id
        task_id = message.task_id

        debug = message.debug
        environment_name = message.environment
        enable_network = message.enable_network
        time_limit = message.time_limit
        hard_time_limit = message.hard_time_limit or time_limit * 3
        mem_limit = message.mem_limit

        course_fs = self.tasks_fs.from_subfolder(course_id)
        task_fs = course_fs.from_subfolder(task_id)

        if not course_fs.exists() or not task_fs.exists():
            self._logger.warning("Task %s/%s unavailable on this agent", course_id, task_id)
            raise CannotCreateJobException('Task unavailable on agent. Please retry later, the agents should synchronize soon. '
                             'If the error persists, please contact your course administrator.')

        # Check for realistic memory limit value
        if mem_limit < 20:
            mem_limit = 20
        elif mem_limit > self._max_memory_per_slot:
            self._logger.warning("Task %s/%s ask for too much memory (%dMB)! Available: %dMB", course_id, task_id,
                                 mem_limit, self._max_memory_per_slot)
            raise CannotCreateJobException('Not enough memory on agent (available: %dMB). Please contact your course administrator.' % self._max_memory_per_slot)

        if environment_name not in self._containers:
            self._logger.warning("Task %s/%s ask for an unknown environment %s (not in aliases)", course_id, task_id,
                                 environment_name)
            raise CannotCreateJobException('Unknown container. Please contact your course administrator.')

        environment = self._containers[environment_name]["id"]

        ports_needed = self._containers[environment_name]["ports"]

        if debug == "ssh" and 22 not in ports_needed:
            ports_needed.append(22)

        ports = {}
        if len(ports_needed) > 0:
            time_limit = 30 * 60
            hard_time_limit = 30 * 60
        for p in ports_needed:
            if len(self._external_ports) == 0:
                self._logger.warning("User asked for a port but no one are available")
                raise CannotCreateJobException('No ports are available right now. Please retry later.')
            ports[p] = self._external_ports.pop()

        # Create directories for storing all the data for the job
        try:
            container_path = tempfile.mkdtemp(dir=self._tmp_dir)
        except Exception as e:
            self._logger.error("Cannot make container temp directory! %s", str(e), exc_info=True)
            for p in ports:
                self._external_ports.add(ports[p])
            raise CannotCreateJobException('Cannot make container temp directory.')

        task_path = path_join(container_path, 'task')  # tmp_dir/id/task/
        course_path = path_join(container_path, 'course')

        sockets_path = path_join(container_path, 'sockets')  # tmp_dir/id/socket/
        student_path = path_join(task_path, 'student')  # tmp_dir/id/task/student/
        systemfiles_path = path_join(task_path, 'systemfiles')  # tmp_dir/id/task/systemfiles/

        course_common_path = path_join(course_path, 'common')
        course_common_student_path = path_join(course_path, 'common', 'student')

        # Create the needed directories
        os.mkdir(sockets_path)
        os.chmod(container_path, 0o777)
        os.chmod(sockets_path, 0o777)
        os.mkdir(course_path)

        # TODO: avoid copy
        task_fs.copy_from(None, task_path)
        os.chmod(task_path, 0o777)

        if not os.path.exists(student_path):
            os.mkdir(student_path)
            os.chmod(student_path, 0o777)

        # Copy common and common/student if needed
        # TODO: avoid copy
        if course_fs.from_subfolder("$common").exists():
            course_fs.from_subfolder("$common").copy_from(None, course_common_path)
        else:
            os.mkdir(course_common_path)

        if course_fs.from_subfolder("$common").from_subfolder("student").exists():
            course_fs.from_subfolder("$common").from_subfolder("student").copy_from(None, course_common_student_path)
        else:
            os.mkdir(course_common_student_path)

        # Run the container
        try:
            container_id = self._docker.sync.create_container(environment, enable_network, mem_limit, task_path,
                                                              sockets_path, course_common_path,
                                                              course_common_student_path, ports)
        except Exception as e:
            self._logger.warning("Cannot create container! %s", str(e), exc_info=True)
            shutil.rmtree(container_path)
            for p in ports:
                self._external_ports.add(ports[p])
            raise CannotCreateJobException('Cannot create container.')

        # Store info
        self._containers_running[container_id] = message, container_path, future_results
        self._container_for_job[message.job_id] = container_id
        self._student_containers_for_job[message.job_id] = set()

        if len(ports) != 0:
            self._assigned_external_ports[container_id] = list(ports.values())

        try:
            # Start the container
            self._docker.sync.start_container(container_id)
        except Exception as e:
            self._logger.warning("Cannot start container! %s", str(e), exc_info=True)
            shutil.rmtree(container_path)
            for p in ports:
                self._external_ports.add(ports[p])

            raise CannotCreateJobException('Cannot start container')

        return {
            "job_id": message.job_id,
            "container_id": container_id,
            "inputdata": message.inputdata,
            "debug": debug,
            "ports": ports,
            "orig_env": environment_name,
            "orig_memory_limit": mem_limit,
            "orig_time_limit": time_limit,
            "orig_hard_time_limit": hard_time_limit,
            "sockets_path": sockets_path,
            "student_path": student_path,
            "systemfiles_path": systemfiles_path,
            "course_common_student_path": course_common_student_path
        }

def move(self, dst, **kwargs):
        """"""
        _fs, filename = opener.parse(self.uri)
        _fs_dst, filename_dst = opener.parse(dst)
        movefile(_fs, filename, _fs_dst, filename_dst, **kwargs)
        self.uri = dst

Instruction: Given a code description, retrieve the corresponding code.


Question: Remove the Checksum metadata from a path

function removeChecksum(fs, path, callback) {
  removeAttr(fs, path, constants.attributes.checksum, callback);
}

func cleanRepoName(name string) (string, error) {
	if len(name) == 0 {
		return name, errors.New("Empty repo name.")
	}
	if strings.Contains(name, "..") {
		return "", errors.New("Cannot change directory in file name.")
	}
	name = strings.Replace(name, "'", "", -1)
	return strings.TrimPrefix(strings.TrimSuffix(name, ".git"), "/"), nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param NodeRef $nodeRef
@param $metaID
@param int $value

@throws NodeException
@throws SQLException
@throws Exception

public function incrementMeta(NodeRef $nodeRef, $metaID, $value = 1)
    {
        $metaID = ltrim($metaID, '#');

        $this->NodeEvents->fireNodeEvents(__FUNCTION__, '', $nodeRef, $metaID);

        $db = $this->getConnectionForWrite($nodeRef);
        $id = $this->getRecordIDFromNodeRef($nodeRef);

        // determine the meta storage
        $metaDef = $nodeRef->getElement()->getSchema()->getMetaDef($metaID);
        $datatype = $metaDef->getDatatype();
        $table = $db->quoteIdentifier($this->NodeDBMeta->getMetaTable($nodeRef, $datatype));
        $tableid = $this->NodeDBMeta->getPrimaryKey($nodeRef);
        $datatypeCol = $this->NodeDBMeta->getMetaDatatypeColumn($datatype);

        $value = intval($value);
        $newValue = false;
        $oldValue = false;
        $originalMeta = null;

        $maxValue = $this->getMaxIntForDatatype($datatype);
        $minValue = $this->getMinIntForDatatype($datatype);

        try {
            $affectedRows = $db->write("UPDATE {$table} SET {$datatypeCol}Value = LAST_INSERT_ID({$datatypeCol}Value+{$value}) WHERE {$tableid} = {$db->quote($id)} AND Name = {$db->quote($metaID)}", DatabaseInterface::AFFECTED_ROWS);
            if ($affectedRows == 1) {
                $newValue = intval($db->readField("SELECT LAST_INSERT_ID()"));
                $oldValue = $newValue - $value;
            }
        } catch (SQLException $e) {
            if ($e->getCode() != 22003 || strpos($e->getMessage(), 'Numeric value out of range') === false) {
                throw $e;
            }

            // must ask the DB for its current value
            $oldValue = intval($db->readField("SELECT {$datatypeCol}Value FROM {$table} WHERE {$tableid} = {$db->quote($id)} AND Name = {$db->quote($metaID)}"));
            $newValue = $oldValue + $value;

            // ensure the new values don't overflow (note that $value can be positive or negative and isn't necessarily 1)
            if ($newValue > $maxValue) {
                $newValue = $maxValue;
            } elseif ($newValue < $minValue) {
                $newValue = $minValue;
            }

            if ($newValue === $oldValue) {
                $affectedRows = 1;
            } else {
                $affectedRows = $db->write("UPDATE {$table} SET {$datatypeCol}Value = {$newValue} WHERE {$tableid} = {$db->quote($id)} AND Name = {$db->quote($metaID)}", DatabaseInterface::AFFECTED_ROWS);
            }
        } catch (Exception $e) {
            throw $e;
        }

        // new value didn't get set because the meta record hasn't been created yet.
        if ($newValue === false) {
            $newValue = $value;
            // ensure the new values don't overflow (note that $value can be positive or negative and isn't necessarily 1)
            if ($newValue > $maxValue) {
                $newValue = $maxValue;
            } elseif ($newValue < $minValue) {
                $newValue = $minValue;
            }
        }

        if ($affectedRows == 0) {
            $affectedRows = $db->write("INSERT INTO {$table} ({$tableid}, Name, {$datatypeCol}Value) Values ({$db->quote($id)}, {$db->quote($metaID)}, {$newValue}) ON DUPLICATE KEY UPDATE {$datatypeCol}Value = LAST_INSERT_ID({$datatypeCol}Value+{$value})", DatabaseInterface::AFFECTED_ROWS);

            // new record inserted
            if ($affectedRows == 1) {
                $metaEvent = 'add';
                $newMeta = new Meta($metaID, $newValue);
                $newMeta->setMetaStorageDatatype($metaDef->Datatype);
                $originalMeta = null;

            // duplicate key update encountered
            } else if ($affectedRows == 2) {
                $metaEvent = 'update';

                $newValue = intval($db->readField("SELECT LAST_INSERT_ID()"));
                $oldValue = $newValue - $value;

                $newMeta = new Meta($metaID, $newValue);
                $newMeta->setMetaStorageDatatype($metaDef->Datatype);

                $originalMeta = new Meta($metaID, $oldValue);
                $originalMeta->setMetaStorageDatatype($metaDef->Datatype);

            } else {
                throw new NodeException('Unable to increment meta ID ['.$metaID.'] on record ['.$nodeRef.']');
            }
        } else {
            $metaEvent = 'update';

            $newMeta = new Meta($metaID, $newValue);
            $newMeta->setMetaStorageDatatype($metaDef->Datatype);

            $originalMeta = new Meta($metaID, $oldValue);
            $originalMeta->setMetaStorageDatatype($metaDef->Datatype);
        }

        $this->NodeEvents->fireMetaEvents('meta', $metaEvent, $nodeRef, $newMeta, $originalMeta);
    }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param Expr $where

@return static

public function where(Expr $where)
    {
        if ($where instanceof Parameter && $where == Expr::true()) {
            return $this;
        }

        if ($where instanceof BinOp && $where->getOperator() === BinOp::AND_) {
            $this->where($where->getLeft());
            $this->where($where->getRight());
        } else {
            $this->where[] = $where;
        }

        return $this;
    }

public String getParameterValue(String name) throws RepositoryConfigurationException
   {
      String value = getParameterValue(name, null);
      if (value == null)
         throw new RepositoryConfigurationException("Parameter " + name + " not found ");
      return value;
   }

Instruction: Given a code description, retrieve the corresponding code.


public synchronized void commit_one_phase() throws RollbackException, HeuristicHazardException, SystemException {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "commit_one_phase", this);

        // Ensure timeout cannot rollback the underlying transaction
        ((DistributableTransaction) _transaction).addAssociation();

        // If the transaction that this object represents has already been completed,
        // raise an exception if necessary.
        boolean rolledBack = false; // Use locals in case of async completion
        boolean sysException = false;

        final int state = _transaction.getTransactionState().getState();
        switch (state) {
            case TransactionState.STATE_ACTIVE:
                // We have received a commit one phase request
                // from our superior. This transaction should
                // no longer act as a subordinate and should
                // assume superior status prior to beginning
                // commit processing - this is enabled by calling
                // the top-level commit operation.

                // The commit operation may throw the HeuristicHazard exception.  In this case
                // allow it to go back to the caller.  The commit call performs all state checks.
                try {
                    // Resume the transaction created from the incoming
                    // request so that it is installed on the thread.
                    ((EmbeddableTranManagerSet) TransactionManagerFactory.getTransactionManager()).resume(_transaction);

                    // need to prolongFinish to deal with heuristics
                    // as commit_one_phase always calls notifyCompletion
                    _transaction.prolongFinish();
                    _transaction.commit_one_phase();
                    _transaction.notifyCompletion();
                } catch (HeuristicMixedException exc) {
                    // No FFDC code needed.
                    _heuristic = StatefulResource.HEURISTIC_MIXED;
                } catch (HeuristicHazardException exc) {
                    // No FFDC code needed.
                    _heuristic = StatefulResource.HEURISTIC_HAZARD;
                } catch (HeuristicRollbackException exc) {
                    // No FFDC code needed.
                    rolledBack = true;
                    _transaction.notifyCompletion();
                } catch (RollbackException exc) {
                    // No FFDC as rollback is a valid response
                    rolledBack = true;
                    _transaction.notifyCompletion();
                } catch (Throwable exc) { // SecurityException/IllegalStateException/SystemException
                    FFDCFilter.processException(exc, "com.ibm.tx.remote.TransactionWrapper.commit_one_phase", "456", this);
                    Tr.error(tc, "WTRN0070_ONE_PHASE_COMMIT_FAILED", exc);
                    sysException = true;
                    _transaction.notifyCompletion();
                    // destroy();
                }
                break;

            case TransactionState.STATE_COMMITTING:
                // We should only get in this state if the superior failed to get a
                // response on the original commit calls.  We can be in committing
                // state either if we are retrying local resources or in recovery
                // Check the heuristic state and return that.
                _heuristic = _transaction.getResources().getHeuristicOutcome();
                if (_heuristic != StatefulResource.NONE)
                    break;

                // If we are not in any heuristic state then we are not retrying and
                // must be in recovery about to perform the commit.
                // Continue to return transient until we have a real outcome to return.
                // The superior will consider this as heuristic hazard.  Also the
                // same for LPS state.
            case TransactionState.STATE_LAST_PARTICIPANT:
                ((DistributableTransaction) _transaction).removeAssociation();
                final TRANSIENT tre = new TRANSIENT();
                if (tc.isEntryEnabled())
                    Tr.exit(tc, "commit_one_phase", tre);
                throw tre;

            case TransactionState.STATE_COMMITTED:
                // this is probably a retry ... check heuristic state
                _heuristic = _transaction.getResources().getHeuristicOutcome();
                break;

            case TransactionState.STATE_HEURISTIC_ON_COMMIT:
            case TransactionState.STATE_HEURISTIC_ON_ROLLBACK:
                // Should never get in this state as C1P never gets
                // in this state as it presumes superior status even
                // for admin heuristic commit
                break;

            case TransactionState.STATE_ROLLING_BACK:
            case TransactionState.STATE_ROLLED_BACK:
                // Transaction timed out or admin heuristic rollback or LPS rollback
                // again, probably a retry ... throw exception
                rolledBack = true;
                break;

            case TransactionState.STATE_NONE:
                // Transaction has completed and is now finished
                // Normally the remoteable object would be disconnected from the orb,
                // but ... timing may mean get got here while it was happenning
                ((DistributableTransaction) _transaction).removeAssociation();
                final OBJECT_NOT_EXIST one = new OBJECT_NOT_EXIST();
                if (tc.isEntryEnabled())
                    Tr.exit(tc, "commit_one_phase", one);
                throw one;

            default:
                Tr.error(tc, "WTRN0069_COMMIT_BAD_STATE", TransactionState.stateToString(state));
                sysException = true;
                break;
        } // end switch

        ((DistributableTransaction) _transaction).removeAssociation();

        switch (_heuristic)
        {
            case StatefulResource.NONE:
                break;

            default:
//                _transaction.addHeuristic();
                final HeuristicHazardException hh = new HeuristicHazardException();
                if (tc.isEntryEnabled())
                    Tr.exit(tc, "commit_one_phase", hh);
                throw hh;
        }

        if (rolledBack)
        {
            final TRANSACTION_ROLLEDBACK tre = new TRANSACTION_ROLLEDBACK(0, Boolean.TRUE);
            if (tc.isEntryEnabled())
                Tr.exit(tc, "commit_one_phase", tre);
            throw tre;
        }
        else if (sysException)
        {
            final INTERNAL ie = new INTERNAL(MinorCode.LOGIC_ERROR, null);
            if (tc.isEntryEnabled())
                Tr.exit(tc, "commit_one_phase", ie);
            throw ie;
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "commit_one_phase");
    }

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Each column in the series is a dict of dicts

def meta_bar_chart(series=None, N=20):
    ""
    if not series or isinstance(series, basestring):
        series = json.load(load_app_meta)
    if isinstance(series, Mapping) and isinstance(series.values()[0], Mapping):
        rows_received = series['# Received'].items()
    elif isinstance(series, Mapping):
        rows_received = series.items()
    else:
        rows_received = list(series)

    #rows = sorted(rows, key=operator.itemgetter(1), reverse=True)
    rows = sorted(rows_received, key=lambda x: x[1], reverse=True)
    received_names, received_qty = zip(*rows)
    ra_qty = [(series['Qty in RA'].get(name, 0.) or 0.) for name in received_names]
    # percent = [100. - 100. * (num or 0.) / (den or 1.) for num, den in zip(received_qty, ra_qty)]

    # only care about the top 30 model numbers in terms of quantity
    #ind = range(N)

    figs = []

    figs += [plt.figure()]
    ax = figs[-1].add_subplot(111)
    ax.set_ylabel('# Units Returned')
    ax.set_title('Most-Returned LCDTV Models 2013-present')
    x = np.arange(N)
    bars1 = ax.bar(x, received_qty[:N], color='b', width=.4, log=1)
    bars2 = ax.bar(x+.4, ra_qty[:N], color='g', width=.4, log=1)
    ax.set_xticks(range(N))
    ax.set_xticklabels(received_names[:N], rotation=35)
    ax.grid(True)
    ax.legend((bars1[0], bars2[0]), ('# in RA', '# Received'), 'center right')
    figs[-1].show()

def remove_all_for(self, key):

        if not isinstance(key, _string_type):
            raise TypeError("Key need to be a string.")

        for idx in _range(self.__kcount[key]):
            super(VDFDict, self).__delitem__((idx, key))

        self.__omap = list(filter(lambda x: x[1] != key, self.__omap))

        del self.__kcount[key]

Instruction: Given a code description, retrieve the corresponding code.


Question:
Compute the number of characters needed to represent the integer x.

Reimplementation of {@link Long#stringSize}, but public and without loop.

@param x Integer value
@return Number of digits needed

def get(self, field=None, index=None, lpar=0, prompt=1, native=0, mode="h"):
        """"""

        if field: return self._getField(field,native=native,prompt=prompt)

        # may prompt for value if prompt flag is set
        #XXX should change _optionalPrompt so we prompt for each element of
        #XXX the array separately?  I think array parameters are
        #XXX not useful as non-hidden params.

        if prompt: self._optionalPrompt(mode)

        if index is not None:
            sumindex = self._sumindex(index)
            try:
                if native:
                    return self.value[sumindex]
                else:
                    return self.toString(self.value[sumindex])
            except IndexError:
                # should never happen
                raise SyntaxError("Illegal index [" + repr(sumindex) +
                        "] for array parameter " + self.name)
        elif native:
            # return object itself for an array because it is
            # indexable, can have values assigned, etc.
            return self
        else:
            # return blank-separated string of values for array
            return str(self)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Retourne l'instance

@var string $p_name
@var string $p_file

@return \FreeFW\Application\Config

public static function getFactory($p_name, $p_file = null)
    {
        if (self::$factory === null) {
            self::$factory = array();
        }
        if (!array_key_exists($p_name, self::$factory)) {
             self::$factory[$p_name] = new self($p_file);
        }

        return self::$factory[$p_name];
    }

def log(self):
        """"""
        log.info('PyPhi v%s', __about__.__version__)
        if self._loaded_files:
            log.info('Loaded configuration from %s', self._loaded_files)
        else:
            log.info('Using default configuration (no configuration file '
                     'provided)')
        log.info('Current PyPhi configuration:\n %s', str(self))

Instruction: Given a code description, retrieve the corresponding code.


Question: Delete any empty signals for senderkey. Delete senderkey if empty.

def _cleanupConnections(senderkey, signal):
    """"""
    try:
        receivers = connections[senderkey][signal]
    except:
        pass
    else:
        if not receivers:
            # No more connected receivers. Therefore, remove the signal.
            try:
                signals = connections[senderkey]
            except KeyError:
                pass
            else:
                del signals[signal]
                if not signals:
                    # No more signal connections. Therefore, remove the sender.
                    _removeSender(senderkey)

def get_clean_content(self):
        """"""
        fill_chars = {'BLANK_TEMPLATE': ' ', 'ECHO_TEMPLATE': '0'}
        for match in self.pattern.finditer(self.html_content):
            start, end = match.start(), match.end()
            tag = _get_tag(match)
            if tag == 'ECHO':
                self._write_content(start)
                self._index = start
                self._state = 'ECHO_TEMPLATE'
            elif tag == 'START':
                if self._index != start:
                    self._write_content(start)
                self._index = start
                self._state = 'BLANK_TEMPLATE'
            elif tag == 'END':
                if self._state not in ('BLANK_TEMPLATE', 'ECHO_TEMPLATE'):
                    # We got a closing tag but none was open. We decide to carry
                    # on as it may be the case that it was because of a closing
                    # dictionary in javascript like: var dict = {foo:{}}.
                    # See the note on the clean() function for more details.
                    continue
                fill_char = fill_chars[self._state]
                fill = fill_char * (end - self._index)
                if self._state == 'BLANK_TEMPLATE':
                    self._pending.append(fill)
                    self._pending_has_blank = True
                else:
                    assert not self._pending
                    self._output.write(fill)
                self._index = end
                self._state = 'HTML'
            elif tag == 'SPACES':
                self._pending.append(match.group('spaces'))
                self._index = end
            elif tag == 'NEWLINE':
                if self._state == 'HTML':
                    if self._index != start or not self._pending_has_blank:
                        self._write_content(start)
                    self._output.write(match.group('newline'))
                elif self._state == 'BLANK_TEMPLATE':
                    # We discard the content of this template and whatever is in
                    # self._pending.
                    self._output.write(match.group('newline'))
                elif self._state == 'ECHO_TEMPLATE':
                    assert False, 'Echo tags should be in just one line.'
                self._index = end
                self._reset_pending()

        assert self._state == 'HTML', 'Tag was not closed'
        if self._index != len(self.html_content) or not self._pending_has_blank:
            self._write_content()

        return self._output.getvalue()

Instruction: Given a code description, retrieve the corresponding code.


Question:
(PHP 5 >= 5.1.0)
Seeks to a position
@link http://php.net/manual/en/seekableiterator.seek.php
@param int|string $position The position to seek to.
@return void

public function seek($position)
    {
        reset($this->_storage);
        while (($key = key($this->_storage)) !== null && $key !== $position)
        {
            next($this->_storage);
        }
    }

protected function valueAccessor($value, $returnNull = false)
    {
        if (Support::isCallable($value)) {
            return $value;
        }

        return function ($item) use ($value, $returnNull) {
            if (is_null($value)) {
                return $returnNull ? null : $item;
            }
            if (Support::isTraversable($item)) {
                return array_key_exists($value, $item) ? $item[$value] : null;
            }
            if (is_object($item) && isset($item->{$value})) {
                return $item->{$value};
            }
            if (is_object($item) && method_exists($item, $value)) {
                return $item->{$value}();
            }
            if (is_object($item) && method_exists($item, 'get' . ucwords($value))) {
                return $item->{'get' . ucwords($value)}();
            }

            return $returnNull ? null : $item;
        };
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Set the position position

@api
@param float $positionX X position
@param float $positionY Y position
@param float $positionZ (optional) Z position (Z-index)
@return static

public function setPositionPosition($positionX, $positionY, $positionZ = null)
    {
        $this->setPositionProperty($this->positionProperties, $positionX, $positionY, $positionZ);
        return $this;
    }

function parseSetFunction( $funcName, &$args, $tpl, &$text, &$text_len, &$cur_pos,
                               $relatedTemplateName, $startLine, $startColumn, $rootNamespace )
    {
        while ( $cur_pos < $text_len )
        {
            $dollarSignFound = false;

            // skip optional dollar sign
            if ( $text[$cur_pos] == '$' )
            {
                $dollarSignFound = true;
                $cur_pos++;
            }

            // parse variable name
            $wordEndPos = $this->ElementParser->identifierEndPosition( $tpl, $text, $cur_pos, $text_len );
            $varName = substr( $text, $cur_pos, $wordEndPos-$cur_pos );
            $cur_pos = $wordEndPos;

            if ( !$varName )
            {
                $this->showParseErrorMessage( $tpl, $text, $text_len, $cur_pos, $relatedTemplateName, $startLine, $startColumn,
                                              $funcName, 'Empty variable name' );
                return;
            }

            /*
             * If parameter 'name' or 'scope' was passed without dollar sign
             * change its name to '-name' or '-scope', respectively.
             * In this case it is treated specially in the {set}/{let}/{default} functions.
             */
            if ( !$dollarSignFound && ( $varName == 'name' || $varName == 'scope' ) )
                $varName = "-$varName";

            // skip whitespaces
            $cur_pos = $this->ElementParser->whitespaceEndPos( $tpl, $text, $cur_pos, $text_len );

            // if no value, assume boolean true
            if ( $cur_pos >= $text_len or
                 ( $text[$cur_pos] != '=' /*and preg_match( "/[ \t\r\n]/", $text[$cur_pos] )*/ ) )
            {
                unset( $var_data );
                $var_data = array();
                $args[$varName] = array( array( eZTemplate::TYPE_NUMERIC, // type
                                                true, // content
                                                false // debug
                                                ) );
                continue;
            }

            if ( $cur_pos >= $text_len )
                break;

            $cur_pos++;

            // skip whitespaces
            $cur_pos = $this->ElementParser->whitespaceEndPos( $tpl, $text, $cur_pos, $text_len );

            $args[$varName] = $this->ElementParser->parseVariableTag( $tpl, $relatedTemplateName, $text, $cur_pos, $cur_pos, $text_len, $rootNamespace );

            // skip whitespaces
            $cur_pos = $this->ElementParser->whitespaceEndPos( $tpl, $text, $cur_pos, $text_len );
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// PostRaw starts a collector job by creating a POST request with raw binary data.
// Post also calls the previously provided callbacks

func (c *Collector) PostRaw(URL string, requestData []byte) error {
	return c.scrape(URL, "POST", 1, bytes.NewReader(requestData), nil, nil, true)
}

def set_args(self, args, unknown_args=None):

        if unknown_args is None:
            unknown_args = []
        self.logger.setLevel(getattr(logging, args.log_level))

        parent = hdfs.path.dirname(hdfs.path.abspath(args.output.rstrip("/")))
        self.remote_wd = hdfs.path.join(
            parent, utils.make_random_str(prefix="pydoop_submit_")
        )
        self.remote_exe = hdfs.path.join(self.remote_wd, str(uuid.uuid4()))
        self.properties[JOB_NAME] = args.job_name or 'pydoop'
        self.properties[IS_JAVA_RR] = (
            'false' if args.do_not_use_java_record_reader else 'true'
        )
        self.properties[IS_JAVA_RW] = (
            'false' if args.do_not_use_java_record_writer else 'true'
        )
        self.properties[JOB_REDUCES] = args.num_reducers
        if args.job_name:
            self.properties[JOB_NAME] = args.job_name
        self.properties.update(args.job_conf or {})
        self.__set_files_to_cache(args)
        self.__set_archives_to_cache(args)
        self.requested_env = self._env_arg_to_dict(args.set_env or [])
        self.args = args
        self.unknown_args = unknown_args

Instruction: Given a code description, retrieve the corresponding code.


Question:
Print formatted search results.

        Args:
            search_results (list of `ResourceSearchResult`): Search to format.

def print_search_results(self, search_results, buf=sys.stdout):

        formatted_lines = self.format_search_results(search_results)
        pr = Printer(buf)

        for txt, style in formatted_lines:
            pr(txt, style)

def prepare_sorting_fields(self):

        if self.sorting_parameter_name in self.request.query_params:
            # Extract sorting parameter from query string
            self._sorting_fields = [
                _.strip() for _ in self.request.query_params.get(self.sorting_parameter_name).split(',')
            ]

        if self._sorting_fields:
            # Create a list of sorting parameters. Each parameter is a tuple: (field:str, descending:bool)
            self._sorting_fields = [
                (self.sorting_fields_map.get(field.lstrip('-'), field.lstrip('-')), field[0] == '-')
                for field in self._sorting_fields
            ]

Instruction: Given a code description, retrieve the corresponding code.


Question:
Runs this server. There is typically no need to call this method, as the object's constructor
creates a new thread and runs this object automatically.

public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(url.getPort());
            while (true) {
                // Create one script per socket connection.
                // This is purposefully not caching the Script
                // so that the script source file can be changed on the fly,
                // as each connection is made to the server.
                //FIXME: Groovy has other mechanisms specifically for watching to see if source code changes.
                // We should probably be using that here.
                // See also the comment about the fact we recompile a script that can't change.
                Script script = groovy.parse(source);
                new GroovyClientConnection(script, autoOutput, serverSocket.accept());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

public function add($job, array $config)
    {
        if (empty($config['schedule'])) {
            throw new Exception("'schedule' is required for '$job' job");
        }

        if (!(isset($config['command']) xor isset($config['closure']))) {
            throw new Exception("Either 'command' or 'closure' is required for '$job' job");
        }

        if (isset($config['command']) &&
            (
                $config['command'] instanceof Closure ||
                $config['command'] instanceof SerializableClosure
            )
        ) {
            $config['closure'] = $config['command'];
            unset($config['command']);

            if ($config['closure'] instanceof SerializableClosure) {
                $config['closure'] = $config['closure']->getClosure();
            }
        }

        $config = array_merge($this->config, $config);
        $this->jobs[$job] = $config;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Extension dependencies

private <T> List<Object> getDependencies(T extension) {
    return new ArrayList<>(evaluateAnnotatedClasses(extension, DependsUpon.class));
  }

public SimpleDependencyPath copy() {
        SimpleDependencyPath copy = new SimpleDependencyPath();
        copy.path.addAll(path);
        copy.nodes.addAll(nodes);
        return copy;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// newTimedStatusUpdater returns a function which waits a given period of time
// before querying the apiserver for updated data.

func newTimedStatusUpdater(ctx *cmd.Context, api destroyControllerAPI, controllerModelUUID string, clock clock.Clock) func(time.Duration) environmentStatus {
	return func(wait time.Duration) environmentStatus {
		if wait > 0 {
			<-clock.After(wait)
		}

		// If we hit an error, status.HostedModelCount will be 0, the polling
		// loop will stop and we'll go directly to destroying the model.
		ctrStatus, modelsStatus, err := newData(api, controllerModelUUID)
		if err != nil {
			ctx.Infof("Unable to get the controller summary from the API: %s.", err)
		}

		return environmentStatus{
			controller: ctrStatus,
			models:     modelsStatus,
		}
	}
}

func (c *Client) Status(patterns []string) (*params.FullStatus, error) {
	var result params.FullStatus
	p := params.StatusParams{Patterns: patterns}
	if err := c.facade.FacadeCall("FullStatus", p, &result); err != nil {
		return nil, err
	}
	// Older servers don't fill out model type, but
	// we know a missing type is an "iaas" model.
	if result.Model.Type == "" {
		result.Model.Type = model.IAAS.String()
	}
	return &result, nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Store an instance for injection by class name or alias.

@param string $name Class name or alias
@param object $instance

@return Manager

public function set($name, $instance)
    {
        $key = $this->makeKey($name);

        $this->alias($name, $this->describe(get_class($instance)));

        $this->instances[$key] = $instance;

        return $this;
    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Retrieve the models primary field for display purposes.

@param            $item   Model to retrieve primary field of
@param null|array $config CrudApi Configuration

@return string

public function getPrimaryField($item, $config = null)
    {
        /* If config is not overridden then load crudapi config */
        if ($config === null) {
            $config = config('crudapi');
        }
        if (!isset($config['models']['fields']['default'])) {
            $defaultField = 'name';
        } else {
            $defaultField = $config['models']['fields']['default'];
        }

        /* Get the items Class */
        $class = get_class($item);

        $stripped_class = str_replace($this->crudApi->namespace, '', $class);
        // if class starts with a \ remove it.
        if (substr($stripped_class, 0, 1) == '\\') {
            $stripped_class = substr($stripped_class, 1);
        }

        $primaryFields = $config['models']['fields']['primary'];

        if (array_key_exists($stripped_class, $primaryFields)) {
            return $primaryFields[$stripped_class];
        } else {
            //return the default
            return $defaultField;
        }
    }

public function populateUpdateFields($data) {

        $data['id']                 = $this->request->input('id');
        $data['user_id']            = $this->request->input('user_id');
        $data['priority_id']        = $this->request->input('priority_id');

        if (isset($data['from_email_address'])) {
            $data['from_email_address'] = $this->request->input('from_email_address');
        }

        if (isset($data['from_name'])) {
            $data['from_name']          = $this->request->input('from_name');
        }

        if (isset($data['to_email_address'])) {
            $data['to_email_address']   = $this->request->input('to_email_address');
        }

        if (isset($data['to_name'] )) {
            $data['to_name']            = $this->request->input('to_name');
        }

        $data['priority_id']        = $this->request->input('priority_id');
        $data['archived']           = $this->request->input('archived');
        $data['updated_at']         = Carbon::now();
        $data['updated_by']         = Auth::user()->id;

        return $data;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Use this API to fetch appfwsignatures resource of given name .

public static appfwsignatures get(nitro_service service, String name) throws Exception{
		appfwsignatures obj = new appfwsignatures();
		obj.set_name(name);
		appfwsignatures response = (appfwsignatures) obj.get_resource(service);
		return response;
	}

private <TResponse> TResponse callServiceGetApi(
            String path, Map<String, String> queryParams,
            Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callGetApi(mServiceCredentials, path, queryParams, responseClass);
    }

Instruction: Given a code description, retrieve the corresponding code.