Question:
// Set sets the key to value. It replaces any existing
// values.

func (v Values) Set(key, value string) {
	v[key] = []string{value}
}

func (r *Reconciler) groupRwsetByBlock(elements []*gossip2.PvtDataElement) map[uint64]rwsetByKeys {
	rwSetByBlockByKeys := make(map[uint64]rwsetByKeys) // map from block num to rwsetByKeys

	// Iterate over data fetched from peers
	for _, element := range elements {
		dig := element.Digest
		if _, exists := rwSetByBlockByKeys[dig.BlockSeq]; !exists {
			rwSetByBlockByKeys[dig.BlockSeq] = make(map[rwSetKey][]byte)
		}
		for _, rws := range element.Payload {
			hash := hex.EncodeToString(util2.ComputeSHA256(rws))
			key := rwSetKey{
				txID:       dig.TxId,
				namespace:  dig.Namespace,
				collection: dig.Collection,
				seqInBlock: dig.SeqInBlock,
				hash:       hash,
			}
			rwSetByBlockByKeys[dig.BlockSeq][key] = rws
		}
	}
	return rwSetByBlockByKeys
}

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


Question:
Get the http client config.

@return array

private function getHttpClientConfig()
    {
        $config = [
            'base_uri' => 'http://ip-api.com/',
            'headers' => [
                'User-Agent' => 'Laravel-GeoIP',
            ],
            'query' => [
                'fields' => 16895,
            ],
        ];

        // Using the Pro service
        if ($this->getOption('key')) {
            $config['base_uri']     = $this->isSecure() ? 'https://pro.ip-api.com/' : 'http://pro.ip-api.com/';
            $config['query']['key'] = $this->getOption('key');
        }

        return $config;
    }

private function parseHeaders() {

            foreach($this->amfResponse->getHeaders() as $header) {

                switch($header['name']) {

                    case 'ReplaceGatewayUrl' :
                        if (is_string($header['data'])) {
                            $this->endPoint = $header['data'];
                        }
                        break;

                }

            }

        }

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


Question: Returns true if a chain can have any child properties

function hasChildren(parts) {
	// Concatenate the chain with each other part, and see if any concatenations are valid functions
	const validChildren = allParts
		.filter(newPart => parts.indexOf(newPart) === -1)
		.map(newPart => parts.concat([newPart]))
		.filter(longer => verify(longer, false));

	return validChildren.length > 0;
}

public function maybeMatch(string $variable = null, array $labels = []): self
    {
        $query = new self;
        $query->clauses = $this->clauses->add(
            new Clause\OptionalMatchClause(
                Clause\Expression\Path::startWithNode($variable, $labels)
            )
        );

        return $query;
    }

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


Question:
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string

func (o *GetEndpointIDLabelsURL) WithBasePath(bp string) *GetEndpointIDLabelsURL {
	o.SetBasePath(bp)
	return o
}

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

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

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


Question: Streaming version of {@code |cleanHtml}.

public static LoggingAdvisingAppendable cleanHtmlStreaming(
      LoggingAdvisingAppendable delegate, Collection<? extends OptionalSafeTag> optionalSafeTags) {
    return new CleanHtmlAppendable(delegate, optionalSafeTags);
  }

public function first_html_part(&$part = null, $enriched = false)
    {
        if ($this->has_html_part($enriched, $part)) {
            $body = $this->get_part_body($part->mime_id, true);

            if ($part->mimetype == 'text/enriched') {
                $body = rcube_enriched::to_html($body);
            }

            return $body;
        }
    }

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


Question: The main layout function:

function tree(d, i) {
    var nodes = hierarchy.call(this, d, i),
        t = nodes[0],
        wt = wrapTree(t);

    wroot = wt;
    zerothWalk(wt, 0);
    firstWalk(wt);
    secondWalk(wt, 0);
    renormalize(wt);

    return nodes;
  }

public void setHeader(@NonNull View view, boolean padding, boolean divider) {
        setHeader(view, padding, divider, null);
    }

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


Question: // Return a type name to use for a schema.

func typeForSchema(schema *openapi.Schema) string {
	if schema.XRef != "" {
		return "reference"
	}
	if len(schema.Enum) > 0 {
		enumType := typeNameForSchema(schema)
		return "enum-of-" + enumType
	}
	typeName := typeNameForSchema(schema)
	if typeName == "array" {
		if schema.Items != nil {
			// items contains an array of schemas
			itemType := ""
			for i, itemSchema := range schema.Items.Schema {
				if i > 0 {
					itemType += "|"
				}
				itemType += typeForSchema(itemSchema)
			}
			return "array-of-" + itemType
		} else if schema.XRef != "" {
			return "array-of-reference"
		} else {
			// we need to do more work to understand this type
			return fmt.Sprintf("array-of-[%+v]", schema)
		}
	} else if typeName == "object" {
		// this object might be representable with a map
		// but not if it has properties
		if (schema.Properties != nil) && (len(schema.Properties.AdditionalProperties) > 0) {
			return typeName
		}
		if schema.AdditionalProperties != nil {
			if schema.AdditionalProperties.GetSchema() != nil {
				additionalPropertiesSchemaType := typeForSchema(schema.AdditionalProperties.GetSchema())
				return "map-of-" + additionalPropertiesSchemaType
			}
			if schema.AdditionalProperties.GetBoolean() == false {
				// no additional properties are allowed, so we're not sure what to do if we get here...
				return typeName
			}
		}
		if schema.Items != nil {
			itemType := ""
			for i, itemSchema := range schema.Items.Schema {
				if i > 0 {
					itemType += "|"
				}
				itemType += typeForSchema(itemSchema)
			}
			return "map-of-" + itemType
		}
		return "map-of-object"
	} else {
		return typeName
	}
}

public function onSchemaValidation(ConstraintEventSchema $event)
    {
        $this->currentSchema = $event->getSchema();
        $this->currentData = $event->getElement();
    }

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


Question:
Parse 'pair' after leading slash.

@param int $offset
@throws \UnexpectedValueException
@return string

private function _parsePairAfterSlash(int &$offset): string
    {
        $idx = $offset;
        if ($idx >= $this->_len) {
            throw new \UnexpectedValueException(
                "Unexpected end of escape sequence.");
        }
        $c = $this->_dn[$idx++];
        // special | \ | " | SPACE
        if (false !== strpos(self::SPECIAL_CHARS . '\\" ', $c)) {
            $val = $c;
        } else { // hexpair
            if ($idx >= $this->_len) {
                throw new \UnexpectedValueException("Unexpected end of hexpair.");
            }
            $val = @hex2bin($c . $this->_dn[$idx++]);
            if (false === $val) {
                throw new \UnexpectedValueException("Invalid hexpair.");
            }
        }
        $offset = $idx;
        return $val;
    }

public function check()
    {
        $this->pingBinFactory();

        $ipAddress = ip_address_from_hostname($this->target->hostname);

        $latency = $this->ping($ipAddress);

        $latencyFormatted = $latency ? "{$latency}ms" : 'error!';

        $this->target->setDisplay(
            "{$this->target->name} ({$latencyFormatted})"
        );

        if ($latency === false || $latency > $this->target->acceptedLatency) {
            $result = $this->makeResult(
                false,
                sprintf(
                    $this->target->getErrorMessage(),
                    $this->hosnameAndIp($this->target->hostname, $ipAddress),
                    $latency === false ? '[ping error]' : $latency,
                    $this->target->acceptedLatency
                )
            );
        } else {
            $result = $this->makeHealthyResult();
        }

        return $result->setValue($latency)->setValueHuman("{$latency}ms");
    }

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


Question:
Write the output to the file.

@param body the documentation content to be written to the file.
@param path the path for the file.

private void writeToFile(Content body, DocPath path) throws DocFileIOException {
        Content htmlDocType = configuration.isOutputHtml5()
                ? DocType.HTML5
                : DocType.TRANSITIONAL;
        Content head = new HtmlTree(HtmlTag.HEAD);
        head.addContent(HtmlTree.TITLE(new StringContent(
                configuration.getText("doclet.Window_Source_title"))));
        head.addContent(getStyleSheetProperties());
        Content htmlTree = HtmlTree.HTML(configuration.getLocale().getLanguage(),
                head, body);
        Content htmlDocument = new HtmlDocument(htmlDocType, htmlTree);
        messages.notice("doclet.Generating_0", path.getPath());
        DocFile df = DocFile.createFileForOutput(configuration, path);
        try (Writer w = df.openWriter()) {
            htmlDocument.write(w, true);
        } catch (IOException e) {
            throw new DocFileIOException(df, DocFileIOException.Mode.WRITE, e);
        }

    }

protected function addPageParameterNode()
    {
    	$builder = new TreeBuilder();
    	$node = $builder->root('page');

    	$node
	    	->treatTrueLike(array(
	    		'versionable' => false,
	    		'signable' => false,
	    		'form' => array(
	    			'type' => "ASF\DocumentBundle\Form\Type\PageType",
	    			'name' => 'page_type'
	    		)
	    	))
	    	->treatFalseLike(array(
    			'versionable' => false,
    			'signable' => false,
	    		'form' => array(
	    			'type' => "ASF\DocumentBundle\Form\Type\PageType",
	    			'name' => 'page_type'
	    		)
	    	))
	    	->addDefaultsIfNotSet()
	    	->children()
	    		->booleanNode('versionable')
	    			->defaultFalse()
	    		->end()
	    		->booleanNode('signable')
	    			->defaultFalse()
	    		->end()
		    	->arrayNode('form')
			    	->addDefaultsIfNotSet()
			    	->children()
				    	->scalarNode('type')
				    		->defaultValue('ASF\DocumentBundle\Form\Type\PageType')
				    	->end()
				    	->scalarNode('name')
				    		->defaultValue('page_type')
				    	->end()
				    	->arrayNode('validation_groups')
				    		->prototype('scalar')->end()
				    		->defaultValue(array("Default"))
				    	->end()
			    	->end()
		    	->end()
	    	->end()
    	;

    	return $node;
    }

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


Question:
Gets the list of classes which can be created, with checks for permissions.
Will fallback to the default model class for the given DataGrid

@param DataGrid $grid
@return array

public function getClassesCreate($grid)
    {
        // Get explicit or fallback class list
        $classes = $this->getClasses();
        if (empty($classes) && $grid) {
            $classes = array($grid->getModelClass());
        }

        // Filter out classes without permission
        return array_filter($classes, function ($class) {
            return singleton($class)->canCreate();
        });
    }

public function connection($name = null)
    {
        if (is_null($name)) {
            $name = $this->getDefaultConnection();
        }

        if (! isset($this->connections[$name])) {
            throw new InvalidArgumentException("Connection [{$name}] is not registered.");
        }

        return $this->connections[$name];
    }

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


Question:
When a straight answer won't do, BS to the rescue!

@return string

public static function bs()
    {
        return
            static::$bsParts[0][array_rand(static::$bsParts[0])] . ' ' .
            static::$bsParts[1][array_rand(static::$bsParts[1])] . ' ' .
            static::$bsParts[2][array_rand(static::$bsParts[2])];
    }

def body
      msg = "Hello.\n\n"
      if job.status == 200
        msg += "Your backup of database #{job.rds_id} is complete.\n"+
          (job.files.empty? ? "" : "Output is at #{job.files.first[:url]}\n")
      else
        msg += "Your backup is incomplete. (job ID #{job.backup_id})\n"
      end
      msg += "Job status: #{job.message}"
    end

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


Question: Return a authorize url.

public function getAuthorizeUrl($request_token, $callback_uri = NULL, $state = NULL) {
    $request_token = array(
      'oauth_token' => is_array($request_token) ? $request_token['oauth_token'] : $request_token,
    );
    // authorize
    $url = Url::factory($this->getConfig('base_url'));
    $url->addPath($this->getConfig('authorize_path'));
    $url->setQuery($request_token);
    return (string)$url;
  }

def options(self, *args, **kwargs):
        '''

        '''
        # Allow X-Auth-Token in requests
        request_headers = self.request.headers.get('Access-Control-Request-Headers')
        allowed_headers = request_headers.split(',')

        # Filter allowed header here if needed.

        # Allow request headers
        self.set_header('Access-Control-Allow-Headers', ','.join(allowed_headers))

        # Allow X-Auth-Token in responses
        self.set_header('Access-Control-Expose-Headers', 'X-Auth-Token')

        # Allow all methods
        self.set_header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST')

        self.set_status(204)
        self.finish()

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


Question:
registerApi - the factory for middleware that registers api in response object

@param  {ModelAPIRouter|ModelAPIExpress} apiObject the ModelAPIRouter or ModelAPIRouter
@return {Function}           description

function registerApi(isApp, apiObject) {

  if (isApp) {
    return function (req, res, next) {
      res.__api = apiObject;
      return next();
    };
  };

  return function (req, res, next) {
    res.__modelAPI = apiObject;
    return next();
  };
}

public function generateRoutables(Router $router = null, $prefix = null)
    {
        $router ?: $router = new Router;

        $prefix ?: $prefix = $this->buildUriPrefix($this->reflection->getShortName());

        foreach ($this->getRoutableReflectionMethodList() as $reflection) {

            $this->addRouteFromMethod($router, $reflection->getName(), $prefix);
        }

        return $router;
    }

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


Question: @throws PageException

private void doGetDebug() throws PageException {
	Struct sct = new StructImpl();
	pageContext.setVariable(getString("admin", action, "returnVariable"), sct);

	sct.set(DEBUG, Caster.toBoolean(config.debug()));
	sct.set(KeyConstants._database, Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_DATABASE)));
	sct.set(KeyConstants._exception, Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)));
	sct.set("tracing", Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_TRACING)));
	sct.set("dump", Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_DUMP)));
	sct.set("timer", Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_TIMER)));
	sct.set("implicitAccess", Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_IMPLICIT_ACCESS)));
	sct.set("queryUsage", Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_QUERY_USAGE)));
    }

public function catchError(array $error_files)
    {
        $this->app->set(Web::ERROR_VIEWS, $error_files);
        $whoops = new Run;
        if ($this->debug) {
            error_reporting(E_ALL);
            $whoops->pushHandler(new PrettyPageHandler);
        } else {
            error_reporting(E_ERROR);
            $whoops->pushHandler($this->getErrorView());
        }
        $whoops->register();
        return $this;
    }

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


Question:
@param $ids

@return StorageDataRequest fetch result is array [ 'key1' => ['primary' => 'key1', ...], ... ]

public function getReadRequest($ids)
    {
        $db = $this->_getConnection();
        $table = $this->table;
        $self = $this;
        $primary = $this->_getPrimaryKetArray();

        $request = new StorageDataRequest(
            [$ids],
            function ($ids) use ($db, $table, $self, $primary) {
                if (!$db) {
                    $self->logError('Missing connection on getReadRequest on table: ' . $table);
                    return false;
                }

                $whereLines = [];
                foreach ($ids as $id) {
                    $whereArray = [];
                    $whereBind = $self->prepareBind($self->prepareKey($primary, $id), $db);
                    foreach ($whereBind as $key => $value) {
                        $whereArray[] = $key . ' = ' . $value;
                    }
                    $whereLines[] = implode(' AND ', $whereArray);
                }

                $query = 'SELECT * FROM ' . $table
                    . ' WHERE (' . implode(' ) OR (', $whereLines) . ')';

                $stmnt = $db->query($query);

                if (!$stmnt) {
                    $this->logError('Cannot execute getReadRequest on table: ' . $table . ':' . implode(',', $db->errorInfo()), [
                        'code' => $db->errorCode(),
                    ]);

                    return false;
                }

                $result = $stmnt->fetchAll(PDO::FETCH_ASSOC);

                if (!$result && (int) $stmnt->errorCode() > 0) {
                    $this->logError('Error on execution on getReadRequest on table: ' . $table . ':' . implode(',',
                            $stmnt->errorInfo()), [
                        'code' => $stmnt->errorCode(),
                    ]);

                    return false;
                }

                return $result;
            });

        return $request;
    }

protected function _afterEntityFetch(AnCommandContext $context)
    {
        //set the persistd flag
        $this->setPersisted(true);

        //set the raw data
        $this->_data->setRowData($context['data']);

        //force setting the keys
        foreach ($context['keys'] as $key => $value) {
            $this->_data[$key] = $value;
        }
    }

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


Question: // SetPolicyArn sets the PolicyArn field's value.

func (s *PolicyGrantingServiceAccess) SetPolicyArn(v string) *PolicyGrantingServiceAccess {
	s.PolicyArn = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

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


Question:
Checks if an override exists for a given operator.
@param {string} operator Operator
@returns {boolean} Whether or not an override has been provided for the operator

function overrideExistsForOperator(operator) {
            return options.overrides && Object.prototype.hasOwnProperty.call(options.overrides, operator);
        }

private void createProxyJsMethod(Builder componentExposedTypeBuilder,
      ExecutableElement originalMethod, String proxyMethodName) {
    Emit emitAnnotation = originalMethod.getAnnotation(Emit.class);

    MethodSpec.Builder proxyMethodBuilder = MethodSpec
        .methodBuilder(proxyMethodName)
        .addModifiers(Modifier.PUBLIC)
        .addAnnotation(JsMethod.class)
        .addAnnotation(getUnusableByJSAnnotation())
        .returns(ClassName.get(originalMethod.getReturnType()));

    originalMethod
        .getParameters()
        .forEach(parameter -> proxyMethodBuilder.addParameter(TypeName.get(parameter.asType()),
            parameter.getSimpleName().toString()));

    String methodCallParameters = getSuperMethodCallParameters(originalMethod);
    boolean hasReturnValue = !"void".equals(originalMethod.getReturnType().toString());
    if (hasReturnValue) {
      proxyMethodBuilder.addStatement("$T result = super.$L($L)",
          originalMethod.getReturnType(),
          originalMethod.getSimpleName().toString(),
          methodCallParameters);
    } else {
      proxyMethodBuilder.addStatement("super.$L($L)",
          originalMethod.getSimpleName().toString(),
          methodCallParameters);
    }

    if (emitAnnotation != null) {
      addEmitEventCall(originalMethod, proxyMethodBuilder, methodCallParameters);
    }

    if (hasReturnValue) {
      proxyMethodBuilder.addStatement("return result");
    }

    componentExposedTypeBuilder.addMethod(proxyMethodBuilder.build());
  }

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


Question: Create the UI artefacts for the "Print contacts" sub form.

private void createPrintContactsSubForm() {
		add(new WHeading(HeadingLevel.H3, "Print to CSV"));

		WButton printBtn = new WButton("Print");
		printBtn.setAction(new Action() {
			@Override
			public void execute(final ActionEvent event) {
				printDetails();
			}
		});
		printBtn.setImage("/image/document-print.png");
		printBtn.setImagePosition(WButton.ImagePosition.EAST);

		WFieldLayout layout = new WFieldLayout();
		add(layout);
		layout.setMargin(new Margin(Size.LARGE, null, null, null));
		layout.addField("Print output", printOutput);
		layout.addField((WLabel) null, printBtn);
		add(new WAjaxControl(printBtn, printOutput));
	}

private function generateTermsOfUsePdf($customer)
    {
        $this->set('customer', $customer);
        $this->set('saveParam', 'I');
        $this->RequestHandler->renderAs($this, 'pdf');
        return $this->render('generateTermsOfUsePdf');
    }

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


Question: Make sure that t is a 1D array and compatible with the C position array.

def _validate_prepare_time(self, t, pos_c):

        if hasattr(t, 'unit'):
            t = t.decompose(self.units).value

        if not isiterable(t):
            t = np.atleast_1d(t)

        t = np.ascontiguousarray(t.ravel())

        if len(t) > 1:
            if len(t) != pos_c.shape[0]:
                raise ValueError("If passing in an array of times, it must have a shape "
                                 "compatible with the input position(s).")

        return t

def _supervised_evaluation_error_checking(targets, predictions):

    _raise_error_if_not_sarray(targets, "targets")
    _raise_error_if_not_sarray(predictions, "predictions")
    if (len(targets) != len(predictions)):
        raise _ToolkitError(
         "Input SArrays 'targets' and 'predictions' must be of the same length.")

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


Question:
Finishes a takeout, with specified result sent back to Telegram.

        Returns:
            ``True`` if the operation was successful, ``False`` otherwise.

async def end_takeout(self, success):

        try:
            async with _TakeoutClient(True, self, None) as takeout:
                takeout.success = success
        except ValueError:
            return False
        return True

protected function fail($error = '')
    {
        $this->isFinished = true;
        $this->isSuccess = false;
        $this->error = $error;
    }

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


Question: // New push package will be written to w.

func New(w io.Writer) Package {
	return Package{
		z:        zip.NewWriter(w),
		manifest: make(map[string]string),
	}
}

public static function read($file)
    {
        $cwd = getcwd();
        $log = $cwd.'/producer.log';

        if (file_exists($file)) {
            file_put_contents($log, file_get_contents($file), FILE_APPEND);
        }
    }

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


Question: Append path to base_url in a sensible way.

def append_url(base_url, path):

    if base_url[-1] != "/":
        base_url += "/"
    if path[0] == "/":
        path = path[1:]
    return urljoin(base_url, path)

protected function getResourcesBaseUri()
    {
        if ($this->absoluteBaseUri === null) {
            $this->absoluteBaseUri = $this->detectResourcesBaseUri();
        }

        return $this->absoluteBaseUri;
    }

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


Question:
Returns the object inside Writable

@param object
@return
@throws IllegalAccessException
@throws InstantiationException
@throws InvocationTargetException
@throws NoSuchMethodException

private static Writable getWritableFromObject(Object object) {

        Writable writable = null;

        if (object instanceof String) {

            writable = new Text(object.toString());

        } else if (object instanceof Long) {

            writable = new LongWritable((Long) object);

        } else {

            writable = new IntWritable((Integer) object);

        }
        // writable = writable!=null?writable:new Text("");
        return writable;
    }

@Deprecated
    public static @CheckForNull
    JavaClassAndMethod findConcreteMethod(JavaClass javaClass, String methodName, String methodSig) {

        if (DEBUG_METHOD_LOOKUP) {
            System.out.println("Check " + javaClass.getClassName());
        }
        Method[] methodList = javaClass.getMethods();
        for (Method method : methodList) {
            if (method.getName().equals(methodName) && method.getSignature().equals(methodSig)
                    && accessFlagsAreConcrete(method.getAccessFlags())) {
                JavaClassAndMethod m = new JavaClassAndMethod(javaClass, method);

                return m;

            }
        }
        if (DEBUG_METHOD_LOOKUP) {
            System.out.println("\t==> NOT FOUND");
        }
        return null;
    }

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


Question:
Write a debug message to the logs

@param message   The debug message
@param exception

public void debug(final String message, final Exception exception) {
        messages.add(new LogMessage(message + " " + exception.getMessage(), LogMessage.Type.DEBUG));
        log.debug(message, exception);
    }

func (user *User) Add(message newMessage) error {
	switch message.(type) {
	case *UserPost:
		post := message.(*UserPost)
		if post.To == 0 {
			post.To = user.ID()
		}
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *ProjectPost:
		post := message.(*ProjectPost)
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *UserPostComment:
		comment := message.(*UserPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *ProjectPostComment:
		comment := message.(*ProjectPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *Pm:
		pm := message.(*Pm)
		if err := createMessage(pm, user.ID(), pm.To, pm.Text(), pm.Language()); err != nil {
			return err
		}
		return Db().Create(pm)
	}

	return fmt.Errorf("Invalid parameter type: %s", reflect.TypeOf(message))
}

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


Question: Enqueues a job into SharQ.

def _view_enqueue(self, queue_type, queue_id):
        """"""
        response = {
            'status': 'failure'
        }
        try:
            request_data = json.loads(request.data)
        except Exception, e:
            response['message'] = e.message
            return jsonify(**response), 400

        request_data.update({
            'queue_type': queue_type,
            'queue_id': queue_id
        })

        try:
            response = self.sq.enqueue(**request_data)
        except Exception, e:
            response['message'] = e.message
            return jsonify(**response), 400

        return jsonify(**response), 201

def create(self):

        steps = [
            (self.create_role, (), {}),
            (self.create_vpc, (), {}),
            (self.create_cluster, (), {}),
            (self.create_node_group, (), {}),
            (self.create_spot_nodes, (), {}),
            (self.create_utilities, (), {}),
        ]
        # Execute creation.
        for step in tqdm.tqdm(steps, ncols=70):
            method, args, kwargs = step
            method(*args, **kwargs)

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


Question:
Helper method to get search operators

@param mixed $data Data to use for provision
@param mixed[] $options Options to use for provision
@return mixed[]

protected function getSearchOperators($data = null, array $options = []) : array
    {
        $result = $this->config->getProvider('searchOperators');
        $result = new $result($this->config);
        $result = $result->provide($data, $options);

        return $result;
    }

public static Pair<Optional<Table>, Optional<List<Partition>>> getDestinationTableMeta(String dbName,
      String tableName, Properties props) {

    Optional<Table> table = Optional.<Table>absent();
    Optional<List<Partition>> partitions = Optional.<List<Partition>>absent();

    try {
      HiveMetastoreClientPool pool = HiveMetastoreClientPool.get(props,
          Optional.fromNullable(props.getProperty(HiveDatasetFinder.HIVE_METASTORE_URI_KEY)));
      try (AutoReturnableObject<IMetaStoreClient> client = pool.getClient()) {
        table = Optional.of(client.get().getTable(dbName, tableName));
        if (table.isPresent()) {
          org.apache.hadoop.hive.ql.metadata.Table qlTable = new org.apache.hadoop.hive.ql.metadata.Table(table.get());
          if (HiveUtils.isPartitioned(qlTable)) {
            partitions = Optional.of(HiveUtils.getPartitions(client.get(), qlTable, Optional.<String>absent()));
          }
        }
      }
    } catch (NoSuchObjectException e) {
      return ImmutablePair.of(table, partitions);
    } catch (IOException | TException e) {
      throw new RuntimeException("Could not fetch destination table metadata", e);
    }

    return ImmutablePair.of(table, partitions);
  }

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


Question:
Determine if the browser is Phoenix or not (last updated 1.7)
@return boolean True if the browser is Phoenix otherwise false

protected function checkBrowserPhoenix()
    {
        if (stripos($this->_agent, 'Phoenix') !== false) {
            $aversion = explode('/', stristr($this->_agent, 'Phoenix'));
            if (isset($aversion[1])) {
                $this->setVersion($aversion[1]);
                $this->setBrowser(self::BROWSER_PHOENIX);
                return true;
            }
        }
        return false;
    }

function overrideTasks() {
    function noop() {
        Elixir.log.heading.error('Quorra don\'t have php tests!')
    }

    Elixir.extend('phpSpec', noop);
    Elixir.extend('phpunit', noop);
    Elixir.extend('babel', function () {
        new Elixir.Task('babel', function () {
            Elixir.log.heading('Alert!').heading("'mix.babel()' is not supported in Quorra Elixir. " +
            "You'll want to instead call 'mix.rollup().'");

            process.exit(1);
        });
    });
}

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


Question:
Marks the response as "immutable".

@param bool $immutable enables or disables the immutable directive

@return $this

@final

public function setImmutable($immutable = true)
    {
        if ($immutable) {
            $this->headers->addCacheControlDirective('immutable');
        } else {
            $this->headers->removeCacheControlDirective('immutable');
        }

        return $this;
    }

public function directCreateAction(Request $request)
    {
        $filter = new Filter();
        $filter->setName($request->request->get('filter_name'));
        $filter->setDescription($request->request->get('filter_description'));
        $filter->setState($request->request->getBoolean('filter_public') ? FilterStateEnum::ALL : FilterStateEnum::SELF);
        $filter->setCreatorUsername($this->getUser()->getUsername());

        $filter->setRoute($request->request->get('filter_route'));
        $filter->setArguments(json_decode($request->request->get('filter_route_arguments'), true));
        $filter->setConditions(json_decode($request->get('filter_conditions'), true));

        if (!is_array($filter->getConditions()) || !is_array($filter->getArguments())) {
            throw new BadRequestHttpException();
        }

        if ($this->router->getRouteCollection()->get($filter->getRoute()) === null) {
            throw new BadRequestHttpException();
        }

        $this->entityManager->persist($filter);
        $this->entityManager->flush();

        return $this->redirect($this->router->generate(
            $filter->getRoute(),
            array_merge($filter->getArguments(), $filter->getConditions())
        ));
    }

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


Question: // Copy returns a copy of the request header.

func (h *Header) Copy() *Header {
	return &Header{h.Version, h.Type, h.Length, h.Transaction}
}

private function _setResponseHeaders()
    {
        $this->_response->setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT", true)
                        ->setHeader("Last-Modified", gmdate("D, d M Y H:i:s") . " GMT", true)
                        ->setHeader("Cache-Control", "no-store, no-cache, must-revalidate", true)
                        ->setHeader("Cache-Control", "post-check=0, pre-check=0", false)
                        ->setHeader("Pragma", "no-cache", true)
                        ->sendHeaders();
    }

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


Question:
Clone metadata map.

@param current metadata map to clone
@return a clone of the original map

private Map<String, Element> cloneElementMap(final Map<String, Element> current) {
        final Map<String, Element> topicMetaTable = new HashMap<>(16);
        for (final Entry<String, Element> topicMetaItem: current.entrySet()) {
            topicMetaTable.put(topicMetaItem.getKey(), (Element) resultDoc.importNode(topicMetaItem.getValue(), true));
        }
        return topicMetaTable;
    }

private function createMaps(RouteCollectionInterface $routes)
    {
        foreach ($routes->all() as $name => $route) {
            foreach ($route->getMethods() as $method) {
                $this->mMap[$method][] = $name;
            }

            foreach ($route->getSchemes() as $scheme) {
                $this->scMap[$scheme][] = $name;
            }

            $this->spMap[$route->getContext()->getStaticPath()][] = $name;
        }
    }

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


Question:
Publish all module resources

@param string $targetDir
@param array $extensions

public function publish($targetDir = null, array $extensions = array())
    {
        if (!$targetDir) {
            $targetDir = $this->targetDir;
        }

        $this->publishResources($targetDir, $extensions);
        $this->publishThemeFiles($targetDir, $extensions);

        return $this;
    }

protected function getOptions()
    {
        return [
            [
                'path',
                'p',
                InputOption::VALUE_OPTIONAL,
                sprintf('Path to the javscript assets directory (default: "%s")', $this->config->get('laroute.path'))
            ],
            [
                'filename',
                'f',
                InputOption::VALUE_OPTIONAL,
                sprintf('Filename of the javascript file (default: "%s")', $this->config->get('laroute.filename'))
            ],
            [
                'namespace',
                null,
                InputOption::VALUE_OPTIONAL, sprintf('Javascript namespace for the functions (think _.js) (default: "%s")', $this->config->get('laroute.namespace'))
            ],
            [
                'prefix',
                'pr',
                InputOption::VALUE_OPTIONAL, sprintf('Prefix for the generated URLs (default: "%s")', $this->config->get('laroute.prefix'))
            ],
        ];
    }

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


Question: // MonthWide returns the locales wide month given the 'month' provided

func (km *km) MonthWide(month time.Month) string {
	return km.monthsWide[month]
}

static public function create($params, LocatorInterface $locator = null) {
		if (! is_array($params) && ! $params instanceof Traversable) {
			throw new InvalidOptions('Options must be an array or a Traversable implementation');
		}

		if ($params instanceof Traversable) {
			$params = Std::iteratorToArray($params);
		}

		$translator = new Translator();

		foreach ($params as $param => $value) {
			if ($param === 'cacheStrategy') {
				$class = self::NAMESPACE_CACHE . '\Strategy' . ucfirst($value);

				$translator->setCache(new $class($locator));
				unset($params[$param]);
				continue;
			}

			if ($param === 'resources') {
				if (! is_array($value) && ! $value instanceof Traversable) {
					throw new InvalidOptions('Resources definition must be an array or a Traversable implementation');
				}

				$translator->setResources(self::createResources($value));
				unset($params[$param]);
				continue;
			}

			if ($param === 'bbcodes') {
				if ($value) {
					$bbcodes = new BBCodes();

					if (isset($params['paramsPattern'])) {
						$bbcodes->setParamsPattern($params['paramsPattern']);
					}

					$translator->addPlugin($bbcodes, 'bbcodes');
				}

				unset($params[$param]);
			}
		}

		$translator->setOptions($params, false, false);

		return $translator;
	}

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


Question: Removes the child element

def remove(self, child):
        """"""
        if not isinstance(child, AbstractElement):
            raise ValueError("Expected AbstractElement, got " + str(type(child)))
        if child.parent == self:
            child.parent = None
        self.data.remove(child)
        #delete from index
        if child.id and self.doc and child.id in self.doc.index:
            del self.doc.index[child.id]

private boolean findAndRemove(Object e) {
        if (e != null) {
            for (Node pred = null, p = head; p != null; ) {
                Object item = p.item;
                if (p.isData) {
                    if (item != null && item != FORGOTTEN && e.equals(item) &&
                        p.tryMatchData()) {
                        unsplice(pred, p);
                        return true;
                    }
                }
                else if (item == null)
                    break;
                pred = p;
                if ((p = p.next) == UNLINKED) { // stale
                    pred = null;
                    p = head;
                }
            }
        }
        return false;
    }

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


Question:
Go, Johnny, Go!

@param Controller $obj_controller

public function dispatch(Controller $obj_controller)
    {
        $obj_controller->preDispatch();
        $obj_controller->dispatch();
        $obj_controller->postDispatch();
        $this->sendResponse($obj_controller->getResponse());
    }

protected void init(Object target, PropertyInfo propInfo, PropertyGrid propGrid) {
        this.target = target;
        this.propInfo = propInfo;
        this.propGrid = propGrid;
        this.index = propGrid.getEditorCount();
        wireController();
    }

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


Question:
A NetLocation instance with some GeoIP or pygeoip information
        about location, asn, city (if available).

def location(self):

        if self._location:
            return self._location

        if self.ip != 'unknown':
            self._location = NetLocation(self.ip)
        else:
            self._location = NetLocation(None)
        if not self._location.countrycode and self.ip != 'unknown':
            # see if Tor is magic and knows more...
            d = self.controller.get_info_raw('ip-to-country/' + self.ip)
            d.addCallback(self._set_country)
            # ignore errors (e.g. "GeoIP Information not loaded")
            d.addErrback(lambda _: None)
        return self._location

def _get_chromecast_from_service(services, tries=None, retry_wait=None,
                                 timeout=None, blocking=True):
    """"""
    # Build device status from the mDNS service name info, this
    # information is the primary source and the remaining will be
    # fetched later on.
    services, zconf, uuid, model_name, friendly_name = services
    _LOGGER.debug("_get_chromecast_from_service %s", services)
    cast_type = CAST_TYPES.get(model_name.lower(),
                               CAST_TYPE_CHROMECAST)
    device = DeviceStatus(
        friendly_name=friendly_name, model_name=model_name,
        manufacturer=None, uuid=uuid, cast_type=cast_type,
    )
    return Chromecast(host=None, device=device, tries=tries, timeout=timeout,
                      retry_wait=retry_wait, blocking=blocking,
                      services=services, zconf=zconf)

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


Question:
{@inheritDoc}
@see \rocket\ei\manage\draft\DraftProperty::createDraftValueSelection()

public function createDraftValueSelection(FetchDraftStmtBuilder $selectDraftStmtBuilder, DraftManager $dm,
			N2nContext $n2nContext): DraftValueSelection {

		return new SimpleToOneDraftValueSelection($selectDraftStmtBuilder->requestColumn(EiPropPath::from($this)),
				$dm->getEntityManager(), $this->eiPropRelation->getTargetEiType()->getEntityModel());
	}

def select_plugin(self, case_obj):
        """"""
        if case_obj.variant_mode == 'vcf':
            logger.debug("Using vcf plugin")
            plugin = VcfPlugin(case_obj.variant_type)
        elif case_obj.variant_mode == 'gemini':
            logger.debug("Using gemini plugin")
            plugin = GeminiPlugin(case_obj.variant_type)

        #Add case to plugin
        plugin.add_case(case_obj)

        self.variant_type = case_obj.variant_type

        case_id = case_obj.case_id
        return plugin, case_id

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


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

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

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

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

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

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

	parser.simple_key_allowed = false

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

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


Question: Set an attribute of an object to a value or default value.

def _setattr_default(obj, attr, value, default):
    """"""
    if value is None:
        setattr(obj, attr, default)
    else:
        setattr(obj, attr, value)

function(target, obj){
      for (var attr in obj) {
        if(obj.hasOwnProperty(attr)){
          target[attr] = obj[attr];
        }
      }
      return target;
    }

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


Question:
Save one Attachemnt

@param EntityInterface $entity Entity
@param string $upload String to uploaded file or ['path_to_file' => [tag1, tag2, tag3, ...]]
@return entity

public function addUpload(EntityInterface $entity, $upload)
    {
        $tags = [];
        $path = $upload;
        if (is_array($upload)) {
            $tags = reset($upload);
            $path = reset(array_flip($upload));
        }
        $file = Configure::read('Attachments.tmpUploadsPath') . $path;
        $attachment = $this->createAttachmentEntity($entity, $file, $tags);
        $save = $this->save($attachment);
        if ($save) {
            return $attachment;
        }
        return $save;
    }

public function handleAction(Request $request): Envelope
    {
        $request->attributes->set('pbjx_redact_error_message', false);
        $envelope = EnvelopeV1::create();
        if (!$this->isRequestMethodOk($envelope, $request) || !$this->isContentTypeOk($envelope, $request)) {
            return $envelope;
        }

        if ($request->isMethod('GET')) {
            $json = PbjxToken::urlsafeB64Decode($request->query->get('pbj'));
        } elseif (0 === strpos($request->headers->get('Content-Type'), 'multipart/form-data')) {
            $json = $request->request->get('pbj');
        } else {
            $json = $request->getContent();
        }

        $json = (string)$json;
        $data = json_decode($json, true) ?: [];
        if (!$this->isJsonOk($envelope, $request)) {
            return $envelope;
        }

        $pbjxCategory = $request->attributes->get('pbjx_category');
        if (false !== strpos($pbjxCategory, '_')) {
            $pbjxCategory = str_replace('_', '', $pbjxCategory);
            $request->attributes->set('pbjx_category', $pbjxCategory);
        }

        try {
            $expectedCurie = SchemaCurie::fromString(sprintf(
                '%s:%s:%s:%s',
                $request->attributes->get('pbjx_vendor'),
                $request->attributes->get('pbjx_package'),
                $pbjxCategory,
                $request->attributes->get('pbjx_message')
            ));

            $request->attributes->set('pbjx_curie', $expectedCurie->toString());
            $schemaId = isset($data[Schema::PBJ_FIELD_NAME]) ? SchemaId::fromString($data[Schema::PBJ_FIELD_NAME]) : null;

            /** @var Message $class */
            if (null === $schemaId) {
                $class = MessageResolver::resolveCurie($expectedCurie);
                $schema = $class::schema();
                $schemaId = $schema->getId();
            } else {
                $class = MessageResolver::resolveId($schemaId);
            }

            if ($schemaId->getCurie() !== $expectedCurie) {
                throw new \InvalidArgumentException(
                    sprintf(
                        'The resolved schema [%s] doesn\'t match expected curie [%s].',
                        $schemaId->toString(),
                        $expectedCurie->toString()
                    )
                );
            }
        } catch (\Throwable $e) {
            return $envelope
                ->set('code', Code::INVALID_ARGUMENT)
                ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
                ->set('error_name', 'UnprocessableEntity')
                ->set('error_message', $e->getMessage());
        }

        $request->attributes->set('pbjx_input', $data);
        $request->attributes->set('pbjx_bind_unrestricted', $request->attributes->getBoolean('pbjx_bind_unrestricted'));

        try {
            /** @var Command|Event|PbjxRequest $message */
            $message = $class::fromArray($data);
            $message->set('ctx_correlator_ref', $envelope->generateMessageRef());
        } catch (\Throwable $e) {
            return $envelope
                ->set('code', Code::INVALID_ARGUMENT)
                ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
                ->set('error_name', 'UnprocessableEntity')
                ->set('error_message', $e->getMessage());
        }

        $request->attributes->set(
            'pbjx_redact_error_message',
            !$request->attributes->getBoolean('pbjx_console')
        );

        if (!$this->isPbjxTokenOk($envelope, $request, $json)) {
            return $envelope;
        }

        // allows for functional tests/postman tests/etc. to post pbjx but
        // not actually run them.  this is most important for commands/events
        // which can change state but for request, you'd typically not use
        // dry run because you need to get a response in order to make assertions.
        if ($request->headers->has('x-pbjx-dry-run')) {
            return $envelope
                ->set('code', Code::OK)
                ->set('http_code', HttpCode::HTTP_ACCEPTED())
                ->set('message_ref', $message->generateMessageRef());
        }

        if ($message instanceof Command) {
            return $this->handleCommand($envelope, $request, $message);
        }

        if ($message instanceof Event) {
            return $this->handleEvent($envelope, $request, $message);
        }

        if ($message instanceof PbjxRequest) {
            return $this->handleRequest($envelope, $request, $message);
        }

        $request->attributes->set('pbjx_redact_error_message', false);
        return $envelope
            ->set('code', Code::INVALID_ARGUMENT)
            ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
            ->set('error_name', 'UnprocessableEntity')
            ->set(
                'error_message',
                sprintf('This service does not allow you to submit [%s] messages.', $schemaId->toString())
            );
    }

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


Question: Remove one observer, which had priority and callble.

def remove(self, priority, observer, callble):

        self.flush()
        for i in range(len(self) - 1, -1, -1):
            p,o,c = self[i]
            if priority==p and observer==o and callble==c:
                del self._poc[i]

func (cp *CallbackProcessor) Replace(callbackName string, callback func(scope *Scope)) {
	log.Printf("[info] replacing callback `%v` from %v\n", callbackName, fileWithLineNum())
	cp.name = callbackName
	cp.processor = &callback
	cp.replace = true
	cp.parent.processors = append(cp.parent.processors, cp)
	cp.parent.reorder()
}

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


Question:
:param sources: a sequence of sources
        :yields: sources with .indices

def filter(self, sources):

        for src in sources:
            if hasattr(src, 'indices'):   # already filtered
                yield src
                continue
            box = self.integration_distance.get_affected_box(src)
            indices = self.sitecol.within_bbox(box)
            if len(indices):
                src.indices = indices
                yield src

def _json_to_sectionref(data):

    section_term = None
    sections = []
    for section_data in data.get("Sections", []):
        if (section_term is None or
                section_data["Year"] != section_term.year or
                section_data["Quarter"] != section_term.quarter):
            section_term = get_term_by_year_and_quarter(
                section_data["Year"], section_data["Quarter"])
        section = SectionReference(
            term=section_term,
            curriculum_abbr=section_data["CurriculumAbbreviation"],
            course_number=section_data["CourseNumber"],
            section_id=section_data["SectionID"],
            url=section_data["Href"])
        sections.append(section)
    return sections

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


Question:
//setValue sets n value to value.
//if value is a *Values, then n.setValues(values.(*Values)) is used.

func (n *node) setValue(value interface{}) bool {
	if values, ok := value.(*Values); ok {
		return n.setValues(values)
	}
	changed := false
	if n.isSet() {
		changed = value != n.value
	} else {
		changed = true
	}
	n.value = value
	n.children = nil
	return changed
}

public final Object evObjVl(final String pNm) throws ExceptionWithCode {
    if (this.ints != null && this.ints.keySet().contains(pNm)) {
      return this.ints.get(pNm);
    }
    if (this.longs != null && this.longs.keySet().contains(pNm)) {
      return this.longs.get(pNm);
    }
    if (this.strs != null && this.strs.keySet().contains(pNm)) {
      String val = (String) this.strs.get(pNm);
      if (val == null) {
        return null;
      } else {
        if (this.exprs != null && this.exprs.contains(pNm)) {
          return val;
        } else {
          return "'" + val + "'";
        }
      }
    }
    if (this.floats != null && this.floats.keySet().contains(pNm)) {
      return this.floats.get(pNm);
    }
    if (this.doubles != null && this.doubles.keySet().contains(pNm)) {
      return this.doubles.get(pNm);
    }
    if (this.idLongs != null && this.idLongs.keySet().contains(pNm)) {
      return this.idLongs.get(pNm);
    }
    if (this.idStrs != null && this.idStrs.keySet().contains(pNm)) {
      return this.idStrs.get(pNm);
    }
    if (this.idInts != null && this.idInts.keySet().contains(pNm)) {
      return this.idInts.get(pNm);
    }
    throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
      "There is no field - " + pNm);
  }

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


Question:
// unregisterEndpoint unregisters the endpoint with the given id such that it
// won't receive any more packets.

func (d *transportDemuxer) unregisterEndpoint(netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint) {
	for _, n := range netProtos {
		if eps, ok := d.protocol[protocolIDs{n, protocol}]; ok {
			eps.unregisterEndpoint(id, ep)
		}
	}
}

func WriteDisable(
	clientAddr chan<- Addr,
	clientData chan<- WriteData,
	clientResp <-chan WriteResp) {

	clientAddr <- Addr{}
	clientData <- WriteData{Last: true}
	for {
		<-clientResp
	}
}

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


Question:
Sends a direct message to the specified user.
https://dev.twitter.com/rest/reference/post/direct_messages/new
@throws Exception

public function sendDirectMessage(string $username, string $message): stdClass
	{
		return $this->request(
			'direct_messages/events/new',
			'JSONPOST',
			['event' => [
				'type' => 'message_create',
				'message_create' => [
					'target' => ['recipient_id' => $this->loadUserInfo($username)->id_str],
					'message_data' => ['text' => $message],
				],
			]]
		);
	}

public void marshall(CreateDeploymentRequest createDeploymentRequest, ProtocolMarshaller protocolMarshaller) {

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

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

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


Question:
This method calculates the valence of an atom.

@param atom          The IAtom for which the DescriptorValue is requested
@param container      Parameter is the atom container.
@return The valence of an atom

@Override
    public DescriptorValue calculate(IAtom atom, IAtomContainer container) {
        int atomValence = AtomValenceTool.getValence(atom);
        return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new IntegerResult(
                atomValence), getDescriptorNames());
    }

def provide_attr(attr)
      list_item_attr_value = list_item.public_send(attr)

      # Provide user supplied attr
      return list_item_attr_value if list_item_attr_value.present?

      # Provide object supplied attr
      return object_data[attr] if object_available?

      # Provide error - Object is linked but has been deleted
      return 'Object Unavailable' if list_item.object? && !object_available?

      # Provide empty string - no attr supplied and no object linked
      ''
    end

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


Question:
Convert type variable in correct type. This must be done before work on
SQLMethod

@param value
the value

void resolveTypeVariable(SQLiteModelMethod value) {
		// before proceed, we need to resolve typeVariables
		for (Pair<String, TypeName> item : value.getParameters()) {
			item.value1 = typeVariableResolver.resolve(item.value1);
		}

		value.setReturnClass(typeVariableResolver.resolve(value.getReturnClass()));

	}

public Long getParameterTime(String name) throws RepositoryConfigurationException
   {
      try
      {
         return StringNumberParser.parseTime(getParameterValue(name));
      }
      catch (NumberFormatException e)
      {
         throw new RepositoryConfigurationException(name + ": unparseable time (as Long). " + e, e);
      }
   }

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


Question:
Join one or multiple lines that wrapped. Returns the reconstructed line.
    Takes into account proper spacing between the lines (see
    STRIP_SPACE_CHARS).

def join_wrapped_lines(lines):

    if len(lines) == 1:
        return lines[0]

    joined = lines[0]
    for line in lines[1:]:
        if joined and joined[-1] in STRIP_SPACE_CHARS:
            joined += line
        else:
            joined += ' '
            joined += line

    return joined

def _fix_out_of_sentence_links( alignments, sent_start, sent_end ):
    '''
    '''
    sent_len = sent_end - sent_start
    j = sent_start
    while j < sent_start + sent_len:
        for rel_id, rel in enumerate( alignments[j][PARSER_OUT] ):
            if int( rel[1] ) >= sent_len:
                # If the link points out-of-the-sentence, fix
                # the link so that it points inside the sentence
                # boundaries:
                wid = j - sent_start
                if sent_len == 1:
                    # a single word becomes a root
                    rel[1] = -1
                elif wid-1 > -1:
                    # word at the middle/end is linked to the previous
                    rel[1] = wid - 1
                elif wid-1 == -1:
                    # word at the beginning is linked to the next
                    rel[1] = wid + 1
                alignments[j][PARSER_OUT][rel_id] = rel
        j += 1

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


Question: // TagKeySeriesIDIterator returns a series iterator for a tag key.

func (f *LogFile) TagKeySeriesIDIterator(name, key []byte) tsdb.SeriesIDIterator {
	f.mu.RLock()
	defer f.mu.RUnlock()

	mm, ok := f.mms[string(name)]
	if !ok {
		return nil
	}

	tk, ok := mm.tagSet[string(key)]
	if !ok {
		return nil
	}

	// Combine iterators across all tag keys.
	itrs := make([]tsdb.SeriesIDIterator, 0, len(tk.tagValues))
	for _, tv := range tk.tagValues {
		if tv.cardinality() == 0 {
			continue
		}
		itrs = append(itrs, tsdb.NewSeriesIDSetIterator(tv.seriesIDSet()))
	}

	return tsdb.MergeSeriesIDIterators(itrs...)
}

def _validate_id_types(self):
        ''''''

        for sequences in [self.uniparc_sequences, self.fasta_sequences, self.seqres_sequences, self.rosetta_sequences]:
            for chain_id, sequence in sequences.iteritems():
                sequence_id_types = set(map(type, sequence.ids()))
                if sequence_id_types:
                    assert(len(sequence_id_types) == 1)
                    assert(sequence_id_types.pop() == types.IntType)

        for chain_id, sequence in self.atom_sequences.iteritems():
            sequence_id_types = set(map(type, sequence.ids()))
            assert(len(sequence_id_types) == 1)
            sequence_id_type = sequence_id_types.pop()
            assert(sequence_id_type == types.StringType or sequence_id_type == types.UnicodeType)

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


Question:
Clears the redo log.

@throws IOException
if the redo log cannot be cleared.

public void clear() throws IOException
   {
      if (out != null)
      {
         out.truncate(0);
         out.close();
         out = PrivilegedFileHelper.fileOutputStream(logFile).getChannel();
         out.position(1024 * fileSize - 1);
         out.write(ByteBuffer.wrap(new byte[]{0}));
         out.position(0);
         out.force(false);
      }
   }

private String getDebugLog(final Object[] args) {
        final StringBuilder sb = new StringBuilder(name);
        sb.append('(');

        int i = 0;
        for (final Object param : args) {
            if (i > 0) {
                sb.append(',');
            }

            if (param == null) {
                sb.append("NULL");
            } else if (params.get(i).isSensitive()) {
                sb.append("<SENSITIVE>");
            } else {
                sb.append(param);
            }

            i++;
            if (sb.length() > TRUNCATE_DEBUG_PARAMS_MAX_LENGTH) {
                break;
            }
        }

        if (sb.length() > TRUNCATE_DEBUG_PARAMS_MAX_LENGTH) {

            // Truncate params for debug output
            return sb.substring(0, TRUNCATE_DEBUG_PARAMS_MAX_LENGTH) + TRUNCATE_DEBUG_PARAMS_ELLIPSIS + ")";
        } else {
            sb.append(')');
            return sb.toString();
        }
    }

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


Question: // GetContainerFromShortID gets an oci container matching the specified full or partial id

func (c *ContainerServer) GetContainerFromShortID(cid string) (*oci.Container, error) {
	if cid == "" {
		return nil, fmt.Errorf("container ID should not be empty")
	}

	containerID, err := c.ctrIDIndex.Get(cid)
	if err != nil {
		return nil, fmt.Errorf("container with ID starting with %s not found: %v", cid, err)
	}

	ctr := c.GetContainer(containerID)
	if ctr == nil {
		return nil, fmt.Errorf("specified container not found: %s", containerID)
	}
	return ctr, nil
}

function(options){
      var name = options.name
        , model = options.model
        , implementation = options.implementation
        , cid = options.cid;

      // save the new things by internal cid
      this._names[cid] = name;
      this._models[cid] = model;
      this._implementations[cid] = implementation;

      this._updateLength();

      return this;
    }

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


Question:
Creates a QUERY_REPLY message.

@param leader the current leader in broadcasting phase.
@return a protobuf message.

public static Message buildQueryReply(String leader) {
    QueryReply reply = QueryReply.newBuilder()
                                 .setLeader(leader)
                                 .build();
    return Message.newBuilder().setType(MessageType.QUERY_LEADER_REPLY)
                               .setReply(reply)
                               .build();
  }

public function basic_publish(
        $msg,
        $exchange = '',
        $routing_key = '',
        $mandatory = false,
        $immediate = false,
        $ticket = null
    ) {
        $pkt = new AMQPWriter();
        $pkt->write($this->pre_publish($exchange, $routing_key, $mandatory, $immediate, $ticket));

        try {
            $this->connection->send_content(
                $this->channel_id,
                60,
                0,
                mb_strlen($msg->body, 'ASCII'),
                $msg->serialize_properties(),
                $msg->body,
                $pkt
            );
        } catch (AMQPConnectionClosedException $e) {
            $this->do_close();
            throw $e;
        }

        if ($this->next_delivery_tag > 0) {
            $this->published_messages[$this->next_delivery_tag] = $msg;
            $this->next_delivery_tag = bcadd($this->next_delivery_tag, '1', 0);
        }
    }

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


Question: // NewSharedContentAddMemberType returns a new SharedContentAddMemberType instance

func NewSharedContentAddMemberType(Description string) *SharedContentAddMemberType {
	s := new(SharedContentAddMemberType)
	s.Description = Description
	return s
}

def share_extension_with_host(self, publisher_name, extension_name, host_type, host_name):

        route_values = {}
        if publisher_name is not None:
            route_values['publisherName'] = self._serialize.url('publisher_name', publisher_name, 'str')
        if extension_name is not None:
            route_values['extensionName'] = self._serialize.url('extension_name', extension_name, 'str')
        if host_type is not None:
            route_values['hostType'] = self._serialize.url('host_type', host_type, 'str')
        if host_name is not None:
            route_values['hostName'] = self._serialize.url('host_name', host_name, 'str')
        self._send(http_method='POST',
                   location_id='328a3af8-d124-46e9-9483-01690cd415b9',
                   version='5.0-preview.1',
                   route_values=route_values)

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


Question: Item from TSV representation.

def load(self, text, fieldnames=None):
    """"""
    lines = text.split('\n')
    fieldnames = load_line(lines[0])
    values = load_line(lines[1])
    self.__dict__ = dict(zip(fieldnames, values))

def format_stackdriver_json(record, message):

    subsecond, second = math.modf(record.created)

    payload = {
        "message": message,
        "timestamp": {"seconds": int(second), "nanos": int(subsecond * 1e9)},
        "thread": record.thread,
        "severity": record.levelname,
    }

    return json.dumps(payload)

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


Question: find the final set of selectors

protected function multiplySelectors($env) {
        $envs = array();
        while (null !== $env) {
            if (!empty($env->selectors)) {
                $envs[] = $env;
            }
            $env = $env->parent;
        };

        $selectors = array();
        $parentSelectors = array(array());
        while ($env = array_pop($envs)) {
            $selectors = array();
            foreach ($env->selectors as $selector) {
                foreach ($parentSelectors as $parent) {
                    $selectors[] = $this->joinSelectors($parent, $selector);
                }
            }
            $parentSelectors = $selectors;
        }

        return $selectors;
    }

def _pick_exit(self, block_address, stmt_idx, target_ips):

        # TODO: Support context-sensitivity

        tpl = (stmt_idx, target_ips)
        if tpl not in self.chosen_exits[block_address]:
            self.chosen_exits[block_address].append(tpl)

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


Question: Returns git_diff_path relative to cwd.

def relative_path(cls, git_diff_path):

        # Remove git_root from src_path for searching the correct filename
        # If cwd is `/home/user/work/diff-cover/diff_cover`
        # and src_path is `diff_cover/violations_reporter.py`
        # search for `violations_reporter.py`
        root_rel_path = os.path.relpath(cls._cwd, cls._root)
        rel_path = os.path.relpath(git_diff_path, root_rel_path)

        return rel_path

public function cd($dir)
    {
        $this->workingDir[] = $dir;
        if (!is_dir($this->currentDir())) {
            throw new ExpectationException($this->currentDir() . " is not a directory");
        }
    }

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


Question:
Hash a password with password_hash function
@param string $password 72 caractères maximum
@param string $algo
@return string 60 caractères

public static function passwordHash(string $password, string $algo = PASSWORD_BCRYPT): string
    {
        return password_hash($password, $algo);
    }

private function unparseUrl($data)
    {
        $scheme = isset($data['scheme']) ? $data['scheme'] . '://' : '';
        $host = isset($data['host']) ? $data['host'] : '';
        $port = isset($data['port']) ? ':' . $data['port'] : '';
        $user = isset($data['user']) ? $data['user'] : '';
        $pass = isset($data['pass']) ? ':' . $data['pass'] : '';
        $pass = ($user || $pass) ? "$pass@" : '';
        $path = isset($data['path']) ? $data['path'] : '';
        $query = isset($data['query']) ? '?' . $data['query'] : '';
        $fragment = isset($data['fragment']) ? '#' . $data['fragment'] : '';

        return "$scheme$user$pass$host$port$path$query$fragment";
    }

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


Question: // CriticalD implements the method for the KayveeLogger interface.

func (ml *MockRouteCountLogger) CriticalD(title string, data map[string]interface{}) {
	ml.logger.CriticalD(title, data)
}

def logs_handle_job(job_uuid: str,
                    job_name: str,
                    log_lines: Optional[Union[str, Iterable[str]]],
                    temp: bool = True) -> None:
    """"""
    handle_job_logs(job_uuid=job_uuid,
                    job_name=job_name,
                    log_lines=log_lines,
                    temp=temp)

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


Question:
Open a single square bracket.

@return this JsonWriter
@throws IOException if an I/O error has occurred

public JsonWriter openSquareBracket() throws IOException {
        if (!willWriteValue) {
            indent();
        }
        writer.write("[");
        nextLine();
        indentDepth++;
        willWriteValue = false;
        return this;
    }

private void flush(final Collection<Writer> writers) {
		for (Writer writer : writers) {
			try {
				writer.flush();
			} catch (Exception ex) {
				InternalLogger.log(Level.ERROR, ex, "Failed to flush writer");
			}
		}
	}

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


Question:
*
Get list of {@link AutoScalingGroup}s for a given tag

@param tag Tag to filter the auto scaling groups
@return List of {@link AutoScalingGroup}s qualifying the filter tag

public List<AutoScalingGroup> getAutoScalingGroupsWithTag(Tag tag) {

    final AmazonAutoScaling autoScaling = getAmazonAutoScalingClient();

    final DescribeAutoScalingGroupsRequest describeAutoScalingGroupsRequest = new DescribeAutoScalingGroupsRequest();

    final List<AutoScalingGroup> allAutoScalingGroups = autoScaling
        .describeAutoScalingGroups(describeAutoScalingGroupsRequest)
        .getAutoScalingGroups();

    final List<AutoScalingGroup> filteredAutoScalingGroups = Lists.newArrayList();
    for (AutoScalingGroup autoScalingGroup : allAutoScalingGroups) {
      for (TagDescription tagDescription : autoScalingGroup.getTags()) {
        if (tagDescription.getKey().equalsIgnoreCase(tag.getKey()) &&
            tagDescription.getValue().equalsIgnoreCase(tag.getValue())) {
          filteredAutoScalingGroups.add(autoScalingGroup);
        }
      }
    }

    return filteredAutoScalingGroups;
  }

public static void parseStoreAttribute(XMLExtendedStreamReader reader, int index, AbstractStoreConfigurationBuilder<?, ?> storeBuilder) throws XMLStreamException {
      String value = reader.getAttributeValue(index);
      Attribute attribute = Attribute.forName(reader.getAttributeLocalName(index));
      switch (attribute) {
         case SHARED: {
            storeBuilder.shared(Boolean.parseBoolean(value));
            break;
         }
         case READ_ONLY: {
            storeBuilder.ignoreModifications(Boolean.valueOf(value));
            break;
         }
         case PRELOAD: {
            storeBuilder.preload(Boolean.parseBoolean(value));
            break;
         }
         case FETCH_STATE: {
            storeBuilder.fetchPersistentState(Boolean.parseBoolean(value));
            break;
         }
         case PURGE: {
            storeBuilder.purgeOnStartup(Boolean.parseBoolean(value));
            break;
         }
         case SINGLETON: {
            storeBuilder.singleton().enabled(Boolean.parseBoolean(value));
            break;
         }
         case TRANSACTIONAL: {
            storeBuilder.transactional(Boolean.parseBoolean(value));
            break;
         }
         case MAX_BATCH_SIZE: {
            storeBuilder.maxBatchSize(Integer.parseInt(value));
            break;
         }
         case SEGMENTED: {
            storeBuilder.segmented(Boolean.parseBoolean(value));
            break;
         }
         default: {
            throw ParseUtils.unexpectedAttribute(reader, index);
         }
      }
   }

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


Question:
Get the service name arguments and return the filtered argument list
@param argv argument list
@param serviceId[0] is the service id if it's given in the argv, "" otherwise
@return argument list without service name argument

public static String[] getServiceName(String[] argv, String[] serviceId)
      throws IllegalArgumentException {
    ArrayList<String> newArgvList = new ArrayList<String>();
    for (int i = 0; i < argv.length; i++) {
      if ("-service".equals(argv[i])) {
        if (i+1 == argv.length ) {
          throw new IllegalArgumentException("Doesn't have service id");
        }
        serviceId[0] = argv[++i];
      } else {
        newArgvList.add(argv[i]);
      }
    }
    String[] newArgvs = new String[newArgvList.size()];
    newArgvList.toArray(newArgvs);
    return newArgvs;
  }

public Observable<ServiceResponse<Void>> deleteValueWithServiceResponseAsync(String tagName, String tagValue) {
        if (tagName == null) {
            throw new IllegalArgumentException("Parameter tagName is required and cannot be null.");
        }
        if (tagValue == null) {
            throw new IllegalArgumentException("Parameter tagValue is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.deleteValue(tagName, tagValue, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = deleteValueDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question:
/*
Package-private initializer for unit testing

void setInitializationData(Bundle contributingBundle, ServiceReference<?> urlConverterSR) {
		if (this.contributingBundle != null || this.urlConverterSR != null) {
			throw new IllegalStateException();
		}
		this.contributingBundle = contributingBundle;
		this.urlConverterSR = urlConverterSR;
	}

public void init(EvaluatePP inst, long nrf)
	{
		instance = inst;
		act = new long[(int) nrf];
		fin = new long[(int) nrf];
		req = new long[(int) nrf];
		active = new long[(int) nrf];
		waiting = new long[(int) nrf];
	}

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


Question:
SAME AS WHERE, BUT NO JOINGS (HAVING X IN ... HAVING X NOT IN ...)
@param $soql
@return array<LogicalJunction>

public function parseHavingSoql($soql)
    {
        $this->tokenizer->setInput($soql);

        $this->tokenizer->expect(TokenType::BOF);

        return $this->parseHavingLogicalGroup();
    }

public function addLabels(Search $entity)
    {
        if ($entity->getLabels()->count()) {
            $this->add(function (QueryBuilder $query) use ($entity) {
                $ids = [];
                foreach ($entity->getLabels() as $label) {
                    $ids[] = (int) $label->getId();
                }
                $query
                    ->innerJoin('i.labels', 'l')
                    ->andWhere('l.id IN ('.implode(',', $ids).')');
            });
            $this->select->andHaving('COUNT(i.id) = '.$entity->getLabels()->count());
        }

        return $this;
    }

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


Question:
Delete a file(/s) and/or folder(/s).

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

public function deleteMedia(Request $request)
    {
        // if single file/folder '?s=name'
        if ($request->has('s')) {
            if (is_dir(storage_path('app') . DIRECTORY_SEPARATOR . $request->input('s'))) {
                return $this->deleteDirectory($request);
            } else {
                return $this->deleteFile($request);
            }
        }

        // if multiple files
        if ($request->has('files')) {
            Storage::delete($request->input('files'));
        }

        // if multiple directories
        if ($request->has('directories')) {
            if (is_array($request->input('directories'))) {
                foreach ($request->input('directories') as $directory) {
                    Storage::deleteDirectory($directory);
                }
            } else {
                Storage::deleteDirectory($request->input('directories'));
            }
        }

        if ($request->wantsJson()) {
            return $this->notifySuccess('File/Folder deleted successfully!');
        }

        flash()->success('File/Folder deleted successfully!');

        return redirect()->back();
    }

public function handleRequest($parent, $upstream)
    {
        $req = $this->beginRequest($parent, $upstream);
        return $req ?: $parent;
    }

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


Question: Write the Escher Opt record that is part of MSODRAWING.

def store_mso_opt_chart   #:nodoc:
    type        = 0xF00B
    version     = 3
    instance    = 9
    data        = ''
    length      = nil

    data = store_mso_protection_and_text
    data += [0x0181].pack('v')   +        # Fill Style -> fillColor
    [0x0800004E].pack('V')       +
    [0x0183].pack('v')           +        # Fill Style -> fillBackColor
    [0x0800004D].pack('V')       +

    [0x01BF].pack('v')           +        # Fill Style -> fNoFillHitTest
    [0x00110010].pack('V')       +
    [0x01C0].pack('v')           +        # Line Style -> lineColor
    [0x0800004D].pack('V')       +
    [0x01FF].pack('v')           +        # Line Style -> fNoLineDrawDash
    [0x00080008].pack('V')       +
    [0x023F].pack('v')           +        # Shadow Style -> fshadowObscured
    [0x00020000].pack('V')       +
    [0x03BF].pack('v')           +        # Group Shape -> fPrint
    [0x00080000].pack('V')

    add_mso_generic(type, version, instance, data, length)
  end

def get_stats(self):

        stats = {}
        for name, cls in self.stats.items():
            path = self.paths[name]
            if os.path.exists(path):
                try:
                    stats[name] = self._PARSERS[cls](fileops.read(path))
                except IOError as e:
                    # XXX: we have to distinguish unexpected errors from the expected ones
                    if e.errno == errno.EOPNOTSUPP:
                        # Since 3.5 memory.memsw.* are always created even if disabled.
                        # If disabled we will get EOPNOTSUPP when read or write them.
                        # See commit af36f906c0f4c2ffa0482ecdf856a33dc88ae8c5 of the kernel.
                        pass
                    if e.errno == errno.EIO:
                        # memory.kmem.slabinfo throws EIO until limit_in_bytes is set.
                        pass
                    else:
                        raise
        return stats

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


Question:
// newModelExistsHandler returns a reply handler which will return a
// ModelNotFound error if the value of reply is false. It is expected to be
// used as the reply handler for an EXISTS command.

func newModelExistsHandler(collection *Collection, modelID string) ReplyHandler {
	return func(reply interface{}) error {
		exists, err := redis.Bool(reply, nil)
		if err != nil {
			return err
		}
		if !exists {
			return ModelNotFoundError{
				Collection: collection,
				Msg:        fmt.Sprintf("Could not find %s with id = %s", collection.spec.name, modelID),
			}
		}
		return nil
	}
}

public function evaluate()
    {
        $currentContext = $this->runtime->getCurrentContext();
        $this->pluginViewNode = $currentContext['node'];
        /** @var $parentResponse Response */
        $parentResponse = $this->runtime->getControllerContext()->getResponse();
        $pluginResponse = new ActionResponse($parentResponse);

        $pluginRequest = $this->buildPluginRequest();
        if ($pluginRequest->getControllerObjectName() === '') {
            $message = 'Master View not selected';
            if ($this->pluginViewNode->getProperty('plugin')) {
                $message = 'Plugin View not selected';
            }
            if ($this->pluginViewNode->getProperty('view')) {
                $message ='Master View or Plugin View not found';
            }
            return $this->pluginViewNode->getContext()->getWorkspaceName() !== 'live' || $this->objectManager->getContext()->isDevelopment() ? '<p>' . $message . '</p>' : '<!-- ' . $message . '-->';
        }
        $this->dispatcher->dispatch($pluginRequest, $pluginResponse);
        return $pluginResponse->getContent();
    }

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


Question:
Add a row to the block, each String represents a piece of text which should be aligned.
@param o Variable number of Strings to align.

public void align(Object... o) {
    int i = 0;
    String s[] = new String[o.length];

    for (int ii = 0; ii < o.length; ii++) { if (o[ii] != null) { s[ii] = o[ii].toString(); } }

    while (i < s.length && i < maxColumnLength.size()) {
      int l = (s[i] == null ? 0 : s[i].length());

      if (maxColumnLength.get(i) < l) {
        maxColumnLength.set(i, l);
      }

      i++;
    }

    while (i < s.length) {
      maxColumnLength.add((s[i] == null ? 0 : s[i].length()));
      i++;
    }

    rows.add(s);
  }

private void setSentenceSpan(JSONObject cNode, JSONObject parent) {
    try {
      JSONObject data = cNode.getJSONObject("data");

      int leftPosC = data.getInt(SENTENCE_LEFT);
      int rightPosC = data.getInt(SENTENCE_RIGHT);

      data = parent.getJSONObject("data");

      if (data.has(SENTENCE_LEFT)) {
        data.put(SENTENCE_LEFT, Math.min(leftPosC, data.getInt(SENTENCE_LEFT)));
      } else {
        data.put(SENTENCE_LEFT, leftPosC);
      }

      if (data.has(SENTENCE_RIGHT)) {
        data.put(SENTENCE_RIGHT,
                Math.max(rightPosC, data.getInt(SENTENCE_RIGHT)));
      } else {
        data.put(SENTENCE_RIGHT, rightPosC);
      }
    } catch (JSONException ex) {
      log.debug("error while setting left and right position for sentences", ex);
    }
  }

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


Question:
// WithIdleTimeout returns a new copy of the options with the IdleTimeout
// property set to the given value. It does not mutate the original options.

func (options PoolOptions) WithIdleTimeout(timeout time.Duration) PoolOptions {
	options.IdleTimeout = timeout
	return options
}

def _parse_coroutine(self):

        while True:
            d = yield

            if d == int2byte(0):
                pass  # NOP

            # Go to state escaped.
            elif d == IAC:
                d2 = yield

                if d2 == IAC:
                    self.received_data(d2)

                # Handle simple commands.
                elif d2 in (NOP, DM, BRK, IP, AO, AYT, EC, EL, GA):
                    self.command_received(d2, None)

                # Handle IAC-[DO/DONT/WILL/WONT] commands.
                elif d2 in (DO, DONT, WILL, WONT):
                    d3 = yield
                    self.command_received(d2, d3)

                # Subnegotiation
                elif d2 == SB:
                    # Consume everything until next IAC-SE
                    data = []

                    while True:
                        d3 = yield

                        if d3 == IAC:
                            d4 = yield
                            if d4 == SE:
                                break
                            else:
                                data.append(d4)
                        else:
                            data.append(d3)

                    self.negotiate(b''.join(data))
            else:
                self.received_data(d)

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