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

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

func (p *pinner) Flush() error {
	p.lock.Lock()
	defer p.lock.Unlock()

	ctx := context.TODO()

	internalset := cid.NewSet()
	recordInternal := internalset.Add

	root := &mdag.ProtoNode{}
	{
		n, err := storeSet(ctx, p.internal, p.directPin.Keys(), recordInternal)
		if err != nil {
			return err
		}
		if err := root.AddNodeLink(linkDirect, n); err != nil {
			return err
		}
	}

	{
		n, err := storeSet(ctx, p.internal, p.recursePin.Keys(), recordInternal)
		if err != nil {
			return err
		}
		if err := root.AddNodeLink(linkRecursive, n); err != nil {
			return err
		}
	}

	// add the empty node, its referenced by the pin sets but never created
	err := p.internal.Add(ctx, new(mdag.ProtoNode))
	if err != nil {
		return err
	}

	err = p.internal.Add(ctx, root)
	if err != nil {
		return err
	}

	k := root.Cid()

	internalset.Add(k)
	if err := p.dstore.Put(pinDatastoreKey, k.Bytes()); err != nil {
		return fmt.Errorf("cannot store pin state: %v", err)
	}
	p.internalPin = internalset
	return nil
}

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


Question:
Get metadata about a ZIP Code Tabulation Area (ZCTA).

    Parameters
    ----------
    zcta : str
        ID of ZIP Code Tabulation Area

    Returns
    -------
    metadata : dict
        Dict of data about the ZCTA, including lat/long coordinates.

def get_zcta_metadata(zcta):

    conn = metadata_db_connection_proxy.get_connection()
    cur = conn.cursor()
    cur.execute(
        """
      select
        *
      from
        zcta_metadata
      where
        zcta_id = ?
    """,
        (zcta,),
    )
    row = cur.fetchone()
    if row is None:
        raise UnrecognizedZCTAError(zcta)
    return {col[0]: row[i] for i, col in enumerate(cur.description)}

def _check_choices_attribute(self):   # pragma: no cover
        """"""

        if self.choices:
            warning_params = {
                'msg': (
                    "'choices' contains an invalid time zone value '{value}' "
                    "which was not found as a supported time zone by pytz "
                    "{version}."
                ),
                'hint': "Values must be found in pytz.all_timezones.",
                'obj': self,
            }

            for option_key, option_value in self.choices:
                if isinstance(option_value, (list, tuple)):
                    # This is an optgroup, so look inside the group for
                    # options.
                    for optgroup_key in map(lambda x: x[0], option_value):
                        if optgroup_key not in pytz.all_timezones:
                            # Make sure we don't raise this error on empty
                            #   values
                            if optgroup_key not in self.empty_values:
                                # Update the error message by adding the value
                                warning_params.update({
                                    'msg': warning_params['msg'].format(
                                        value=optgroup_key,
                                        version=pytz.VERSION
                                    )
                                })

                                # Return the warning
                                return [
                                    checks.Warning(**warning_params)
                                ]

                elif option_key not in pytz.all_timezones:
                    # Make sure we don't raise this error on empty
                    #   values
                    if option_key not in self.empty_values:
                        # Update the error message by adding the value
                        warning_params.update({
                            'msg': warning_params['msg'].format(
                                value=option_key,
                                version=pytz.VERSION
                            )
                        })

                        # Return the warning
                        return [
                            checks.Warning(**warning_params)
                        ]

        # When no error, return an empty list
        return []

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


Question:
Send a reset link to the given user.

@param  \Illuminate\Http\Request  $request
@return \Illuminate\Http\Response

public function sendResetLinkEmail(Request $request)
    {
        //$this->validate($request, ['email' => 'required|email']);

        $userId = Signup::where('mobile_number', $request->all('mobile_number'))->value('user_id');
        $user = User::find($userId);
        $response = Password::INVALID_USER;
        if ( $user ) {
            $email = [ 'email' => $user->email ];
            // $email = $request->only('email');

            // We will send the password reset link to this user. Once we have attempted
            // to send the link, we will examine the response then see the message we
            // need to show to the user. Finally, we'll send out a proper response.
            $response = $this->broker()->sendResetLink(
                $email, $this->resetNotifier()
            );

            if ($response === Password::RESET_LINK_SENT) {

                //return trans($response);
            }
        }

        // If an error was returned by the password broker, we will get this message
        // translated so we can notify a user of the problem. We'll redirect back
        // to where the users came from so they can attempt this process again.
        //return back()->withErrors(
        //    ['email' => trans($response)]
        //);

        switch ($response)
        {
            case Password::RESET_LINK_SENT:
                return response()->json(['success' => 'true','message'=> "Password recovery link has been send to your email address"]);
                exit;
            case Password::INVALID_USER:
                return response()->json(['error' => 'invalid_credentials','data'=> "We can't find a user that matches these credentials"], 404);
                exit;
        }
    }

protected function generateStandardUrl(array $urlParameters = array(), $absolute = false)
    {
        $urlParameters = $this->addRequestVariablesToUrlParameters($urlParameters);

        $anchor = '';
        if ($this->hasAnchor())
        {
            $anchor = '#'.$this->getAnchor();
        }

        return $this->getRouter()->generate($this->getRouteName(), $urlParameters, $absolute) . $anchor;
    }

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


Question: Prints out market item price.

def get_price(ctx, currency):
    """"""
    appid = ctx.obj['appid']
    title = ctx.obj['title']

    item_ = Item(appid, title)
    item_.get_price_data(currency)

    click.secho('Lowest price: %s %s' % (item_.price_lowest, item_.price_currency), fg='green')

func (s *Statement) Custom(options Options, statements ...Code) *Statement {
	g := &Group{
		close:     options.Close,
		items:     statements,
		multi:     options.Multi,
		name:      "custom",
		open:      options.Open,
		separator: options.Separator,
	}
	*s = append(*s, g)
	return s
}

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


Question:
Request a resource form the API, first checking if there is a cached
    response available. Returns the parsed JSON data.

def get_cached(path, cache_name=None, **kwargs):

    if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:
        if cache_name is None:
            cache_name = path
        cache_file = os.path.join(gw2api.cache_dir, cache_name)
        if mtime(cache_file) >= time.time() - gw2api.cache_time:
            with open(cache_file, "r") as fp:
                return json.load(fp)
    else:
        cache_file = None

    r = gw2api.session.get(gw2api.BASE_URL + path, **kwargs)

    if not r.ok:
        try:
            response = r.json()
        except ValueError:  # pragma: no cover
            response = None
        if isinstance(response, dict) and "text" in response:
            r.reason = response["text"]

    r.raise_for_status()
    data = r.json()

    if cache_file:
        with open(cache_file, "w") as fp:
            json.dump(data, fp, indent=2)

    return data

func (c *Client) Read() (*DeviceCollection, error) {
	resp, err := c.doHTTPGet(deviceURL, url.Values{"app_type": {"app_station"}})
	//dc := &DeviceCollection{}

	if err = processHTTPResponse(resp, err, c.Dc); err != nil {
		return nil, err
	}

	return c.Dc, nil
}

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


Question:
Returns the witness transaction id (aka witness id) as per BIP144. For transactions without witness, this is the
same as {@link #getTxId()}.

public Sha256Hash getWTxId() {
        if (cachedWTxId == null) {
            if (!hasWitnesses() && cachedTxId != null) {
                cachedWTxId = cachedTxId;
            } else {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    bitcoinSerializeToStream(baos, hasWitnesses());
                } catch (IOException e) {
                    throw new RuntimeException(e); // cannot happen
                }
                cachedWTxId = Sha256Hash.wrapReversed(Sha256Hash.hashTwice(baos.toByteArray()));
            }
        }
        return cachedWTxId;
    }

func (w *Watcher) handleEvent(data []byte) {
	buf := bytes.NewBuffer(data)
	msg := &cnMsg{}
	hdr := &procEventHeader{}

	binary.Read(buf, byteOrder, msg)
	binary.Read(buf, byteOrder, hdr)

	switch hdr.What {
	case PROC_EVENT_FORK:
		event := &forkProcEvent{}
		binary.Read(buf, byteOrder, event)
		ppid := int(event.ParentTgid)
		pid := int(event.ChildTgid)

		if w.isWatching(ppid, PROC_EVENT_EXEC) {
			// follow forks
			watch, _ := w.watches[ppid]
			w.Watch(pid, watch.flags)
		}

		if w.isWatching(ppid, PROC_EVENT_FORK) {
			w.Fork <- &ProcEventFork{ParentPid: ppid, ChildPid: pid}
		}
	case PROC_EVENT_EXEC:
		event := &execProcEvent{}
		binary.Read(buf, byteOrder, event)
		pid := int(event.ProcessTgid)

		if w.isWatching(pid, PROC_EVENT_EXEC) {
			w.Exec <- &ProcEventExec{Pid: pid}
		}
	case PROC_EVENT_EXIT:
		event := &exitProcEvent{}
		binary.Read(buf, byteOrder, event)
		pid := int(event.ProcessTgid)

		if w.isWatching(pid, PROC_EVENT_EXIT) {
			w.RemoveWatch(pid)
			w.Exit <- &ProcEventExit{Pid: pid}
		}
	}
}

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


Question: // LGet is like Get but does not follow a symlink at the end of the path.

func LGet(path, name string) ([]byte, error) {
	return get(path, name, func(name string, data []byte) (int, error) {
		return lgetxattr(path, name, data)
	})
}

func (c *Client) MGet(keys ...string) ([]string, error) {
	tmp := make([]interface{}, len(keys)+1)
	tmp[0] = "MGET"
	for n, k := range keys {
		tmp[n+1] = k
	}
	v, err := c.execOnFirst(true, tmp...)
	if err != nil {
		return nil, err
	}
	switch v.(type) {
	case []interface{}:
		items := v.([]interface{})
		resp := make([]string, len(items))
		for n, item := range items {
			switch item.(type) {
			case string:
				resp[n] = item.(string)
			}
		}
		return resp, nil
	}
	return nil, ErrServerError
}

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


Question: Private Helpers.

function setConfigurationAndOptions(pcConfig) {
	// Clone pcConfig.
	this.pcConfig = merge(true, pcConfig);

	// Fix pcConfig.
	Adapter.fixPeerConnectionConfig(this.pcConfig);

	this.options = {
		iceTransportsRelay: (this.pcConfig.iceTransports === 'relay'),
		iceTransportsNone: (this.pcConfig.iceTransports === 'none'),
		gatheringTimeout: this.pcConfig.gatheringTimeout,
		gatheringTimeoutAfterRelay: this.pcConfig.gatheringTimeoutAfterRelay
	};

	// Remove custom rtcninja.RTCPeerConnection options from pcConfig.
	delete this.pcConfig.gatheringTimeout;
	delete this.pcConfig.gatheringTimeoutAfterRelay;

	debug('setConfigurationAndOptions | processed pcConfig: %o', this.pcConfig);
}

protected function hint(question_attempt $qa, question_hint $hint) {
        return html_writer::nonempty_tag('div',
                $qa->get_question()->format_hint($hint, $qa), array('class' => 'hint'));
    }

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


Question:
Number of husbands.

@return string

public function totalMarriedMales(): string
    {
        $n = (int) DB::table('families')
            ->where('f_file', '=', $this->tree->id())
            ->where('f_gedcom', 'LIKE', "%\n1 MARR%")
            ->distinct()
            ->count('f_husb');

        return I18N::number($n);
    }

public static function createSellReturn($id, $printerNumber, $taxSystem, Correction $correction)
    {
        return new static($id, static::INTENT_SELL_RETURN, $printerNumber, $taxSystem, $correction);
    }

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


Question:
Disable the profiler if the number of disable requests matches the
        number of enable requests.

def disable_by_count(self):

        if self.enable_count > 0:
            self.enable_count -= 1
            if self.enable_count == 0:
                self.disable()

def _monitor_pbc_status(self):
        """"""
        LOG.info('Starting to Monitor PBC status.')
        inspect = celery.current_app.control.inspect()
        workers = inspect.ping()
        start_time = time.time()
        while workers is None:
            time.sleep(0.1)
            elapsed = time.time() - start_time
            if elapsed > 20.0:
                LOG.warning('PBC not found!')
                break
        if workers is not None:
            for worker in workers:
                _tasks = inspect.registered_tasks()[worker]
                LOG.info('Worker: %s tasks:', worker)
                for task_index, task_name in enumerate(_tasks):
                    LOG.info('  %02d : %s', task_index, task_name)

        while True:
            LOG.info('Checking PBC status (%d/%d)', self._num_pbcs,
                     self._max_pbcs)
            celery_app = celery.current_app
            inspect = celery_app.control.inspect()
            workers = inspect.ping()
            if workers is None:
                LOG.warning('PBC service not found!')
            else:
                LOG.info('PBC state:  %s', celery_app.events.State())
                _active = inspect.active()
                _scheduled = inspect.scheduled()
                for worker in workers:
                    LOG.info('  Worker %s: scheduled: %s, active: %s',
                             worker, _active[worker], _scheduled[worker])
            time.sleep(self._report_interval)

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


Question:
Creates a document from a string

@param  string  $string  the source string
@return  bool  true if great success!
@throws  InvalidArgumentException  if $string is not a string
@since  0.1.0

public function read($string)
	{
		// if $string is not a string, short-circuit
		if ( ! is_string($string)) {
			throw new \InvalidArgumentException(
				__METHOD__."() expects parameter one, string, to, er, be a string"
			);
		}

		// otherwise, create a new text chunker
		$chunker = new \Jstewmc\Chunker\Text($string);

		return $this->create($chunker);
	}

function() {
        var doc = null;
        var docStrings = [
            "Msxml2.DOMDocument.6.0",
            "Msxml2.DOMDocument.5.0",
            "Msxml2.DOMDocument.4.0",
            "MSXML2.DOMDocument.3.0",
            "MSXML2.DOMDocument",
            "MSXML.DOMDocument",
            "Microsoft.XMLDOM"
        ];

        for (var d = 0; d < docStrings.length; d++) {
            if (doc === null) {
                try {
                    doc = new ActiveXObject(docStrings[d]);
                } catch (e) {
                    doc = null;
                }
            } else {
                break;
            }
        }

        return doc;
    }

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


Question: internal methods =

function getBaseUrl (hostUrl, psaDoc, relType, desc) {
  assert(psaDoc && typeof psaDoc === 'object', 'Invalid PSA service description document')
  assert(psaDoc.links && Array.isArray(psaDoc.links), 'Invalid PSA service description document (no links array)')
  var link = psaDoc.links.find(link => {
    var rel = link.rel
    return rel && typeof rel === 'string' && rel.indexOf(relType) !== -1
  })
  if (!link) {
    throw new Error(`Service does not provide the pinning-service ${desc} API (rel ${relType})`)
  }
  var href = link.href
  assert(href && typeof href === 'string', 'Invalid PSA service description document (no href on API link)')
  if (href.startsWith('/')) {
    href = hostUrl + link.href
  }
  return href
}

private void registerChildInternal(IgnoreDomainResourceTypeResource child) {
        child.setParent(this);
        children.put(child.getName(), child);
    }

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


Question:
returns a list of all the ResourceBuilders listening to the Event-ID
@param event the eventID
@return a List of ResourceBuilders

private List<ResourceBuilderModel> getRegisteredListForEvent(String event) {
        if(eventSubscribers.containsKey(event)) {
            return eventSubscribers.get(event);
        } else {
            LinkedList<ResourceBuilderModel> tempList = new LinkedList<>();
            eventSubscribers.put(event, tempList);
            return tempList;
        }
    }

def consume(self, routingKey, msg):

        builder_info = yield self.master.data.get(("builders", msg['builderid']))

        if self._builder_name_matches(builder_info):
            properties = yield self.master.data.get(("builds", msg['buildid'], "properties"))

            if self._regex:
                filtered_prop_names = [
                    pn for pn in properties if re.match(self._property_name, pn)]
            else:
                filtered_prop_names = [self._property_name]

            for pn in filtered_prop_names:
                try:
                    ret_val = self._callback(properties, pn)
                except KeyError:
                    raise CaptureCallbackError("CaptureProperty failed."
                                               " The property %s not found for build number %s on"
                                               " builder %s."
                                               % (pn, msg['number'], builder_info['name']))
                context = self._defaultContext(msg, builder_info['name'])
                series_name = "%s-%s" % (builder_info['name'], pn)
                post_data = {
                    "name": pn,
                    "value": ret_val
                }
                yield self._store(post_data, series_name, context)

        else:
            yield defer.succeed(None)

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


Question: Updates the font in the preview component according to the selected values.

private void updateComponents() {
        updatingComponents = true;

        Font font = getFont();

        fontList.setSelectedValue(font.getName(), true);
        sizeList.setSelectedValue(font.getSize(), true);
        boldCheckBox.setSelected(font.isBold());
        italicCheckBox.setSelected(font.isItalic());

        if (previewText == null) {
            previewLabel.setText(font.getName());
        }

        // set the font and fire a property change
        Font oldValue = previewLabel.getFont();
        previewLabel.setFont(font);
        firePropertyChange("font", oldValue, font);

        updatingComponents = false;
    }

public BaseFontParameters getBaseFontParameters(String name) {
        String alias = (String)aliases.get(name);
        if (alias == null)
            return (BaseFontParameters)mapper.get(name);
        BaseFontParameters p = (BaseFontParameters)mapper.get(alias);
        if (p == null)
            return (BaseFontParameters)mapper.get(name);
        else
            return p;
    }

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


Question: Parse any date format

static final java.util.Date parseDate(String formatted) {
        if (formatted == null || formatted.trim().equals(""))
            return null;

        try {
            DatatypeFactory factory = DatatypeFactory.newInstance();
            XMLGregorianCalendar calendar = factory.newXMLGregorianCalendar(formatted);
            return calendar.toGregorianCalendar().getTime();
        }
        catch (Exception e) {
            Matcher matcher = PATTERN_DD_MM_YYYY.matcher(formatted);

            // Try matching dd.MM.yyyy date formats first
            if (matcher.find()) {
                String yyyy = matcher.group(3);
                String mm = matcher.group(2);
                String dd = matcher.group(1);
                String hh = defaultIfEmpty(matcher.group(4), "0");
                String min = defaultIfEmpty(matcher.group(5), "0");
                String ss = defaultIfEmpty(matcher.group(6), "0");
                String ms = defaultIfEmpty(matcher.group(7), "0");

                return getDate(Integer.parseInt(yyyy),
                               Integer.parseInt(mm),
                               Integer.parseInt(dd),
                               Integer.parseInt(hh),
                               Integer.parseInt(min),
                               Integer.parseInt(ss),
                               Integer.parseInt(ms));
            }

            // Then try matching yyyy-MM-dd date formats
            else {
                Matcher matcher2 = PATTERN_YYYY_MM_DD.matcher(formatted);

                if (matcher2.find()) {
                    String yyyy = matcher2.group(1);
                    String mm = defaultIfEmpty(matcher2.group(2), "1");
                    String dd = defaultIfEmpty(matcher2.group(3), "1");
                    String hh = defaultIfEmpty(matcher2.group(4), "0");
                    String min = defaultIfEmpty(matcher2.group(5), "0");
                    String ss = defaultIfEmpty(matcher2.group(6), "0");
                    String ms = defaultIfEmpty(matcher2.group(7), "0");

                    return getDate(Integer.parseInt(yyyy),
                                   Integer.parseInt(mm),
                                   Integer.parseInt(dd),
                                   Integer.parseInt(hh),
                                   Integer.parseInt(min),
                                   Integer.parseInt(ss),
                                   Integer.parseInt(ms));
                }

                // Finally, try matching plain timestamps
                else {
                    try {
                        return new Date(Long.parseLong(formatted));
                    } catch (NumberFormatException ignore) {
                        return null;
                    }
                }
            }
        }
    }

def get_all_supported_types_for_ext(self, ext_to_match: str, strict_type_matching: bool = False) -> Set[Type]:

        matching = self.find_all_matching_parsers(required_ext=ext_to_match, strict=strict_type_matching)[0]
        return {typ for types in [p.supported_types for p in (matching[0] + matching[1] + matching[2])]
                for typ in types}

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


Question: Create repository internally. serverUrl and connProps contain specific properties for db creation.

protected void createRepositoryInternally(String backupId, RepositoryEntry rEntry, String rToken,
      DBCreationProperties creationProps) throws RepositoryConfigurationException, RepositoryCreationException
   {
      if (rpcService != null)
      {
         String stringRepositoryEntry = null;
         try
         {
            JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
            JsonValue json = generatorImpl.createJsonObject(rEntry);
            stringRepositoryEntry = json.toString();
         }
         catch (JsonException e)
         {
            throw new RepositoryCreationException("Can not serialize repository entry: " + e.getMessage(), e);
         }

         // notify coordinator node to create repository
         try
         {
            Object result =
               rpcService.executeCommandOnCoordinator(createRepository, true, backupId, stringRepositoryEntry, rToken,
                  creationProps);

            if (result != null)
            {
               if (result instanceof Throwable)
               {
                  throw new RepositoryCreationException("Can't create repository " + rEntry.getName(),
                     (Throwable)result);
               }
               else
               {
                  throw new RepositoryCreationException("createRepository command returned uknown result type.");
               }
            }
         }
         catch (RPCException e)
         {
            Throwable cause = (e).getCause();
            if (cause instanceof RepositoryCreationException)
            {
               throw (RepositoryCreationException)cause;
            }
            else if (cause instanceof RepositoryConfigurationException)
            {
               throw (RepositoryConfigurationException)cause;
            }
            else
            {
               throw new RepositoryCreationException(e.getMessage(), e);
            }
         }

         // execute startRepository at all cluster nodes (coordinator will ignore this command)
         try
         {
            List<Object> results =
               rpcService.executeCommandOnAllNodes(startRepository, true, stringRepositoryEntry, creationProps);

            for (Object result : results)
            {
               if (result != null)
               {
                  if (result instanceof Throwable)
                  {
                     throw new RepositoryCreationException("Repository " + rEntry.getName()
                        + " created on coordinator, but can not be started at other cluster nodes", ((Throwable)result));
                  }
                  else
                  {
                     throw new RepositoryCreationException("startRepository command returns uknown result type");
                  }
               }
            }
         }
         catch (RPCException e)
         {
            throw new RepositoryCreationException("Repository " + rEntry.getName()
               + " created on coordinator, can not be started at other cluster node: " + e.getMessage(), e);
         }
      }
      else
      {
         try
         {
            createRepositoryLocally(backupId, rEntry, rToken, creationProps);
         }
         finally
         {
            pendingRepositories.remove(rToken);
         }
      }
   }

public void serviceName_dedicatedConnect_name_PUT(String serviceName, String name, OvhDedicatedConnect body) throws IOException {
		String qPath = "/vrack/{serviceName}/dedicatedConnect/{name}";
		StringBuilder sb = path(qPath, serviceName, name);
		exec(qPath, "PUT", sb.toString(), body);
	}

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


Question:
/*
! @param {AkeraConnector} Akera connector class

function DiscoveryDecorator(AkeraConnector) {

  function getDatabasesMeta(conn, cb) {
    conn.getMetaData(function(err, meta) {
      if (err !== null)
        cb(err);
      else {
        meta.allDatabases().then(function(dbs) {
          cb(null, dbs);
        }, cb);
      }
    });
  }

  function getTableMeta(conn, schema, table, cb) {
    getDatabasesMeta(conn,
        function(err, dbs) {
          if (err !== null)
            cb(err);
          else {
            var callback = function(err) {
              if (err !== null)
                cb(err);

              for ( var t in tables) {
                if (table === tables[t].getName()) {
                  cb(null, tables[t]);
                  return;
                }
              }

              cb(new Error('Table not found in database: ' + schema + '.'
                  + table));
            };

            // select first database as default if not specified
            if (!schema)
              schema = dbs[0].getLname();

            for ( var d in dbs) {
              if (schema === dbs[d].getLname()) {
                var tables = [];
                var info = {
                  idx : d,
                  schema : schema
                };

                fetchSchemaTables(dbs, info, tables, callback);

                return;
              }
            }
            cb(new Error('Database not connected: ' + schema));
          }
        });
  }

  var dataTypeConversion = {
    DATE : 'Date',
    DATETIME : 'Date',
    'DATETIME-TZ' : 'Date',
    LOGICAL : 'Boolean',
    DECIMAL : 'Number',
    INTEGER : 'Number',
    INT64 : 'Number',
    CHARACTER : 'String',
    CLOB : 'String',
    BLOB : 'Buffer'
  };

  function getTableModel(tblMeta, cb) {
    tblMeta.getAllFields().then(function(fields) {
      var result = [];

      for ( var f in fields) {
        var field = fields[f];

        result.push({
          owner : tblMeta.getDatabase(),
          tableName : tblMeta.getName(),
          columnName : field.name,
          dataType : field.type,
          nullable : field.mandatory ? 'N' : 'Y',
          type : dataTypeConversion[field.type.toUpperCase()]
        });
      }

      cb(null, result);
    }, cb);
  }

  function getTablePrimaryKeys(tblMeta, cb) {
    tblMeta.getPk().then(function(pk) {
      var result = [];

      for ( var f in pk.fields) {
        var field = pk.fields[f];

        result.push({
          owner : tblMeta.getDatabase(),
          tableName : tblMeta.getName(),
          columnName : field.name,
          keySeq : field.fld_pos,
          pkName : field.idx_name
        });
      }

      cb(null, result);
    }, cb);
  }

  function getDatabaseSchemas(dbs, options) {
    var offset = 0;
    var limit = dbs.length;
    var result = [];

    if (options !== null && typeof options === 'object') {
      if (typeof options.offset === 'number')
        offset = options.offset;
      if (typeof options.skip === 'number')
        offset += options.skip;
      if (typeof options.limit === 'number')
        limit = options.limit;
    }

    for (var i = offset; i < limit; i++) {
      result.push({
        catalog : dbs[i].getLname(),
        schema : dbs[i].getLname()
      });
    }

    return result;
  }

  function getModelDefinitions(tblsMeta) {
    var result = [];

    for ( var t in tblsMeta) {
      result.push({
        type : 'table',
        name : tblsMeta[t].getName(),
        owner : tblsMeta[t].getDatabase()
      });
    }

    return result;
  }

  function getDatabaseTables(dbMeta, cb) {
    dbMeta.allTables().then(function(tables) {
      cb(null, tables);
    }, cb);
  }

  function fetchSchemaTables(dbs, info, tables, cb) {
    getDatabaseTables(dbs[info.idx], function(err, tbls) {
      if (err !== null)
        cb(err);
      else {
        for ( var t in tbls) {
          tables.push(tbls[t]);
        }
        // reach the end of databases or found the one we're looking for
        if ((info.schema && info.schema === dbs[info.idx].getLname())
            || ++info.idx === dbs.length)
          cb(null, tables);
        else
          fetchSchemaTables(dbs, info, tables, cb);
      }
    });
  }

  AkeraConnector.prototype.discoverDatabaseSchemas = function(options, cb) {
    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    getDatabasesMeta(this, function(err, dbs) {
      if (err !== null)
        cb(err);
      else {
        cb(null, getDatabaseSchemas(dbs, options));
      }
    });
  };

  /**
   * Discover model definitions
   *
   * @param {Object}
   *         options Options for discovery
   * @param {Function}
   *         [cb] The callback function
   */
  AkeraConnector.prototype.discoverModelDefinitions = function(options, cb) {
    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    var schema = null;
    if (options !== null && typeof options === 'object') {
      schema = options.owner || options.schema;
    }

    getDatabasesMeta(this, function(err, dbs) {
      if (err !== null)
        cb(err);
      else {
        var tables = [];
        var info = {
          idx : 0,
          schema : schema
        };

        fetchSchemaTables(dbs, info, tables, function(err) {
          if (err !== null)
            cb(err);

          cb(null, getModelDefinitions(tables));
        });
      }
    });

  };

  /**
   * Discover model properties from a table
   *
   * @param {String}
   *         table The table name
   * @param {Object}
   *         options The options for discovery (schema/owner)
   * @param {Function}
   *         [cb] The callback function
   *
   */
  AkeraConnector.prototype.discoverModelProperties = function(table, options,
      cb) {
    var schema = null;

    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    if (table === null && typeof table !== 'string') {
      cb(new Error('Table name is mandatory for model properties discovery.'));
      return;
    }

    if (options !== null && typeof options === 'object') {
      schema = options.owner || options.schema;
    }

    if (!schema) {
      schema = this.getDefaultSchema();
    }

    getTableMeta(this, schema, table, function(err, tblMeta) {
      if (err) {
        cb(err);
      } else {
        getTableModel(tblMeta, cb);
      }
    });
  };

  /**
   * Discover model primary keys from a table
   *
   * @param {String}
   *         table The table name
   * @param {Object}
   *         options The options for discovery (schema/owner)
   * @param {Function}
   *         [cb] The callback function
   *
   */
  AkeraConnector.prototype.discoverPrimaryKeys = function(table, options, cb) {
    var schema = null;

    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    if (table === null && typeof table !== 'string') {
      cb(new Error('Table name is mandatory for model primary keys discovery.'));
      return;
    }

    if (options !== null && typeof options === 'object') {
      schema = options.owner || options.schema;
    }

    if (!schema) {
      schema = this.getDefaultSchema();
    }

    getTableMeta(this, schema, table, function(err, tblMeta) {
      if (err) {
        cb(err);
      } else {
        getTablePrimaryKeys(tblMeta, cb);
      }
    });
  };

  AkeraConnector.prototype.getDefaultSchema = function() {
    if (this.dataSource && this.dataSource.settings
        && this.dataSource.settings.database) {
      return this.dataSource.settings.database;
    }
    return undefined;
  };
}

private Canal doToModel(CanalDO canalDo) {
        Canal canal = new Canal();
        try {
            canal.setId(canalDo.getId());
            canal.setName(canalDo.getName());
            canal.setStatus(canalDo.getStatus());
            canal.setDesc(canalDo.getDescription());
            CanalParameter parameter = canalDo.getParameters();
            AutoKeeperCluster zkCluster = autoKeeperClusterService.findAutoKeeperClusterById(parameter.getZkClusterId());
            if (zkCluster != null) {
                parameter.setZkClusters(Arrays.asList(StringUtils.join(zkCluster.getServerList(), ',')));
            }
            canal.setCanalParameter(canalDo.getParameters());
            canal.setGmtCreate(canalDo.getGmtCreate());
            canal.setGmtModified(canalDo.getGmtModified());
        } catch (Exception e) {
            logger.error("ERROR ## change the canal Do to Model has an exception");
            throw new ManagerException(e);
        }

        return canal;
    }

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


Question:
Return a (compiled) regular expression for tokenization.

  Args:
    meta_left, meta_right: e.g. '{' and '}'

  - The regular expressions are memoized.
  - This function is public so the syntax highlighter can use it.

def MakeTokenRegex(meta_left, meta_right):

    key = meta_left, meta_right
    if key not in _token_re_cache:
        # - Need () grouping for re.split
        # - The first character must be a non-space.  This allows us to ignore
        # literals like function() { return 1; } when
        # - There must be at least one (non-space) character inside {}
        _token_re_cache[key] = re.compile(
            r'(' +
            re.escape(meta_left) +
            r'\S.*?' +
            re.escape(meta_right) +
            r')')
    return _token_re_cache[key]

def prepare_metadata(self):
        # type: () -> None

        assert self.source_dir

        with indent_log():
            if self.use_pep517:
                self.prepare_pep517_metadata()
            else:
                self.run_egg_info()

        if not self.req:
            if isinstance(parse_version(self.metadata["Version"]), Version):
                op = "=="
            else:
                op = "==="
            self.req = Requirement(
                "".join([
                    self.metadata["Name"],
                    op,
                    self.metadata["Version"],
                ])
            )
            self._correct_build_location()
        else:
            metadata_name = canonicalize_name(self.metadata["Name"])
            if canonicalize_name(self.req.name) != metadata_name:
                logger.warning(
                    'Generating metadata for package %s '
                    'produced metadata for project name %s. Fix your '
                    '#egg=%s fragments.',
                    self.name, metadata_name, self.name
                )
                self.req = Requirement(metadata_name)

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


Question: Perform a GET request to url with optional authentication

def rest_get(self, url, params=None, headers=None, auth=None, verify=True, cert=None):

        res = requests.get(url, params=params, headers=headers, auth=auth, verify=verify,
                           cert=cert)
        return res.text, res.status_code

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

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


Question: Sets the mass (masses) for the test (datasets).

def set_nom_cap(self, nom_caps, dataset_number=None, validated=None):

        self._set_run_attribute("nom_cap", nom_caps,
                                dataset_number=dataset_number,
                                validated=validated)

def generate_answers
      masterless = @options[:masterless]
      return super if masterless

      dashboard = only_host_with_role(@hosts, 'dashboard')
      database = only_host_with_role(@hosts, 'database')
      master = only_host_with_role(@hosts, 'master')

      the_answers = super
      if dashboard != master
        # in 3.2, dashboard needs the master certname
        the_answers[dashboard.name][:q_puppetmaster_certname] = master.to_s
      end

      # do we want to check for updates?
      pe_check_for_updates = answer_for(@options, :q_pe_check_for_updates, 'n')
      the_answers[dashboard.name][:q_pe_check_for_updates] = pe_check_for_updates
      the_answers[master.name][:q_pe_check_for_updates] = pe_check_for_updates

      if @options[:type] == :upgrade && dashboard != database
        # In a split configuration, there is no way for the upgrader
        # to know how much disk space is available for the database
        # migration. We tell it to continue on, because we're
        # awesome.
        the_answers[dashboard.name][:q_upgrade_with_unknown_disk_space] = 'y'
      end
      @hosts.each do |h|
        h[:answers] = the_answers[h.name]
      end
      return the_answers
    end

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


Question:
// KVSUnlock is similar to KVSSet but only performs the set if the lock can be
// unlocked (the key must already exist and be locked).

func (s *Store) KVSUnlock(idx uint64, entry *structs.DirEntry) (bool, error) {
	tx := s.db.Txn(true)
	defer tx.Abort()

	unlocked, err := s.kvsUnlockTxn(tx, idx, entry)
	if !unlocked || err != nil {
		return false, err
	}

	tx.Commit()
	return true, nil
}

public function updateKstrukturs($id, $data) {
		// find
		$model = $this->get($id);

		if ($model === null) {
			return new NotFound(['message' => 'Skill not found.']);
		}

		// pass update to internal logic
		try {
			$this->doUpdateKstrukturs($model, $data);
		} catch (ErrorsException $e) {
			return new NotValid(['errors' => $e->getErrors()]);
		}

		// save and dispatch events
		$this->dispatch(SkillEvent::PRE_KSTRUKTURS_UPDATE, $model, $data);
		$this->dispatch(SkillEvent::PRE_SAVE, $model, $data);
		$rows = $model->save();
		$this->dispatch(SkillEvent::POST_KSTRUKTURS_UPDATE, $model, $data);
		$this->dispatch(SkillEvent::POST_SAVE, $model, $data);

		if ($rows > 0) {
			return Updated(['model' => $model]);
		}

		return NotUpdated(['model' => $model]);
	}

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


Question:
Guess in how many chunks we should split this file. Should return the same value consistently
for the same file (segments are immutable) so that a full segment can be rebuilt from the upper
layers without anyone actually specifying the chunks numbers.

private int figureChunksNumber(String fileName) throws IOException {
      long fileLength = directory.fileLength(fileName);
      return figureChunksNumber(fileName, fileLength, autoChunkSize);
   }

func Dissect(dissect bool, data []byte) {
	if dissect {
		dissectLock.Lock()
		defer dissectLock.Unlock()

		initParser()
		parser.DecodeLayers(data, &cache.decoded)

		for _, typ := range cache.decoded {
			switch typ {
			case layers.LayerTypeEthernet:
				fmt.Println(gopacket.LayerString(&cache.eth))
			case layers.LayerTypeIPv4:
				fmt.Println(gopacket.LayerString(&cache.ip4))
			case layers.LayerTypeIPv6:
				fmt.Println(gopacket.LayerString(&cache.ip6))
			case layers.LayerTypeTCP:
				fmt.Println(gopacket.LayerString(&cache.tcp))
			case layers.LayerTypeUDP:
				fmt.Println(gopacket.LayerString(&cache.udp))
			case layers.LayerTypeICMPv4:
				fmt.Println(gopacket.LayerString(&cache.icmp4))
			case layers.LayerTypeICMPv6:
				fmt.Println(gopacket.LayerString(&cache.icmp6))
			default:
				fmt.Println("Unknown layer")
			}
		}
		if parser.Truncated {
			fmt.Println("  Packet has been truncated")
		}

	} else {
		fmt.Print(hex.Dump(data))
	}
}

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


Question: Persist user profile to the storage.

private void saveUserProfile(Session session, UserProfile profile, boolean broadcast) throws RepositoryException,
      Exception
   {
      Node userNode = utils.getUserNode(session, profile.getUserName());
      Node profileNode = getProfileNode(userNode);

      boolean isNewProfile = profileNode.isNew();

      if (broadcast)
      {
         preSave(profile, isNewProfile);
      }

      writeProfile(profile, profileNode);

      session.save();
      putInCache(profile);

      if (broadcast)
      {
         postSave(profile, isNewProfile);
      }
   }

def save(self, save_json=True, save_xml=True):

        if self.layer_is_file_based:
            if save_json:
                self.write_to_file(self.json_uri)
            if save_xml:
                self.write_to_file(self.xml_uri)
        else:
            self.write_to_db(save_json, save_xml)

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


Question: Returns the value of the given key; or null of no such entry exists.

public T get(String key) {
        rlock.lock();
        try {
            return map.get(key);
        } finally {
            rlock.unlock();
        }
    }

public K find(final V id, final K defaultValue) {
    	return firstNonNull(find(id), defaultValue);
    }

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


Question:
// Migrate config version `6` to `7'. Remove alias map and introduce
// named Host config. Also no more glob match for host config entries.

func migrateConfigV6ToV7() {
	if !isMcConfigExists() {
		return
	}

	mcCfgV6, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV6())
	fatalIf(probe.NewError(e), "Unable to load mc config V6.")

	if mcCfgV6.Version() != "6" {
		return
	}

	cfgV7 := newConfigV7()
	aliasIndex := 0

	// old Aliases.
	oldAliases := mcCfgV6.Data().(*configV6).Aliases

	// We dropped alias support in v7. We only need to migrate host configs.
	for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts {
		// Look through old aliases, if found any matching save those entries.
		for aliasName, aliasedHost := range oldAliases {
			if aliasedHost == host {
				cfgV7.Hosts[aliasName] = hostConfigV7{
					URL:       host,
					AccessKey: hostCfgV6.AccessKeyID,
					SecretKey: hostCfgV6.SecretAccessKey,
					API:       hostCfgV6.API,
				}
				continue
			}
		}
		if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" ||
			hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" ||
			hostCfgV6.AccessKeyID == "" ||
			hostCfgV6.SecretAccessKey == "" {
			// Ignore default entries. configV7.loadDefaults() will re-insert them back.
		} else if host == "https://s3.amazonaws.com" {
			// Only one entry can exist for "s3" domain.
			cfgV7.Hosts["s3"] = hostConfigV7{
				URL:       host,
				AccessKey: hostCfgV6.AccessKeyID,
				SecretKey: hostCfgV6.SecretAccessKey,
				API:       hostCfgV6.API,
			}
		} else if host == "https://storage.googleapis.com" {
			// Only one entry can exist for "gcs" domain.
			cfgV7.Hosts["gcs"] = hostConfigV7{
				URL:       host,
				AccessKey: hostCfgV6.AccessKeyID,
				SecretKey: hostCfgV6.SecretAccessKey,
				API:       hostCfgV6.API,
			}
		} else {
			// Assign a generic "cloud1", cloud2..." key
			// for all other entries that has valid keys set.
			alias := fmt.Sprintf("cloud%d", aliasIndex)
			aliasIndex++
			cfgV7.Hosts[alias] = hostConfigV7{
				URL:       host,
				AccessKey: hostCfgV6.AccessKeyID,
				SecretKey: hostCfgV6.SecretAccessKey,
				API:       hostCfgV6.API,
			}
		}
	}
	// Load default settings.
	cfgV7.loadDefaults()
	mcNewCfgV7, e := quick.NewConfig(cfgV7, nil)
	fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `7`.")

	e = mcNewCfgV7.Save(mustGetMcConfigPath())
	fatalIf(probe.NewError(e), "Unable to save config version `7`.")

	console.Infof("Successfully migrated %s from version `6` to version `7`.\n", mustGetMcConfigPath())
}

def save_linked_hdds_info(self):

        hdd_table = []
        if self.linked_clone:
            if os.path.exists(self.working_dir):
                hdd_files = yield from self._get_all_hdd_files()
                vm_info = yield from self._get_vm_info()
                for entry, value in vm_info.items():
                    match = re.search("^([\s\w]+)\-(\d)\-(\d)$", entry)  # match Controller-PortNumber-DeviceNumber entry
                    if match:
                        controller = match.group(1)
                        port = match.group(2)
                        device = match.group(3)
                        if value in hdd_files and os.path.exists(os.path.join(self.working_dir, self._vmname, "Snapshots", os.path.basename(value))):
                            log.info("VirtualBox VM '{name}' [{id}] detaching HDD {controller} {port} {device}".format(name=self.name,
                                                                                id=self.id,
                                                                                controller=controller,
                                                                                port=port,
                                                                                device=device))
                            hdd_table.append(
                                {
                                    "hdd": os.path.basename(value),
                                    "controller": controller,
                                    "port": port,
                                    "device": device,
                                }
                            )

            if hdd_table:
                try:
                    hdd_info_file = os.path.join(self.working_dir, self._vmname, "hdd_info.json")
                    with open(hdd_info_file, "w", encoding="utf-8") as f:
                        json.dump(hdd_table, f, indent=4)
                except OSError as e:
                    log.warning("VirtualBox VM '{name}' [{id}] could not write HHD info file: {error}".format(name=self.name,
                                                                                id=self.id,
                                                                                error=e.strerror))

        return hdd_table

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


Question:
Creates the JSON object for the available time entries route response.

    Returns:
      The JSON object for the available time entries route response.

def available_time_entries_impl(self):

    result = {}
    if self._db_connection_provider:
      db = self._db_connection_provider()
      # For each run, pick a tag.
      cursor = db.execute(
          '''
          SELECT
            TagPickingTable.run_name,
            Tensors.step,
            Tensors.computed_time
          FROM (/* For each run, pick any tag. */
            SELECT
              Runs.run_id AS run_id,
              Runs.run_name AS run_name,
              Tags.tag_id AS tag_id
            FROM Runs
            JOIN Tags
              ON Tags.run_id = Runs.run_id
            WHERE
              Tags.plugin_name = ?
            GROUP BY Runs.run_id) AS TagPickingTable
          JOIN Tensors
            ON Tensors.series = TagPickingTable.tag_id
          WHERE Tensors.step IS NOT NULL
          ORDER BY Tensors.step
          ''', (metadata.PLUGIN_NAME,))
      for (run, step, wall_time) in cursor:
        if run not in result:
          result[run] = []
        result[run].append(self._create_time_entry(step, wall_time))
    else:
      # Read data from disk.
      all_runs = self._multiplexer.PluginRunToTagToContent(
          metadata.PLUGIN_NAME)
      for run, tag_to_content in all_runs.items():
        if not tag_to_content:
          # This run lacks data for this plugin.
          continue
        # Just use the list of tensor events for any of the tags to determine
        # the steps to list for the run. The steps are often the same across
        # tags for each run, albeit the user may elect to sample certain tags
        # differently within the same run. If the latter occurs, TensorBoard
        # will show the actual step of each tag atop the card for the tag.
        tensor_events = self._multiplexer.Tensors(
            run, min(six.iterkeys(tag_to_content)))
        result[run] = [self._create_time_entry(e.step, e.wall_time)
                       for e in tensor_events]
    return result

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question: Spend some time to get an accurate size.

def measureSize(self, diffTo, diffFrom, estimatedSize, chunkSize, isInteractive):

        diff = self.toObj.diff(diffTo, diffFrom, estimatedSize)
        isInteractive = self.toObj.bool(isInteractive)
        self.butterStore.showProgress = None if isInteractive else False
        self.butterStore.measureSize(diff, int(chunkSize))
        return self.toDict.diff(diff)

def set_position(self, pos):
        """"""
        time_in_ms = int(pos)*1000
        return self.apple_tv.set_property('dacp.playingtime', time_in_ms)

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


Question: Write the <c:layout> element.

def write_layout(layout = nil, type = nil) # :nodoc:
      tag = 'c:layout'

      if layout
        @writer.tag_elements(tag)  { write_manual_layout(layout, type) }
      else
        @writer.empty_tag(tag)
      end
    end

public static com.liferay.commerce.product.model.CProduct createCProduct(
		long CProductId) {
		return getService().createCProduct(CProductId);
	}

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


Question: Support for keyboard navigation

function (event) {
                    this._lastKeyOrBlurEvent = this._currentKeyOrBlurEvent;
                    switch (event.type) {
                        case "keyup":
                            if (event.keyCode === Key.shift) {
                                this._currentKeyOrBlurEvent = null;
                            } else {
                                this._currentKeyOrBlurEvent = "keyboard";
                            }
                            break;
                        case "focusout":
                            //anchor element no longer in focus, clear up the stack
                            this._currentKeyOrBlurEvent = null;
                            break;
                        default:
                            break;

                    }
                }

@TargetApi(Build.VERSION_CODES.KITKAT)
    public static boolean hasHostCardEmulationNfcFeature(PackageManager manager) {
        return manager.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION);
    }

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


Question: Adds a join clause to the query, allowing for advanced joins with an anonymous function as the second argument. function(table, first, operator, second)

function _join(table, first) {
    var join;
    var joinType = this._joinType();
    if (typeof first === 'function') {
      join = new JoinClause(table, joinType);
      first.call(join, join);
      this._statements.push(join);
      return this;
    }
    if (joinType === 'raw') {
      join = new JoinClause(this.client.raw(table, first), 'raw');
      this._statements.push(join);
      return this;
    }

    join = new JoinClause(table, joinType);
    if (arguments.length > 1) {
      join.on.apply(join, normalizeArr.apply(null, arguments).slice(1));
    }
    this._statements.push(join);
    return this;
  }

func (er *expressionRewriter) constructBinaryOpFunction(l expression.Expression, r expression.Expression, op string) (expression.Expression, error) {
	lLen, rLen := getRowLen(l), getRowLen(r)
	if lLen == 1 && rLen == 1 {
		return expression.NewFunction(er.ctx, op, types.NewFieldType(mysql.TypeTiny), l, r)
	} else if rLen != lLen {
		return nil, ErrOperandColumns.GenByArgs(lLen)
	}
	funcs := make([]expression.Expression, lLen)
	for i := 0; i < lLen; i++ {
		var err error
		funcs[i], err = er.constructBinaryOpFunction(getRowArg(l, i), getRowArg(r, i), op)
		if err != nil {
			return nil, errors.Trace(err)
		}
	}
	return expression.ComposeCNFCondition(er.ctx, funcs...), nil
}

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


Question:
Add the hooks defined in $filters and $actions.

@since 1.0.0

@param array $hooks The contents of $filters or $actions.

final private function add_hooks($hooks)
    {
        foreach ($hooks as $tag => $filter) {
            if (\is_string($filter)) {
                $this->add_filter($tag, $filter);
            } else {
                foreach ($filter as $priority => $callbacks) {
                    if (\is_string($callbacks)) {
                        $this->add_filter($tag, $callbacks, $priority);
                    } else {
                        $count = \count($callbacks);

                        for ($i = 0; $i < $count; $i++) {
                            $this->add_filter($tag, $callbacks[ $i ], $priority);
                        }
                    }
                }
            }
        }
    }

public function getFilters() {
            return array( // Numbers
                'num_format'  => new \Twig_Filter_Function('num::format'),
                // Text
                'limit_words' => new \Twig_Filter_Function('Text::limit_words'),
                'limit_chars' => new \Twig_Filter_Function('Text::limit_chars'),
                'auto_link'   => new \Twig_Filter_Function('Text::auto_link'),
                'auto_p'      => new \Twig_Filter_Function('Text::auto_p'),
                'bytes'       => new \Twig_Filter_Function('Text::bytes'),
                'lower'       => new \Twig_Filter_Function('mb_strtolower'),
                'upper'       => new \Twig_Filter_Function('mb_strtoupper'),
                'ucfirst'     => new \Twig_Filter_Function('ucfirst'),
                'ucwords'     => new \Twig_Filter_Function('ucwords'),
                'strip_tags'  => new \Twig_Filter_Function('strip_tags'),
                'trim'        => new \Twig_Filter_Function('trim'),
                'int'         => new \Twig_Filter_Function('intval'),
                'xss_clean'   => new \Twig_Filter_Function('Security::xss_clean'),
                'urlencode'   => new \Twig_Filter_Function('urlencode'),
                'highlight'   => new \Twig_Filter_Function('\Meerkat\Twig\Twig_Extension::f_highlight'),
            );
        }

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


Question: Builds a response object

protected function buildResponse($e)
	{
		// build a response
		$responseBuilder = new Http\ResponseBuilder();
		return $responseBuilder
			->setStatusCode(500)
			->notCachable()
			->setBody($this->buildResponseBody($e))
			->build();
	}

def wo_resp(self, resp):

        if self._data is not None:
            resp['res'] = self.to_str(self._data)

        return self.wo_json(resp)

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


Question: extracts the header key

def extract_header_value(response, key)
        response.headers[key].class == Array ? response.headers[key].first.to_i : response.headers[key].to_i
      end

func (self *simplePBundle) SetReturnHeader(k string, v string) {
	self.out[k] = v
}

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


Question:
Returns true if this tag should close itself (e.g. no </tag> element)
@return {Boolean} True if this tag should close itself

function() {
    for (var i = this.notSelfClosingTags.length - 1; i >= 0; i--) {
      if (this.tagName == this.notSelfClosingTags[i]) return false;
    }

    return true;
  }

public function leaveNode(Node $node) {
        if ($this->phpClass instanceof PhpClass) {
            if ($node instanceof Class_) {
                if (!empty($node->extends) && count($node->extends->parts) > 0) {
                    $this->phpClass->setExtends(implode('\\', $node->extends->parts));
                }

                if (!empty($node->implements) && is_array($node->implements)) {
                    foreach ($node->implements as $implements) {
                        $this->phpClass->setImplements(implode('\\', $implements->parts));
                    }
                }

                if ($node->type === 0) {
                    $this->phpClass->setClassType(PhpClass::TYPE_CLASS);
                } elseif ($node->type === 16) {
                    $this->phpClass->setClassType(PhpClass::TYPE_ABSTRACT_CLASS);
                } elseif ($node->type === 32) {
                    $this->phpClass->setClassType(PhpClass::TYPE_FINAL_CLASS);
                }

                $this->phpClass->setClass($node->name);
            } elseif ($node instanceof Interface_) {
                if (!empty($node->extends) && is_array($node->extends)) {
                    foreach ($node->extends as $implements) {
                        $this->phpClass->setImplements(implode('\\', $implements->parts));
                    }
                }

                $this->phpClass->setClassType(PhpClass::TYPE_INTERFACE);
                $this->phpClass->setClass($node->name);
            } elseif ($node instanceof Trait_) {
                $this->phpClass->setClassType(PhpClass::TYPE_TRAIT);
                $this->phpClass->setClass($node->name);
            } elseif ($node instanceof Namespace_) {
                $this->phpClass->setNamespace(implode('\\', $node->name->parts));
            } elseif ($node instanceof TraitUse) {
                if (!empty($node->traits) && is_array($node->traits)) {
                    foreach ($node->traits as $trait) {
                        $this->phpClass->setTraits(implode('\\', $trait->parts));
                    }
                }
            }
        }
    }

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


Question: // Return the total size for each argument patterns.

func getTotalSizes(argPatterns []ellipses.ArgPattern) []uint64 {
	var totalSizes []uint64
	for _, argPattern := range argPatterns {
		var totalSize uint64 = 1
		for _, p := range argPattern {
			totalSize = totalSize * uint64(len(p.Seq))
		}
		totalSizes = append(totalSizes, totalSize)
	}
	return totalSizes
}

@SafeVarargs
    public final void waterfall(final C context, final Outcome<C> outcome, final Function<C>... functions) {
        _series(context, outcome, functions);
    }

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


Question:
The Uri Path.

@return the uri path.

public String path() {
    /* build the fully qualified url with all query parameters */
    StringBuilder path = new StringBuilder();
    if (this.target != null) {
      path.append(this.target);
    }
    if (this.uriTemplate != null) {
      path.append(this.uriTemplate.toString());
    }
    if (path.length() == 0) {
      /* no path indicates the root uri */
      path.append("/");
    }
    return path.toString();

  }

protected function GetResponseURL($sResponse)
    {
        $sReturnURLBase = $this->getActivePageService()->getActivePage()->GetRealURLPlain(array(), true);
        if ('.html' === substr($sReturnURLBase, -5)) {
            $sReturnURLBase = substr($sReturnURLBase, 0, -5);
        }
        if ('/' !== substr($sReturnURLBase, -1)) {
            $sReturnURLBase .= '/';
        }
        // remove http:// and https:// since these are set in the interface
        $sReturnURLBase = str_replace('https://', '', $sReturnURLBase);
        $sReturnURLBase = str_replace('http://', '', $sReturnURLBase);

        return $sReturnURLBase.self::URL_IDENTIFIER.$sResponse;
    }

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


Question:
Sets the value of "appId" property. If a null value is passed in, it
indicates that the property is not set.

@param  appId    value of "appId" property

public void setAppId(String appId) {
        if (appId == null) {
            _properties.remove(AMQP_PROP_APP_ID);
            return;
        }
        _properties.put(AMQP_PROP_APP_ID, appId);
    }

func (sf *ScalarFunction) Eval(row chunk.Row) (d types.Datum, err error) {
	var (
		res    interface{}
		isNull bool
	)
	switch tp, evalType := sf.GetType(), sf.GetType().EvalType(); evalType {
	case types.ETInt:
		var intRes int64
		intRes, isNull, err = sf.EvalInt(sf.GetCtx(), row)
		if mysql.HasUnsignedFlag(tp.Flag) {
			res = uint64(intRes)
		} else {
			res = intRes
		}
	case types.ETReal:
		res, isNull, err = sf.EvalReal(sf.GetCtx(), row)
	case types.ETDecimal:
		res, isNull, err = sf.EvalDecimal(sf.GetCtx(), row)
	case types.ETDatetime, types.ETTimestamp:
		res, isNull, err = sf.EvalTime(sf.GetCtx(), row)
	case types.ETDuration:
		res, isNull, err = sf.EvalDuration(sf.GetCtx(), row)
	case types.ETJson:
		res, isNull, err = sf.EvalJSON(sf.GetCtx(), row)
	case types.ETString:
		res, isNull, err = sf.EvalString(sf.GetCtx(), row)
	}

	if isNull || err != nil {
		d.SetValue(nil)
		return d, err
	}
	d.SetValue(res)
	return
}

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


Question:
Sorts the data before return in dataBuilder.

@param {Object} dataObj - An object containing the data and schema.
@param {Array} sortingDetails - An array containing the sorting configs.

function sortData(dataObj, sortingDetails) {
    const { data, schema } = dataObj;
    let fieldName;
    let sortMeta;
    let fDetails;
    let i = sortingDetails.length - 1;

    for (; i >= 0; i--) {
        fieldName = sortingDetails[i][0];
        sortMeta = sortingDetails[i][1];
        fDetails = fieldInSchema(schema, fieldName);

        if (!fDetails) {
            // eslint-disable-next-line no-continue
            continue;
        }

        if (isCallable(sortMeta)) {
            // eslint-disable-next-line no-loop-func
            mergeSort(data, (a, b) => sortMeta(a[fDetails.index], b[fDetails.index]));
        } else if (isArray(sortMeta)) {
            const groupedData = groupData(data, fDetails.index);
            const sortingFn = sortMeta[sortMeta.length - 1];
            const targetFields = sortMeta.slice(0, sortMeta.length - 1);
            const targetFieldDetails = targetFields.map(f => fieldInSchema(schema, f));

            groupedData.forEach((groupedDatum) => {
                groupedDatum.push(createSortingFnArg(groupedDatum, targetFields, targetFieldDetails));
            });

            mergeSort(groupedData, (a, b) => {
                const m = a[2];
                const n = b[2];
                return sortingFn(m, n);
            });

            // Empty the array
            data.length = 0;
            groupedData.forEach((datum) => {
                data.push(...datum[1]);
            });
        } else {
            sortMeta = String(sortMeta).toLowerCase() === 'desc' ? 'desc' : 'asc';
            mergeSort(data, getSortFn(fDetails.type, sortMeta, fDetails.index));
        }
    }

    dataObj.uids = [];
    data.forEach((value) => {
        dataObj.uids.push(value.pop());
    });
}

public function changeSort(int $id, ?int $prevId, ?int $nextId)
	{
		$this->mapper->changeSort('position', $id, $prevId, $nextId);
	}

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


Question:
Setup the prototype of the entity this mapper works with.

@param  object $prototype

protected function setPrototype($prototype)
    {
        if ($this->entityName) {
            throw RuntimeException::setPrototypeCalledAgain();
        }

        $this->entityName = is_object($prototype)
            ? get_class($prototype)
            : $prototype;
    }

function _gpfDefClassAttrBuild (member, attribute, newPrototype) {
    /*jshint validthis:true*/
    var attributeEntityDefinition = _gpfDefineEntitiesFindByConstructor(attribute.constructor);
    if (!attributeEntityDefinition._singleton) {
        attribute._memberName = member;
        attribute._ClassConstructor = newPrototype.constructor;
    }
    attribute._build(member, this, newPrototype); //eslint-disable-line no-invalid-this
}

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


Question: // Add a point to the given point.

func (p *Point) Add(point *Point) *Point {
	p[0] += point[0]
	p[1] += point[1]

	return p
}

public function votePlus($post_id)
    {
        $this->checkId($post_id);

        return $this->vote($post_id, self::VOTE_PLUS);
    }

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


Question: InternalSARL.g:8533:1: entryRuleXSwitchExpression returns [EObject current=null] : iv_ruleXSwitchExpression= ruleXSwitchExpression EOF ;

public final EObject entryRuleXSwitchExpression() throws RecognitionException {
        EObject current = null;

        EObject iv_ruleXSwitchExpression = null;

        try {
            // InternalSARL.g:8533:58: (iv_ruleXSwitchExpression= ruleXSwitchExpression EOF )
            // InternalSARL.g:8534:2: iv_ruleXSwitchExpression= ruleXSwitchExpression EOF
            {
            if ( state.backtracking==0 ) {
               newCompositeNode(grammarAccess.getXSwitchExpressionRule());
            }
            pushFollow(FOLLOW_1);
            iv_ruleXSwitchExpression=ruleXSwitchExpression();

            state._fsp--;
            if (state.failed) return current;
            if ( state.backtracking==0 ) {
               current =iv_ruleXSwitchExpression;
            }
            match(input,EOF,FOLLOW_2); if (state.failed) return current;

            }

        }

            catch (RecognitionException re) {
                recover(input,re);
                appendSkippedTokens();
            }
        finally {
        }
        return current;
    }

public Filter<S> getFilter() {
        Filter<S> filter = null;
        for (QueryExecutor<S> executor : mExecutors) {
            Filter<S> subFilter = executor.getFilter();
            filter = filter == null ? subFilter : filter.or(subFilter);
        }
        return filter;
    }

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


Question:
// DatasourceReachable - Determines if the named datasource is reachable with
// the given arguments. Reads from the datasource, and discards the returned data.

func (d *Data) DatasourceReachable(alias string, args ...string) bool {
	source, ok := d.Sources[alias]
	if !ok {
		return false
	}
	_, err := d.readSource(source, args...)
	return err == nil
}

def process_raw_data(cls, raw_data):
        """"""
        properties = raw_data.get("properties", {})

        load_balancing_rules = []
        for raw_content in properties.get("loadBalancingRules", []):
            resource = Resource.from_raw_data(raw_content)
            load_balancing_rules.append(resource)
        properties["loadBalancingRules"] = load_balancing_rules

        inbound_nat_rules = []
        for raw_content in properties.get("inboundNatRules", []):
            resource = Resource.from_raw_data(raw_content)
            inbound_nat_rules.append(resource)
        properties["inboundNatRules"] = inbound_nat_rules

        outbound_nat_rules = []
        for raw_content in properties.get("outboundNatRules", []):
            resource = Resource.from_raw_data(raw_content)
            outbound_nat_rules.append(resource)
        properties["outboundNatRules"] = outbound_nat_rules

        raw_content = properties.get("subnet", None)
        if raw_content is not None:
            resource = Resource.from_raw_data(raw_content)
            properties["subnet"] = resource

        return super(FrontendIPConfigurations, cls).process_raw_data(raw_data)

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


Question:
query multi object from database delgate to JdbCQueryTemp's
queryMultiObject method

@param queryParams
@param sqlquery
@return
@throws Exception

public List queryMultiObject(Collection queryParams, String sqlquery) throws Exception {
		JdbcTemp jdbcTemp = new JdbcTemp(dataSource);
		return jdbcTemp.queryMultiObject(queryParams, sqlquery);
	}

public function selectRunningActivity()
	{
		$stmt = $this->pdo->prepare(<<<EOT
SELECT
	t1.*,
	t2.ProjectId AS "Project.ProjectId",
	t2.Name AS "Project.Name",
	t2.Description AS "Project.Description",
	t2.Created AS "Project.Created"
FROM `$this->tableName` AS t1
LEFT JOIN Projects AS t2 ON t1.ProjectId = t2.ProjectId
WHERE t1.Stopped IS NULL OR t1.Stopped = ''
LIMIT 1 ;
EOT
		);
		$res = $stmt->execute();

		if ($res === false) {
			return null;
		}

		$row = $stmt->fetch();

		if (!is_array($row)) {
			return null;
		}

		return $this->prepareEntity($row);
	}

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


Question: //Key provides convenient method to create a Key

func Key(key ...string) string {
	keychain := append(rootChain, key...)
	str := strings.Join(keychain, "/")
	return str + "/"
}

public static <V> Optional<V> associated(Associator associator,
            Class<V> type, Serializable id) {
        return associator.associated(new TypedIdKey<>(type, id), type);
    }

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


Question: Execute queries against MySQL, merge and return as a dict

def ext_pillar(minion_id,
               pillar,
               *args,
               **kwargs):
    '''

    '''
    return MySQLExtPillar().fetch(minion_id, pillar, *args, **kwargs)

def migrate(app_name=None, revision=None):
    ""
    cmd = ['python bin/manage.py syncdb --migrate']
    if app_name:
        cmd.append(app_name)
        if revision:
            cmd.append(revision)
    verun(' '.join(cmd))

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


Question: The distance between two skip-connections.

def skip_connection_distance(a, b):
    """"""
    if a[2] != b[2]:
        return 1.0
    len_a = abs(a[1] - a[0])
    len_b = abs(b[1] - b[0])
    return (abs(a[0] - b[0]) + abs(len_a - len_b)) / (max(a[0], b[0]) + max(len_a, len_b))

def channel_difference(chan, pixel, x, y)
      ChunkyPNG::Color.send(chan, pixel) + ChunkyPNG::Color.send(chan, @images.last[x,y]) - 2 * [ChunkyPNG::Color.send(chan, pixel), ChunkyPNG::Color.send(chan, @images.last[x,y])].min
    end

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


Question:
Get OS hardening Secure TTY audits.

    :returns:  dictionary of audits

def get_audits():

    audits = []
    audits.append(TemplatedFile('/etc/securetty', SecureTTYContext(),
                                template_dir=TEMPLATES_DIR,
                                mode=0o0400, user='root', group='root'))
    return audits

func NewScreen() (Screen, error) {
	// Windows is happier if we try for a console screen first.
	if s, _ := NewConsoleScreen(); s != nil {
		return s, nil
	} else if s, e := NewTerminfoScreen(); s != nil {
		return s, nil
	} else {
		return nil, e
	}
}

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


Question:
{@inheritDoc}

@see org.modeshape.jcr.query.parse.BasicSqlQueryParser#parseLiteralValue(org.modeshape.common.text.TokenStream,
org.modeshape.jcr.query.model.TypeSystem)

@Override
    protected Object parseLiteralValue( TokenStream tokens,
                                        TypeSystem typeSystem ) {
        if (tokens.canConsume("TIMESTAMP")) {
            Position pos = tokens.previousPosition();
            // This should be a timestamp represented as a single-quoted string ...
            String value = removeBracketsAndQuotes(tokens.consume(), tokens.previousPosition());
            TypeFactory<?> dateTimeFactory = typeSystem.getDateTimeFactory();
            try {
                // Convert to a date and then back to a string to get canonical form ...
                Object dateTime = dateTimeFactory.create(value);
                return dateTime;
                // return dateTimeFactory.asString(dateTime);
            } catch (ValueFormatException e) {
                String msg = GraphI18n.expectingLiteralAndUnableToParseAsDate.text(value, pos.getLine(), pos.getColumn());
                throw new ParsingException(pos, msg);
            }
        }
        return super.parseLiteralValue(tokens, typeSystem);
    }

public static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation) {

        if (operation == null)
            throw new IllegalArgumentException(
                    "The operation parameter must be specified!");

        ShapeMarshaller marshaller = new ShapeMarshaller()
                .withAction(operation.getName())
                .withVerb(operation.getHttp().getMethod())
                .withRequestUri(operation.getHttp().getRequestUri());
        Input input = operation.getInput();
        if (input != null) {
            marshaller.setLocationName(input.getLocationName());
            // Pass the xmlNamespace trait from the input reference
            XmlNamespace xmlNamespace = input.getXmlNamespace();
            if (xmlNamespace != null) {
                marshaller.setXmlNameSpaceUri(xmlNamespace.getUri());
            }
        }
        if (!StringUtils.isNullOrEmpty(service.getTargetPrefix()) && Metadata.isNotRestProtocol(service.getProtocol())) {
            marshaller.setTarget(service.getTargetPrefix() + "." + operation.getName());
        }
        return marshaller;

    }

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


Question:
// Greater asserts that the first element is greater than the second
//
//    assert.Greater(t, 2, 1)
//    assert.Greater(t, float64(2), float64(1))
//    assert.Greater(t, "b", "a")

func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
	if h, ok := t.(tHelper); ok {
		h.Helper()
	}

	e1Kind := reflect.ValueOf(e1).Kind()
	e2Kind := reflect.ValueOf(e2).Kind()
	if e1Kind != e2Kind {
		return Fail(t, "Elements should be the same type", msgAndArgs...)
	}

	res, isComparable := compare(e1, e2, e1Kind)
	if !isComparable {
		return Fail(t, fmt.Sprintf("Can not compare type \"%s\"", reflect.TypeOf(e1)), msgAndArgs...)
	}

	if res != -1 {
		return Fail(t, fmt.Sprintf("\"%s\" is not greater than \"%s\"", e1, e2), msgAndArgs...)
	}

	return true
}

public function assertBundles(TableNode $expected) {
    $bundle_info = [];
    foreach ($this->getContentEntityTypes() as $entity_type) {
      $bundles = $this->entityTypeManager()
        ->getStorage($entity_type->getBundleEntityType())
        ->loadMultiple();
      foreach ($bundles as $bundle) {
        $description = '';
        $description_getter = 'getDescription';
        if (method_exists($bundle, $description_getter)) {
          $description = call_user_func([
            $bundle,
            $description_getter,
          ]);
        }
        if (!isset($description) || !$description) {
          $description = '';
        }

        $bundle_info[] = [
          $bundle->label(),
          $bundle->id(),
          $entity_type->getBundleLabel(),
          $description,
        ];
      }
    }
    $actual = new TableNode($bundle_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Name',
        'Machine name',
        'Type',
        'Description',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
      ->assert();
  }

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


Question:
Samples random context from a dialog. Contexts are uniformly sampled from the whole dialog.
    :param dialog:
    :param rng:
    :return: context, index of next utterance that follows the context

def create_random_context(dialog, rng, minimum_context_length=2, max_context_length=20):

    # sample dialog context
    #context_turns = rng.randint(minimum_context_length,len(dialog)-1)
    max_len = min(max_context_length, len(dialog)) - 2
    if max_len <= minimum_context_length:
        context_turns = max_len
    else:
        context_turns = rng.randint(minimum_context_length, max_len)

    # create string
    return dialog_turns_to_string(dialog[:context_turns]), context_turns

def _get_db_refs(term):
    """"""
    db_refs = {}
    # Here we extract the text name of the Agent
    # There are two relevant tags to consider here.
    # The <text> tag typically contains a larger phrase surrounding the
    # term but it contains the term in a raw, non-canonicalized form.
    # The <name> tag only contains the name of the entity but it is
    # canonicalized. For instance, MAP2K1 appears as MAP-2-K-1.
    agent_text_tag = term.find('name')
    if agent_text_tag is not None:
        db_refs['TEXT'] = agent_text_tag.text
        # If we have some drum-terms, the matched-name of the first
        # drum-term (e.g. "MAP2K1") is a better value for TEXT than
        # the name of the TERM (e.g. "MAP-2-K-1") so we put that in there
        drum_terms = term.findall('drum-terms/drum-term')
        if drum_terms:
            matched_name = drum_terms[0].attrib.get('matched-name')
            if matched_name:
                db_refs['TEXT'] = matched_name

    # We make a list of scored grounding terms from the DRUM terms
    grounding_terms = _get_grounding_terms(term)
    if not grounding_terms:
        # This is for backwards compatibility with EKBs without drum-term
        # scored entries. It is important to keep for Bioagents
        # compatibility.
        dbid = term.attrib.get('dbid')
        if dbid:
            dbids = dbid.split('|')
            for dbname, dbid in [d.split(':') for d in dbids]:
                if not db_refs.get(dbname):
                    db_refs[dbname] = dbid
        return db_refs, None, []

    # This is the INDRA prioritization of grounding name spaces. Lower score
    # takes precedence.
    ns_priority = {
        'HGNC': 1,
        'UP': 1,
        'FPLX': 2,
        'CHEBI': 3,
        'PC': 3,
        'GO': 4,
        'FA': 5,
        'XFAM': 5,
        'NCIT': 5
    }
    # We get the top priority entry from each score group
    score_groups = itertools.groupby(grounding_terms, lambda x: x['score'])
    top_per_score_group = []
    ambiguities = []
    for score, group in score_groups:
        entries = list(group)
        for entry in entries:
            priority = 100
            for ref_ns, ref_id in entry['refs'].items():
                # Skip etc UP entries
                if ref_ns == 'UP' and ref_id == 'etc':
                    continue
                try:
                    priority = min(priority, ns_priority[ref_ns])
                except KeyError:
                    pass
                if ref_ns == 'UP':
                    if not up_client.is_human(ref_id):
                        priority = 4
            entry['priority'] = priority
        if len(entries) > 1:
            top_entry = entries[0]
            top_idx = 0
            for i, entry in enumerate(entries):
                # We take the lowest priority entry within the score group
                # as the top entry
                if entry['priority'] < top_entry['priority']:
                    # This is a corner case in which a protein family
                    # should be prioritized over a specific protein,
                    # specifically when HGNC was mapped from NCIT but
                    # FPLX was not mapped from NCIT, the HGNC shouldn't
                    # take precedence.
                    if entry.get('comment') == 'HGNC_FROM_NCIT' and \
                        'FPLX' in top_entry['refs'] and \
                        top_entry.get('comment') != 'FPLX_FROM_NCIT':
                        continue
                    top_entry = entry
                    top_idx = i
            for i, entry in enumerate(entries):
                if i == top_idx:
                    continue
                if (entry['priority'] - top_entry['priority']) <= 1:
                    ambiguities.append((top_entry, entry))
        else:
            top_entry = entries[0]
        top_per_score_group.append(top_entry)
    # Get the top priority for each score group
    priorities = [entry['priority'] for entry in top_per_score_group]

    # By default, we coose the top priority entry from the highest score group
    top_grounding = top_per_score_group[0]
    # Sometimes the top grounding has much lower priority and not much higher
    # score than the second grounding. Typically 1.0 vs 0.82857 and 5 vs 2.
    # In this case we take the second entry. A special case is handled where
    # a FPLX entry was mapped from FA, in which case priority difference of < 2
    # is also accepted.
    if len(top_per_score_group) > 1:
        score_diff = top_per_score_group[0]['score'] - \
                     top_per_score_group[1]['score']
        priority_diff = top_per_score_group[0]['priority'] - \
                        top_per_score_group[1]['priority']
        if score_diff < 0.2 and (priority_diff >= 2 or \
            top_per_score_group[0].get('comment') == 'FPLX_FROM_FA'):
            top_grounding = top_per_score_group[1]
    relevant_ambiguities = []
    for amb in ambiguities:
        if top_grounding not in amb:
            continue
        if top_grounding == amb[0]:
            relevant_ambiguities.append({'preferred': amb[0],
                                         'alternative': amb[1]})
        else:
            relevant_ambiguities.append({'preferred': amb[1],
                                         'alternative': amb[0]})

    for k, v in top_grounding['refs'].items():
        db_refs[k] = v

    # Now standardize db_refs to the INDRA standards
    # We need to add a prefix for CHEBI
    chebi_id = db_refs.get('CHEBI')
    if chebi_id and not chebi_id.startswith('CHEBI:'):
        db_refs['CHEBI'] = 'CHEBI:%s' % chebi_id
    # We need to strip the trailing version number for XFAM and rename to PF
    pfam_id = db_refs.get('XFAM')
    if pfam_id:
        pfam_id = pfam_id.split('.')[0]
        db_refs.pop('XFAM', None)
        db_refs['PF'] = pfam_id
    # We need to add GO prefix if it is missing
    go_id = db_refs.get('GO')
    if go_id:
        if not go_id.startswith('GO:'):
            db_refs['GO'] = 'GO:%s' % go_id
    # We need to deal with Nextprot families
    nxp_id = db_refs.get('FA')
    if nxp_id:
        db_refs.pop('FA', None)
        db_refs['NXPFA'] = nxp_id
    # We need to rename PC to PUBCHEM
    pc_id = db_refs.get('PC')
    if pc_id:
        db_refs.pop('PC', None)
        db_refs['PUBCHEM'] = pc_id

    # Here we also get and return the type, which is a TRIPS
    # ontology type. This is to be used in the context of
    # Bioagents.
    ont_type = top_grounding['type']

    return db_refs, ont_type, relevant_ambiguities

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


Question: // nodeAggregations returns a metric timeseries for a metric of the Node entity.

func (a *HistoricalApi) nodeAggregations(request *restful.Request, response *restful.Response) {
	key := core.HistoricalKey{
		ObjectType: core.MetricSetTypeNode,
		NodeName:   request.PathParameter("node-name"),
	}
	a.processAggregationRequest(key, request, response)
}

func (g *Cloud) ListNetworkEndpoints(name, zone string, showHealthStatus bool) ([]*computebeta.NetworkEndpointWithHealthStatus, error) {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	mc := newNetworkEndpointGroupMetricContext("list_networkendpoints", zone)
	healthStatus := "SKIP"
	if showHealthStatus {
		healthStatus = "SHOW"
	}
	req := &computebeta.NetworkEndpointGroupsListEndpointsRequest{
		HealthStatus: healthStatus,
	}
	l, err := g.c.BetaNetworkEndpointGroups().ListNetworkEndpoints(ctx, meta.ZonalKey(name, zone), req, filter.None)
	return l, mc.Observe(err)
}

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


Question:
Get the top tag IDs.

@param array    $sourceIds
@param int|null $limit
@param bool     $withCount

@return array

public function getTopTagIds(array $sourceIds = [], int $limit = null, bool $withCount = false): array
    {
        /** @var Model $model */
        $model = $this->framework->getAdapter(Model::class);

        $tagIds = $model->getRelatedValues($this->sourceTable, $this->sourceField, $sourceIds);
        $tagIds = \array_map('intval', $tagIds);

        if (0 === \count($tagIds)) {
            return [];
        }

        $helper = [];

        // Create the helper array with tag occurrences
        foreach ($tagIds as $tagId) {
            ++$helper[$tagId];
        }

        // Sort the helper array descending
        \arsort($helper);

        // Strip the count data
        if (!$withCount) {
            $helper = \array_keys($helper);
        }

        return \array_slice($helper, 0, $limit, $withCount);
    }

public function getTopContent($parameters = [], $parseResult = true)
    {
        $this->setParams([
            'metrics'    => 'ga:pageviews,ga:uniquePageviews,ga:timeOnPage,ga:bounces,ga:entrances,ga:exits',
            'dimensions' => 'ga:pagePath',
            'sort'       => '-ga:pageviews',
        ]);

        return $this->execute($parameters, $parseResult);
    }

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


Question: Marshall the given parameter object.

public void marshall(ListProjectsRequest listProjectsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(listProjectsRequest.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(listProjectsRequest.getNextToken(), NEXTTOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question:
Returns a model definition

@param $definition
@param bool $xml
@return array
@throws Exception

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

private function _addError($relationModel, $owner, $relationName, $prettyRelationName)
    {
        foreach ($relationModel->errors as $attribute => $attributeErrors) {
            foreach ($attributeErrors as $error) {
                $owner->addError($relationName, "{$prettyRelationName}: {$error}");
            }
        }
    }

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


Question:
Helpers
Prevents a function from being called too often, waits until a timer elapses to call it again

@param fn Function to call

function debounce(fn) {
	    if (!App.vars.debounceTimer) fn.call(this);
	    if (App.vars.debounceTimer) global.clearTimeout(App.vars.debounceTimer);
	    App.vars.debounceTimer = global.setTimeout(function() {
	        App.vars.debounceTimer = null;
	        fn.call(this);
	    }, App.setup.debounce);
	}

def start(self):

        with self._lock_send_remaining_time:
            if self._send_remaining_time <= 0.0:
                local_send_interval = self._send_interval
                if self._send_interval < 0.1:
                    local_send_interval = 0.1
                self._send_remaining_time = self._send_time
                if self._send_remaining_time < local_send_interval:
                    self._send_remaining_time = local_send_interval
                thread = Thread(target=self._run)
                thread.daemon = True
                thread.start()

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


Question: // Strings hashes a list of strings to a unique hashcode.

func Strings(strings []string) string {
	var buf bytes.Buffer

	for _, s := range strings {
		buf.WriteString(fmt.Sprintf("%s-", s))
	}

	return fmt.Sprintf("%d", String(buf.String()))
}

def digest_sha2(*files)
      files.flatten.collect { |file|
        File.exists?(file) ? Digest::SHA2.hexdigest(File.read(file)) : nil
      }
    end

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


Question: // OverrideHeader replaces the headers of the HTTP response

func (rm *responseModifier) OverrideHeader(b []byte) error {
	header := http.Header{}
	if err := json.Unmarshal(b, &header); err != nil {
		return err
	}
	rm.header = header
	return nil
}

public function assertRegionHeading($heading, $region)
    {
        $regionObj = $this->getRegion($region);

        foreach (array('h1', 'h2', 'h3', 'h4', 'h5', 'h6') as $tag) {
            $elements = $regionObj->findAll('css', $tag);
            if (!empty($elements)) {
                foreach ($elements as $element) {
                    if (trim($element->getText()) === $heading) {
                        return;
                    }
                }
            }
        }

        throw new \Exception(sprintf('The heading "%s" was not found in the "%s" region on the page %s', $heading, $region, $this->getSession()->getCurrentUrl()));
    }

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


Question:
Add static $factory for $key.

@param string $key
@param string $factory
@return StaticFactoryResolver
@throws InvalidStaticFactory

public function addStaticFactory(string $key, string $factory): StaticFactoryResolver
    {
        if (is_subclass_of($factory, StaticFactoryInterface::class, true) === false) {
            throw new InvalidStaticFactory($factory);
        }

        $this->factories[$key] = $factory;

        return $this;
    }

func (c *BootstrapConfig) ConfigureArgs(args *BootstrapTplArgs) error {

	// Attempt to setup sink(s) from high-level config. Note the args are passed
	// by ref and modified in place.
	if err := c.generateStatsSinks(args); err != nil {
		return err
	}

	if c.StatsConfigJSON != "" {
		// StatsConfig overridden explicitly
		args.StatsConfigJSON = c.StatsConfigJSON
	} else {
		// Attempt to setup tags from high-level config. Note the args are passed by
		// ref and modified in place.
		if err := c.generateStatsConfig(args); err != nil {
			return err
		}
	}

	if c.StaticClustersJSON != "" {
		args.StaticClustersJSON = c.StaticClustersJSON
	}
	if c.StaticListenersJSON != "" {
		args.StaticListenersJSON = c.StaticListenersJSON
	}
	// Setup prometheus if needed. This MUST happen after the Static*JSON is set above
	if c.PrometheusBindAddr != "" {
		if err := c.generatePrometheusConfig(args); err != nil {
			return err
		}
	}

	if c.TracingConfigJSON != "" {
		args.TracingConfigJSON = c.TracingConfigJSON
	}

	if c.StatsFlushInterval != "" {
		args.StatsFlushInterval = c.StatsFlushInterval
	}

	return nil
}

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


Question:
Call action with built params

@param callable               $callable
@param ServerRequestInterface $request
@param ResponseInterface      $response
@param array                  $routeArguments

@return mixed
@throws Exception

protected function callHandler(
        callable $callable,
        ServerRequestInterface $request,
        ResponseInterface $response,
        array $routeArguments
    ) {
        # Action is a closure
        if ($callable instanceof Closure) {
            array_unshift($routeArguments, $request, $response);
            $result = call_user_func_array($callable, $routeArguments);
        } else {
            # Action is a method of an Action class
            if (is_array($callable) && $callable[0] instanceof Action\ActionInterface) {
                $callable[0]->setResponse($response);
                $callable[0]->setRequest($request);
            }

            # Call Action method
            $result   = $this->callAction($callable, $request, $response, $routeArguments);
            /** @var Action\ActionInterface $action */
            $action   = $callable[0];
            $response = $action->getResponse();
        }

        if (($result instanceof ResponseInterface)) {
            $response = $result;
        } else {
            $response = $this->buildResponse($result, $response, $request);
        }

        return $response;
    }

func (c *Conn) IndexWithParameters(index string, _type string, id string, parentId string, version int, op_type string,
	routing string, timestamp string, ttl int, percolate string, timeout string, refresh bool,
	args map[string]interface{}, data interface{}) (BaseResponse, error) {
	var url string
	var retval BaseResponse
	url, err := GetIndexUrl(index, _type, id, parentId, version, op_type, routing, timestamp, ttl, percolate, timeout, refresh)
	if err != nil {
		return retval, err
	}
	var method string
	if len(id) == 0 {
		method = "POST"
	} else {
		method = "PUT"
	}
	body, err := c.DoCommand(method, url, args, data)
	if err != nil {
		return retval, err
	}
	if err == nil {
		// marshall into json
		jsonErr := json.Unmarshal(body, &retval)
		if jsonErr != nil {
			return retval, jsonErr
		}
	}
	return retval, err
}

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