Question:
Implementation of comparable interface, sorting by first then second.

@param other Object to compare to
@return comparison result

@Override
  public int compareTo(DoubleIntPair other) {
    int fdiff = Double.compare(this.first, other.first);
    if(fdiff != 0) {
      return fdiff;
    }
    return this.second - other.second;
  }

static boolean pointRelatePoint_(Point point_a, Point point_b,
			double tolerance, String scl, ProgressTracker progress_tracker) {
		Point2D pt_a = point_a.getXY();
		Point2D pt_b = point_b.getXY();
		int[] matrix = new int[9];

		for (int i = 0; i < 9; i++)
			matrix[i] = -1;

		if (Point2D.sqrDistance(pt_a, pt_b) <= tolerance * tolerance) {
			matrix[MatrixPredicate.InteriorInterior] = 0;
		} else {
			matrix[MatrixPredicate.InteriorExterior] = 0;
			matrix[MatrixPredicate.ExteriorInterior] = 0;
		}

		matrix[MatrixPredicate.ExteriorExterior] = 2;

		boolean bRelation = relationCompare_(matrix, scl);
		return bRelation;
	}

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


Question:
Start packet groups on ports.

        :param clear_time_stamps: True - clear time stamps, False - don't.
        :param ports: list of ports to start traffic on, if empty start on all ports.

def start_packet_groups(self, clear_time_stamps=True, *ports):

        port_list = self.set_ports_list(*ports)
        if clear_time_stamps:
            self.api.call_rc('ixClearTimeStamp {}'.format(port_list))
        self.api.call_rc('ixStartPacketGroups {}'.format(port_list))

private function load_command_config_file($file, $prefix) {

    $yaml = $this->sm->get('pegase.component.yaml.spyc');
    $data = $yaml->parse($file);
    $mm = $this->sm->get('pegase.core.module_manager');

    foreach($data as $command_name => $command) {

      if(key_exists('prefix', $command)) {
        $prefix_to_add = $command['prefix'];
      }
      else
        $prefix_to_add = $command_name;

      if(key_exists('class', $command) && key_exists('method', $command)) {

        if(!key_exists('parameters', $command))
          $command['parameters'] = null;

        if(!key_exists('options', $command))
          $command['options'] = null;

        $this->add_command(array(
          'name' => $prefix . $prefix_to_add,
          'class' => $command['class'],
          'method' => $command['method'],
          'parameters' => $command['parameters'],
          'options' => $command['options']
        ));
      }
      else if(key_exists('import', $command)) {
        $this->load_command_config_file(
          $mm->get_file($command['import']['module'], $command['import']['file']),
          $prefix . $prefix_to_add);
      }
    }
  }

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


Question: // introspect is useful for finding out what calls are going to be made in the batched call

func (ctx *BatchedContext) introspect() string {
	var buf bytes.Buffer
	fmt.Fprintf(&buf, "Queue: %d", len(ctx.queue))
	for _, v := range ctx.queue {
		fmt.Fprintf(&buf, "\n\t[QUEUE] %s", v.fnargs)
	}
	return buf.String()
}

def run_iteration(self):
        '''
        '''

        self._employer_phase()
        self._calc_probability()
        self._onlooker_phase()
        self._check_positions()

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


Question: Fetch assets contents at `path`, may be either url or location on disk.  If path is not absolute it will be interpreted relative to `root` (`root` will either be a working directory or a url base).  Should resolve to a buffer in all cases

function(path, root) {
  return new P(function(resolve, reject) {
    if(isRelativePath(path)) {
      path = isUrl(root) ?
        url.resolve(root, path) :
        join(root, path);
    }

    if(isUrl(path)) {
      request.get(path, {encoding: null}, function(err, response, body) {
        if(err) { return reject(err); }
        return response.statusCode === 200 ?
          resolve(body) :
          reject(new Error('Got status ' + response.statusCode + ' fetching ' + path));
      });
    } else {
      fs.readFile(path, function(err, body) {
        return err ?
          reject(err) :
          resolve(body);
      });
    }
  });
}

def greedy_replace(self, seq):
        '''

        '''
        if not self._suffix_links_set:
            self._set_suffix_links()
        # start at the root
        current = self.root
        buffered = ''
        outstr = ''
        for char in seq:
            while char not in current:
                if current.has_dict_suffix:
                    current = current.dict_suffix
                    outstr += buffered[:-current.depth]
                    outstr += current.value
                    buffered = ''
                    current = self.root
                    break
                elif current.has_suffix:
                    current = current.suffix
                    if current.depth:
                        outstr += buffered[:-current.depth]
                        buffered = buffered[-current.depth:]
                    else:
                        outstr += buffered
                        buffered = ''
                        break
                else:
                    current = self.root
                    outstr += buffered
                    buffered = ''
                    break
            if char in current:
                buffered += char
                current = current[char]
                if current.has_value:
                    outstr += buffered[:-current.depth]
                    outstr += current.value
                    buffered = ''
                    current = self.root
            else:
                assert current is self.root
                outstr += buffered + char
                buffered = ''
        if current.has_dict_suffix:
            current = current.dict_suffix
            outstr += buffered[:-current.depth]
            outstr += current.value
        else:
            outstr += buffered
        return outstr

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


Question:
Defines if the visualization of the gauge value should be visible.

@param VISIBLE

public void setValueVisible(final boolean VISIBLE) {
        if (null == valueVisible) {
            _valueVisible = VISIBLE;
            fireTileEvent(VISIBILITY_EVENT);
        } else {
            valueVisible.set(VISIBLE);
        }
    }

def _monitoring_metrics_list(args, _):
  """"""
  project_id = args['project']
  pattern = args['type'] or '*'
  descriptors = gcm.MetricDescriptors(context=_make_context(project_id))
  dataframe = descriptors.as_dataframe(pattern=pattern)
  return _render_dataframe(dataframe)

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


Question:
Creates an error message for a not found exception.

@param string $baseMessage The base error message
@param string $path        The requested path
@param array  $parameters  The query parameters (if defined)

@return string

public static function createErrorMessage(string $baseMessage, string $path = null, array $parameters = []): string
    {
        $errorMessage = $baseMessage;
        if ($path !== null) {
            $errorMessage .= sprintf(
                static::PATH_MESSAGE,
                $path,
                \GuzzleHttp\Psr7\build_query($parameters)
            );
        }
        return $errorMessage;
    }

public function err($text = '', $nl = true)
	{
		fwrite(STDERR, $this->processor->process($text) . ($nl ? "\n" : null));

		return $this;
	}

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


Question:
Returns the absolute value of the element in the matrix that has the largest absolute value.

Max{ |aij| } for all i and j

@param a A matrix. Not modified.
@return The max abs element value of the matrix.

public static double elementMaxAbs( DMatrix2x2 a ) {
        double max = Math.abs(a.a11);
        double tmp = Math.abs(a.a12); if( tmp > max ) max = tmp;
        tmp = Math.abs(a.a21); if( tmp > max ) max = tmp;
        tmp = Math.abs(a.a22); if( tmp > max ) max = tmp;

        return max;
    }

def __get_max_min_time_1(self, table):

        try:
            # find the values and units we need to calculate
            vals, units = self.__get_max_min_time_2(table, ["age", "yearbp", "yrbp"], True)

            if not vals and not units:
                vals, units = self.__get_max_min_time_2(table, ["year", "yr"], True)

            if not vals and not units:
                vals, units = self.__get_max_min_time_2(table, ["age", "yearbp", "yrbp"], False)

            if not vals and not units:
                vals, units = self.__get_max_min_time_2(table, ["year", "yr"], False)

            # now put this data into the noaa data sorted self for writing to file.
            # year farthest in the past
            _max = max(vals)
            _min = min(vals)
            if _min or _min in [0, 0.0]:
                self.noaa_data_sorted["Data_Collection"]["Earliest_Year"] = str(_min)
            if _max or _max in [0, 0.0]:
                self.noaa_data_sorted["Data_Collection"]["Most_Recent_Year"] = str(_max)
            # AD or... yrs BP?
            self.noaa_data_sorted["Data_Collection"]["Time_Unit"] = units

        except Exception as e:
            logger_lpd_noaa.debug("get_max_min_time_2: {}".format(e))

        return

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


Question: Support full-text-search

function enableSearch() {
    var query;
    var relHref = $("meta[property='docfx\\:rel']").attr("content");
    if (typeof relHref === 'undefined') {
      return;
    }
    try {
      var worker = new Worker(relHref + 'styles/search-worker.js');
      if (!worker && !window.worker) {
        localSearch();
      } else {
        webWorkerSearch();
      }

      renderSearchBox();
      highlightKeywords();
      addSearchEvent();
    } catch (e) {
      console.error(e);
    }

    //Adjust the position of search box in navbar
    function renderSearchBox() {
      autoCollapse();
      $(window).on('resize', autoCollapse);
      $(document).on('click', '.navbar-collapse.in', function (e) {
        if ($(e.target).is('a')) {
          $(this).collapse('hide');
        }
      });

      function autoCollapse() {
        var navbar = $('#autocollapse');
        if (navbar.height() === null) {
          setTimeout(autoCollapse, 300);
        }
        navbar.removeClass(collapsed);
        if (navbar.height() > 60) {
          navbar.addClass(collapsed);
        }
      }
    }

    // Search factory
    function localSearch() {
      console.log("using local search");
      var lunrIndex = lunr(function () {
        this.ref('href');
        this.field('title', { boost: 50 });
        this.field('keywords', { boost: 20 });
      });
      lunr.tokenizer.seperator = /[\s\-\.]+/;
      var searchData = {};
      var searchDataRequest = new XMLHttpRequest();

      var indexPath = relHref + "index.json";
      if (indexPath) {
        searchDataRequest.open('GET', indexPath);
        searchDataRequest.onload = function () {
          if (this.status != 200) {
            return;
          }
          searchData = JSON.parse(this.responseText);
          for (var prop in searchData) {
            if (searchData.hasOwnProperty(prop)){
              lunrIndex.add(searchData[prop]);
            }
          }
        }
        searchDataRequest.send();
      }

      $("body").bind("queryReady", function () {
        var hits = lunrIndex.search(query);
        var results = [];
        hits.forEach(function (hit) {
          var item = searchData[hit.ref];
          results.push({ 'href': item.href, 'title': item.title, 'keywords': item.keywords });
        });
        handleSearchResults(results);
      });
    }

    function webWorkerSearch() {
      console.log("using Web Worker");
      var indexReady = $.Deferred();

      worker.onmessage = function (oEvent) {
        switch (oEvent.data.e) {
          case 'index-ready':
            indexReady.resolve();
            break;
          case 'query-ready':
            var hits = oEvent.data.d;
            handleSearchResults(hits);
            break;
        }
      }

      indexReady.promise().done(function () {
        $("body").bind("queryReady", function () {
          worker.postMessage({ q: query });
        });
      });
    }

    // Highlight the searching keywords
    function highlightKeywords() {
      var q = url('?q');
      if (q !== null) {
        var keywords = q.split("%20");
        keywords.forEach(function (keyword) {
          if (keyword !== "") {
            $('.data-searchable *').mark(keyword);
            $('article *').mark(keyword);
          }
        });
      }
    }

    function addSearchEvent() {
      $('body').bind("searchEvent", function () {
        $('#search-query').keypress(function (e) {
          return e.which !== 13;
        });

        $('#search-query').keyup(function () {
          query = $(this).val();
          if (query.length < 3) {
            flipContents("show");
          } else {
            flipContents("hide");
            $("body").trigger("queryReady");
            $('#search-results>.search-list').text('Search Results for "' + query + '"');
          }
        }).off("keydown");
      });
    }

    function flipContents(action) {
      if (action === "show") {
        $('.hide-when-search').show();
        $('#search-results').hide();
      } else {
        $('.hide-when-search').hide();
        $('#search-results').show();
      }
    }

    function relativeUrlToAbsoluteUrl(currentUrl, relativeUrl) {
      var currentItems = currentUrl.split(/\/+/);
      var relativeItems = relativeUrl.split(/\/+/);
      var depth = currentItems.length - 1;
      var items = [];
      for (var i = 0; i < relativeItems.length; i++) {
        if (relativeItems[i] === '..') {
          depth--;
        } else if (relativeItems[i] !== '.') {
          items.push(relativeItems[i]);
        }
      }
      return currentItems.slice(0, depth).concat(items).join('/');
    }

    function extractContentBrief(content) {
      var briefOffset = 512;
      var words = query.split(/\s+/g);
      var queryIndex = content.indexOf(words[0]);
      var briefContent;
      if (queryIndex > briefOffset) {
        return "..." + content.slice(queryIndex - briefOffset, queryIndex + briefOffset) + "...";
      } else if (queryIndex <= briefOffset) {
        return content.slice(0, queryIndex + briefOffset) + "...";
      }
    }

    function handleSearchResults(hits) {
      var numPerPage = 10;
      $('#pagination').empty();
      $('#pagination').removeData("twbs-pagination");
      if (hits.length === 0) {
        $('#search-results>.sr-items').html('
No results found
');
      } else {
        $('#pagination').twbsPagination({
          totalPages: Math.ceil(hits.length / numPerPage),
          visiblePages: 5,
          onPageClick: function (event, page) {
            var start = (page - 1) * numPerPage;
            var curHits = hits.slice(start, start + numPerPage);
            $('#search-results>.sr-items').empty().append(
              curHits.map(function (hit) {
                var currentUrl = window.location.href;
                var itemRawHref = relativeUrlToAbsoluteUrl(currentUrl, relHref + hit.href);
                var itemHref = relHref + hit.href + "?q=" + query;
                var itemTitle = hit.title;
                var itemBrief = extractContentBrief(hit.keywords);

                var itemNode = $('
').attr('class', 'sr-item');
                var itemTitleNode = $('
').attr('class', 'item-title').append($('').attr('href', itemHref).attr("target", "_blank").text(itemTitle));
                var itemHrefNode = $('
').attr('class', 'item-href').text(itemRawHref);
                var itemBriefNode = $('
').attr('class', 'item-brief').text(itemBrief);
                itemNode.append(itemTitleNode).append(itemHrefNode).append(itemBriefNode);
                return itemNode;
              })
            );
            query.split(/\s+/).forEach(function (word) {
              if (word !== '') {
                $('#search-results>.sr-items *').mark(word);
              }
            });
          }
        });
      }
    }
  }

public boolean matchKeyword(String keyword) {
		return tok.ttype == StreamTokenizer.TT_WORD && tok.sval.equals(keyword)
				&& keywords.contains(tok.sval);
	}

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


Question:
Gets an existing NamedAdminObjectServiceInfo with the specified id, or
creates one and inserts it into {@link #adminObjectServices}.

<p>Caller must hold a lock on this object.

private NamedAdminObjectServiceInfo createNamedAdminObjectServiceInfo(String id) {
        NamedAdminObjectServiceInfo aosInfo = adminObjectServices.get(id);
        if (aosInfo == null) {
            aosInfo = new NamedAdminObjectServiceInfo(id,
                            new ConcurrentServiceReferenceSet<AdminObjectService>(REFERENCE_ADMIN_OBJECT_SERVICES),
                            new ConcurrentServiceReferenceSet<AdminObjectService>(REFERENCE_ADMIN_OBJECT_SERVICES));
            adminObjectServices.put(id, aosInfo);
        }
        return aosInfo;
    }

private void unlock(Object holder) throws PSQLException {
    if (lockedFor != holder) {
      throw new PSQLException(GT.tr("Tried to break lock on database connection"),
          PSQLState.OBJECT_NOT_IN_STATE);
    }
    lockedFor = null;
    this.notify();
  }

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


Question:
Disable processing of requests on all other client connections
        until the server is ungrabbed. Server grabbing should be avoided
        as much as possible.

def grab_server(self, onerror = None):
        """"""
        request.GrabServer(display = self.display,
                           onerror = onerror)

func ServeListener(listener net.Listener) {
	DefaultMux.Compile()
	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", DefaultMux)

	log.Println("Starting Goji on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() { log.Printf("Goji received signal, gracefully stopping") })
	graceful.PostHook(func() { log.Printf("Goji stopped") })

	err := graceful.Serve(listener, http.DefaultServeMux)

	if err != nil {
		log.Fatal(err)
	}

	graceful.Wait()
}

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


Question:
Run clustering iterations until a
termination condition is hit.
This is done by first classifying all points,
and then updating cluster centers based on
those classified points

private void iterations() {
        int iterationCount = 0;
        while ((clusteringStrategy.getTerminationCondition() != null
                        && !clusteringStrategy.getTerminationCondition().isSatisfied(iterationHistory))
                        || iterationHistory.getMostRecentIterationInfo().isStrategyApplied()) {
            currentIteration++;
            removePoints();
            classifyPoints();
            applyClusteringStrategy();
            log.trace("Completed clustering iteration {}", ++iterationCount);
        }
    }

def _render_dendrogram(dnd, ax, displacement):
    ''''''
    # set of unique colors that reflect the set of types of the neurites
    colors = set()

    for n, (indices, ctype) in enumerate(zip(dnd.groups, dnd.types)):

        # slice rectangles array for the current neurite
        group = dnd.data[indices[0]:indices[1]]

        if n > 0:
            # displace the neurites by half of their maximum x dimension
            # plus half of the previous neurite's maxmimum x dimension
            displacement += 0.5 * (dnd.dims[n - 1][0] + dnd.dims[n][0])

        # arrange the trees without overlapping with each other
        group += (displacement, 0.)

        # create the polygonal collection of the dendrogram
        # segments
        _generate_collection(group, ax, ctype, colors)

    soma_square = dnd.soma

    if soma_square is not None:

        _generate_collection((soma_square + (displacement / 2., 0.),), ax, NeuriteType.soma, colors)
        ax.plot((displacement / 2., displacement), (0., 0.), color='k')
        ax.plot((0., displacement / 2.), (0., 0.), color='k')

    return displacement

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


Question:
Load a resource by resourceId.

@param serializerId
the serializer id
@param artifactSerializers
the serializers in which to put the resource
@param resourcePath
the canonical path of the resource
@param resources
the map in which to put the resource

public static void loadResource(final String serializerId,
      @SuppressWarnings("rawtypes") final Map<String, ArtifactSerializer> artifactSerializers,
      final String resourcePath, final Map<String, Object> resources) {

    final File resourceFile = new File(resourcePath);
    if (resourceFile != null) {
      final String resourceId = IOUtils
          .normalizeLexiconName(resourceFile.getName());
      final ArtifactSerializer<?> serializer = artifactSerializers
          .get(serializerId);
      final InputStream resourceIn = IOUtils.openFromFile(resourceFile);
      try {
        resources.put(resourceId, serializer.create(resourceIn));
      } catch (final InvalidFormatException e) {
        e.printStackTrace();
      } catch (final IOException e) {
        e.printStackTrace();
      } finally {
        try {
          resourceIn.close();
        } catch (final IOException e) {
        }
      }
    }
  }

def list_migration_issues_courses(self, course_id, content_migration_id):

        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - PATH - content_migration_id
        """ID"""
        path["content_migration_id"] = content_migration_id

        self.logger.debug("GET /api/v1/courses/{course_id}/content_migrations/{content_migration_id}/migration_issues with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/content_migrations/{content_migration_id}/migration_issues".format(**path), data=data, params=params, all_pages=True)

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


Question: // ByPosition returns the Comparator at the given position.

func (sl *SkipList) ByPosition(position uint64) common.Comparator {
	n, _ := sl.searchByPosition(position+1, nil, nil)
	if n == nil {
		return nil
	}

	return n.entry
}

func RegisterDAO(priority int, condition func() bool, dao DAO) {
	registered = append(registered, registeredDAO{dao, condition, priority})
	sort.Sort(registered)
}

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


Question:
@param int                  $id
@param Request              $request

@return Response

@throws EntityNotFoundException

public function editAction($id, Request $request)
    {
        $contentType = $this->contentTypeManager->getContentTypeById($id);

        if ($contentType === null) {
            throw EntityNotFoundException::fromClassNameAndIdentifier(
                $this->configurationManager->getEntityClass('content_type'),
                [$id]
            );
        }

        $fieldTypes = [];
        foreach ($contentType->getFields() as $field) {
            $fieldTypes[$field->getId()] = $field->getType();
        }

        $form = $this->createForm(ContentTypeFormType::class, $contentType, [
            'action' => $this->generateUrl('sherlockode_acb_content_type_edit', ['id' => $contentType->getId()]),
            'attr' => [
                'data-change-type-url' => $this->generateUrl('sherlockode_acb_content_type_change_field_type'),
                'class' => 'edit-content-type'
            ],
            'contentType' => $contentType,
        ]);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->contentTypeManager->processFieldsChangeType($contentType, $fieldTypes);
            $this->om->flush();

            return $this->redirectToRoute('sherlockode_acb_content_type_edit', ['id' => $contentType->getId()]);
        }

        return $this->render('@SherlockodeAdvancedContent/ContentType/edit_content_type.html.twig', [
            'form' => $form->createView(),
            'data' => $contentType,
        ]);
    }

public void logMessageForTask(String taskId, String logMessage) {
        Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank");
        postForEntityWithRequestOnly("tasks/" + taskId + "/log", logMessage);
    }

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


Question: // SetLastDeploymentTime sets the LastDeploymentTime field's value.

func (s *Robot) SetLastDeploymentTime(v time.Time) *Robot {
	s.LastDeploymentTime = &v
	return s
}

public void marshall(CreateDeploymentRequest createDeploymentRequest, ProtocolMarshaller protocolMarshaller) {

        if (createDeploymentRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(createDeploymentRequest.getStackId(), STACKID_BINDING);
            protocolMarshaller.marshall(createDeploymentRequest.getAppId(), APPID_BINDING);
            protocolMarshaller.marshall(createDeploymentRequest.getInstanceIds(), INSTANCEIDS_BINDING);
            protocolMarshaller.marshall(createDeploymentRequest.getLayerIds(), LAYERIDS_BINDING);
            protocolMarshaller.marshall(createDeploymentRequest.getCommand(), COMMAND_BINDING);
            protocolMarshaller.marshall(createDeploymentRequest.getComment(), COMMENT_BINDING);
            protocolMarshaller.marshall(createDeploymentRequest.getCustomJson(), CUSTOMJSON_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Create service

@param ServiceLocatorInterface $serviceLocator
@return mixed

public function createService(ServiceLocatorInterface $serviceLocator)
    {

        $authService = $serviceLocator->get('zfcuser_auth_service');
        $config = $serviceLocator->get('ZfcUserLdap\Config');

        $provider = new ZfcRbacIdentityProvider($authService, $config);
        return $provider;
    }

func ResourceLocation(getter ResourceGetter, rt http.RoundTripper, ctx context.Context, id string) (*url.URL, http.RoundTripper, error) {
	// Allow ID as "podname" or "podname:port" or "scheme:podname:port".
	// If port is not specified, try to use the first defined port on the pod.
	scheme, name, port, valid := utilnet.SplitSchemeNamePort(id)
	if !valid {
		return nil, nil, errors.NewBadRequest(fmt.Sprintf("invalid pod request %q", id))
	}
	// TODO: if port is not a number but a "(container)/(portname)", do a name lookup.

	pod, err := getPod(getter, ctx, name)
	if err != nil {
		return nil, nil, err
	}

	// Try to figure out a port.
	if port == "" {
		for i := range pod.Spec.Containers {
			if len(pod.Spec.Containers[i].Ports) > 0 {
				port = fmt.Sprintf("%d", pod.Spec.Containers[i].Ports[0].ContainerPort)
				break
			}
		}
	}

	if err := proxyutil.IsProxyableIP(pod.Status.PodIP); err != nil {
		return nil, nil, errors.NewBadRequest(err.Error())
	}

	loc := &url.URL{
		Scheme: scheme,
	}
	if port == "" {
		loc.Host = pod.Status.PodIP
	} else {
		loc.Host = net.JoinHostPort(pod.Status.PodIP, port)
	}
	return loc, rt, nil
}

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


Question: Clears the state, starts clock

def _clear_state(self, seed=None):
        """"""
        self.start_time = time()
        self.run_stats = []
        self.best_index = -1
        self.best_score = -1
        self.best_config = None

        # Note: These must be set at the start of self.search()
        self.search_space = None

        # Reset the seed
        if seed is not None:
            self.rng = random.Random(seed)

def reset(self):

        self.counter += 1
        local_counter = self.counter

        def timer_timeout():
            if self.counter == local_counter and self.running:
                self.callback()

        self.loop.call_later(self.timeout, timer_timeout)

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


Question:
Bu _kul_id kullanıcısından _tahta_id tahtasında _rol_id rolünü siler
@param {integer} _kul_id
@param {integer} _tahta_id
@param {integer} _rol_id
@returns {Promise}

function f_rol_sil_kullanici(_kul_id, _tahta_id, _rol_id) {
        if (_rol_id) {
            return result.dbQ.hget_json_parse(result.kp.tahta.hsUyeleri(_tahta_id), _kul_id)
                .then(function (_arrUyeRolId) {
                    // tek bir sayı ya da bir dizi gelebilir ve biz diziyle yola devam etmek için concat yapıyoruz
                    _arrUyeRolId = [].concat(_arrUyeRolId);
                    var idxOfRolId = _arrUyeRolId.indexOf(_rol_id);
                    l.info("idxOfRolId>" + idxOfRolId);

                    if (idxOfRolId == -1) {
                        return 0;
                    } else {
                        _arrUyeRolId.splice(idxOfRolId, 1);
                        return result.dbQ.hset(result.kp.tahta.hsUyeleri(_tahta_id), _kul_id, JSON.stringify(_arrUyeRolId));
                    }
                });
        } else {
            l.warning("Silinecek aktif bir rol bulunamadı");
        }
    }

function unexpectedTokenError(token, message) {
        var value, msg = message || Messages.UnexpectedToken;

        if (token) {
            if (!message) {
                msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
                    (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
                    (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
                    (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
                    (token.type === Token.Template) ? Messages.UnexpectedTemplate :
                    Messages.UnexpectedToken;

                if (token.type === Token.Keyword) {
                    if (isFutureReservedWord(token.value)) {
                        msg = Messages.UnexpectedReserved;
                    } else if (strict && isStrictModeReservedWord(token.value)) {
                        msg = Messages.StrictReservedWord;
                    }
                }
            }

            value = (token.type === Token.Template) ? token.value.raw : token.value;
        } else {
            value = 'ILLEGAL';
        }

        msg = msg.replace('%0', value);

        return (token && typeof token.lineNumber === 'number') ?
            createError(token.lineNumber, token.start, msg) :
            createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
    }

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


Question: Will only return either tokens with type PREDEFINED or UNDEFINED

@Override
	public List<Token> tokenize(String s) {
		List<Token> result = new ArrayList<Token>();
		result.add(new UndefinedToken(s));

		for (PredefinedTokenDefinition predefinedTokenDefinition : _predefinedTokenDefitions) {
			Set<Pattern> patterns = predefinedTokenDefinition.getTokenRegexPatterns();
			for (Pattern pattern : patterns) {
				for (ListIterator<Token> it = result.listIterator(); it.hasNext();) {
					Token token = it.next();
					if (token instanceof UndefinedToken) {
						List<Token> replacementTokens = tokenizeInternal(token.getString(), predefinedTokenDefinition,
								pattern);
						if (replacementTokens.size() > 1) {
							it.remove();
							for (Token newToken : replacementTokens) {
								it.add(newToken);
							}
						}
					}
				}
			}
		}

		return result;
	}

public function getToken(IHttpHeaders $headers) {
        $header = $this->getHeader($headers);

        return $this->parseHeader($header);
    }

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


Question:
{@inheritDoc}

@since 0.8.1

@Override
    public Connection getConnection(String dsName, boolean startTransaction) {
        return jdbcHelper.getConnection(dsName, startTransaction);
    }

def inject_solr_document_behavior
      file_path = 'app/models/solr_document.rb'
      if File.exist?(file_path)
        inject_into_file file_path, after: /include Blacklight::Solr::Document.*$/ do
          "\n  # Adds GeoWorks behaviors to the SolrDocument.\n" \
            "  include GeoWorks::SolrDocumentBehavior\n"
        end
      else
        Rails.logger.info "     \e[31mFailure\e[0m  GeoWorks requires a SolrDocument object. This generators assumes that the model is defined in the file #{file_path}, which does not exist."
      end
    end

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


Question: On backspace keypress, checks if there are a pair of brackets or quotation marks to be deleted

function() {
			var editor = this.editor;
			var textView = editor.getTextView();
			if (textView.getOptions("readonly")) { return false; } //$NON-NLS-0$
			var model = editor.getModel();
			forEachSelection(this, false, function(selection, setText) {
				if (selection.start !== selection.end) { return; }

				var prevChar = (selection.start === 0) ? "" : model.getText(selection.start - 1, selection.start); //$NON-NLS-0$
				var nextChar = (selection.start === model.getCharCount()) ? "" : model.getText(selection.start, selection.start + 1); //$NON-NLS-0$

				if (prevChar === "(" && nextChar === ")" || //$NON-NLS-1$ //$NON-NLS-2$
					prevChar === "[" && nextChar === "]" || //$NON-NLS-1$ //$NON-NLS-2$
					prevChar === "{" && nextChar === "}" || //$NON-NLS-1$ //$NON-NLS-2$
					prevChar === "<" && nextChar === ">" || //$NON-NLS-1$ //$NON-NLS-2$
					prevChar === '"' && nextChar === '"' || //$NON-NLS-1$ //$NON-NLS-2$
					prevChar === "'" && nextChar === "'") { //$NON-NLS-1$ //$NON-NLS-2$
					setText("", selection.start, selection.start + 1); //$NON-NLS-0$
				}
			}, true);
			return false;
		}

public static boolean isQuoted(String name) {
    return name != null && name.length() != 0
        && ((name.charAt(0) == '`' && name.charAt(name.length() - 1) == '`')
        || (name.charAt(0) == '"' && name.charAt(name.length() - 1) == '"'));
  }

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


Question:
creates an index
@param $index
@param array $configuration
@return mixed
@see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html

public function createIndex($index, $configuration = null)
    {
        $body = $configuration !== null ? Json::encode($configuration) : null;

        return $this->db->put([$index], [], $body);
    }

public void marshall(ReservedElasticsearchInstanceOffering reservedElasticsearchInstanceOffering, ProtocolMarshaller protocolMarshaller) {

        if (reservedElasticsearchInstanceOffering == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getReservedElasticsearchInstanceOfferingId(),
                    RESERVEDELASTICSEARCHINSTANCEOFFERINGID_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getElasticsearchInstanceType(), ELASTICSEARCHINSTANCETYPE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getDuration(), DURATION_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getFixedPrice(), FIXEDPRICE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getUsagePrice(), USAGEPRICE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getCurrencyCode(), CURRENCYCODE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getPaymentOption(), PAYMENTOPTION_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getRecurringCharges(), RECURRINGCHARGES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Rotate text
@link http://www.fpdf.org/en/script/script2.php

@param  int $x
@param  int $y
@param  string $txt
@param  int $angle

@return void

public function rotatedText($x, $y, $txt, $angle)
    {
        //Text rotated around its origin
        $this->rotate($angle, $x, $y);
        $this->Text($x, $y, $txt);
        $this->rotate(0);
    }

protected function translateTitle($id, array $parameters = array(), $domain = null)
    {
        return $this->translator->trans($id, $parameters, $domain);
    }

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


Question:
Split a version specification into a list of version constraints.

@param  string  $version

@return array

protected static function splitConstraints($version)
    {
        $found   = [];
        $pattern = '/(?<!^|as|[=>< ,]) *(?<!-)[, ](?!-) *(?!,|as|$)/';

        foreach (preg_split('/\s*\|\|?\s*/', trim($version)) as $constraints) {
            $andConstraints = preg_split($pattern, $constraints);

            foreach ($andConstraints as $constraint) {
                $found[] = $constraint;
            }
        }

        return $found;
    }

func ValidateStatefulSetSpec(spec *apps.StatefulSetSpec, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}

	switch spec.PodManagementPolicy {
	case "":
		allErrs = append(allErrs, field.Required(fldPath.Child("podManagementPolicy"), ""))
	case apps.OrderedReadyPodManagement, apps.ParallelPodManagement:
	default:
		allErrs = append(allErrs, field.Invalid(fldPath.Child("podManagementPolicy"), spec.PodManagementPolicy, fmt.Sprintf("must be '%s' or '%s'", apps.OrderedReadyPodManagement, apps.ParallelPodManagement)))
	}

	switch spec.UpdateStrategy.Type {
	case "":
		allErrs = append(allErrs, field.Required(fldPath.Child("updateStrategy"), ""))
	case apps.OnDeleteStatefulSetStrategyType:
		if spec.UpdateStrategy.RollingUpdate != nil {
			allErrs = append(
				allErrs,
				field.Invalid(
					fldPath.Child("updateStrategy").Child("rollingUpdate"),
					spec.UpdateStrategy.RollingUpdate,
					fmt.Sprintf("only allowed for updateStrategy '%s'", apps.RollingUpdateStatefulSetStrategyType)))
		}
	case apps.RollingUpdateStatefulSetStrategyType:
		if spec.UpdateStrategy.RollingUpdate != nil {
			allErrs = append(allErrs,
				apivalidation.ValidateNonnegativeField(
					int64(spec.UpdateStrategy.RollingUpdate.Partition),
					fldPath.Child("updateStrategy").Child("rollingUpdate").Child("partition"))...)
		}
	default:
		allErrs = append(allErrs,
			field.Invalid(fldPath.Child("updateStrategy"), spec.UpdateStrategy,
				fmt.Sprintf("must be '%s' or '%s'",
					apps.RollingUpdateStatefulSetStrategyType,
					apps.OnDeleteStatefulSetStrategyType)))
	}

	allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.Replicas), fldPath.Child("replicas"))...)
	if spec.Selector == nil {
		allErrs = append(allErrs, field.Required(fldPath.Child("selector"), ""))
	} else {
		allErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...)
		if len(spec.Selector.MatchLabels)+len(spec.Selector.MatchExpressions) == 0 {
			allErrs = append(allErrs, field.Invalid(fldPath.Child("selector"), spec.Selector, "empty selector is invalid for statefulset"))
		}
	}

	selector, err := metav1.LabelSelectorAsSelector(spec.Selector)
	if err != nil {
		allErrs = append(allErrs, field.Invalid(fldPath.Child("selector"), spec.Selector, ""))
	} else {
		allErrs = append(allErrs, ValidatePodTemplateSpecForStatefulSet(&spec.Template, selector, fldPath.Child("template"))...)
	}

	if spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways {
		allErrs = append(allErrs, field.NotSupported(fldPath.Child("template", "spec", "restartPolicy"), spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)}))
	}
	if spec.Template.Spec.ActiveDeadlineSeconds != nil {
		allErrs = append(allErrs, field.Forbidden(fldPath.Child("template", "spec", "activeDeadlineSeconds"), "activeDeadlineSeconds in StatefulSet is not Supported"))
	}

	return allErrs
}

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


Question:
Create ngrams list for text.
@param string $text
@param int $maxNgrams How many ngrams to use.
@return int[]

public function createLM( $text, $maxNgrams ) {
		$ngram = [];
		foreach ( preg_split( "/[{$this->wordSeparator}]+/u", $text ) as $word ) {
			if ( empty( $word ) ) {
				continue;
			}
			$word = "_" . $word . "_";
			$len = mb_strlen( $word, "UTF-8" );
			for ( $i = 0; $i < $len; $i++ ) {
				$rlen = $len - $i;
				if ( $rlen > 4 ) {
					@$ngram[mb_substr( $word, $i, 5, "UTF-8" )]++;
				}
				if ( $rlen > 3 ) {
					@$ngram[mb_substr( $word, $i, 4, "UTF-8" )]++;
				}
				if ( $rlen > 2 ) {
					@$ngram[mb_substr( $word, $i, 3, "UTF-8" )]++;
				}
				if ( $rlen > 1 ) {
					@$ngram[mb_substr( $word, $i, 2, "UTF-8" )]++;
				}
				@$ngram[mb_substr( $word, $i, 1, "UTF-8" )]++;
			}
		}
		if ( $this->minFreq ) {
			$min = $this->minFreq;
			$ngram = array_filter( $ngram, function ( $v ) use ( $min ) {
				return $v > $min;
			} );
		}
		uksort( $ngram, function ( $k1, $k2 ) use ( $ngram ) {
				if ( $ngram[$k1] == $ngram[$k2] ) {
					return strcmp( $k1, $k2 );
				}
				return $ngram[$k2] - $ngram[$k1];
		} );
		if ( count( $ngram ) > $maxNgrams ) {
			array_splice( $ngram, $maxNgrams );
		}
		return $ngram;
	}

def _macronize_word(self, word):

        head_word = word[0]
        tag = word[1]
        if tag is None:
            logger.info('Tagger {} could not tag {}.'.format(self.tagger, head_word))
            return head_word, tag, head_word
        elif tag == 'U--------':
            return (head_word, tag.lower(), head_word)
        else:
            entries = self._retrieve_morpheus_entry(head_word)
            if entries is None:
                return head_word, tag.lower(), head_word
            matched_entry = [entry for entry in entries if entry[0] == tag.lower()]
            if len(matched_entry) == 0:
                logger.info('No matching Morpheus entry found for {}.'.format(head_word))
                return head_word, tag.lower(), entries[0][2]
            elif len(matched_entry) == 1:
                return head_word, tag.lower(), matched_entry[0][2].lower()
            else:
                logger.info('Multiple matching entries found for {}.'.format(head_word))
                return head_word, tag.lower(), matched_entry[1][2].lower()

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


Question: Auto Generated Code

def fcoe_get_login_input_fcoe_login_vfid(self, **kwargs):

        config = ET.Element("config")
        fcoe_get_login = ET.Element("fcoe_get_login")
        config = fcoe_get_login
        input = ET.SubElement(fcoe_get_login, "input")
        fcoe_login_vfid = ET.SubElement(input, "fcoe-login-vfid")
        fcoe_login_vfid.text = kwargs.pop('fcoe_login_vfid')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

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


Question: // SetAbortIncompleteMultipartUpload sets the AbortIncompleteMultipartUpload field's value.

func (s *LifecycleRule) SetAbortIncompleteMultipartUpload(v *AbortIncompleteMultipartUpload) *LifecycleRule {
	s.AbortIncompleteMultipartUpload = v
	return s
}

def download_from_link(self, link, **kwargs):

        # old:new format
        old_arg_map = {'save_path': 'savepath'}  # , 'label': 'category'}

        # convert old option names to new option names
        options = kwargs.copy()
        for old_arg, new_arg in old_arg_map.items():
            if options.get(old_arg) and not options.get(new_arg):
                options[new_arg] = options[old_arg]

        if type(link) is list:
            options['urls'] = "\n".join(link)
        else:
            options['urls'] = link

        # workaround to send multipart/formdata request
        # http://stackoverflow.com/a/23131823/4726598
        dummy_file = {'_dummy': (None, '_dummy')}

        return self._post('command/download', data=options, files=dummy_file)

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


Question: Extracts pop receipt and time next visible from headers.

def _parse_queue_message_from_headers(response):
    '''

    '''
    headers = _parse_response_for_dict(response)

    message = QueueMessage()
    message.pop_receipt = headers.get('x-ms-popreceipt')
    message.time_next_visible = parser.parse(headers.get('x-ms-time-next-visible'))

    return message

function(names, typeVersion, value) {
			var out = {};

			// is more than just whitespace
			if(value && modules.utils.isOnlyWhiteSpace(value) === false) {
				out.value = value;
			}
			// add type i.e. ["h-card", "h-org"]
			if(modules.utils.isArray(names)) {
				out.type = names;
			} else {
				out.type = [names];
			}
			out.properties = {};
			// metadata properties for parsing
			out.typeVersion = typeVersion;
			out.times = [];
			out.dates = [];
			out.altValue = null;

			return out;
		}

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


Question:
@param int $idCompany

@return \Generated\Shared\Transfer\ProductListCollectionTransfer

public function getProductListCollectionByIdCompany(int $idCompany): ProductListCollectionTransfer
    {
        /** @var \Orm\Zed\ProductList\Persistence\SpyProductList[] $productListEntities */
        $productListEntities = $this->getFactory()
            ->getProductListQuery()
            ->useSpyProductListCompanyQuery()
                ->filterByFkCompany($idCompany)
            ->endUse()
            ->find();

        $productListCollectionTransfer = new ProductListCollectionTransfer();
        $productListCompanyMapper = $this->getFactory()->createProductListCompanyMapper();

        foreach ($productListEntities as $productListEntity) {
            $productListCollectionTransfer->addProductList(
                $productListCompanyMapper->mapProductList($productListEntity, new ProductListTransfer())
            );
        }

        return $productListCollectionTransfer;
    }

public function addParticipation($testIdentifier, $variationIdentifier)
    {
        Assert::string($testIdentifier, 'Test identifier must be a string');
        Assert::string($variationIdentifier, 'Variation name must be a string');

        $this->participations[$testIdentifier] = $variationIdentifier;
    }

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


Question: SQL-escape a string.

public static String sqlEscapeString(String value) {
        StringBuilder escaper = new StringBuilder();

        DatabaseUtils.appendEscapedSQLString(escaper, value);

        return escaper.toString();
    }

def safely_encode(unicode_or_str, encoding='utf-8'):
  '''  '''
  if isinstance(unicode_or_str, unicode):
    rstr = unicode_or_str.encode(encoding, 'replace')
  elif isinstance(unicode_or_str, str):
    rstr = unicode_or_str
  else:
    raise Exception(u'Not of type unicode or str')

  return rstr

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


Question: ReSharper disable once UnusedLocals

function background(options) {
    options = options || {};
    // ReSharper disable once UnusedParameter
    return function (config) {
        var values = [];
        [
            'attachment',
            'clip',
            'color',
            'image',
            'origin',
            'position',
            'repeat',
            'size'
        ].forEach(function (prop) {
            if (options.hasOwnProperty(prop)) {
                values.push(options[prop]);
            }
        });
        if (values.length) {
            return [['background', values.join(' ')]];
        }
        return [];
    };
}

@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case DroolsPackage.ON_ENTRY_SCRIPT_TYPE__SCRIPT:
				setScript(SCRIPT_EDEFAULT);
				return;
			case DroolsPackage.ON_ENTRY_SCRIPT_TYPE__SCRIPT_FORMAT:
				setScriptFormat(SCRIPT_FORMAT_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

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


Question:
SubselectFromClause ::= "FROM" SubselectIdentificationVariableDeclaration {"," SubselectIdentificationVariableDeclaration}*

@return AST\SubselectFromClause

public function SubselectFromClause()
    {
        $this->match(Lexer::T_FROM);

        $identificationVariables   = [];
        $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration();

        while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
            $this->match(Lexer::T_COMMA);

            $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration();
        }

        return new AST\SubselectFromClause($identificationVariables);
    }

private function selectNodeType(\DOMNode $node, $val): bool
    {
        if (\is_array($val)) {
            return $this->buildXml($node, $val);
        } elseif ($val instanceof \SimpleXMLElement) {
            $child = $this->dom->importNode(dom_import_simplexml($val), true);
            $node->appendChild($child);
        } elseif ($val instanceof \Traversable) {
            $this->buildXml($node, $val);
        } elseif (\is_object($val)) {
            return $this->selectNodeType($node, $this->serializer->normalize($val, $this->format, $this->context));
        } elseif (is_numeric($val)) {
            return $this->appendText($node, (string) $val);
        } elseif (\is_string($val) && $this->needsCdataWrapping($val)) {
            return $this->appendCData($node, $val);
        } elseif (\is_string($val)) {
            return $this->appendText($node, $val);
        } elseif (\is_bool($val)) {
            return $this->appendText($node, (int) $val);
        } elseif ($val instanceof \DOMNode) {
            $child = $this->dom->importNode($val, true);
            $node->appendChild($child);
        }

        return true;
    }

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


Question:
Process the license tag.

@param   PHP_CodeSniffer_File  $phpcsFile  The file being scanned.
@param   array                 $tags       The tokens for these tags.

@return  void

protected function processLicense(PHP_CodeSniffer_File $phpcsFile, array $tags)
	{
		$tokens = $phpcsFile->getTokens();

		foreach ($tags as $tag)
		{
			if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING)
			{
				// No content.
				continue;
			}

			$content = $tokens[($tag + 2)]['content'];
			$matches = array();
			preg_match('/^([^\s]+)\s+(.*)/', $content, $matches);

			if (count($matches) !== 3)
			{
				$error = '@license tag must contain a URL and a license name';
				$phpcsFile->addError($error, $tag, 'IncompleteLicense');
			}
		}
	}

public function parseType(string $input)
    {
        $matches = $properties = [];
        if (\preg_match(self::STRUCT, trim($input), $matches)) {
            /* Optional parse properties of the struct, could be empty complex types */
            \preg_match_all(self::PROPERTY, $matches['properties'], $properties);

            $struct = new Struct();
            $struct->setName($matches['name']);

            for ($x = 0, $max = count($properties['name']); $x < $max; $x++) {
                $type = $this->convertWsdlTypeToPhpType($properties['type'][$x]);
                $name = $this->covertNameToPhpName($properties['name'][$x]);
                $struct->addProperty(new Property($name, $type));
            }

            return $struct;
        } elseif (\preg_match(self::ARRAY_OF_COMPLEX_TYPE, trim($input), $matches)) {
            $struct = new Struct();
            $struct->setName($matches['name']);
            $struct->addProperty(new Property($matches['type'], $matches['type'] . '[]'));
            return $struct;
        } elseif (\preg_match(self::SIMPLE_TYPE, trim($input), $matches)) {
            return new Property($matches['name'], $matches['type']);
        } else {
            throw new \Exception(sprintf('Unable to parse input [%s]', $input));
        }
    }

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


Question:
Create the ExtDirect API based on controllers files.

@return string JSON description of Direct API

private function createApi()
    {
        $routes = $this->app["routes"];

        $actions = $this->getRouteActions($routes);

        return array(
            'url' => $this->app['request']->getBaseUrl().
                     $this->app['direct.route.pattern'],
            'type' => $this->app['direct.api.type'],
            'namespace' => $this->app['direct.api.namespace'],
            'id' => $this->app['direct.api.id'],
            'actions' => $actions
        );
    }

public function request($method, $endpoint, array $parameters = null)
    {
        $url = $this->config->getEndpoint() . $endpoint;

        // Client should always send OAuth2 tokens in its headers
        $headers = array('Authorization' => 'Bearer ' . $this->config->getAccessToken());

        return $this->client->request($method, $url, $parameters, $headers);
    }

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


Question: // SetName sets the Name field's value.

func (s *ChannelSpecification) SetName(v string) *ChannelSpecification {
	s.Name = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question:
// getParentDeviceNumChildrenRefs returns the NumChildren value for the given
// linkLayerDeviceDocID. If the linkLayerDevicesRefsDoc is missing, no error and
// -1 children are returned.

func getParentDeviceNumChildrenRefs(st *State, linkLayerDeviceDocID string) (int, error) {
	devicesRefs, closer := st.db().GetCollection(linkLayerDevicesRefsC)
	defer closer()

	var doc linkLayerDevicesRefsDoc
	err := devicesRefs.FindId(linkLayerDeviceDocID).One(&doc)
	if err == mgo.ErrNotFound {
		return -1, nil
	} else if err != nil {
		return 0, errors.Trace(err)
	}
	return doc.NumChildren, nil
}

def devices(self):
        """"""
        context = Context()

        existing_devices = context.list_devices(subsystem="hidraw")
        future_devices = self._get_future_devices(context)

        for hidraw_device in itertools.chain(existing_devices, future_devices):
            hid_device = hidraw_device.parent
            if hid_device.subsystem != "hid":
                continue

            cls = HID_DEVICES.get(hid_device.get("HID_NAME"))
            if not cls:
                continue

            for child in hid_device.parent.children:
                event_device = child.get("DEVNAME", "")
                if event_device.startswith("/dev/input/event"):
                    break
            else:
                continue

            try:
                device_addr = hid_device.get("HID_UNIQ", "").upper()
                if device_addr:
                    device_name = "{0} {1}".format(device_addr,
                                                   hidraw_device.sys_name)
                else:
                    device_name = hidraw_device.sys_name

                yield cls(name=device_name,
                          addr=device_addr,
                          type=cls.__type__,
                          hidraw_device=hidraw_device.device_node,
                          event_device=event_device)

            except DeviceError as err:
                self.logger.error("Unable to open DS4 device: {0}", err)

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


Question: Returns true if this is an output script wrapped in a versioned pushdata for segwit softfork.

def versioned_script?
      return chunks.size == 1 &&
             chunks[0].pushdata? &&
             chunks[0].canonical? &&
             chunks[0].pushdata.bytesize > 2
    end

func NewWorker(
	upgradeComplete gate.Lock,
	agent agent.Agent,
	apiConn api.Connection,
	jobs []multiwatcher.MachineJob,
	openState func() (*state.StatePool, error),
	preUpgradeSteps func(st *state.StatePool, agentConf agent.Config, isController, isMasterServer, isCaas bool) error,
	machine StatusSetter,
	isCaas bool,
) (worker.Worker, error) {
	w := &upgradesteps{
		upgradeComplete: upgradeComplete,
		agent:           agent,
		apiConn:         apiConn,
		jobs:            jobs,
		openState:       openState,
		preUpgradeSteps: preUpgradeSteps,
		machine:         machine,
		tag:             agent.CurrentConfig().Tag(),
		isCaas:          isCaas,
	}
	w.tomb.Go(w.run)
	return w, nil
}

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


Question: Decodes text by using the browser

function nativeDecode(text) {
      var elm;

      elm = document.createElement("div");
      elm.innerHTML = text;

      return elm.textContent || elm.innerText || text;
    }

public function detranslify($inString)
    {
        $dirtyResult = str_replace(self::$_EN_ALPHABET, self::$_RU_ALPHABET, $inString);
        return preg_replace(self::$_CORRECTION_PATTERN, self::$_CORRECTION_REPLACEMENT, $dirtyResult);
    }

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


Question: /* Model API save

function(o, callback) {

    var self = this;

    // Note: Validation has already been performed by ModelObject

    // Convert `id` to `_id`
    convertMongoID(o);

    // Get _id, and prepare update data
    var _id = o._id;
    delete o._id;

    if (typeof _id == 'undefined') {
      callback.call(this, new Error("Unable to update model object without ID"));
      return;
    }

    // Validate, throw error on failure
    var err = this.validateProperties(o, {noRequired: true});

    if (err) callback.call(self, err);

    else {

      this.driver.updateById({
        _id: _id,
        collection: this.context,
        values: o
      }, function(err, docs) {
        callback.call(self, err);
      });

    }

  }

public function create(
        string $title,
        string $description,
        $amount,
        array $optional = []
    ): Response {
        $body = \array_merge(\compact('title', 'description', 'amount'), $optional);

        list($headers, $stream) = $this->prepareMultipartRequestPayloads([], $body);

        return $this->stream('POST', 'open_collections', $headers, $body);
    }

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


Question: Returns the local server's inet address.

@Override
  public InetAddress addressLocal()
  {
    if (_localAddr == null) {
      try {
        _localAddr = InetAddress.getByName(getLocalHost());
      } catch (Exception e) {
        log.log(Level.FINE, e.toString(), e);
      }
    }

    return _localAddr;
  }

@Override
    public synchronized void resolve(JingleSession session) throws XMPPException, NotConnectedException, InterruptedException {

        setResolveInit();

        clearCandidates();

        TransportCandidate candidate = new TransportCandidate.Fixed(
                resolvedPublicIP, getFreePort());
        candidate.setLocalIp(resolvedLocalIP);

        LOGGER.fine("RESOLVING : " + resolvedPublicIP + ":" + candidate.getPort());

        addCandidate(candidate);

        setResolveEnd();

    }

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


Question:
Builds permissions index data for a given layout.

The purpose of the index is to allow for efficient presence filtering
based on changing user permissions.

@param MenuLayoutDataInterface $layout
@return MenuPermissionsIndexDataInterface

public function buildPermissionsIndex(MenuLayoutDataInterface $layout)
    {
        $this->permissionsIndex = new PermissionsIndexData;
        $this->permissions      = [];

        $this->compileIndexForLayoutLayer($layout->layout());

        $this->permissions = array_unique($this->permissions);
        $this->permissionsIndex->permissions = $this->permissions;

        return $this->permissionsIndex;
    }

public function init()
    {
        parent::init();
        if (!$this->template->hasTag($this->item_tag)) {
            if (@$this->app->compat_42 && $this instanceof Menu_Basic) {
                // look for MenuItem

                $default = $this->item_tag;

                $this->item_tag = 'MenuItem';
                $this->container_tag = 'Item';
                if (!$this->template->hasTag($this->item_tag)) {
                    throw $this->template->exception('Template must have "'.$default.'" tag')
                        ->addMoreInfo('compat', 'Also tried for compatibility reason "'.$this->item_tag.'" tag');
                }
            } else {
                throw $this->template->exception('Template must have "'.$this->item_tag.'" tag');
            }
        }

        $this->row_t = $this->template->cloneRegion($this->item_tag);

        if ($this->template->hasTag('sep')) {
            $this->sep_html = $this->template->get('sep');
        }
    }

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


Question:
Adapts a filter with {@link URI} base type to a filter with {@link HttpResponseWarcRecord} base type.

@param original the original filter.
@return the adapted filter.

public static Filter<HttpResponseWarcRecord> adaptFilterURI2HttpResponseWarcRecord(final Filter<URI> original) {
		return new AbstractFilter<HttpResponseWarcRecord>() {
			@Override
			public boolean apply(final HttpResponseWarcRecord response) {
				return original.apply(response.getWarcTargetURI());
			}
			@Override
			public String toString() {
				return original.toString();
			}
			@Override
			public Filter<HttpResponseWarcRecord> copy() {
				return adaptFilterURI2HttpResponseWarcRecord(original.copy());
			}
		};
	}

public void marshall(SearchRequest searchRequest, ProtocolMarshaller protocolMarshaller) {

        if (searchRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(searchRequest.getCursor(), CURSOR_BINDING);
            protocolMarshaller.marshall(searchRequest.getExpr(), EXPR_BINDING);
            protocolMarshaller.marshall(searchRequest.getFacet(), FACET_BINDING);
            protocolMarshaller.marshall(searchRequest.getFilterQuery(), FILTERQUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getHighlight(), HIGHLIGHT_BINDING);
            protocolMarshaller.marshall(searchRequest.getPartial(), PARTIAL_BINDING);
            protocolMarshaller.marshall(searchRequest.getQuery(), QUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryOptions(), QUERYOPTIONS_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryParser(), QUERYPARSER_BINDING);
            protocolMarshaller.marshall(searchRequest.getReturn(), RETURN_BINDING);
            protocolMarshaller.marshall(searchRequest.getSize(), SIZE_BINDING);
            protocolMarshaller.marshall(searchRequest.getSort(), SORT_BINDING);
            protocolMarshaller.marshall(searchRequest.getStart(), START_BINDING);
            protocolMarshaller.marshall(searchRequest.getStats(), STATS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Check if the current resource is the same as the requester.
 The resource must respond to `resource.id` method.

def requested_by?(resource)
      user = resource.respond_to?(:owner) ? resource.owner : resource
      case
      when current_resource_owner.nil?
        false
      when !user.is_a?(current_resource_owner.class)
        false
      when current_resource_owner.id == user.id
        true
      else
        false
      end
    end

protected List<CmsPair<CmsResource, CmsResource>> getMatchingResources(String source, String target)
    throws CmsException {

        List<CmsResource> sourceResources = readTree(source);
        Map<String, CmsResource> sourceRelative = getResourcesByRelativePath(sourceResources, source);

        List<CmsResource> targetResources = readTree(target);
        Map<String, CmsResource> targetRelative = getResourcesByRelativePath(targetResources, target);

        List<CmsPair<CmsResource, CmsResource>> result = new ArrayList<CmsPair<CmsResource, CmsResource>>();
        sourceRelative.keySet().retainAll(targetRelative.keySet());
        for (Map.Entry<String, CmsResource> entry : sourceRelative.entrySet()) {
            String key = entry.getKey();
            CmsResource sourceRes = entry.getValue();
            CmsResource targetRes = targetRelative.get(key);
            result.add(CmsPair.create(sourceRes, targetRes));
        }
        return result;
    }

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


Question:
/* (non-Javadoc)
@see com.ibm.ws.sib.processor.runtime.MessageProcessorControllable#getLocalQueueIterator()

public SIMPIterator getLocalQueueIterator()
  {
    DestinationTypeFilter filter = new DestinationTypeFilter();
    filter.QUEUE = Boolean.TRUE;
    filter.LOCAL = Boolean.TRUE;
    SIMPIterator queuesItr = destinationIndex.iterator(filter);
    return new ControllableIterator(queuesItr);
  }

def get_handlers(self, component_context, instance):

        # Extract information from the context
        configs = component_context.get_handler(
            ipopo_constants.HANDLER_TEMPORAL
        )
        requires_filters = component_context.properties.get(
            ipopo_constants.IPOPO_REQUIRES_FILTERS, None
        )
        temporal_timeouts = component_context.properties.get(
            ipopo_constants.IPOPO_TEMPORAL_TIMEOUTS, None
        )

        # Prepare requirements
        new_configs = self._prepare_configs(
            configs, requires_filters, temporal_timeouts
        )

        # Return handlers
        return [
            TemporalDependency(field, requirement, timeout)
            for field, (requirement, timeout) in new_configs.items()
        ]

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


Question: // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RouteIngressCondition.

func (in *RouteIngressCondition) DeepCopy() *RouteIngressCondition {
	if in == nil {
		return nil
	}
	out := new(RouteIngressCondition)
	in.DeepCopyInto(out)
	return out
}

func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	path, err := pathFor(blobDataPathSpec{
		digest: dgst,
	})

	if err != nil {
		return distribution.Descriptor{}, err
	}

	fi, err := bs.driver.Stat(ctx, path)
	if err != nil {
		switch err := err.(type) {
		case driver.PathNotFoundError:
			return distribution.Descriptor{}, distribution.ErrBlobUnknown
		default:
			return distribution.Descriptor{}, err
		}
	}

	if fi.IsDir() {
		// NOTE(stevvooe): This represents a corruption situation. Somehow, we
		// calculated a blob path and then detected a directory. We log the
		// error and then error on the side of not knowing about the blob.
		dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path)
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	// TODO(stevvooe): Add method to resolve the mediatype. We can store and
	// cache a "global" media type for the blob, even if a specific repo has a
	// mediatype that overrides the main one.

	return distribution.Descriptor{
		Size: fi.Size(),

		// NOTE(stevvooe): The central blob store firewalls media types from
		// other users. The caller should look this up and override the value
		// for the specific repository.
		MediaType: "application/octet-stream",
		Digest:    dgst,
	}, nil
}

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


Question:
Authorize to platform with client credentials

        This should be used if you posses client_id/client_secret pair
        generated by platform.

def authorize_client_credentials(
        self, client_id, client_secret=None, scope="private_agent"
    ):

        self.auth_data = {
            "grant_type": "client_credentials",
            "scope": [ scope ],
            "client_id": client_id,
            "client_secret": client_secret
        }

        self._do_authorize()

def set_request_defaults(endpoint, private_token, sudo=nil)
      raise Error::MissingCredentials.new("Please set an endpoint to API") unless endpoint
      @private_token = private_token

      self.class.base_uri endpoint
      self.class.default_params :sudo => sudo
      self.class.default_params.delete(:sudo) if sudo.nil?
    end

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


Question:
@param Request $request

@Config\Route("", name="open_orchestra_api_workflow_functions_list")
@Config\Method({"GET"})

@Config\Security("is_granted('ROLE_ACCESS_WORKFLOWFUNCTION')")

@return FacadeInterface

public function listAction(Request $request)
    {
        $repository =  $this->get('open_orchestra_workflow_function.repository.workflow_function');

        $configuration = PaginateFinderConfiguration::generateFromRequest($request);
        $mapping = $this
            ->get('open_orchestra.annotation_search_reader')
            ->extractMapping($this->container->getParameter('open_orchestra_workflow_function.document.workflow_function.class'));
        $configuration->setDescriptionEntity($mapping);
        $workflowFunctionCollection = $repository->findForPaginate($configuration);
        $recordsTotal = $repository->count();
        $recordsFiltered = $repository->countWithFilter($configuration);

        $facade = $this->get('open_orchestra_api.transformer_manager')->get('workflow_function_collection')->transform($workflowFunctionCollection);
        $facade->recordsTotal = $recordsTotal;
        $facade->recordsFiltered = $recordsFiltered;

        return $facade;
    }

func (gm *serverMethod) setup(apiDef *raml.APIDefinition, r *raml.Resource, rd *resource.Resource, methodName string) error {
	gm.MethodName = strings.Title(serverMethodName(gm.Endpoint, gm.DisplayName, methodName, rd.Name))

	// setting middlewares
	middlewares := []string{}

	// security middlewares
	for _, v := range gm.SecuredBy {
		if !security.ValidateScheme(v.Name, apiDef) {
			continue
		}
		// oauth2 middleware
		m, err := getOauth2MwrHandler(v)
		if err != nil {
			return err
		}
		middlewares = append(middlewares, m)
	}

	gm.Middlewares = strings.Join(middlewares, ", ")

	return nil
}

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


Question: // getLink is a wrapper that fetches the netlink corresponding to the ifname

func getLink(ifname string) (netlink.Link, error) {
	// find the link
	link, err := netlink.LinkByName(ifname)
	if err != nil {
		if !strings.Contains(err.Error(), "Link not found") {
			log.Errorf("unable to find link %q. Error: %q", ifname, err)
			return link, err
		}
		// try once more as sometimes (somehow) link creation is taking
		// sometime, causing link not found error
		time.Sleep(1 * time.Second)
		link, err = netlink.LinkByName(ifname)
		if err != nil {
			log.Errorf("unable to find link %q. Error %q", ifname, err)
		}
		return link, err
	}
	return link, err
}

public static <T> Optional<List<T>> dotGetList(final Map map, final String pathString, final Class<T> clazz) {
        return dotGet(map, List.class, pathString).map(c -> (List<T>) c);
    }

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


Question:
Process a single PSE update, using form data array.

@param array $data the form data

protected function processSingleProductSaleElementUpdate($data)
    {
        $event = new ProductSaleElementUpdateEvent(
            $this->getExistingObject(),
            $data['product_sale_element_id']
        );

        $event
            ->setReference($data['reference'])
            ->setPrice($data['price'])
            ->setCurrencyId($data['currency'])
            ->setWeight($data['weight'])
            ->setQuantity($data['quantity'])
            ->setSalePrice($data['sale_price'])
            ->setOnsale($data['onsale'])
            ->setIsnew($data['isnew'])
            ->setIsdefault($data['isdefault'])
            ->setEanCode($data['ean_code'])
            ->setTaxRuleId($data['tax_rule'])
            ->setFromDefaultCurrency($data['use_exchange_rate'])
        ;

        $this->dispatch(TheliaEvents::PRODUCT_UPDATE_PRODUCT_SALE_ELEMENT, $event);

        // Log object modification
        if (null !== $changedObject = $event->getProductSaleElement()) {
            $this->adminLogAppend(
                $this->resourceCode,
                AccessManager::UPDATE,
                sprintf(
                    "Product Sale Element (ID %s) for product reference %s modified",
                    $changedObject->getId(),
                    $event->getProduct()->getRef()
                ),
                $changedObject->getId()
            );
        }
    }

protected function parserSearchData($search)
    {
        $searchData = [];

        if (stripos($search, ':')) {
            $fields = explode(';', $search);

            foreach ($fields as $row) {
                try {
                    list($field, $value) = explode(':', $row);
                    $searchData[$field] = $value;
                } catch (\Exception $e) {
                    //Surround offset error
                }
            }
        }

        return $searchData;
    }

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


Question: Parse text with datetime to aware datetime (with timezone).

def parse_datetime_aware(s, tz=None):

    assert settings.USE_TZ
    if isinstance(s, datetime.datetime):
        return s
    d = parse_datetime(s)
    if d is None:
        raise ValueError
    return timezone.make_aware(d, tz or timezone.get_current_timezone())

public function getIsoFormats($locale = null)
    {
        return [
            'LT' => $this->getTranslationMessage('formats.LT', $locale, 'h:mm A'),
            'LTS' => $this->getTranslationMessage('formats.LTS', $locale, 'h:mm:ss A'),
            'L' => $this->getTranslationMessage('formats.L', $locale, 'MM/DD/YYYY'),
            'LL' => $this->getTranslationMessage('formats.LL', $locale, 'MMMM D, YYYY'),
            'LLL' => $this->getTranslationMessage('formats.LLL', $locale, 'MMMM D, YYYY h:mm A'),
            'LLLL' => $this->getTranslationMessage('formats.LLLL', $locale, 'dddd, MMMM D, YYYY h:mm A'),
        ];
    }

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


Question: // GetACL gets the ACL configuration with the given parameters.

func (c *Client) GetACL(i *GetACLInput) (*ACL, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == 0 {
		return nil, ErrMissingVersion
	}

	if i.Name == "" {
		return nil, ErrMissingName
	}

	path := fmt.Sprintf("/service/%s/version/%d/acl/%s", i.Service, i.Version, i.Name)
	resp, err := c.Get(path, nil)
	if err != nil {
		return nil, err
	}

	var a *ACL
	if err := decodeJSON(&a, resp.Body); err != nil {
		return nil, err
	}
	return a, nil
}

public Javalin put(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
        return addHandler(HandlerType.PUT, path, handler, permittedRoles);
    }

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


Question: Returns the type closure of the base type.

public final Set<BaseType> getBaseTypeClosure(BaseTypeFactory typeFactory)
  {
    if (_typeClosureSet == null) {
      LinkedHashSet<BaseType> baseTypeSet = new LinkedHashSet<BaseType>();

      for (Type type : getTypeClosure(typeFactory)) {
        baseTypeSet.add(typeFactory.createForSource(type));
      }

      _typeClosureSet = baseTypeSet;
    }

    return _typeClosureSet;
  }

func (_m *API) ImagePull(ctx context.Context, ref string, all bool) (io.ReadCloser, error) {
	ret := _m.Called(ctx, ref, all)

	var r0 io.ReadCloser
	if rf, ok := ret.Get(0).(func(context.Context, string, bool) io.ReadCloser); ok {
		r0 = rf(ctx, ref, all)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(io.ReadCloser)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, string, bool) error); ok {
		r1 = rf(ctx, ref, all)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

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


Question:
@name            getGroup ()

@since            1.0.0
@version         1.4.1
@author          Can Berkol

@param           mixed $group

@return          mixed           $response

public function getGroup($group)
    {
        $timeStamp = time();
        if ($group instanceof BundleEntity\MemberGroup) {
            return new ModelResponse($group, 1, 0, null, false, 'S:D:002', 'Entries successfully fetched from database.', $timeStamp, time());
        }
        $result = null;
        switch ($group) {
            case is_numeric($group):
                $result = $this->em->getRepository($this->entity['mg']['name'])->findOneBy(array('id' => $group));
                break;
            case is_string($group):
                $result = $this->em->getRepository($this->entity['mg']['name'])->findOneBy(array('code' => $group));
                break;
        }
        if (is_null($result)) {
            return new ModelResponse($result, 0, 0, null, true, 'E:D:002', 'Unable to find request entry in database.', $timeStamp, time());
        }

        return new ModelResponse($result, 1, 0, null, false, 'S:D:002', 'Entries successfully fetched from database.', $timeStamp, time());
    }

public function addReturnTypes(Context $context)
    {
        if ($this->return_vars_in_scope !== null) {
            $this->return_vars_in_scope = TypeAnalyzer::combineKeyedTypes(
                $context->vars_in_scope,
                $this->return_vars_in_scope
            );
        } else {
            $this->return_vars_in_scope = $context->vars_in_scope;
        }

        if ($this->return_vars_possibly_in_scope !== null) {
            $this->return_vars_possibly_in_scope = array_merge(
                $context->vars_possibly_in_scope,
                $this->return_vars_possibly_in_scope
            );
        } else {
            $this->return_vars_possibly_in_scope = $context->vars_possibly_in_scope;
        }
    }

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


Question: // upload an existing template into the CloudStack cloud.

func (s *TemplateService) GetUploadParamsForTemplate(p *GetUploadParamsForTemplateParams) (*GetUploadParamsForTemplateResponse, error) {
	resp, err := s.cs.newRequest("getUploadParamsForTemplate", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r GetUploadParamsForTemplateResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}

public function getJobTemplate($jobTemplate)
    {
        $jobTemplateId = Utilities::getEntityId(
            $jobTemplate,
            'WindowsAzure\MediaServices\Models\JobTemplate'
        );

        return JobTemplate::createFromOptions(
            $this->_getEntity("JobTemplates('{$jobTemplateId}')")
        );
    }

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


Question:
Package schemas for export.
@return bool
@throws InternalServerErrorException
@throws \DreamFactory\Core\Exceptions\RestException

private function packageSchemas()
    {
        if (!empty($this->exportSchemas)) {
            $schemas = [];

            foreach ($this->exportSchemas as $serviceName => $component) {
                if (is_array($component)) {
                    $component = implode(',', $component);
                }

                if (is_numeric($serviceName)) {
                    /** @type Service $service */
                    $service = Service::find($serviceName);
                } else {
                    /** @type Service $service */
                    $service = Service::whereName($serviceName)->whereDeletable(1)->first();
                }

                if (!empty($service) && !empty($component)) {
                    if ($service->type === 'sql_db') {
                        $result = ServiceManager::handleRequest(
                            $serviceName,
                            Verbs::GET,
                            '_schema',
                            ['ids' => $component]
                        );
                        if ($result->getStatusCode() >= 300) {
                            throw ResponseFactory::createExceptionFromResponse($result);
                        }

                        $schema = $result->getContent();
                        $schemas[] = [
                            'name'  => $serviceName,
                            'table' => ($this->resourceWrapped) ? $schema[$this->resourceWrapper] : $schema
                        ];
                    }
                }
            }

            if (!empty($schemas) &&
                !$this->zip->addFromString('schema.json', json_encode(['service' => $schemas], JSON_UNESCAPED_SLASHES))
            ) {
                throw new InternalServerErrorException("Can not include database schema in package file.");
            }

            return true;
        }

        return false;
    }

public function execute(TransactionData $transactionData, $argument = null)
    {
        foreach ($this->expectationBackup->listExpectations() as $expectation) {
            $this->expectationStorage->addExpectation($expectation);
        }
        $this->logger->debug('Pre-defined expectations are restored, scenarios and requests history are cleared.');

        $transactionData->setResponse(
            $transactionData->getResponse()->withStatus(200)
        );
    }

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


Question: // WithContent sets the object / value to be stored at the specified key

func (builder *StoreValueCommandBuilder) WithContent(object *Object) *StoreValueCommandBuilder {
	setProtobufFromValue(builder.protobuf, object)
	builder.value = object
	return builder
}

def collect_table_content(table_bboxes, elems):

    # list of table content chars
    table_contents = [[] for _ in range(len(table_bboxes))]
    prev_content = None
    prev_bbox = None
    for cid, c in enumerate(elems):
        # Annotations should not fall outside alone
        if isinstance(c, LTAnno):
            if prev_content is not None:
                prev_content.append(c)
            continue
        # Generally speaking table contents should be included sequentially
        # and we can avoid checking all tables for elems inside
        # Elements only need to intersect the bbox for table as some
        # formatting of fonts may result in slightly out of bbox text
        if prev_bbox is not None and intersect(prev_bbox, c.bbox):
            prev_content.append(c)
            continue
        # Search the rest of the tables for membership when done with
        # the current one
        for table_id, table_bbox in enumerate(table_bboxes):
            if intersect(table_bbox, c.bbox):
                prev_bbox = table_bbox
                prev_content = table_contents[table_id]
                prev_content.append(c)
                break
    return table_contents

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


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

public void setElement(JvmOperation newElement)
	{
		JvmOperation oldElement = element;
		element = newElement;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, XAnnotationsPackage.XANNOTATION_ELEMENT_VALUE_PAIR__ELEMENT, oldElement, element));
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question:
A handy update() method which returns self :)

        :rtype: DictProxy

def update(self, *args, **kwargs):

        super(DictProxy, self).update(*args, **kwargs)
        return self

public void marshall(DescribeUpdateRequest describeUpdateRequest, ProtocolMarshaller protocolMarshaller) {

        if (describeUpdateRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(describeUpdateRequest.getName(), NAME_BINDING);
            protocolMarshaller.marshall(describeUpdateRequest.getUpdateId(), UPDATEID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: Return absolute path for configuration file with specified filename.

def get_conf_path(filename=None):
    """"""
    conf_dir = osp.join(get_home_dir(), '.condamanager')

    if not osp.isdir(conf_dir):
        os.mkdir(conf_dir)

    if filename is None:
        return conf_dir
    else:
        return osp.join(conf_dir, filename)

public function readConfig()
    {
        // by default, read local file: projectBase/config.php
        // in which only an array $config defined
        $config=[];
        if (file_exists($this->projectBase.'/config.php')) {
            require($this->projectBase . '/config.php');
        }
        $this->config=$config;
    }

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


Question:
Public: Encode a mapping array into a compact VLQ string.

 ary - Two dimensional Array of Integers.

 Returns a VLQ encoded String seperated by , and ;.

def vlq_encode_mappings(ary)
      ary.map { |group|
        group.map { |segment|
          vlq_encode(segment)
        }.join(',')
      }.join(';')
    end

def generate_one(basename, xml):
    ''''''

    directory = os.path.join(basename, xml.basename)

    print("Generating C implementation in directory %s" % directory)
    mavparse.mkdir_p(directory)

    if xml.little_endian:
        xml.mavlink_endian = "MAVLINK_LITTLE_ENDIAN"
    else:
        xml.mavlink_endian = "MAVLINK_BIG_ENDIAN"

    if xml.crc_extra:
        xml.crc_extra_define = "1"
    else:
        xml.crc_extra_define = "0"

    if xml.command_24bit:
        xml.command_24bit_define = "1"
    else:
        xml.command_24bit_define = "0"

    if xml.sort_fields:
        xml.aligned_fields_define = "1"
    else:
        xml.aligned_fields_define = "0"

    # work out the included headers
    xml.include_list = []
    for i in xml.include:
        base = i[:-4]
        xml.include_list.append(mav_include(base))

    # form message lengths array
    xml.message_lengths_array = ''
    if not xml.command_24bit:
        for msgid in range(256):
            mlen = xml.message_min_lengths.get(msgid, 0)
            xml.message_lengths_array += '%u, ' % mlen
        xml.message_lengths_array = xml.message_lengths_array[:-2]

    # and message CRCs array
    xml.message_crcs_array = ''
    if xml.command_24bit:
        # we sort with primary key msgid
        for msgid in sorted(xml.message_crcs.keys()):
            xml.message_crcs_array += '{%u, %u, %u, %u, %u, %u}, ' % (msgid,
                                                                      xml.message_crcs[msgid],
                                                                      xml.message_min_lengths[msgid],
                                                                      xml.message_flags[msgid],
                                                                      xml.message_target_system_ofs[msgid],
                                                                      xml.message_target_component_ofs[msgid])
    else:
        for msgid in range(256):
            crc = xml.message_crcs.get(msgid, 0)
            xml.message_crcs_array += '%u, ' % crc
    xml.message_crcs_array = xml.message_crcs_array[:-2]

    # form message info array
    xml.message_info_array = ''
    if xml.command_24bit:
        # we sort with primary key msgid
        for msgid in sorted(xml.message_names.keys()):
            name = xml.message_names[msgid]
            xml.message_info_array += 'MAVLINK_MESSAGE_INFO_%s, ' % name
    else:
        for msgid in range(256):
            name = xml.message_names.get(msgid, None)
            if name is not None:
                xml.message_info_array += 'MAVLINK_MESSAGE_INFO_%s, ' % name
            else:
                # Several C compilers don't accept {NULL} for
                # multi-dimensional arrays and structs
                # feed the compiler a "filled" empty message
                xml.message_info_array += '{"EMPTY",0,{{"","",MAVLINK_TYPE_CHAR,0,0,0}}}, '
    xml.message_info_array = xml.message_info_array[:-2]

    # add some extra field attributes for convenience with arrays
    for m in xml.message:
        m.msg_name = m.name
        if xml.crc_extra:
            m.crc_extra_arg = ", %s" % m.crc_extra
        else:
            m.crc_extra_arg = ""
        for f in m.fields:
            if f.print_format is None:
                f.c_print_format = 'NULL'
            else:
                f.c_print_format = '"%s"' % f.print_format
            if f.array_length != 0:
                f.array_suffix = '[%u]' % f.array_length
                f.array_prefix = '*'
                f.array_tag = '_array'
                f.array_arg = ', %u' % f.array_length
                f.array_return_arg = '%s, %u, ' % (f.name, f.array_length)
                f.array_const = 'const '
                f.decode_left = ''
                f.decode_right = ', %s->%s' % (m.name_lower, f.name)
                f.return_type = 'uint16_t'
                f.get_arg = ', %s *%s' % (f.type, f.name)
                if f.type == 'char':
                    f.c_test_value = '"%s"' % f.test_value
                else:
                    test_strings = []
                    for v in f.test_value:
                        test_strings.append(str(v))
                    f.c_test_value = '{ %s }' % ', '.join(test_strings)
            else:
                f.array_suffix = ''
                f.array_prefix = ''
                f.array_tag = ''
                f.array_arg = ''
                f.array_return_arg = ''
                f.array_const = ''
                f.decode_left = "%s->%s = " % (m.name_lower, f.name)
                f.decode_right = ''
                f.get_arg = ''
                f.return_type = f.type
                if f.type == 'char':
                    f.c_test_value = "'%s'" % f.test_value
                elif f.type == 'uint64_t':
                    f.c_test_value = "%sULL" % f.test_value
                elif f.type == 'int64_t':
                    f.c_test_value = "%sLL" % f.test_value
                else:
                    f.c_test_value = f.test_value

    # cope with uint8_t_mavlink_version
    for m in xml.message:
        m.arg_fields = []
        m.array_fields = []
        m.scalar_fields = []
        for f in m.ordered_fields:
            if f.array_length != 0:
                m.array_fields.append(f)
            else:
                m.scalar_fields.append(f)
        for f in m.fields:
            if not f.omit_arg:
                m.arg_fields.append(f)
                f.putname = f.name
            else:
                f.putname = f.const_value

    generate_mavlink_h(directory, xml)
    generate_version_h(directory, xml)
    generate_main_h(directory, xml)
    for m in xml.message:
        generate_message_h(directory, m)
    generate_testsuite_h(directory, xml)

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


Question: // SetNextToken sets the NextToken field's value.

func (s *ListListenersInput) SetNextToken(v string) *ListListenersInput {
	s.NextToken = &v
	return s
}

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

	// Force new line.
	if parser.mark.column != 0 {
		parser.mark.column = 0
		parser.mark.line++
	}

	// Reset the indentation level.
	if !yaml_parser_unroll_indent(parser, -1) {
		return false
	}

	// Reset simple keys.
	if !yaml_parser_remove_simple_key(parser) {
		return false
	}

	parser.simple_key_allowed = false

	// Create the STREAM-END token and append it to the queue.
	token := yaml_token_t{
		typ:        yaml_STREAM_END_TOKEN,
		start_mark: parser.mark,
		end_mark:   parser.mark,
	}
	yaml_insert_token(parser, -1, &token)
	return true
}

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


Question:
Pause producing or consumption for the provided list of partitions

 @param list [TopicPartitionList] The topic with partitions to pause

 @raise [RdkafkaTopicPartitionListError] When pausing subscription fails.

 @return [nil]

def pause(list)
      unless list.is_a?(TopicPartitionList)
        raise TypeError.new("list has to be a TopicPartitionList")
      end
      tpl = list.to_native_tpl
      response = Rdkafka::Bindings.rd_kafka_pause_partitions(@native_kafka, tpl)

      if response != 0
        list = TopicPartitionList.from_native_tpl(tpl)
        raise Rdkafka::RdkafkaTopicPartitionListError.new(response, list, "Error pausing '#{list.to_h}'")
      end
    end

def _build_tree_by_level(self, time_qualifier, collection_name, since):

        invalid_tree_records = dict()
        invalid_tq_records = dict()

        try:
            job_records = self.job_dao.get_all(collection_name, since)
            for job_record in job_records:
                tree = self.get_tree(job_record.process_name)
                if tree is None:
                    utils.increment_family_property(job_record.process_name, invalid_tree_records)
                    continue

                job_time_qualifier = context.process_context[job_record.process_name].time_qualifier
                if time_qualifier != job_time_qualifier:
                    utils.increment_family_property(job_record.process_name, invalid_tq_records)
                    continue

                tree.update_node(job_record)

        except LookupError:
            self.logger.warning('No job records in {0}.'.format(collection_name))

        for name, counter in invalid_tree_records.items():
            self.logger.warning('Skipping {0} job records for {1} since no tree is handling it.'
                                .format(counter, name))

        for name, counter in invalid_tq_records.items():
            self.logger.warning('Skipping {0} job records for {1} since the process has different time qualifier.'
                                .format(counter, name))

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


Question: $ANTLR start "T__123"

public final void mT__123() throws RecognitionException {
        try {
            int _type = T__123;
            int _channel = DEFAULT_TOKEN_CHANNEL;
            // InternalSARL.g:109:8: ( 'ELSE' )
            // InternalSARL.g:109:10: 'ELSE'
            {
            match("ELSE");

            }

            state.type = _type;
            state.channel = _channel;
        }
        finally {
        }
    }

public boolean matchKeyword(String keyword) {
		return tok.ttype == StreamTokenizer.TT_WORD && tok.sval.equals(keyword)
				&& keywords.contains(tok.sval);
	}

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


Question:
From Python collections module documentation

    moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0

def moving_average(iterable, n):

    it = iter(iterable)
    d = collections.deque(itertools.islice(it, n - 1))
    d.appendleft(0)
    s = sum(d)
    for elem in it:
        s += elem - d.popleft()
        d.append(elem)
        yield s / float(n)

def multiple_chunks(self, chunk_size=None):

        if not chunk_size:
            chunk_size = self.DEFAULT_CHUNK_SIZE
        return self.size > chunk_size

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


Question: Loads simple vendor list

public function loadVendorList()
    {
        $oBaseObject = $this->getBaseObject();
        $sFieldList = $oBaseObject->getSelectFields();
        $sViewName = $oBaseObject->getViewName();
        $this->getBaseObject()->setShowArticleCnt($this->_blShowVendorArticleCnt);

        $sWhere = '';
        if (!$this->isAdmin()) {
            $sWhere = $oBaseObject->getSqlActiveSnippet();
            $sWhere = $sWhere ? " where $sWhere and " : ' where ';
            $sWhere .= "{$sViewName}.oxtitle != '' ";
        }

        $sSelect = "select {$sFieldList} from {$sViewName} {$sWhere} order by {$sViewName}.oxtitle";
        $this->selectString($sSelect);
    }

public static function build($component, array $options = [])
    {
        $ret = $component->options . ' ';
        if ((isset($component->field)) && ($component->field !== '')) {
            $ret .= $component->field . ' ';
        }
        $ret .= TokensList::build($component->unknown);

        return $ret;
    }

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