Question:
Register a notification.

@param   string $message The message to print.
@param   string $type    The type of notification [self::ERROR|self::SUCCESS|self::INFO].

static function notify( $message, $type )
    {
        $nots = State::get( 'notifications' );
        array_push( $nots, array( 'message' => $message, 'type' => $type ) );
        State::set( 'notifications', $nots );
    }

public void writeExternal(ObjectOutput out) throws IOException {
		if(logger.isDebugEnabled()) {
        	logger.debug("writeExternal - sessionKey=" + sessionKey);
        }

		out.writeObject(sipFactoryImpl);
		if(sessionKey != null) {
			out.writeUTF(sessionKey.toString());
		} else {
			if (null == sipSession) {
				out.writeUTF("");
			} else {
				out.writeUTF(sipSession.getId());
			}
		}
		if(attributes != null && attributes.size() > 0) {
			out.writeInt(attributes.size());
			Object[][] attributesArray = new Object[2][attributes.size()];
			int i = 0;
			for (Entry<String, Object> entry : attributes.entrySet()) {
				attributesArray [0][i] = entry.getKey();
				attributesArray [1][i] = entry.getValue();
				i++;
			}
			out.writeObject(attributesArray);
		} else {
			out.writeInt(0);
		}
		if(transactionApplicationData != null) {
			out.writeBoolean(true);
			out.writeObject(transactionApplicationData);
		} else {
			out.writeBoolean(false);
		}
		out.writeUTF(headerForm.toString());
		if(currentApplicationName != null) {
			out.writeUTF(currentApplicationName);
		} else {
			out.writeUTF("");
		}
		out.writeBoolean(isMessageSent);
		if(ReplicationStrategy.EarlyDialog == StaticServiceHolder.sipStandardService.getReplicationStrategy()) {
			if (logger.isDebugEnabled()) {
				logger.debug("writeExternal transaction = " + transaction);
			}
			if(transaction == null) {
				out.writeUTF("");
			} else {
				if (logger.isDebugEnabled()) {
					logger.debug("writeExternal transactionId = " + transaction.getBranchId() + " transactionType " + (transaction instanceof ServerTransaction));
				}
				out.writeUTF(transaction.getBranchId());
				out.writeBoolean(transaction instanceof ServerTransaction);
			}
		}
		out.writeUTF(message.toString());
	}

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


Question: Backup all zones on control system to the given file.

def zone_schedules_backup(self, filename):
        """"""
        _LOGGER.info("Backing up schedules from ControlSystem: %s (%s)...",
                     self.systemId, self.location.name)

        schedules = {}

        if self.hotwater:
            _LOGGER.info("Retrieving DHW schedule: %s...",
                         self.hotwater.zoneId)

            schedule = self.hotwater.schedule()
            schedules[self.hotwater.zoneId] = {
                'name': 'Domestic Hot Water',
                'schedule': schedule}

        for zone in self._zones:
            zone_id = zone.zoneId
            name = zone.name

            _LOGGER.info("Retrieving Zone schedule: %s - %s", zone_id, name)

            schedule = zone.schedule()
            schedules[zone_id] = {'name': name, 'schedule': schedule}

        schedule_db = json.dumps(schedules, indent=4)

        _LOGGER.info("Writing to backup file: %s...", filename)
        with open(filename, 'w') as file_output:
            file_output.write(schedule_db)

        _LOGGER.info("Backup completed.")

def setup_zk
      unless @zk
        @zk = ZK.new("#{@options[:zkservers]}#{@options[:chroot] || ''}")
        @zk.register(manual_failover_path) do |event|
          handle_manual_failover_update(event)
        end
        @zk.on_connected { @zk.stat(manual_failover_path, :watch => true) }
      end

      create_path(@root_znode)
      create_path(current_state_root)
      @zk.stat(manual_failover_path, :watch => true)
    end

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


Question: Fetch the discovery document at the given url.

def FetchDiscoveryDoc(discovery_url, retries=5):
    """"""
    discovery_urls = _NormalizeDiscoveryUrls(discovery_url)
    discovery_doc = None
    last_exception = None
    for url in discovery_urls:
        for _ in range(retries):
            try:
                content = _GetURLContent(url)
                if isinstance(content, bytes):
                    content = content.decode('utf8')
                discovery_doc = json.loads(content)
                break
            except (urllib_error.HTTPError, urllib_error.URLError) as e:
                logging.info(
                    'Attempting to fetch discovery doc again after "%s"', e)
                last_exception = e
    if discovery_doc is None:
        raise CommunicationError(
            'Could not find discovery doc at any of %s: %s' % (
                discovery_urls, last_exception))
    return discovery_doc

def get_docs(self, arg=None):
        '''

        '''
        if arg:
            if '*' in arg:
                target_mod = arg
                _use_fnmatch = True
            else:
                target_mod = arg + '.' if not arg.endswith('.') else arg
                _use_fnmatch = False
            if _use_fnmatch:
                docs = [(fun, self.functions[fun].__doc__)
                        for fun in fnmatch.filter(self.functions, target_mod)]
            else:
                docs = [(fun, self.functions[fun].__doc__)
                        for fun in sorted(self.functions)
                        if fun == arg or fun.startswith(target_mod)]
        else:
            docs = [(fun, self.functions[fun].__doc__)
                    for fun in sorted(self.functions)]
        docs = dict(docs)
        return salt.utils.doc.strip_rst(docs)

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


Question: function _showTypeDetails()

private static function _convertMatrixReferences($formula) {
		static $matrixReplaceFrom = array('{',';','}');
		static $matrixReplaceTo = array('MKMATRIX(MKMATRIX(','),MKMATRIX(','))');

		//	Convert any Excel matrix references to the MKMATRIX() function
		if (strpos($formula,'{') !== FALSE) {
			//	If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
			if (strpos($formula,'"') !== FALSE) {
				//	So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
				//		the formula
				$temp = explode('"',$formula);
				//	Open and Closed counts used for trapping mismatched braces in the formula
				$openCount = $closeCount = 0;
				$i = FALSE;
				foreach($temp as &$value) {
					//	Only count/replace in alternating array entries
					if ($i = !$i) {
						$openCount += substr_count($value,'{');
						$closeCount += substr_count($value,'}');
						$value = str_replace($matrixReplaceFrom,$matrixReplaceTo,$value);
					}
				}
				unset($value);
				//	Then rebuild the formula string
				$formula = implode('"',$temp);
			} else {
				//	If there's no quoted strings, then we do a simple count/replace
				$openCount = substr_count($formula,'{');
				$closeCount = substr_count($formula,'}');
				$formula = str_replace($matrixReplaceFrom,$matrixReplaceTo,$formula);
			}
			//	Trap for mismatched braces and trigger an appropriate error
			if ($openCount < $closeCount) {
				if ($openCount > 0) {
					return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '}'");
				} else {
					return $this->_raiseFormulaError("Formula Error: Unexpected '}' encountered");
				}
			} elseif ($openCount > $closeCount) {
				if ($closeCount > 0) {
					return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '{'");
				} else {
					return $this->_raiseFormulaError("Formula Error: Unexpected '{' encountered");
				}
			}
		}

		return $formula;
	}

func newEvent(typ string, value interface{}, prevValue interface{}) *event {
	return &event{
		typ:       typ,
		value:     value,
		prevValue: prevValue,
	}
}

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


Question: Reset the CR bit in each input image's DQ array

def resetDQBits(imageObjectList, cr_bits_value=4096):
    """"""

    if cr_bits_value > 0:
        for img in imageObjectList:
            for chip in range(1,img._numchips+1,1):
                sci_chip = img._image[img.scienceExt,chip]
                resetbits.reset_dq_bits(sci_chip.dqfile, cr_bits_value,
                                        extver=chip, extname=sci_chip.dq_extn)

def create_chan_labels(self):

        self.idx_label = []
        for one_grp in self.parent.channels.groups:
            for one_label in one_grp['chan_to_plot']:
                item = QGraphicsSimpleTextItem(one_label)
                item.setBrush(QBrush(QColor(one_grp['color'])))
                item.setFlag(QGraphicsItem.ItemIgnoresTransformations)
                self.idx_label.append(item)

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


Question: ________________________________ TAGS

function(context, descriptor, originalArgs) {
		var name = originalArgs[0],
			template = originalArgs[1];
		var newDescriptor = new SOD();
		template.toHTMLString(context, newDescriptor);
		tagOutput(descriptor, newDescriptor, name);
	}

protected function stripTagAttributes($word)
    {
        $space = $this->stringUtil->strpos($word, ' ', 1);

        if ($space) {
            return '<' . $this->stringUtil->substr($word, 1, $space) . '>';
        }

        return trim($word, '<>');
    }

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


Question:
Returns the Configuration Option for a specific section the current Environment

@param string $key Section/Parameter name
@param mixed $default Default value
@return mixed

public function getEnvOption($key, $default = null)
    {
        if (!array_key_exists('environments', $this->configuration) || !is_array($this->configuration['environments'])) {
            return $default;
        }

        if (!array_key_exists($this->environment, $this->configuration['environments'])) {
            return $default;
        }

        if (array_key_exists($key, $this->configuration['environments'][$this->environment])) {
            return $this->configuration['environments'][$this->environment][$key];
        }

        return $default;
    }

public ApiResponse<DynconfigGetConfigResponse> dynconfigGetConfigWithHttpInfo() throws ApiException {
        com.squareup.okhttp.Call call = dynconfigGetConfigValidateBeforeCall(null, null);
        Type localVarReturnType = new TypeToken<DynconfigGetConfigResponse>(){}.getType();
        return apiClient.execute(call, localVarReturnType);
    }

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


Question:
Determine the number of differing bytes.

    :param buf: original buffer.
    :param fuzzed_buf: fuzzed buffer.
    :return: number of different bytes.
    :rtype: int

def number_of_modified_bytes(buf, fuzzed_buf):

    count = 0
    for idx, b in enumerate(buf):
        if b != fuzzed_buf[idx]:
            count += 1
    return count

func tail(log logger.Logger, which string, stem string, numBytes int) (ret string) {

	numFiles := 0

	log.Debug("+ tailing %s file with stem %q", which, stem)
	defer func() {
		log.Debug("- collected %d bytes from %d files", len(ret), numFiles)
	}()

	if len(stem) == 0 {
		log.Debug("| skipping %s logs (since no stem given)", which)
		return
	}

	lognames := listLogFiles(log, stem)
	var parts []string
	remaining := numBytes

	// Keep reading logs in reverse chronological order until we've read nothing
	// more, or we've filled up numBytes worth of buffer, or we didn't have to read
	// the whole file.
	for _, logname := range lognames {
		data, seeked := tailFile(log, which, logname, remaining)
		if len(data) == 0 {
			break
		}
		parts = append(parts, data)
		numFiles++
		remaining -= len(data)
		if remaining <= 0 || seeked {
			break
		}
	}

	// Reverse the array; took this one-line from StackOverflow answer
	for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
		parts[i], parts[j] = parts[j], parts[i]
	}

	return strings.Join(parts, "")
}

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


Question:
Gets the browsers value for this BrowserTargeting.

@return browsers   * Browsers that are being targeted or excluded by the {@link
LineItem}.

public com.google.api.ads.admanager.axis.v201805.Technology[] getBrowsers() {
        return browsers;
    }

def _init_harness(self):

        self._hc = HarnessController(self.result_dir)
        self._hc.stop()
        time.sleep(1)
        self._hc.start()
        time.sleep(2)

        harness_config = ConfigParser.ConfigParser()
        harness_config.read('%s\\Config\\Configuration.ini' % settings.HARNESS_HOME)
        if harness_config.has_option('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate') and \
                harness_config.getboolean('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate'):
            logger.error('BrowserAutoNavigate in Configuration.ini should be False')
            raise FailError('BrowserAutoNavigate in Configuration.ini should be False')
        if settings.MIXED_DEVICE_TYPE:
            if harness_config.has_option('THREAD_HARNESS_CONFIG', 'EnableDeviceSelection') and \
                    not harness_config.getboolean('THREAD_HARNESS_CONFIG', 'EnableDeviceSelection'):
                logger.error('EnableDeviceSelection in Configuration.ini should be True')
                raise FailError('EnableDeviceSelection in Configuration.ini should be True')

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


Question:
Add the navigation detail link.

@param members the members to be linked
@param liNav the content tree to which the navigation detail link will be added

protected void addNavDetailLink(List<?> members, Content liNav) {
        addNavDetailLink(members.size() > 0 ? true : false, liNav);
    }

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

        return true;
    }

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


Question:
Checks if a database exists on the MySQL server.

    CLI Example:

    .. code-block:: bash

        salt '*' mysql.db_exists 'dbname'

def db_exists(name, **connection_args):
    '''

    '''
    dbc = _connect(**connection_args)
    if dbc is None:
        return False
    cur = dbc.cursor()
    # Warn: here db identifier is not backtyped but should be
    #  escaped as a string value. Note also that LIKE special characters
    # '_' and '%' should also be escaped.
    args = {"dbname": name}
    qry = "SHOW DATABASES LIKE %(dbname)s;"
    try:
        _execute(cur, qry, args)
    except MySQLdb.OperationalError as exc:
        err = 'MySQL Error {0}: {1}'.format(*exc.args)
        __context__['mysql.error'] = err
        log.error(err)
        return False
    cur.fetchall()
    return cur.rowcount == 1

def setup_schema(command, conf, vars):
    """"""
    # Load the models

    # <websetup.websetup.schema.before.model.import>
    from depotexample import model
    # <websetup.websetup.schema.after.model.import>

    # <websetup.websetup.schema.before.metadata.create_all>
    print("Creating tables")
    model.metadata.create_all(bind=config['tg.app_globals'].sa_engine)
    # <websetup.websetup.schema.after.metadata.create_all>
    transaction.commit()
    print('Initializing Migrations')
    import alembic.config, alembic.command
    alembic_cfg = alembic.config.Config()
    alembic_cfg.set_main_option("script_location", "migration")
    alembic_cfg.set_main_option("sqlalchemy.url", config['sqlalchemy.url'])
    alembic.command.stamp(alembic_cfg, "head")

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


Question: Return default distroinfo info file

def info_file(distro=None):
    """"""
    if not distro:
        distro = cfg['DISTRO']
    info_file_conf = distro.upper() + 'INFO_FILE'
    try:
        return cfg[info_file_conf]
    except KeyError:
        raise exception.InvalidUsage(
            why="Couldn't find config option %s for distro: %s"
                % (info_file_conf, distro))

def init_config(self, app):
        """"""
        # Set up API endpoints for records.
        for k in dir(config):
            if k.startswith('RECORDS_REST_'):
                app.config.setdefault(k, getattr(config, k))

        # Resolve the Elasticsearch error handlers
        handlers = app.config['RECORDS_REST_ELASTICSEARCH_ERROR_HANDLERS']
        for k, v in handlers.items():
            handlers[k] = obj_or_import_string(v)

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


Question:
Gets the ReflectionProperty for the single identifier field.

@return \ReflectionProperty

@throws BadMethodCallException If the class has a composite identifier.

public function getSingleIdReflectionProperty()
    {
        if ($this->isIdentifierComposite) {
            throw new BadMethodCallException("Class " . $this->name . " has a composite identifier.");
        }
        return $this->reflFields[$this->identifier[0]];
    }

private Type extractContainingType(Attribute.Compound ca,
                                       DiagnosticPosition pos,
                                       TypeSymbol annoDecl)
    {
        // The next three checks check that the Repeatable annotation
        // on the declaration of the annotation type that is repeating is
        // valid.

        // Repeatable must have at least one element
        if (ca.values.isEmpty()) {
            log.error(pos, "invalid.repeatable.annotation", annoDecl);
            return null;
        }
        Pair<MethodSymbol,Attribute> p = ca.values.head;
        Name name = p.fst.name;
        if (name != names.value) { // should contain only one element, named "value"
            log.error(pos, "invalid.repeatable.annotation", annoDecl);
            return null;
        }
        if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
            log.error(pos, "invalid.repeatable.annotation", annoDecl);
            return null;
        }

        return ((Attribute.Class)p.snd).getValue();
    }

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


Question:
BracketsOpt = { [Annotations] "[" "]" }*

annotations is the list of annotations targeting
the expression t.

private JCExpression bracketsOpt(JCExpression t,
            List<JCAnnotation> annotations) {
        List<JCAnnotation> nextLevelAnnotations = typeAnnotationsOpt();

        if (token.kind == LBRACKET) {
            int pos = token.pos;
            nextToken();
            t = bracketsOptCont(t, pos, nextLevelAnnotations);
        } else if (!nextLevelAnnotations.isEmpty()) {
            if (permitTypeAnnotationsPushBack) {
                this.typeAnnotationsPushedBack = nextLevelAnnotations;
            } else {
                return illegal(nextLevelAnnotations.head.pos);
            }
        }

        if (!annotations.isEmpty()) {
            t = toP(F.at(token.pos).AnnotatedType(annotations, t));
        }
        return t;
    }

public function parse(Twig_Token $token)
    {
        $parser = $this->parser;
        $stream = $parser->getStream();

        $view = $parser->getExpressionParser()->parseExpression();

        $variablesOverride = new Twig_Node_Expression_Array(array(), $token->getLine());
        if ($stream->test(Twig_Token::NAME_TYPE, 'with')) {
            $stream->next();

            $variablesOverride->addElement($this->parser->getExpressionParser()->parseExpression());
        }

        $stream->expect(Twig_Token::BLOCK_END_TYPE);

        $viewTemplateExpr = new Twig_Node_Expression_MethodCall(
            $view,
            'getTemplateFile',
            new Twig_Node_Expression_Array(array(), $token->getLine()),
            $token->getLine()
        );

        $variablesExpr = new Twig_Node_Expression_MethodCall(
            $view,
            'getTemplateVars',
            $variablesOverride,
            $token->getLine()
        );

        return new Twig_Node_Include(
            $viewTemplateExpr,
            $variablesExpr,
            $only = false,
            $ignoreMissing = false,
            $token->getLine()
        );
    }

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


Question:
Creates the shadow user if needed

@param array $userInfo

@return \DreamFactory\Core\Models\BaseModel|\Illuminate\Database\Eloquent\Model|null|static
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException
@throws \Exception

protected function createShadowUser($userInfo)
    {
        $email = filter_var(array_get($userInfo, $this->emailField), FILTER_SANITIZE_EMAIL);
        if (empty($email)) {
            throw new InternalServerErrorException(
                'Failed to retrieve alternate user\'s email address using field ' . $this->emailField . '.'
            );
        }

        $dfUser = User::whereEmail($email)->first();
        if (empty($dfUser)) {
            $altUser = [
                'email'      => $email,
                'first_name' => 'Alternate',
                'last_name'  => 'User',
                'name'       => 'Alternate User'
            ];
            $dfUser = User::create($altUser);
        }

        return $dfUser;
    }

func (fmd *FakeMysqlDaemon) CheckSuperQueryList() error {
	if fmd.ExpectedExecuteSuperQueryCurrent != len(fmd.ExpectedExecuteSuperQueryList) {
		return fmt.Errorf("SuperQueryList wasn't consumed, saw %v queries, was expecting %v", fmd.ExpectedExecuteSuperQueryCurrent, len(fmd.ExpectedExecuteSuperQueryList))
	}
	return nil
}

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


Question: Get the template from: YAML, hierarchy, or class

def template(self, resources):

        template_name = self.acquire(resources, 'template')
        if template_name:
            return template_name
        else:
            # We're putting an exception for "resource", the built-in
            # rtype/directive. We want it to work out-of-the-box without
            # requiring an _templates/resource.html in the docs project.
            # Instead, use the page.html the ships with Sphinx.
            if self.rtype == 'resource':
                return 'page'
            else:
                return self.rtype

def members(self, x):
        """"""
        if x not in self._parents:
            yield x
            return
        cur_x = x
        while True:
            yield cur_x
            cur_x = self._prev_next[cur_x][1]
            if cur_x == x:
                break

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


Question: Callback for upload progress events:

function (e, data) {
                if (data.context) {
                    var progress = Math.floor(data.loaded / data.total * 100);
                    data.context.find('.progress')
                        .attr('aria-valuenow', progress)
                        .find('.bar').css(
                            'width',
                            progress + '%'
                        );
                }
            }

public function getWaiting(TemplateInterface $template, MediaType $mediaType, $createOnDemand = true)
    {
        $filename = $this->worker->getWaitingFilename($template, $mediaType);

        if (file_exists($filename)) {
            return $filename;
        }

        if (!$createOnDemand) {
            return null;
        }

        $this->worker->write($mediaType, $template);

        return $filename;
    }

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


Question:
Format the date to ISO8601 format "combined date and time in UTC". Ex: 2018-05-30T13:07:26Z.

@param \DateTime|null $date

@return null|string

public function formatDateTimeUtc(\DateTime $date = null)
    {
        if (null === $date) {
            return null;
        }

        $date->setTimezone(new \DateTimeZone('UTC'));

        return $date->format("Y-m-d\TH:i:s\Z");
    }

public function parseLiteral($valueNode, ?array $variables = null): Carbon
    {
        if (! $valueNode instanceof StringValueNode) {
            throw new Error(
                'Query error: Can only parse strings got: '.$valueNode->kind,
                [$valueNode]
            );
        }

        return $this->tryParsingDateTime($valueNode->value, Error::class);
    }

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


Question:
@param mixed $value

@throws \Error Thrown if the promise has already been resolved.

private function resolve($value = null)
    {
        if ($this->resolved) {
            $message = "Promise has already been resolved";

            if (isset($this->resolutionTrace)) {
                $trace = formatStacktrace($this->resolutionTrace);
                $message .= ". Previous resolution trace:\n\n{$trace}\n\n";
            } else {
                // @codeCoverageIgnoreStart
                $message .= ", define environment variable AMP_DEBUG or const AMP_DEBUG = true and enable assertions "
                    . "for a stacktrace of the previous resolution.";
                // @codeCoverageIgnoreEnd
            }

            throw new \Error($message);
        }

        \assert((function () {
            $env = \getenv("AMP_DEBUG") ?: "0";
            if (($env !== "0" && $env !== "false") || (\defined("AMP_DEBUG") && \AMP_DEBUG)) {
                $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
                \array_shift($trace); // remove current closure
                $this->resolutionTrace = $trace;
            }

            return true;
        })());

        if ($value instanceof ReactPromise) {
            $value = Promise\adapt($value);
        }

        $this->resolved = true;
        $this->result = $value;

        if ($this->onResolved === null) {
            return;
        }

        $onResolved = $this->onResolved;
        $this->onResolved = null;

        if ($this->result instanceof Promise) {
            $this->result->onResolve($onResolved);
            return;
        }

        try {
            $result = $onResolved(null, $this->result);

            if ($result === null) {
                return;
            }

            if ($result instanceof \Generator) {
                $result = new Coroutine($result);
            }

            if ($result instanceof Promise || $result instanceof ReactPromise) {
                Promise\rethrow($result);
            }
        } catch (\Throwable $exception) {
            Loop::defer(static function () use ($exception) {
                throw $exception;
            });
        }
    }

function toPromise( obj ) {
    if( !obj ) {
        return obj;
    }
    if( isPromise( obj ) ) {
        return obj;
    }
    if( isGeneratorFunction( obj ) || isGenerator( obj ) ) {
        return co.call( this, obj );
    }
    if( 'function' == typeof obj ) {
        return thunkToPromise.call( this, obj );
    }
    if( Array.isArray( obj ) ) {
        return arrayToPromise.call( this, obj );
    }
    if( isObject( obj ) ) {
        return objectToPromise.call( this, obj );
    }
    return obj;
}

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


Question: Write `DatasetInfo` as JSON to `dataset_info_dir`.

def write_to_directory(self, dataset_info_dir):
    """"""
    # Save the metadata from the features (vocabulary, labels,...)
    if self.features:
      self.features.save_metadata(dataset_info_dir)

    if self.redistribution_info.license:
      with tf.io.gfile.GFile(self._license_filename(dataset_info_dir),
                             "w") as f:
        f.write(self.redistribution_info.license)

    with tf.io.gfile.GFile(self._dataset_info_filename(dataset_info_dir),
                           "w") as f:
      f.write(self.as_json)

def _from_dict(cls, _dict):
        """"""
        args = {}
        xtra = _dict.copy()
        if 'id' in _dict:
            args['id'] = _dict.get('id')
            del xtra['id']
        if 'metadata' in _dict:
            args['metadata'] = _dict.get('metadata')
            del xtra['metadata']
        if 'collection_id' in _dict:
            args['collection_id'] = _dict.get('collection_id')
            del xtra['collection_id']
        if 'result_metadata' in _dict:
            args['result_metadata'] = QueryResultMetadata._from_dict(
                _dict.get('result_metadata'))
            del xtra['result_metadata']
        if 'title' in _dict:
            args['title'] = _dict.get('title')
            del xtra['title']
        args.update(xtra)
        return cls(**args)

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


Question:
Send the request

@throws Exceptions\ErrorAPI
@throws Exceptions\InvalidArgument
@throws Exceptions\InvalidResponse

public function execute()
    {
        // Build the previously set data
        $this->networkCtx->setApiCtxData(
            $this->requestCtx
        );

        // Send the request
        $this->networkCtx->sendRequest();

        // Set the request context
        $this->responseCtx->setRequestCtx(
            $this->requestCtx
        );

        // Parse the response
        $this->responseCtx->parseResponse(
            $this->networkCtx->getResponseBody()
        );
    }

public function call($method, $parameters)
    {
        try {
            $ch = curl_init($this->base_url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->encode($method, $parameters));
            curl_setopt($ch, CURLOPT_TIMEOUT, 600);

            $response = curl_exec($ch);

            if ($response === false) {
                $e = new TransportException(curl_error($ch), curl_getinfo($ch, CURLINFO_HTTP_CODE));
                curl_close($ch);

                throw  $e;
            }

            curl_close($ch);

            return $this->decode($response);
        } catch (XmlrpcException $e) {
            throw new TransportException('XML parsing error', 0, $e);
        }
    }

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


Question:
Validates that the provided slice array contains only non-overlapped slices valid for a query {@code reversed}
or not on a table using {@code comparator}.

public static boolean validateSlices(ColumnSlice[] slices, CellNameType type, boolean reversed)
    {
        Comparator<Composite> comparator = reversed ? type.reverseComparator() : type;

        for (int i = 0; i < slices.length; i++)
        {
            Composite start = slices[i].start;
            Composite finish = slices[i].finish;

            if (start.isEmpty() || finish.isEmpty())
            {
                if (start.isEmpty() && i > 0)
                    return false;

                if (finish.isEmpty())
                    return i == slices.length - 1;
            }
            else
            {
                // !finish.isEmpty() is imposed by prior loop
                if (i > 0 && comparator.compare(slices[i - 1].finish, start) >= 0)
                    return false;

                if (comparator.compare(start, finish) > 0)
                    return false;
            }
        }
        return true;
    }

private function minFightersCheck()
    {
        $fighters = $this->getFighters();
        $areas = $this->settings->fightingAreas;
        $fighterType = $this->championship->category->isTeam
            ? trans_choice('laravel-tournaments::core.team', 2)
            : trans_choice('laravel-tournaments::core.competitor', 2);

        $minFighterCount = $fighters->count() / $areas;

        if ($this->settings->hasPreliminary && $fighters->count() / ($this->settings->preliminaryGroupSize * $areas) < 1) {
            throw new TreeGenerationException(trans('laravel-tournaments::core.min_competitor_required', [
                'number' => $this->settings->preliminaryGroupSize * $areas,
                'fighter_type' => $fighterType,
            ]), 422);
        }

        if ($minFighterCount < ChampionshipSettings::MIN_COMPETITORS_BY_AREA) {
            throw new TreeGenerationException(trans('laravel-tournaments::core.min_competitor_required', [
                'number' => ChampionshipSettings::MIN_COMPETITORS_BY_AREA,
                'fighter_type' => $fighterType,
            ]), 422);
        }
    }

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


Question:
// Sign the package and close.
// Passbook needs Apple's intermediate WWDR certificate.

func (p *Package) Sign(cert tls.Certificate, wwdr *x509.Certificate) error {
	if p.err != nil {
		return p.err
	}

	// assert that private key is RSA
	key, ok := cert.PrivateKey.(*rsa.PrivateKey)
	if !ok {
		return errors.New("expected RSA private key type")
	}

	manifestBytes, err := json.Marshal(p.manifest)
	if err != nil {
		return err
	}

	zf, err := p.z.Create("manifest.json")
	if err != nil {
		return err
	}
	zf.Write(manifestBytes)

	// sign manifest.json with PKCS #7
	// and add signature to the zip file
	zf, err = p.z.Create("signature")
	if err != nil {
		return err
	}
	sig, err := pkcs7.Sign2(bytes.NewReader(manifestBytes), cert.Leaf, key, wwdr)
	if err != nil {
		return err
	}
	zf.Write(sig)

	return p.z.Close()
}

def tools_path_identifier(path)
      path_identifier = rvm(:tools, "path-identifier", path.to_s)
      if path_identifier.exit_status == 2
        error_message = "The rvmrc located in '#{path}' could not be loaded, likely due to trust mechanisms."
        error_message << " Please run 'rvm rvmrc {trust,untrust} \"#{path}\"' to continue, or set rvm_trust_rvmrcs_flag to 1."
        raise ErrorLoadingRVMRC, error_message
      end
      return normalize(path_identifier.stdout)
    end

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


Question:
加密
1.构造密钥生成器
2.根据encodeRules规则初始化密钥生成器
3.产生密钥
4.创建和初始化密码器
5.内容加密
6.返回字符串

public static String encode(String content, String secret) {
        try {
            //1.构造密钥生成器，指定为AES算法,不区分大小写
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            //2.根据encodeRules规则初始化密钥生成器
            //生成一个256位的随机源,根据传入的字节数组
            keygen.init(256, new SecureRandom(secret.getBytes()));
            //3.产生原始对称密钥
            SecretKey original_key = keygen.generateKey();
            //4.获得原始对称密钥的字节数组
            byte[] raw = original_key.getEncoded();
            //5.根据字节数组生成AES密钥
            SecretKey key = new SecretKeySpec(raw, "AES");
            //6.根据指定算法AES自成密码器
            Cipher cipher = Cipher.getInstance("AES");
            //7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte[] byte_encode = content.getBytes(StandardCharsets.UTF_8);
            //9.根据密码器的初始化方式--加密：将数据加密
            byte[] byte_AES = cipher.doFinal(byte_encode);
            //10.将加密后的数据转换为字符串
            return new BASE64Encoder().encode(byte_AES);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果有错就返加null
        return null;
    }

private function key_import()
    {
        // Import process
        if ($data = rcube_utils::get_input_value('_keys', rcube_utils::INPUT_POST)) {
            $this->enigma->load_engine();
            $this->enigma->engine->password_handler();

            $result = $this->enigma->engine->import_key($data);

            if (is_array($result)) {
                if (rcube_utils::get_input_value('_generated', rcube_utils::INPUT_POST)) {
                    $this->rc->output->command('enigma_key_create_success');
                    $this->rc->output->show_message('enigma.keygeneratesuccess', 'confirmation');
                }
                else {
                    $this->rc->output->show_message('enigma.keysimportsuccess', 'confirmation',
                        array('new' => $result['imported'], 'old' => $result['unchanged']));

                    if ($result['imported'] && !empty($_POST['_refresh'])) {
                        $this->rc->output->command('enigma_list', 1, false);
                    }
                }
            }
            else {
                $this->rc->output->show_message('enigma.keysimportfailed', 'error');
            }

            $this->rc->output->send();
        }
        else if ($_FILES['_file']['tmp_name'] && is_uploaded_file($_FILES['_file']['tmp_name'])) {
            $this->enigma->load_engine();
            $result = $this->enigma->engine->import_key($_FILES['_file']['tmp_name'], true);

            if (is_array($result)) {
                // reload list if any keys has been added
                if ($result['imported']) {
                    $this->rc->output->command('parent.enigma_list', 1);
                }
                else {
                    $this->rc->output->command('parent.enigma_loadframe');
                }

                $this->rc->output->show_message('enigma.keysimportsuccess', 'confirmation',
                    array('new' => $result['imported'], 'old' => $result['unchanged']));
            }
            else if ($result instanceof enigma_error && $result->getCode() == enigma_error::BADPASS) {
                $this->password_prompt($result);
            }
            else {
                $this->rc->output->show_message('enigma.keysimportfailed', 'error');
            }

            $this->rc->output->send('iframe');
        }
        else if ($err = $_FILES['_file']['error']) {
            if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
                $this->rc->output->show_message('filesizeerror', 'error',
                    array('size' => $this->rc->show_bytes(rcube_utils::max_upload_size())));
            } else {
                $this->rc->output->show_message('fileuploaderror', 'error');
            }

            $this->rc->output->send('iframe');
        }

        $this->rc->output->add_handlers(array(
            'importform' => array($this, 'tpl_key_import_form'),
        ));

        $this->rc->output->set_pagetitle($this->enigma->gettext('keyimport'));
        $this->rc->output->send('enigma.keyimport');
    }

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


Question: region > newToDo (action)

@MemberOrder(sequence = "40")
    public StringInterpolatorDemoToDoItem newToDo(
            @ParameterLayout(named = "Description") @Parameter(regexPattern = "\\w[@&:\\-\\,\\.\\+ \\w]*")
            final String description,
            @ParameterLayout(named = "Documentation page")
            final String documentationPage) {

        final StringInterpolatorDemoToDoItem toDoItem = container.newTransientInstance(StringInterpolatorDemoToDoItem.class);
        toDoItem.setDescription(description);
        toDoItem.setDocumentationPage(documentationPage);

        container.persist(toDoItem);
        container.flush();

        return toDoItem;
    }

public function fieldsAction(Request $request)
    {
        return $this->handleView(
            $this->view(
                array_values(
                    array_diff_key(
                        $this->getManager()->getFieldDescriptors($this->getLocale($request)),
                        [
                            'statusId' => false,
                            'categoryIds' => false,
                        ]
                    )
                ),
                200
            )
        );
    }

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


Question: Print `member` to `f`.

def _write_member_markdown_to_file(self, f, prefix, name, member):
    """"""
    if (inspect.isfunction(member) or inspect.ismethod(member) or
        isinstance(member, property)):
      print("- - -", file=f)
      print("", file=f)
      self._print_function(f, prefix, name, member)
      print("", file=f)
    elif inspect.isclass(member):
      print("- - -", file=f)
      print("", file=f)
      print("%s `class %s` {#%s}" % (prefix, name,
                                     _get_anchor(self._module_to_name, name)),
            file=f)
      print("", file=f)
      self._write_class_markdown_to_file(f, name, member)
      print("", file=f)
    else:
      raise RuntimeError("Member %s has unknown type %s" % (name, type(member)))

protected function write($message, array $record = array())
    {
        $record = array_merge($this->defautlRecord, $record);
        $record['msg'] = $message;
        $this->output->writeln($this->formatter->format($record));
    }

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


Question:
@param \Yosmanyga\Validation\Resource\Definition\ObjectDefinition $definition

@return \Yosmanyga\Validation\Validator\ObjectValidator

public function compile($definition)
    {
        $validators = [];

        if (isset($definition->validators)) {
            if (isset($definition->validators['properties'])) {
                foreach ($definition->validators['properties'] as $property => $validatorDefinitions) {
                    foreach ($validatorDefinitions as $validator) {
                        $validators[$property][] = parent::compile($validator);
                    }
                }
            }
        }

        return new ObjectValidator($validators);
    }

def apply_configuration(yml)
      if yml.include?("packages")
        yml["packages"].each do |k, v|
          valid_data = validate_data("packages", v, PACKAGE_SCHEMA)
          @package_info[k] = valid_data
        end
      end

      if yml.include?("platforms")
        yml["platforms"].each do |k, v|
          valid_data = validate_data("platforms", v, PLATFORM_SCHEMA)
          @platform_info[k] = valid_data
        end
      end

      if yml.include?("compile")
        valid_data = validate_data("compile", yml["compile"], COMPILE_SCHEMA)
        valid_data.each { |k, v| @compile_info[k] = v }
      end

      if yml.include?("unittest")
        valid_data = validate_data("unittest", yml["unittest"], UNITTEST_SCHEMA)
        valid_data.each { |k, v| @unittest_info[k] = v }
      end

      self
    end

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


Question:
Whether the URI is a relative-path reference.

A relative reference that does not begin with a slash character is termed a relative-path reference.

@param UriInterface $uri

@return bool
@link https://tools.ietf.org/html/rfc3986#section-4.2

public static function isRelativePathReference(UriInterface $uri)
    {
        $uriPath = $uri->getPath();
        return $uri->getScheme() === ''
            && $uri->getAuthority() === ''
            && (!isset($uriPath[0]) || $uriPath[0] !== '/');
    }

def child_url_record(self, url: str, inline: bool=False,
                         link_type: Optional[LinkType]=None,
                         post_data: Optional[str]=None,
                         level: Optional[int]=None):
        '''
        '''
        url_record = URLRecord()
        url_record.url = url
        url_record.status = Status.todo
        url_record.try_count = 0
        url_record.level = self.url_record.level + 1 if level is None else level
        url_record.root_url = self.url_record.root_url or self.url_record.url
        url_record.parent_url = self.url_record.url
        url_record.inline_level = (self.url_record.inline_level or 0) + 1 if inline else 0
        url_record.link_type = link_type
        url_record.post_data = post_data

        return url_record

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


Question: Imports plugin manifest files to the database.

protected function import()
    {
        $plugin = (object) null;
        $plugin->name = basename($this->composerPackage->getPrettyName());
        $plugin->version = substr($this->composerPackage->getPrettyVersion(), 0, 10);
        $plugin->author = '';
        $plugin->author_uri = '';
        $plugin->description = '';
        $plugin->type = 0;
        $plugin->order = 5;
        $plugin->flags = 0;
        $plugin->allow_html_help = 0;
        $plugin->help = '';

        if (!empty($this->manifest->extra->manifest)) {
            foreach ((array) get_object_vars($plugin) as $name => $value) {
                if (isset($this->manifest->extra->manifest->$name)) {
                    $this->manifest->$name = $this->manifest->extra->manifest->$name;
                }
            }
        }

        if (!empty($this->manifest->authors) && is_array($this->manifest->authors)) {
            if (isset($this->manifest->authors[0]->name)) {
                $plugin->author = $this->manifest->authors[0]->name;
            }

            if (isset($this->manifest->authors[0]->homepage)) {
                $plugin->author_uri = $this->manifest->authors[0]->homepage;
            }
        }

        if (isset($this->manifest->author)) {
            $plugin->author = $this->manifest->author;
        }

        if (isset($this->manifest->author_uri)) {
            $plugin->author_uri = $this->manifest->author_uri;
        }

        if (isset($this->manifest->homepage)) {
            $plugin->author_uri = $this->manifest->homepage;
        }

        if (isset($this->manifest->description)) {
            $plugin->description = $this->manifest->description;
        }

        if (isset($this->manifest->type)) {
            $plugin->type = (int) $this->manifest->type;
        }

        if (version_compare(get_pref('version'), '4.5.0') < 0 && $plugin->type === 5) {
            $plugin->type = 0;
        }

        if (isset($this->manifest->order)) {
            $plugin->order = (int) $this->manifest->order;
        }

        if (isset($this->manifest->flags)) {
            $plugin->flags = (int) $this->manifest->flags;
        }

        $plugin->code = $this->code();
        $plugin->md5 = md5($plugin->code);
        $plugin->help_raw = $this->help();
        $plugin->textpack = $this->textpack();
        $this->plugin[] = $plugin;
    }

@Override
    public boolean canImport(String mediaType) {
        return (MediaType.NATIVE_MEDIATYPE_SYNTAX_MAP.containsKey(mediaType) ||
                this.serviceTransformationEngine.canTransform(mediaType));
    }

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


Question: Metodo que asigna a la variable recipientes un nuevo destinatario.

public function addRecipient($name, $email, $amount) {
    if (count($this->recipients) == self::LIMIT_RECIPIENTS) {
      // El servicio tiene un limite
      return;
    }
    $this->recipients[] = array(
      'name' => $name,
      'email' => $email,
      'amount' => $amount,
    );
  }

public function mail($lead_id = 0, $params)
    {
        if ($this->apikey === null) {
            $this->login();
        }

        $parameters = array_merge($params, [
            'apikey' => $this->apikey,
            'notification_settings' => [
                'sms_enable' => false,
                'email_enable' => false,
                'webhook_enable' => true,
            ]
        ]);

        if ($lead_id !== 0) {
            $parameters['custom_data'] = [
                'userDomainAmo' => $this->parameters->getAuth('domain'),
                'userLoginAmo' => $this->parameters->getAuth('login'),
                'userHashAmo' => $this->parameters->getAuth('apikey'),
                'userTypeAmo' => 2,
                'userIdAmo' => $lead_id,
            ];
        }

        return $this->request(self::METHOD_POST, '/mail', $parameters);
    }

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


Question:
i-mode ブラウザのバージョンを返す。
 http://labs.unoh.net/2009/07/i_20.html

def imode_browser_version
      case @request.env['HTTP_USER_AGENT']
      when %r{^DoCoMo/1.0/}
        ver = '1.0'
      when %r{^DoCoMo/2.0 }
        @request.env['HTTP_USER_AGENT'] =~ / (\w+)\(c(\d+);/
        model = Regexp.last_match(1)
        cache_size = Regexp.last_match(2).to_i

        ver = if cache_size >= 500
                (%w[P03B P05B L01B].member?(model) ? '2.0LE' : '2.0')
              else
                '1.0'
              end
      else
        # DoCoMo/3.0以降等は、とりあえず非v1.0扱い
        ver = '2.0'
      end

      ver
    end

def _get_fashion_mnist(directory):
  """"""
  # Fashion mnist files have the same names as MNIST.
  # We must choose a separate name (by adding 'fashion-' prefix) in the tmp_dir.
  for filename in [
      _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_FILENAME,
      _MNIST_TEST_DATA_FILENAME, _MNIST_TEST_LABELS_FILENAME
  ]:
    generator_utils.maybe_download(directory,
                                   _FASHION_MNIST_LOCAL_FILE_PREFIX + filename,
                                   _FASHION_MNIST_URL + filename)

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


Question: // WithContext adds the context to the get endpoint ID healthz params

func (o *GetEndpointIDHealthzParams) WithContext(ctx context.Context) *GetEndpointIDHealthzParams {
	o.SetContext(ctx)
	return o
}

public function asEndpoint()
    {
        $graphVersionPrefix = '';
        if ($this->graphVersion) {
            $graphVersionPrefix = '/'.$this->graphVersion;
        }

        return $graphVersionPrefix.$this->graphNode->asUrl($this->appSecret);
    }

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


Question:
*
Upload asset file from resource

@param string   $url      Url for upload
@param resource $resource Handle of uploading file

private function _uploadAssetFileFromResource($url, $resource)
    {
        $blockSize = self::MAX_BLOCK_SIZE;
        $blockIds = [];

        $blockContent = fread($resource, $blockSize);
        if (feof($resource)) {
            $this->_uploadAssetFileSingle($url, $blockContent);

            return;
        }

        $blockId = $this->_generateBlockId(count($blockIds));

        $blockIds[] = $blockId;
        $this->_uploadBlock($url, $blockId, $blockContent);

        while (!feof($resource)) {
            $blockContent = fread($resource, $blockSize);

            $blockId = $this->_generateBlockId(count($blockIds));

            $blockIds[] = $blockId;
            $this->_uploadBlock($url, $blockId, $blockContent);
        }

        $this->_commitBlocks($url, $blockIds);
    }

public function update($hash = null, $data)
    {
        // If the hash is not received, get it from the request
        $hash = $hash?: $this->app->request->token();

        // Update the file in the tokens storage
        $token = $this->get($hash);
        $data = array_merge_recursive($token, $data);
        $stored = file_put_contents($this->path($hash), json_encode($data));

        // Return the data or false in case of failure
        return ($stored)? $data : false;
    }

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


Question:
This constructor will create a I/O line stream
from a writable and readable stream

function LineStream(writeStream, readStream) {
    var self = this;
    this.writeStream = writeStream;
    this.readStream = readStream;

    // resume streams
    this.readStream.resume();

    // save data in this buffer
    this.buffer = "";

    // new data from stream will be handled by this
    this.readStream.on('data', function (chunk) {
      self.buffer += chunk;

      // go through the buffer and isolate each message by a linebreak
      var i, start = 0;
      while ((i = self.buffer.indexOf('\n', start)) >= 0) {

        // parse line as JSON and emit line
        self.emit('message', JSON.parse(self.buffer.slice(start, i)));
        start = i + 1;
      }
      self.buffer = self.buffer.slice(start);
    });
  }

func NewWriter(dest io.Writer, state ws.State, op ws.OpCode) *Writer {
	return NewWriterBufferSize(dest, state, op, 0)
}

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


Question: Initialize the sdk logic.

public static function init() {
		if ( ! isset( self::$instance ) && ! ( self::$instance instanceof Loader ) ) {
			self::$instance = new Loader();
			$modules        = array_merge( self::$available_modules, apply_filters( 'themeisle_sdk_modules', [] ) );
			foreach ( $modules as $key => $module ) {
				if ( ! class_exists( 'ThemeisleSDK\\Modules\\' . ucwords( $module, '_' ) ) ) {
					unset( $modules[ $key ] );
				}
			}
			self::$available_modules = $modules;
		}
	}

def _load_all_link_database(self):
        """"""
        _LOGGER.debug("Starting: _load_all_link_database")
        self.devices.state = 'loading'
        self._get_first_all_link_record()
        _LOGGER.debug("Ending: _load_all_link_database")

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


Question:
Remove
@param array|string $removeList
@return bool

public static function remove($removeList = array())
    {
        if (!is_array($removeList)) {
            $removeList = array($removeList);
        }
        foreach ($removeList as $value) {
            if (!empty($value)) {
                if (is_dir($value)) {
                    self::deleteDirectory($value);
                }
                if (is_file($value)) {
                    unlink($value);
                }
            }
        }
        return true;
    }

private function parseOptionsArray($options, \stdClass $result)
    {
        foreach ($options as $option => $value) {
            if (! property_exists($this, $option)) {
                $result->invalidOptions[] = $option;
                continue;
            }

            //Define Option
            $this->$option = $value;
            unset($result->missingOptions[$option]);
        }
    }

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


Question:
_do_document(self, node) -> None
        Process a document node. documentOrder holds whether the document
        element has been encountered such that PIs/comments can be written
        as specified.

def _do_document(self, node):
        ''''''

        self.documentOrder = _LesserElement
        for child in node.childNodes:
            if child.nodeType == Node.ELEMENT_NODE:
                self.documentOrder = _Element        # At document element
                self._do_element(child)
                self.documentOrder = _GreaterElement # After document element
            elif child.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
                self._do_pi(child)
            elif child.nodeType == Node.COMMENT_NODE:
                self._do_comment(child)
            elif child.nodeType == Node.DOCUMENT_TYPE_NODE:
                pass
            else:
                raise TypeError, str(child)

def post_save(sender, instance, created, **kwargs):

    # Only create order model instances for
    # those modules specified in settings.
    model_label = '.'.join([sender._meta.app_label, sender._meta.object_name])
    labels = resolve_labels(model_label)

    order_field_names = is_orderable(model_label)
    if order_field_names:
        orderitem_set = getattr(
            instance,
            resolve_order_item_related_set_name(labels)
        )
        if not orderitem_set.all():
            fields = {}
            for order_field_name in order_field_names:
                fields[order_field_name] = 1
            orderitem_set.model.objects.create(item=instance, **fields)
            sanitize_order(orderitem_set.model)

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


Question:
Extend view

@param  string $dir
@param  string $ext
@return string $this->__cached

private function mextend($dir, $ext)
	{
		$this->__cached = preg_replace_callback($this->usingDirective('extends\((.*?)\)'), function($match)  use ($dir, $ext) {
			$view = str_replace("'", "", $match[1]);
			$view = str_replace('"', '', $view);

			$path = $dir . $this->DS .$view . $ext;
			$view = $view;

			if (file_exists($path)) {
				return '<!--%' .base64_encode($view). '%-->' . PHP_EOL . file_get_contents($path);
			}
			else {
				$this->exception('"' . $path . '" does not exist.');
			}
		}, $this->__cached);

		$this->mcustom($this->__directives);
	}

func (t *Template) GetAllAWSElastiCacheParameterGroupResources() map[string]*resources.AWSElastiCacheParameterGroup {
	results := map[string]*resources.AWSElastiCacheParameterGroup{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSElastiCacheParameterGroup:
			results[name] = resource
		}
	}
	return results
}

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


Question:
<p>
A list of source stack app IDs to be included in the cloned stack.
</p>

@return A list of source stack app IDs to be included in the cloned stack.

public java.util.List<String> getCloneAppIds() {
        if (cloneAppIds == null) {
            cloneAppIds = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return cloneAppIds;
    }

def load(self, callback=None, errback=None, reload=False):

        if not reload and self.data:
            raise AddressException('Address already loaded')

        def success(result, *args):
            self.data = result
            self.id = result['id']
            self.prefix = result['prefix']
            self.type = result['type']
            self.network = Network(self.config, id=result['network_id'])
            # self.scope_group = Scopegroup(config=self.config, id=result['scope_group_id']) NYI
            if self.type != 'host':
                self.report = self._rest.report(self.id)
                children = self._rest.retrieve_children(self.id)
                self.children = [Address(self.config, id=child['id']) for child in
                                 children if len(children) > 0]
            try:
                parent = self._rest.retrieve_parent(self.id)
                self.parent = Address(self.config, id=parent['id'])
            except ResourceException:
                pass
            if callback:
                return callback(self)
            else:
                return self

        if self.id is None:
            if self.prefix is None or self.type is None or self.network is None:
                raise AddressException('Must at least specify an id or prefix, type and network')
            else:
                network_id = self.network.id
                try:
                    self.id = [address for address in self._rest.list() if address['prefix'] == self.prefix and address[
                        'type'] == self.type and address['network_id'] == network_id][0]['id']
                except IndexError:
                    raise AddressException("Could not find address by prefix. It may not exist, or is a child address. "
                                           "Use the topmost parent prefix or specify ID")

        return self._rest.retrieve(self.id, callback=success,
                                   errback=errback)

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


Question:
isArrayLike
@param obj
@returns {boolean|*}

function (obj) {
            return vQ.isArray(obj) || !vQ.isFunction(obj) &&
                ( obj.length === 0 || typeof obj.length === 'number' && obj.length > 0 && ( obj.length - 1 ) in obj );
        }

private function checkResultCount(array $result, $query)
    {
        if (count($result) === 0) {
            throw new RowNotFoundException('Row not found for query: ' . $query);
        }

        if (count($result) > 1) {
            throw new MultipleRowFoundException('Multiple row found for query: ' . $query);
        }
    }

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


Question:
@param string $string String to check

@return mixed

public static function removeDisallowedJavaScriptInLinksOrImgTags($string)
    {
        $string = preg_replace(
            "#<a.+?href=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>.*?</a>#si",
            "",
            $string
        );
        $string = preg_replace(
            "#<img.+?src=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>#si",
            "",
            $string
        );

        return preg_replace("#<(script|xss).*?\>#si", "", $string);
    }

def check_data(yaml_data, errors_array)
      valid = check_not_empty?(yaml_data, errors_array)
      valid &&= check_syntax_valid?(yaml_data, errors_array)
      valid &&= check_overlapping_keys?(yaml_data, errors_array)

      valid
    end

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


Question:
Invalidates an input stream from the cache.

@param inputStream the cached input stream
@throws IOException when the invalidated input stream fails to release

public void invalidate(CachedSeekableInputStream inputStream) throws IOException {
    mUnderFileInputStreamCache.invalidate(inputStream.getResourceId());
    release(inputStream);
  }

public static void main(final String[] args) {
        Switch about = new Switch("a", "about", "display about message");
        Switch help = new Switch("h", "help", "display help message");

        FileArgument expectedFile = new FileArgument("e", "expected-file", "expected interpretation file, default stdin; at least one of expected or observed file must be provided", false);
        FileArgument observedFile = new FileArgument("b", "observed-file", "observed interpretation file, default stdin; at least one of expected or observed file must be provided", false);
        FileArgument outputFile = new FileArgument("o", "output-file", "output file, default stdout", false);
        IntegerArgument resolution = new IntegerArgument("r", "resolution", "resolution, must be in the range [1..4], default " + DEFAULT_RESOLUTION, false);
        StringListArgument loci = new StringListArgument("l", "loci", "list of loci to validate, default " + DEFAULT_LOCI, false);
        Switch printSummary = new Switch("s", "summary", "print summary");

        ArgumentList arguments = new ArgumentList(about, help, expectedFile, observedFile, outputFile, resolution, loci, printSummary);
        CommandLine commandLine = new CommandLine(args);

        ValidateInterpretation validateInterpretation = null;
        try
        {
            CommandLineParser.parse(commandLine, arguments);
            if (about.wasFound()) {
                About.about(System.out);
                System.exit(0);
            }
            if (help.wasFound()) {
                Usage.usage(USAGE, null, commandLine, arguments, System.out);
                System.exit(0);
            }

            // todo: allow for configuration of glclient
            validateInterpretation = new ValidateInterpretation(expectedFile.getValue(), observedFile.getValue(), outputFile.getValue(), resolution.getValue(DEFAULT_RESOLUTION), loci.getValue(DEFAULT_LOCI), printSummary.wasFound(), LocalGlClient.create());
        }
        catch (CommandLineParseException e) {
            if (about.wasFound()) {
                About.about(System.out);
                System.exit(0);
            }
            if (help.wasFound()) {
                Usage.usage(USAGE, null, commandLine, arguments, System.out);
                System.exit(0);
            }
            Usage.usage(USAGE, e, commandLine, arguments, System.err);
            System.exit(-1);
        }
        try {
            System.exit(validateInterpretation.call());
        }
        catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

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


Question: // SetIsActive sets the IsActive field's value.

func (s *Blueprint) SetIsActive(v bool) *Blueprint {
	s.IsActive = &v
	return s
}

def activate_user(query):

    user = _query_to_user(query)
    if click.confirm(f'Are you sure you want to activate {user!r}?'):
        user.active = True
        user_manager.save(user, commit=True)
        click.echo(f'Successfully activated {user!r}')
    else:
        click.echo('Cancelled.')

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


Question:
Export to SavedModel format.

  Args:
    model: Estimator object
    model_type: string indicating model type. "wide", "deep" or "wide_deep"
    export_dir: directory to export the model.
    model_column_fn: Function to generate model feature columns.

def export_model(model, model_type, export_dir, model_column_fn):

  wide_columns, deep_columns = model_column_fn()
  if model_type == 'wide':
    columns = wide_columns
  elif model_type == 'deep':
    columns = deep_columns
  else:
    columns = wide_columns + deep_columns
  feature_spec = tf.feature_column.make_parse_example_spec(columns)
  example_input_fn = (
      tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec))
  model.export_savedmodel(export_dir, example_input_fn,
                          strip_default_attrs=True)

def get_features2(self):

        feature_names = []
        feature_values = []

        # Get all the names of features.
        all_vars = vars(self)
        for name in all_vars.keys():
            # Omit input variables such as date, mag, err, etc.
            if not (name == 'date' or name == 'mag' or name == 'err'
                    or name == 'n_threads' or name == 'min_period'):
                # Filter some other unnecessary features.
                if not (name == 'f' or name == 'f_phase'
                        or name == 'period_log10FAP'
                        or name == 'weight' or name == 'weighted_sum'
                        or name == 'median' or name == 'mean' or name == 'std'):
                    feature_names.append(name)

        # Sort by the names.
        # Sorting should be done to keep maintaining the same order of features.
        feature_names.sort()

        # Get feature values.
        for name in feature_names:
            feature_values.append(all_vars[name])

        return feature_names, feature_values

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


Question:
@param $value

@return AbstractJob
@throws JobException

public function setExpiredOn($value)
    {
        if (!is_int($value)) {
            throw new JobException('Job setExpiredOn can sets only integer type!');
        }

        return $this->setData(self::P_EXPIRED_ON, $value);
    }

def store_pulse_jobs(pulse_job, exchange, routing_key):

    newrelic.agent.add_custom_parameter("exchange", exchange)
    newrelic.agent.add_custom_parameter("routing_key", routing_key)

    JobLoader().process_job(pulse_job)

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


Question:
Download daily 10 year treasury rates from the Federal Reserve and
    return a pandas.Series.

def get_daily_10yr_treasury_data():
    """"""
    url = "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15" \
          "&series=bcb44e57fb57efbe90002369321bfb3f&lastObs=&from=&to=" \
          "&filetype=csv&label=include&layout=seriescolumn"
    return pd.read_csv(url, header=5, index_col=0, names=['DATE', 'BC_10YEAR'],
                       parse_dates=True, converters={1: dataconverter},
                       squeeze=True)

func (b *Bittrex) Withdraw(address, currency string, quantity decimal.Decimal) (withdrawUuid string, err error) {
	r, err := b.client.do("GET", fmt.Sprintf("account/withdraw?currency=%s&quantity=%s&address=%s", strings.ToUpper(currency), quantity, address), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	var u Uuid
	err = json.Unmarshal(response.Result, &u)
	withdrawUuid = u.Id
	return
}

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


Question:
Creates a table in AWS DynamoDB which will be shared between apps.
@param readCapacity read capacity
@param writeCapacity write capacity
@return true if created

public static boolean createSharedTable(long readCapacity, long writeCapacity) {
		if (StringUtils.isBlank(SHARED_TABLE) || StringUtils.containsWhitespace(SHARED_TABLE) ||
				existsTable(SHARED_TABLE)) {
			return false;
		}
		try {
			GlobalSecondaryIndex secIndex = new GlobalSecondaryIndex().
					withIndexName(getSharedIndexName()).
					withProvisionedThroughput(new ProvisionedThroughput().
							withReadCapacityUnits(1L).
							withWriteCapacityUnits(1L)).
					withProjection(new Projection().withProjectionType(ProjectionType.ALL)).
					withKeySchema(new KeySchemaElement().withAttributeName(Config._APPID).withKeyType(KeyType.HASH),
							new KeySchemaElement().withAttributeName(Config._ID).withKeyType(KeyType.RANGE));

			getClient().createTable(new CreateTableRequest().withTableName(getTableNameForAppid(SHARED_TABLE)).
					withKeySchema(new KeySchemaElement(Config._KEY, KeyType.HASH)).
					withSSESpecification(new SSESpecification().withEnabled(ENCRYPTION_AT_REST_ENABLED)).
					withAttributeDefinitions(new AttributeDefinition(Config._KEY, ScalarAttributeType.S),
							new AttributeDefinition(Config._APPID, ScalarAttributeType.S),
							new AttributeDefinition(Config._ID, ScalarAttributeType.S)).
					withGlobalSecondaryIndexes(secIndex).
					withProvisionedThroughput(new ProvisionedThroughput(readCapacity, writeCapacity)));
		} catch (Exception e) {
			logger.error(null, e);
			return false;
		}
		return true;
	}

public static Writable newInstance(Class<? extends Writable> c,
      Configuration conf) {
    return newInstance(c, conf, true);
  }

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


Question: Execute an experiment over the model

def createExperiment(uuid: str):

    data = request.get_json()
    G = DelphiModel.query.filter_by(id=uuid).first().model
    if os.environ.get("TRAVIS") is not None:
        config_file="bmi_config.txt"
    else:
        if not os.path.exists("/tmp/delphi"):
            os.makedirs("/tmp/delphi", exist_ok=True)
        config_file="/tmp/delphi/bmi_config.txt"

    G.initialize(initialize_indicators = False, config_file=config_file)
    for n in G.nodes(data=True):
        rv = n[1]["rv"]
        rv.partial_t = 0.0
        for variable in data["interventions"]:
            if n[1]["id"] == variable["id"]:
                # TODO : Right now, we are only taking the first value in the
                # "values" list. Need to generalize this so that you can have
                # multiple interventions at different times.

                # TODO : The subtraction of 1 is a TEMPORARY PATCH to address
                # the mismatch in semantics between the ICM API and the Delphi
                # model. MUST FIX ASAP.
                rv.partial_t = variable["values"]["value"]["value"] - 1
                for s0 in G.s0:
                    s0[f"∂({n[0]})/∂t"] = rv.partial_t
                break

    id = str(uuid4())
    experiment = ForwardProjection(baseType="ForwardProjection", id=id)
    db.session.add(experiment)
    db.session.commit()

    result = ForwardProjectionResult(id=id, baseType="ForwardProjectionResult")
    db.session.add(result)
    db.session.commit()

    d = dateutil.parser.parse(data["projection"]["startTime"])

    n_timesteps = data["projection"]["numSteps"]

    for i in range(n_timesteps):
        if data["projection"]["stepSize"] == "MONTH":
            d = d + relativedelta(months=1)
        elif data["projection"]["stepSize"] == "YEAR":
            d = d + relativedelta(years=1)

        for n in G.nodes(data=True):
            CausalVariable.query.filter_by(
                id=n[1]["id"]
            ).first().lastUpdated = d.isoformat()
            result.results.append(
                {
                    "id": n[1]["id"],
                    "baseline": {
                        "active": "ACTIVE",
                        "time": d.isoformat(),
                        "value": {"baseType": "FloatValue", "value": 1.0},
                    },
                    "intervened": {
                        "active": "ACTIVE",
                        "time": d.isoformat(),
                        "value": {
                            "baseType": "FloatValue",
                            "value": np.median([s[n[0]] for s in G.s0]),
                        },
                    },
                }
            )

        G.update(update_indicators=False)

        # Hack for 12-month evaluation - have the partial derivative decay over
        # time to restore equilibrium

        tau = 1.0 # Time constant to control the rate of the decay
        for n in G.nodes(data=True):
            for variable in data["interventions"]:
                if n[1]["id"] == variable["id"]:
                    rv = n[1]["rv"]
                    for s0 in G.s0:
                        s0[f"∂({n[0]})/∂t"] = rv.partial_t * exp(-tau*i)

    db.session.add(result)
    db.session.commit()

    return jsonify(
        {
            "id": experiment.id,
            "message": "Forward projection sent successfully",
        }
    )

@Override
  public void exec(String sql, Result<Object> result, Object ...args)
  {
    _kraken.query(sql).exec(result, args);
  }

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


Question: Run a refactoring and return any suggested fixes as a result.

public List<SuggestedFix> drive(Scanner scanner, Pattern includeFilePattern) {
    JsFlumeCallback callback = new JsFlumeCallback(scanner, includeFilePattern);
    NodeTraversal.traverse(compiler, rootNode, callback);
    List<SuggestedFix> fixes = callback.getFixes();
    fixes.addAll(scanner.processAllMatches(callback.getMatches()));
    return fixes;
  }

public function rewind()
    {
        $this->current = null;
        foreach ($this->branch as $item) {
            $item->rewind();
        }
        reset($this->branch);
    }

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


Question:
Returns a new consistent tree map type.

@param <K> the key type
@param <V> the value type
@return a new consistent tree map type

@SuppressWarnings("unchecked")
  public static <K extends Comparable<K>, V> AtomicSortedMapType<K, V> instance() {
    return INSTANCE;
  }

function _Type(
    type,       // :: String
    name,       // :: String
    url,        // :: String
    arity,      // :: NonNegativeInteger
    format,
    // :: Nullable ((String -> String, String -> String -> String) -> String)
    supertypes, // :: Array Type
    test,       // :: Any -> Boolean
    tuples      // :: Array (Array3 String (a -> Array b) Type)
  ) {
    var t = Object.create (Type$prototype);
    t._test = test;
    t._extractors = tuples.reduce (function(_extractors, tuple) {
      _extractors[tuple[0]] = tuple[1];
      return _extractors;
    }, {});
    t.arity = arity;  // number of type parameters
    t.extractors = Z.map (B (toArray), t._extractors);
    t.format = format || function(outer, inner) {
      return Z.reduce (function(s, tuple) {
        return s +
               outer (' ') +
               when (tuple[2].arity > 0)
                    (parenthesize (outer))
                    (inner (tuple[0]) (show (tuple[2])));
      }, outer (name), tuples);
    };
    t.keys = tuples.map (function(tuple) { return tuple[0]; });
    t.name = name;
    t.supertypes = supertypes;
    t.type = type;
    t.types = tuples.reduce (function(types, tuple) {
      types[tuple[0]] = tuple[2];
      return types;
    }, {});
    t.url = url;
    return t;
  }

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


Question: // SeriesCardinality returns the number of series in the engine.

func (e *Engine) SeriesCardinality() int64 {
	e.mu.RLock()
	defer e.mu.RUnlock()
	if e.closing == nil {
		return 0
	}
	return e.index.SeriesN()
}

def renumber_system(self, offset):

        self.universe.protein = self.universe.select_atoms("protein")
        self.universe.protein.residues.resids = self.universe.protein.residues.resids+int(offset)

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


Question: Serializes `object` and writes it to global `result`. Returns true on success, or false on invalid object.

function writeNode(state, level, object, block, compact, iskey) {
  state.tag = null;
  state.dump = object;

  if (!detectType(state, object, false)) {
    detectType(state, object, true);
  }

  var type = _toString.call(state.dump);

  if (block) {
    block = (state.flowLevel < 0 || state.flowLevel > level);
  }

  var objectOrArray = type === '[object Object]' || type === '[object Array]',
      duplicateIndex,
      duplicate;

  if (objectOrArray) {
    duplicateIndex = state.duplicates.indexOf(object);
    duplicate = duplicateIndex !== -1;
  }

  if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
    compact = false;
  }

  if (duplicate && state.usedDuplicates[duplicateIndex]) {
    state.dump = '*ref_' + duplicateIndex;
  } else {
    if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
      state.usedDuplicates[duplicateIndex] = true;
    }
    if (type === '[object Object]') {
      if (block && (Object.keys(state.dump).length !== 0)) {
        writeBlockMapping(state, level, state.dump, compact);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + state.dump;
        }
      } else {
        writeFlowMapping(state, level, state.dump);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
        }
      }
    } else if (type === '[object Array]') {
      var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;
      if (block && (state.dump.length !== 0)) {
        writeBlockSequence(state, arrayLevel, state.dump, compact);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + state.dump;
        }
      } else {
        writeFlowSequence(state, arrayLevel, state.dump);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
        }
      }
    } else if (type === '[object String]') {
      if (state.tag !== '?') {
        writeScalar(state, state.dump, level, iskey);
      }
    } else {
      if (state.skipInvalid) return false;
      throw new YAMLException('unacceptable kind of an object to dump ' + type);
    }

    if (state.tag !== null && state.tag !== '?') {
      state.dump = '!<' + state.tag + '> ' + state.dump;
    }
  }

  return true;
}

function( name, test, startFunc, extra ) {
		var self = this;

		// Require an active state for tests
		self.requireState( munit.ASSERT_STATE_ACTIVE, startFunc || self.ok );

		// Prevent non empty string names
		if ( ! munit.isString( name ) || ! name.length ) {
			throw new munit.AssertionError(
				"Name not found for test on '" + self.nsPath + "'",
				startFunc || self.ok
			);
		}
		// Prevent duplicate tests
		else if ( self.tests[ name ] ) {
			throw new munit.AssertionError(
				"Duplicate Test '" + name + "' on '" + self.nsPath + "'",
				startFunc || self.ok
			);
		}

		// Increment test count and mark it
		self[ !!( test ) ? '_pass' : '_fail' ]( name, startFunc || self.ok, extra );

		// Reached expected number of tests, close off
		if ( self.options.expect > 0 && self.count >= self.options.expect ) {
			self.close();
		}

		return self;
	}

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


Question:
// FindImageWithRef returns image.Info given an image ref. If the image cannot be
// found, it returns the image.Info with the ID provided.

func (rm RepositoryMetadata) FindImageWithRef(ref Ref) Info {
	for _, img := range rm.Images {
		if img.ID == ref {
			return img
		}
	}
	return Info{ID: ref}
}

public function getElementTitle()
	{
		throw new \Exception('Dont use me bro.');

		$title = null;

		switch ($this->resource) {

			case self::RESOURCE_PAGE:
				$pageData = $this->getPage();

				/* @var $pageData Localization */
				if ( ! is_null($pageData)) {
					$title = $pageData->getTitle();
				}
				break;

			case self::RESOURCE_FILE:
				$file = $this->getFile();

				if ($file instanceof File) {
					$localeId = ObjectRepository::getLocaleManager($this)
							->getCurrent()
							->getId();

					$title = $file->getTitle($localeId);
				}

				break;

			case self::RESOURCE_LINK:
				if ( ! empty($this->title)) {
					$title = $this->title;
				} else {
					$title = $this->getHref();
				}

				break;

			case self::RESOURCE_EMAIL:
				if ( ! empty($this->title)) {
					$title = $this->title;
				} else {
					$title = str_replace('mailto:', '', $this->getHref());
				}

			case self::RESOURCE_RELATIVE_PAGE:
				$href = $this->getHref();
				if ($href == self::RELATIVE_FIRST) {
					$title = 'First child';
				} else {
					$title = 'Last child';
				}
				break;

			default:
				$this->log()->warn("Unrecognized resource for supra html markup link tag, data: $this");
		}

		return $title;
	}

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


Question:
Draws a drop shadow beneath the slider thumb.

@param screenCoord the x-coordinate of the slider thumb
@param canvas      the canvas on which to draw the shadow

private void drawThumbShadow(float screenCoord, Canvas canvas) {
        thumbShadowMatrix.setTranslate(screenCoord + thumbShadowXOffset, textOffset + thumbHalfHeight + thumbShadowYOffset);
        translatedThumbShadowPath.set(thumbShadowPath);
        translatedThumbShadowPath.transform(thumbShadowMatrix);
        canvas.drawPath(translatedThumbShadowPath, shadowPaint);
    }

def update_share_image(liststore, tree_iters, col, large_col, pcs_files,
                       dir_name, icon_size, large_icon_size):
    '''
    '''
    def update_image(filepath, tree_iter):
        try:
            tree_path = liststore.get_path(tree_iter)
            if tree_path is None:
                return
            pix = GdkPixbuf.Pixbuf.new_from_file(filepath)
            width = pix.get_width()
            height = pix.get_height()
            small_pix = pix.scale_simple(icon_size,
                                         height * icon_size // width,
                                         GdkPixbuf.InterpType.NEAREST)
            liststore[tree_path][col] = small_pix
            liststore[tree_path][large_col] = pix
        except GLib.GError:
            logger.error(traceback.format_exc())

    def dump_image(url, filepath):
        req = net.urlopen(url)
        if not req or not req.data:
            logger.warn('update_share_image:, failed to request %s' % url)
            return False
        with open(filepath, 'wb') as fh:
            fh.write(req.data)
        return True

    for tree_iter, pcs_file in zip(tree_iters, pcs_files):
        if 'thumbs' not in pcs_file:
            continue
        elif 'url2' in pcs_file['thumbs']:
            key = 'url2'
        elif 'url1' in pcs_file['thumbs']:
            key = 'url1'
        elif 'url3' in pcs_file['thumbs']:
            key = 'url3'
        else:
            continue
        fs_id = pcs_file['fs_id']
        url = pcs_file['thumbs'][key]
        filepath = os.path.join(dir_name, 'share-{0}.jpg'.format(fs_id))
        if os.path.exists(filepath) and os.path.getsize(filepath):
            GLib.idle_add(update_image, filepath, tree_iter)
        elif not url or len(url) < 10:
            logger.warn('update_share_image: failed to get url %s' % url)
        else:
            status = dump_image(url, filepath)
            if status:
                GLib.idle_add(update_image, filepath, tree_iter)

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


Question:
Get the value of the simple content of this element.
        Parameters:
            elt -- the DOM element being parsed
            ps -- the ParsedSoap object.
            mixed -- ignore element content, optional text node

def simple_value(self, elt, ps, mixed=False):
        '''
        '''
        if not _valid_encoding(elt):
            raise EvaluateException('Invalid encoding', ps.Backtrace(elt))
        c = _children(elt)
        if mixed is False:
            if len(c) == 0:
                raise EvaluateException('Value missing', ps.Backtrace(elt))
            for c_elt in c:
                if c_elt.nodeType == _Node.ELEMENT_NODE:
                    raise EvaluateException('Sub-elements in value',
                        ps.Backtrace(c_elt))

        # It *seems* to be consensus that ignoring comments and
        # concatenating the text nodes is the right thing to do.
        return ''.join([E.nodeValue for E in c
                if E.nodeType
                in [ _Node.TEXT_NODE, _Node.CDATA_SECTION_NODE ]])

def process_children(self, node, path, level, parent=None):

        data_parent = parent if parent else node
        chs = node.i_children
        for ch in chs:
            if ch.keyword in ["choice", "case"]:
                self.process_children(ch, path, level, node)
                continue
            p = path + "/" + self.qname(ch)
            tmpl = self.xsl_template(p)
            ct = self.xsl_calltemplate(ch.keyword, tmpl)
            self.xsl_withparam("level", "%d" % level, ct)
            if (data_parent.i_module is None or
                ch.i_module.i_modulename != data_parent.i_module.i_modulename):
                self.xsl_withparam("nsid", ch.i_module.i_modulename + ":", ct)
            if ch.keyword in ["leaf", "leaf-list"]:
                self.type_param(ch, ct)
            elif ch.keyword != "anyxml":
                offset = 2 if ch.keyword == "list" else 1
                self.process_children(ch, p, level + offset)

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


Question: // NewRemoveOfferCommand returns a command used to remove a specified offer.

func NewRemoveOfferCommand() cmd.Command {
	removeCmd := &removeCommand{}
	removeCmd.newAPIFunc = func(controllerName string) (RemoveAPI, error) {
		return removeCmd.NewApplicationOffersAPI(controllerName)
	}
	return modelcmd.WrapController(removeCmd)
}

public void moveRequestInfoToReply(Message messageRequest)
    {
        if (m_messageDataDescChildren != null)
        {
            for (String strKey : m_messageDataDescChildren.keySet())
            {
                MessageDataDesc messageDataDesc = m_messageDataDescChildren.get(strKey);
                MessageDataDesc requestMessageDataDesc = ((BaseMessage)messageRequest).getMessageDataDesc(messageDataDesc.getFullKey(null));
                if (requestMessageDataDesc != null)
                    messageDataDesc.moveRequestInfoToReply(messageRequest);
            }
        }
    }

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


Question: Processing coordinates for rotation/scaling

function(evt) {
        evt.preventDefault();
        evt.stopPropagation();
        if (debug) { timedLog("handleTouchRepositioning"); }
        if (evt.touches.length < 2) {
          return;
        }
        if (debug) { timedLog("handleTouchRepositioning - continued"); }
        var x1 = evt.touches[0].pageX,
          y1 = evt.touches[0].pageY,
          x2 = evt.touches[1].pageX,
          y2 = evt.touches[1].pageY,
          dx = x2 - x1,
          dy = y2 - y1,
          d = Math.sqrt(dx*dx + dy*dy),
          a = Math.atan2(dy,dx),
          da = a - transform.angle + mark.angle,
          s = d/transform.distance * mark.scale;

        transform.modified = true;
        positionable.handleRotationAndScale(da, s);
      }

public void paint (Graphics2D gfx, int x, int y)
    {
        AffineTransform otrans = gfx.getTransform();
        gfx.translate(x, y);
        gfx.transform(_transform);
        _base.paint(gfx, 0, 0);
        gfx.setTransform(otrans);
    }

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


Question:
Queue a frame for sending.  Will send immediately if there are no
        pending synchronous transactions on this connection.

def send_frame(self, frame):
        '''

        '''
        if self.closed:
            if self.close_info and len(self.close_info['reply_text']) > 0:
                raise ChannelClosed(
                    "channel %d is closed: %s : %s",
                    self.channel_id,
                    self.close_info['reply_code'],
                    self.close_info['reply_text'])
            raise ChannelClosed()

        # If there's any pending event at all, then it means that when the
        # current dispatch loop started, all possible frames were flushed
        # and the remaining item(s) starts with a sync callback. After careful
        # consideration, it seems that it's safe to assume the len>0 means to
        # buffer the frame. The other advantage here is
        if not len(self._pending_events):
            if not self._active and \
                    isinstance(frame, (ContentFrame, HeaderFrame)):
                raise Channel.Inactive(
                    "Channel %d flow control activated", self.channel_id)
            self._connection.send_frame(frame)
        else:
            self._pending_events.append(frame)

def _flush(self):

        # Upload segment with workers
        name = self._segment_name % self._seek
        response = self._workers.submit(
            self._client.put_object, self._container, name,
            self._get_buffer())

        # Save segment information in manifest
        self._write_futures.append(dict(
            etag=response, path='/'.join((self._container, name))))

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


Question:
执行command
@access public
@param Query                 $query      查询对象
@param string|array|object   $command 指令
@param mixed                 $extra 额外参数
@param string                $db 数据库名
@return array

public function cmd(Query $query, $command, $extra = null, $db = null)
    {
        if (is_array($command) || is_object($command)) {
            if ($this->getConfig('debug')) {
                $this->log('cmd', 'cmd', $command);
            }

            // 直接创建Command对象
            $command = new Command($command);
        } else {
            // 调用Builder封装的Command对象
            $command = $this->builder->$command($query, $extra);
        }

        return $this->command($command, $db);
    }

func (t *dbTables) parseExprs(mi *modelInfo, exprs []string) (index, name string, info *fieldInfo, success bool) {
	var (
		jtl *dbTable
		fi  *fieldInfo
		fiN *fieldInfo
		mmi = mi
	)

	num := len(exprs) - 1
	var names []string

	inner := true

loopFor:
	for i, ex := range exprs {

		var ok, okN bool

		if fiN != nil {
			fi = fiN
			ok = true
			fiN = nil
		}

		if i == 0 {
			fi, ok = mmi.fields.GetByAny(ex)
		}

		_ = okN

		if ok {

			isRel := fi.rel || fi.reverse

			names = append(names, fi.name)

			switch {
			case fi.rel:
				mmi = fi.relModelInfo
				if fi.fieldType == RelManyToMany {
					mmi = fi.relThroughModelInfo
				}
			case fi.reverse:
				mmi = fi.reverseFieldInfo.mi
			}

			if i < num {
				fiN, okN = mmi.fields.GetByAny(exprs[i+1])
			}

			if isRel && (fi.mi.isThrough == false || num != i) {
				if fi.null || t.skipEnd {
					inner = false
				}

				if t.skipEnd && okN || !t.skipEnd {
					if t.skipEnd && okN && fiN.pk {
						goto loopEnd
					}

					jt, _ := t.add(names, mmi, fi, inner)
					jt.jtl = jtl
					jtl = jt
				}

			}

			if num != i {
				continue
			}

		loopEnd:

			if i == 0 || jtl == nil {
				index = "T0"
			} else {
				index = jtl.index
			}

			info = fi

			if jtl == nil {
				name = fi.name
			} else {
				name = jtl.name + ExprSep + fi.name
			}

			switch {
			case fi.rel:

			case fi.reverse:
				switch fi.reverseFieldInfo.fieldType {
				case RelOneToOne, RelForeignKey:
					index = jtl.index
					info = fi.reverseFieldInfo.mi.fields.pk
					name = info.name
				}
			}

			break loopFor

		} else {
			index = ""
			name = ""
			info = nil
			success = false
			return
		}
	}

	success = index != "" && info != nil
	return
}

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


Question: // SetMaxResults sets the MaxResults field's value.

func (s *ListSimulationApplicationsInput) SetMaxResults(v int64) *ListSimulationApplicationsInput {
	s.MaxResults = &v
	return s
}

public void dataToField(ComponentCache componentCache, int iRowIndex, int iColumnIndex)
    {
        if (componentCache.m_rgcompoments[iColumnIndex] != null)
        {
            String string = null;
            if (componentCache.m_rgcompoments[iColumnIndex] instanceof JTextComponent)
                string = ((JTextComponent)componentCache.m_rgcompoments[iColumnIndex]).getText();
            if (componentCache.m_rgcompoments[iColumnIndex] instanceof JCheckBox)
                if (((JCheckBox)componentCache.m_rgcompoments[iColumnIndex]).isSelected())
                    string = "1";
            //xif (string != null) if (string.length() > 0)
            this.getModel().setValueAt(string, iRowIndex, iColumnIndex);
        }
    }

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


Question:
// removeAllRequests removes all the jsonRequests which contain the response
// channels for outstanding requests.
//
// This function MUST be called with the request lock held.

func (c *Client) removeAllRequests() {
	c.requestMap = make(map[uint64]*list.Element)
	c.requestList.Init()
}

func reorderChunks(name string, respCh <-chan *chunkResp, chunkRespc chan<- *chunkResp, eofCh chan<- struct{}, closedc <-chan struct{}) {
	pending := make(map[int64]*chunkResp)
	var off int64
	for resp := range respCh {
		glog.V(2).Infof("Received chunk (off=%d chunk=<%d bytes> err=%v", resp.off, len(resp.chunk), resp.err)
		pending[resp.off] = resp
		if resp.err != nil && eofCh != nil {
			close(eofCh)
			eofCh = nil
		}
		for {
			resp, ok := pending[off]
			if !ok {
				break
			}
			if resp.err != nil && resp.err != io.EOF {
				glog.Errorf("readahead %s: about to report an error %v", name, resp.err)
			}
			glog.V(2).Infof("Returning chunk (off=%d chunk=<%d bytes> err=%v", resp.off, len(resp.chunk), resp.err)
			select {
			case chunkRespc <- resp:
			case <-closedc:
				// N.B. We are aborting here before draining respCh; the other
				// goroutines will abort asynchronously on closedc as well.
				return
			}
			delete(pending, off)
			off += int64(len(resp.chunk))
		}
	}
}

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


Question: // New returns a Worker backed by config, or an error.

func New(config Config) (worker.Worker, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Trace(err)
	}
	w := &hostkeyreporter{config: config}
	w.tomb.Go(w.run)
	return w, nil
}

async def init(self) -> None:
        ''''''

        if self.data:
            return

        if self.json_data:
            try:
                self.data = json.loads(self.json_data)

            except Exception:
                Log.exception('Falied to load raw configuration')

        else:
            try:
                with open(self.json_path, 'r') as f:
                    self.data = json.load(f)

            except Exception:
                Log.exception('Failed to load configuration from %s',
                              self.json_path)
                self.data = {}

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


Question:
@param $string

@return string

private function sentenceCase($string)
    {
        $sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
        $new_string = '';
        foreach ($sentences as $key => $sentence) {
            $new_string .= 0 === ($key & 1) ?
                ucfirst(mb_strtolower(trim($sentence))) :
                $sentence.' ';
        }

        return trim($new_string);
    }

def hash_to_rets_query_string(hash)
      [].tap do |str|
        hash.each_pair do |k,v|
          val = value_map(v)
          str << "(#{k.to_s.camelize}=#{val})"
        end
      end.join(',')
    end

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


Question: Returns the cache directory used for unpacked resources.

public static File getCacheDir ()
    {
        if (_tmpdir == null) {
            String tmpdir = System.getProperty("java.io.tmpdir");
            if (tmpdir == null) {
                log.info("No system defined temp directory. Faking it.");
                tmpdir = System.getProperty("user.home");
            }
            setCacheDir(new File(tmpdir));
        }
        return _tmpdir;
    }

def find_file(path)
			caller_path = caller_locations(4..4).first.path

			caller_dir =
				begin
					File.dirname(caller_path).sub(views_dir, '') if Tilt[caller_path]
				rescue LoadError
					nil
				end

			find_files(path, controller_dirs | Array(caller_dir))
				.find { |file| Tilt[file] }
		end

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


Question:
Replace all strings in dictionary with compiled
    version of themselves and return dictionary.

def compile_patterns_in_dictionary(dictionary):

    for key, value in dictionary.items():
        if isinstance(value, str):
            dictionary[key] = re.compile(value)
        elif isinstance(value, dict):
            compile_patterns_in_dictionary(value)
    return dictionary

def _sanitise(self):

        for k in self.__dict__:
            if isinstance(self.__dict__[k], np.float32):  # np.float32 has a broken __str__ method
                self.__dict__[k] = np.float64(self.__dict__[k])

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