Question: // NewClient returns a new file download Client, using default configuration.

func NewClient() *Client {
	return &Client{
		UserAgent: "grab",
		HTTPClient: &http.Client{
			Transport: &http.Transport{
				Proxy: http.ProxyFromEnvironment,
			},
		},
	}
}

public String getContentType() {
        if (contentType == null)
            contentType = getHeaderField("content-type");
        if (contentType == null) {
            String ct = null;
            try {
                ct = guessContentTypeFromStream(getInputStream());
            } catch(java.io.IOException e) {
            }
            String ce = properties.findValue("content-encoding");
            if (ct == null) {
                ct = properties.findValue("content-type");

                if (ct == null)
                    if (url.getFile().endsWith("/"))
                        ct = "text/html";
                    else
                        ct = guessContentTypeFromName(url.getFile());
            }

            /*
             * If the Mime header had a Content-encoding field and its value
             * was not one of the values that essentially indicate no
             * encoding, we force the content type to be unknown. This will
             * cause a save dialog to be presented to the user.  It is not
             * ideal but is better than what we were previously doing, namely
             * bringing up an image tool for compressed tar files.
             */

            if (ct == null || ce != null &&
                    !(ce.equalsIgnoreCase("7bit")
                      || ce.equalsIgnoreCase("8bit")
                      || ce.equalsIgnoreCase("binary")))
                ct = "content/unknown";
            setContentType(ct);
        }
        return contentType;
    }

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


Question:
Inserts a new child at the end of the Frame

@param $child Frame The new Frame to insert
@param $update_node boolean Whether or not to update the DOM

function append_child(Frame $child, $update_node = true) {
    if ( $update_node )
      $this->_node->appendChild($child->_node);

    // Remove the child from its parent
    if ( $child->_parent )
      $child->_parent->remove_child($child, false);

    $child->_parent = $this;
    $child->_next_sibling = null;

    // Handle the first child
    if ( !$this->_last_child ) {
      $this->_first_child = $child;
      $this->_last_child = $child;
      $child->_prev_sibling = null;
    } else {
      $this->_last_child->_next_sibling = $child;
      $child->_prev_sibling = $this->_last_child;
      $this->_last_child = $child;
    }
  }

public function createAction(Request $request)
    {
        $contentTypeManager = $this->get('opifer.content.content_type_manager');

        $contentType = $contentTypeManager->create();

        $form = $this->createForm(ContentTypeType::class, $contentType);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            foreach ($form->getData()->getSchema()->getAttributes() as $attribute) {
                $attribute->setSchema($contentType->getSchema());

                foreach ($attribute->getOptions() as $option) {
                    $option->setAttribute($attribute);
                }
            }

            $contentTypeManager->save($contentType);

            $this->addFlash('success', 'Content type has been created successfully');

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

        return $this->render($this->getParameter('opifer_content.content_type_create_view'), [
            'content_type' => $contentType,
            'form' => $form->createView(),
        ]);
    }

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


Question:
/*
Method: add
Add one or more shortcodes
Parameters:
codes(String|Array): If string, adds shortcode for said string.  If array, adds a shortcode for each key as the code and value as callable
method(callable): function/method to call for shortcode

public function add($codes, $method = null){
		if(is_array($codes)){
			foreach($codes as $name=> $method){
				$this->add($name, $method);
			}
		}else{
			$this->shortcodes[$codes] = $method;
			add_shortcode($codes, $method);
		}
		return $this;
	}

public function ajax_import_export( $params ) {

		if ( 'import' === $params->import_export ) {
			$data = trim( $params->import_package );

			$content = '
';

			if ( ! empty( $data ) ) {
				$imported = $this->import( $data );

				if ( ! empty( $imported ) ) {
					$content .= '
Import Complete! The following items were imported:
';

					foreach ( $imported as $type => $import ) {
						$content .= '
' . ucwords( $type ) . '
';

						$content .= '
';

						foreach ( $import as $k => $what ) {
							$content .= '
' . esc_html( $what ) . '
';
						}

						$content .= '
';
					}
				}
			} else {
				$content .= '
Import Error: Invalid Package
';
			}//end if

			$content .= '
';

			echo $content;
		} elseif ( 'export' === $params->import_export ) {
			$params = get_object_vars( $params );
			foreach ( $params as $k => $v ) {
				if ( is_array( $v ) ) {
					$params[ $k ] = array_keys( array_filter( $v ) );
				}
			}

			$package = $this->export( $params );

			echo '
';

			echo PodsForm::field( 'export_package', $package, 'paragraph', array( 'attributes' => array( 'style' => 'width: 94%; max-width: 94%; height: 300px;' ) ) );

			echo '
';
		}//end if

	}

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


Question: content in object format

public Object getObject(String type, Package pkg) {
        if (type==null || type.equals(documentType)) {
            if (object==null && content!=null) {
                object = VariableTranslator.realToObject(pkg, documentType, content);
            }
        } else {
            if (content!=null) {
                documentType = type;
                object = VariableTranslator.realToObject(pkg, documentType, content);
            } else if (object!=null) {
                content = VariableTranslator.realToString(pkg, documentType, object);
                documentType = type;
                object = VariableTranslator.realToObject(pkg, documentType, content);
            }
        }
        return object;
    }

def convert_value_to_ostruct(data)
      case data
      when Hash
        self.class.new(data)
      when Array
        data.collect{|val| self.convert_value_to_ostruct(val)}
      else
        data
      end
    end

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


Question:
Introspect this object for FFDC output.

@return List<String>

public List<String> introspect() {
        List<String> rc = new LinkedList<String>();
        String prefix = getClass().getSimpleName() + "@" + hashCode() + ": ";
        rc.add(prefix + "closed=" + this.closed);
        rc.add(prefix + "processClose=" + this.processClose);
        rc.add(prefix + "checkCancel=" + this.checkCancel);
        rc.add(prefix + "tcpChannel=" + this.tcpChannel);
        rc.add(prefix + "socket=" + this.socket);
        if (null != this.socket) {
            rc.add(prefix + "remoteAddr=" + this.socket.getInetAddress());
            rc.add(prefix + "remotePort=" + this.socket.getPort());
            rc.add(prefix + "localAddr=" + this.socket.getLocalAddress());
            rc.add(prefix + "localPort=" + this.socket.getLocalPort());
        }
        rc.add(prefix + "channel=" + this.channel);
        return rc;
    }

def to_dict(self):
        ''''''
        d = {'connectorId': self.connector_id,
                'name': self.name,
                'dataType': self.data_type,
                'interfaceType': self.interface_type,
                'dataflowType': self.data_flow_type,
                'sourceDataPort': self.source_data_port.to_dict(),
                'targetDataPort': self.target_data_port.to_dict()}
        if self.visible != True:
            d[RTS_EXT_NS_YAML + 'visible'] = self.visible
        if self.subscription_type:
            d['subscriptionType'] = self.subscription_type
        if self.push_interval:
            d['pushInterval'] = self.push_interval
        if self.comment:
            d[RTS_EXT_NS_YAML + 'comment'] = self.comment
        props = []
        for name in self.properties:
            p = {'name': name}
            if self.properties[name]:
                p['value'] = str(self.properties[name])
            props.append(p)
        if props:
            d[RTS_EXT_NS_YAML + 'properties'] = props
        return d

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


Question:
Configure options

@param OptionsResolver $resolver Symfony options resolver
@param string          $region   Region

@throws InvalidOptionsException

private function configureOptions(OptionsResolver $resolver, $region)
    {
        if (isset(GeoData::$list[$region])) {
            $locales = GeoData::$list[$region];
        } else {
            throw new InvalidOptionsException(
                sprintf(
                    'The option "region" with value "%s" is invalid. Accepted values are: "%s".',
                    $region,
                    implode('", "', array_keys(GeoData::$list))
                )
            );
        }

        $resolver->setRequired(['apiKey', 'apiSecret', 'region', 'locale'])
                 ->setAllowedTypes('apiKey', 'string')
                 ->setAllowedTypes('apiSecret', 'string')
                 ->setAllowedTypes('region', 'string')
                 ->setAllowedValues('region', array_keys(GeoData::$list))
                 ->setAllowedTypes('locale', 'string')
                 ->setAllowedValues('locale', $locales);
    }

public function getSelector()
	{
		$direct_settings = array(
			'className', 'css', 'id', 'linkText', 'name', 'partialLinkText', 'tagName', 'xpath', 'label',
		);

		foreach ( $direct_settings as $direct_setting ) {
			if ( $this->$direct_setting ) {
				return array($direct_setting => $this->$direct_setting);
			}
		}

		if ( $this->how && $this->using ) {
			if ( !in_array($this->how, $direct_settings) ) {
				throw new AnnotationException(
					"FindBy annotation expects 'how' to be one of \\QATools\\QATools\\PageObject\\How class constants",
					AnnotationException::TYPE_INCORRECT_USAGE
				);
			}

			return array($this->how => $this->using);
		}

		throw new AnnotationException(
			sprintf(
				"FindBy annotation requires one of '%s' or both 'how' and 'using' parameters specified",
				implode("', '", $direct_settings)
			),
			AnnotationException::TYPE_INCORRECT_USAGE
		);
	}

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


Question:
A tensorflow variable tranfomed to be constrained in a L2 unit ball.

  EXPERIMENTAL: Do not use for adverserial examples if you need to be confident
  they are strong attacks. We are not yet confident in this code.

def unit_ball_L2(shape):

  x = tf.Variable(tf.zeros(shape))
  return constrain_L2(x)

@Override
	public List<Metric> transform(QueryContext context, List<Metric> metrics) {
		throw new UnsupportedOperationException("Downsample transform need constant input!");
	}

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


Question:
Returns a short, descriptive name for the node, such as
"ArrayComprehension".

public String shortName() {
        String classname = getClass().getName();
        int last = classname.lastIndexOf(".");
        return classname.substring(last + 1);
    }

function (indices) {
            if (!ariaUtilsType.isArray(indices)) {
                indices = [indices];
            }

            var suggestionsContainer = this._getSuggestionsContainer();
            var latestSuggestionNode;
            for (var k = 0; k < indices.length; k++) {
                var suggestionNode = suggestionsContainer.children[indices[k] - 1];
                if (suggestionNode) {
                    latestSuggestionNode = suggestionNode;
                    this._addClass(suggestionNode, 'highlight');
                }
            }

            if (latestSuggestionNode != null) {
                latestSuggestionNode.firstChild.setAttribute('tabindex', 0);
                latestSuggestionNode.firstChild.focus();
            }
        }

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


Question: Auto Generated Code

def logical_chassis_fwdl_sanity_output_cluster_output_fwdl_status(self, **kwargs):

        config = ET.Element("config")
        logical_chassis_fwdl_sanity = ET.Element("logical_chassis_fwdl_sanity")
        config = logical_chassis_fwdl_sanity
        output = ET.SubElement(logical_chassis_fwdl_sanity, "output")
        cluster_output = ET.SubElement(output, "cluster-output")
        fwdl_status = ET.SubElement(cluster_output, "fwdl-status")
        fwdl_status.text = kwargs.pop('fwdl_status')

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

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

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

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


Question:
Pass all the regex matches to current compiler

@param  array $matches
@return string

public function compile($matches)
    {
        if (in_array($matches[1], ["include", "includes"])) {
            // todo: Fix dis shet :c
        } else {
            if (isset($matches[5])) {
                $params    = $matches[5];
                $newParams = [];

                foreach (explode(",", $params) as $param) {
                    $newParams[] = preg_replace_callback("/(\w+)=(.*)/is", function ($m) {
                        if (! preg_match("/^(?:\"|')/is", $m[2])) {
                            $m[2] = "\"$m[2]\"";
                        }

                        return "\"{$m[1]}\" => {$m[2]}";
                    }, $param);
                }

                return $this->compiler->wrap("echo \$__env->render(\"{$matches[3]}\", [" . join(",", $newParams) . "])");
            } else {
                return $this->compiler->wrap("echo \$__env->render(\"{$matches[3]}\")");
            }
        }
    }

def init_parser(self):

        parser = argparse.ArgumentParser(description='ROCA TLS Fingerprinter')

        parser.add_argument('--debug', dest='debug', default=False, action='store_const', const=True,
                            help='Debugging logging')

        parser.add_argument('--dump', dest='dump', default=False, action='store_const', const=True,
                            help='Dump all processed info')

        parser.add_argument('--flatten', dest='flatten', default=False, action='store_const', const=True,
                            help='Flatten the dump')

        parser.add_argument('--indent', dest='indent', default=False, action='store_const', const=True,
                            help='Indent the dump')

        parser.add_argument('--hosts', dest='hosts', default=False, action='store_const', const=True,
                            help='Arguments are host names not file names')

        parser.add_argument('files', nargs=argparse.ZERO_OR_MORE, default=[],
                            help='files to process')
        return parser

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


Question:
Builds the JQL select.

@param method
the method
@param result
the result
@param dynamicReplace
the dynamic replace
@param preparedJql
the prepared jql
@return the jql

private static JQL buildJQLSelect(final SQLiteModelMethod method, final JQL result, final Map<JQLDynamicStatementType, String> dynamicReplace, String preparedJql) {
		final Class<? extends Annotation> annotation = BindSqlSelect.class;
		final SQLiteDaoDefinition dao = method.getParent();

		if (StringUtils.hasText(preparedJql)) {
			result.value = preparedJql;

			// In SELECT SQL only where statement can contains bind parameter
			JQLChecker.getInstance().analyze(method, result, new JqlBaseListener() {

				@Override
				public void enterBind_dynamic_sql(Bind_dynamic_sqlContext ctx) {
					JQLDynamicStatementType dynamicType = JQLDynamicStatementType.valueOf(ctx.bind_parameter_name().getText().toUpperCase());

					int start = ctx.getStart().getStartIndex() - 1;
					int stop = ctx.getStop().getStopIndex() + 1;

					String dynamicWhere = result.value.substring(start, stop);

					dynamicReplace.put(dynamicType, dynamicWhere);
				}
			});

			JQLChecker.getInstance().replaceVariableStatements(method, preparedJql, new JQLReplaceVariableStatementListenerImpl() {

				@Override
				public String onWhere(String statement) {
					result.annotatedWhere = true;
					result.staticWhereConditions = true;
					return null;
				}

				@Override
				public String onOrderBy(String statement) {
					result.annotatedOrderBy = true;
					result.staticOrderBy = true;
					return null;
				}

				@Override
				public String onOffset(String statement) {
					result.annotatedOffset = true;
					return null;
				}

				@Override
				public String onLimit(String statement) {
					result.annotatedLimit = true;
					return null;
				}

				@Override
				public String onHaving(String statement) {
					result.annotatedHaving = true;
					return null;
				}

				@Override
				public String onGroup(String statement) {
					result.annotatedGroupBy = true;
					return null;
				}

			});

			forEachParameter(method, new OnMethodParameterListener() {

				@Override
				public void onMethodParameter(VariableElement methodParam) {
					if (methodParam.getAnnotation(BindSqlDynamicOrderBy.class) != null) {
						String orderDynamicName = methodParam.getSimpleName().toString();

						result.paramOrderBy = orderDynamicName;

						// CONSTRAINT: @BindSqlOrderBy can be used only on
						// String
						// parameter type
						AssertKripton.assertTrueOrInvalidTypeForAnnotationMethodParameterException(TypeUtility.isEquals(TypeUtility.typeName(String.class), TypeUtility.typeName(methodParam)),
								method.getParent().getElement(), method.getElement(), methodParam, BindSqlDynamicOrderBy.class);
					}

				}
			});

		} else {
			// extract some informaction from method and bean
			// use annotation's attribute value and exclude and bean definition
			// to
			// define field list
			final Set<String> fields = extractFieldsFromAnnotation(method, BindSqlSelect.class, true);

			boolean distinct = AnnotationUtility.extractAsBoolean(method.getElement(), annotation, AnnotationAttributeType.DISTINCT);
			String annotatedGroupBy = AnnotationUtility.extractAsString(method.getElement(), annotation, AnnotationAttributeType.GROUP_BY);
			String annotatedHaving = AnnotationUtility.extractAsString(method.getElement(), annotation, AnnotationAttributeType.HAVING);

			StringBuilder builder = new StringBuilder();
			builder.append(SELECT_KEYWORD + " ");

			//
			if (distinct) {
				builder.append(DISTINCT_KEYWORD + " ");
			}

			// recreate fields
			builder.append(forEachFields(fields, new OnFieldListener() {

				@Override
				public String onField(String item) {
					return item;
				}
			}));

			// entity name
			builder.append(" " + FROM_KEYWORD + " " + dao.getEntitySimplyClassName());

			// where
			builder.append(defineWhereStatement(method, result, annotation, dynamicReplace));

			// group by
			if (StringUtils.hasText(annotatedGroupBy)) {
				result.annotatedGroupBy = true;
				builder.append(" " + GROUP_BY_KEYWORD + " " + annotatedGroupBy);
			}

			// having
			if (StringUtils.hasText(annotatedHaving)) {
				result.annotatedHaving = true;
				builder.append(" " + HAVING_KEYWORD + " " + annotatedHaving);
			}

			// order by
			builder.append(defineOrderByStatement(method, result, annotation, dynamicReplace));

			// limit
			builder.append(defineLimitStatement(method, result, annotation, dynamicReplace));

			result.value = builder.toString();

		}

		result.value = JQLChecker.getInstance().replace(method, result.value, new JQLReplacerListenerImpl(method, true) {

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				if (inStatement) {
					TypeName typeName = method.findParameterType(method.findParameterNameByAlias(bindParameterName));

					AssertKripton.assertTrueOrInvalidMethodSignException(typeName != null && (TypeUtility.isArray(typeName) || TypeUtility.isCollection(typeName)), method,
							"'in' condition need an array or collection parameter");

					String dynamicSpread = bindParameterName;

					dynamicReplace.put(JQLDynamicStatementType.DYNAMIC_SPREAD, dynamicSpread);
					result.spreadParams.add(dynamicSpread);

					// return
					// "#{"+JQLDynamicStatementType.DYNAMIC_SPREAD+"}";
					return null;
				}

				return null;
			}
		});

		if (method.isPagedLiveData()) {
			// if is a paged live data, it must have pagination
			dynamicReplace.put(JQLDynamicStatementType.DYNAMIC_PAGE_OFFSET, "");
			dynamicReplace.put(JQLDynamicStatementType.DYNAMIC_PAGE_SIZE, "");
		}

		result.operationType = JQLType.SELECT;
		result.dynamicReplace = dynamicReplace;
		return result;
	}

public void marshall(DynamoDBAction dynamoDBAction, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(dynamoDBAction.getTableName(), TABLENAME_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRoleArn(), ROLEARN_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getOperation(), OPERATION_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyField(), HASHKEYFIELD_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyValue(), HASHKEYVALUE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyType(), HASHKEYTYPE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyField(), RANGEKEYFIELD_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyValue(), RANGEKEYVALUE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyType(), RANGEKEYTYPE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getPayloadField(), PAYLOADFIELD_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: Delete a workflow.

def delete(cls, uuid):
        """"""
        to_delete = Workflow.query.get(uuid)
        db.session.delete(to_delete)

public function dropSchema($name)
    {
        $schema = new Schema($name);
        $this->actions[] =  function () use ($schema) {
             return $this->manipulation->drop($schema);
         };
    }

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


Question:
Transform internal URLS to public URLS using our defined mappers

@param string $contentType
@param string $mode
@param string $content
@param string[] $hosts
@return string

public function mapContent($contentType, $mode, $content, $hosts)
    {
        $rewriter = new Rewriter($this);
        $rewriter->setLocalDomains($hosts);

        foreach ($this->contentMappers as $mapper) {
            if ($mapper->supports($contentType)) {
                return $mapper->processAliasing($content, $mode, $rewriter);
            }
        }

        return $content;
    }

func NewProductPrivateHostAPI(client *Client) *ProductPrivateHostAPI {
	return &ProductPrivateHostAPI{
		&baseAPI{
			client: client,
			// FuncGetResourceURL
			FuncGetResourceURL: func() string {
				return "product/privatehost"
			},
		},
	}
}

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


Question:
This function takes care of setting the shading code and
        compiling+linking it into a working program object that is ready
        to use.

def set_shaders(self, vert, frag):

        self._linked = False
        # Create temporary shader objects
        vert_handle = gl.glCreateShader(gl.GL_VERTEX_SHADER)
        frag_handle = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
        # For both vertex and fragment shader: set source, compile, check
        for code, handle, type_ in [(vert, vert_handle, 'vertex'),
                                    (frag, frag_handle, 'fragment')]:
            gl.glShaderSource(handle, code)
            gl.glCompileShader(handle)
            status = gl.glGetShaderParameter(handle, gl.GL_COMPILE_STATUS)
            if not status:
                errors = gl.glGetShaderInfoLog(handle)
                errormsg = self._get_error(code, errors, 4)
                raise RuntimeError("Shader compilation error in %s:\n%s" %
                                   (type_ + ' shader', errormsg))
        # Attach shaders
        gl.glAttachShader(self._handle, vert_handle)
        gl.glAttachShader(self._handle, frag_handle)
        # Link the program and check
        gl.glLinkProgram(self._handle)
        if not gl.glGetProgramParameter(self._handle, gl.GL_LINK_STATUS):
            raise RuntimeError('Program linking error:\n%s'
                               % gl.glGetProgramInfoLog(self._handle))
        # Now we can remove the shaders. We no longer need them and it
        # frees up precious GPU memory:
        # http://gamedev.stackexchange.com/questions/47910
        gl.glDetachShader(self._handle, vert_handle)
        gl.glDetachShader(self._handle, frag_handle)
        gl.glDeleteShader(vert_handle)
        gl.glDeleteShader(frag_handle)
        # Now we know what variables will be used by the program
        self._unset_variables = self._get_active_attributes_and_uniforms()
        self._handles = {}
        self._known_invalid = set()
        self._linked = True

def detect_builtin_shadowing_locals(self, function_or_modifier):

        results = []
        for local in function_or_modifier.variables:
            if self.is_builtin_symbol(local.name):
                results.append((self.SHADOWING_LOCAL_VARIABLE, local, function_or_modifier))
        return results

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


Question: // SetAttributes sets the Attributes field's value.

func (s *RegisterInstanceInput) SetAttributes(v map[string]*string) *RegisterInstanceInput {
	s.Attributes = v
	return s
}

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

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

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


Question:
Represent the ID Token as a JSON Web Token (JWT).
    Return a hash.

def encode_id_token(payload, client):

    keys = get_client_alg_keys(client)
    _jws = JWS(payload, alg=client.jwt_alg)
    return _jws.sign_compact(keys)

function syncCollection(options) {
  var requestData = template.syncCollection({
    props: options.props,
    syncLevel: options.syncLevel,
    syncToken: options.syncToken
  });

  function transformRequest(xhr) {
    setRequestHeaders(xhr, options);
  }

  function transformResponse(xhr) {
    var object = (0, _parser.multistatus)(xhr.responseText);
    var responses = object.response.map(function (res) {
      return { href: res.href, props: getProps(res.propstat) };
    });

    return { responses: responses, syncToken: object.syncToken };
  }

  return new Request({
    method: 'REPORT',
    requestData: requestData,
    transformRequest: transformRequest,
    transformResponse: transformResponse
  });
}

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


Question:
// checkSCPStatus checks that a prior command sent to SCP completed
// successfully. If it did not complete successfully, an error will
// be returned.

func checkSCPStatus(r *bufio.Reader) error {
	code, err := r.ReadByte()
	if err != nil {
		return err
	}

	if code != 0 {
		// Treat any non-zero (really 1 and 2) as fatal errors
		message, _, err := r.ReadLine()
		if err != nil {
			return errwrap.Wrapf("error reading error message: {{err}}", err)
		}

		return errors.New(string(message))
	}

	return nil
}

def git_status_all_repos(cat, hard=True, origin=False, clean=True):

    log = cat.log
    log.debug("gitter.git_status_all_repos()")

    all_repos = cat.PATHS.get_all_repo_folders()
    for repo_name in all_repos:
        log.info("Repo in: '{}'".format(repo_name))
        # Get the initial git SHA
        sha_beg = get_sha(repo_name)
        log.debug("Current SHA: '{}'".format(sha_beg))

        log.info("Fetching")
        fetch(repo_name, log=cat.log)

        git_comm = ["git", "status"]
        _call_command_in_repo(
            git_comm, repo_name, cat.log, fail=True, log_flag=True)

        sha_end = get_sha(repo_name)
        if sha_end != sha_beg:
            log.info("Updated SHA: '{}'".format(sha_end))

    return

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


Question:
Returns a copy of the path with the final edge write locked. This requires that we haven't
already locked the final edge, i.e. the path is incomplete.

@return the new locked path

public LockedInodePath lockFinalEdgeWrite() throws InvalidPathException {
    Preconditions.checkState(!fullPathExists());

    LockedInodePath newPath =
        new LockedInodePath(mUri, this, mPathComponents, LockPattern.WRITE_EDGE);
    newPath.traverse();
    return newPath;
  }

def _match_parent(self, match, yield_parent):

        ret = super(Chain, self)._match_parent(match, yield_parent)
        original_children = Matches(match.children)
        original_end = match.end
        while not ret and match.children:
            last_pattern = match.children[-1].pattern
            last_pattern_children = [child for child in match.children if child.pattern == last_pattern]
            last_pattern_groups_iter = itertools.groupby(last_pattern_children, lambda child: child.match_index)
            last_pattern_groups = {}
            for index, matches in last_pattern_groups_iter:
                last_pattern_groups[index] = list(matches)

            for index in reversed(list(last_pattern_groups)):
                last_matches = list(last_pattern_groups[index])
                for last_match in last_matches:
                    match.children.remove(last_match)
                match.end = match.children[-1].end if match.children else match.start
                ret = super(Chain, self)._match_parent(match, yield_parent)
                if ret:
                    return True
        match.children = original_children
        match.end = original_end
        return ret

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


Question: TODO: Check diff between this and getQuickWindow(SearchProp, name) and remove this

public QuickWindow getQuickWindowByName(String name) {
    List<DesktopWindowInfo> windowList = getDesktopWindowInfoList();

    for (DesktopWindowInfo window : windowList) {
      if (window.getName().equals(name)) {
        return new QuickWindow(window);
      }
    }

    return null;
  }

def page_prev(self):
        """"""
        window_start = (self.parent.value('window_start') -
                        self.parent.value('window_length'))
        if window_start < 0:
            return
        self.parent.overview.update_position(window_start)

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


Question: // SqueezeTrytes squeezes out trytes of the given trit length. Length has to be a multiple of HashTrinarySize.

func (c *Curl) SqueezeTrytes(length int) (Trytes, error) {
	trits, err := c.Squeeze(length)
	if err != nil {
		return "", err
	}
	return TritsToTrytes(trits)
}

def tile(self, username, style_id, z, x, y, tile_size=512, retina=False):
        ""
        if tile_size not in (256, 512):
            raise errors.ImageSizeError('tile_size must be 256 or 512 pixels')

        pth = '/{username}/{style_id}/tiles/{tile_size}/{z}/{x}/{y}'

        values = dict(username=username, style_id=style_id,
                      tile_size=tile_size, z=z, x=x, y=y)

        uri = URITemplate(self.baseuri + pth).expand(**values)
        if retina:
            uri += '@2x'
        res = self.session.get(uri)
        self.handle_http_error(res)
        return res

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


Question:
Deletes a filesystem file stored under task queue storage

@param EntityInterface $taskLogEntity
@return bool

protected function deleteQueueStorageFile(EntityInterface $taskLogEntity)
    {
        if ($filename = $taskLogEntity->getFileNameFromReport()) {
            $file = $this->getQueueStorage()
                ->getFile($filename);

            if($file->exists()) {
                $file->delete();
            }
        }

        return false;
    }

protected final PrcSeSrvSpecEmbFlDel<RS>
    lazyGetPrcSeSrvSpecEmbFlDel(
      final Map<String, Object> pAddParam) throws Exception {
    String beanName = PrcSeSrvSpecEmbFlDel.class.getSimpleName();
    @SuppressWarnings("unchecked")
    PrcSeSrvSpecEmbFlDel<RS> proc = (PrcSeSrvSpecEmbFlDel<RS>)
      this.processorsMap.get(beanName);
    if (proc == null) {
      proc = new PrcSeSrvSpecEmbFlDel<RS>();
      proc.setSrvOrm(getSrvOrm());
      proc.setFindSeSeller(getFindSeSeller());
      proc.setWebAppPath(getWebAppPath());
      proc.setUploadDirectory(getUploadDirectory());
      //assigning fully initialized object:
      this.processorsMap.put(beanName, proc);
      this.logger.info(null, FctBnSeSelEntityProcs.class,
        beanName + " has been created.");
    }
    return proc;
  }

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


Question:
fires on save role

@param Model $model
@throws Exception

public function onSave($model)
    {
        $apiRoles          = ApiRoles::firstOrNew(['role_id' => $model->id]);
        $apiRoles->enabled = (int) Input::get('enabled');
        try {
            $apiRoles->save();
        } catch (Exception $ex) {
            Log::emergency($ex);
            throw new Exception('Unable to save role.');
        }
    }

public function createMark(Result $result, User $user, $mark)
    {
        $mark = new Mark($result, $user, $mark);
        $this->om->persist($mark);
        $this->om->flush();

        $newMarkEvent = new LogResultsNewMarkEvent($mark);
        $this->dispatcher->dispatch('log', $newMarkEvent);

        return $mark;
    }

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


Question: Register js initialization script.

public function registerClientScript()
    {
    	$view = $this->getView();
    	PNotifyAsset::register($view);

    	$options = empty($this->pluginOptions) ? '' : Json::encode($this->pluginOptions);
    	$js = "new PNotify(".$options.");";

    	$view->registerJs($js);
    }

function WebServer(options) {
  EventEmitter.call(this);

  this._options = options;

  this._username = options['username'];
  this._ip = options['ip'];
  this._port = options['port'];
  this._secret = options['secret'];
  this._triggerString = options['trigger_string'];

  this._server = null;
}

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


Question: Adds the nick & uid to the log for a given time/order. No return.

def _storeLog(self, nick, time, uid):
        """"""
        query = dict(uid=uid)
        update = {'$set': dict(nick=nick, time=time)}
        self.db.pastes.update(query, update)

public function build(&$query)
    {
        if (isset($query['alias']) && isset($query['id'])) {
            $query['id'] = $query['id'].'-'.$query['alias'];
            unset($query['alias']);
        }

        $segments = array();

        if (isset($query['oid'])) {
            if ($query['oid'] == 'viewer') {
                $query['oid'] = get_viewer()->uniqueAlias;
            }
            $segments[] = '@'.$query['oid'];
            unset($query['oid']);
        }

        $segments = array_merge($segments, parent::build($query));

        return $segments;
    }

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


Question: // SetModificationStatus indicates an expected call of SetModificationStatus

func (mr *MockMutaterMachineMockRecorder) SetModificationStatus(arg0, arg1, arg2 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetModificationStatus", reflect.TypeOf((*MockMutaterMachine)(nil).SetModificationStatus), arg0, arg1, arg2)
}

private function update()
    {
        $errors = array();
        switch( State::get('action') )
        {
            case 'save':
                $errors = $this->save();
                Notifier::success('Settings saved.');
                break;
            case 'reset-section':
                $section = $this->config->get_section_by_slug(State::get('active_section'));
                $this->reset( $section );
                Notifier::success('<strong>'.$section->title.'</strong> section was reset to its default settings.');
                break;
            case 'reset-all':
                $this->reset();
                Notifier::success('All sections were reset to their default settings.');
                break;
            // No submission (simple request)
            default:
                $this->load();
        }

        $this->set_errors($errors);
    }

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


Question:
get composed component data
@param  {string} uri of root component
@param  {object} locals
@return {Promise} composed data of root component and children

function getComposed(uri, locals) {
  return controller.get(uri, locals).then(data => {
    // TODO: Check that we can't just reference the composer
    // require here because otherwise it's a circular dependency (via html-composer)
    return require('../services/composer').resolveComponentReferences(data, locals);
  });
}

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: // Var renders the var keyword.

func (g *Group) Var() *Statement {
	// notest
	s := Var()
	g.items = append(g.items, s)
	return s
}

public function set($variable, $value = null)
    {
        $this->variables[$variable] = array(
            'safe' => $this->htmlEncode($value),
            'unsafe' => $value
        );

        return $this;
    }

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


Question: Refresh the Command Info

public function refresh() {
    $response = $this->client->get($this->path());
    $this->setData($response->json());
  }

func (cmd *MoveAllocationCommand) Source() (interface{}, error) {
	source := make(map[string]interface{})
	source["index"] = cmd.index
	source["shard"] = cmd.shardId
	source["from_node"] = cmd.fromNode
	source["to_node"] = cmd.toNode
	return source, nil
}

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


Question: Function to add the charges to a given structure.

public static void addCharges(Structure structure) {
		// Loop through the models
		for(int i=0; i<structure.nrModels(); i++){
			for(Chain c: structure.getChains(i)){
				for(Group g: c.getAtomGroups()){
					ChemComp thisChemComp = ChemCompGroupFactory.getChemComp(g.getPDBName());
					List<ChemCompAtom> chemAtoms = thisChemComp.getAtoms();
					for(ChemCompAtom chemCompAtom : chemAtoms) {
						Atom atom = g.getAtom(chemCompAtom.getAtom_id());
						String stringCharge = chemCompAtom.getCharge();
						short shortCharge = 0;
						if (stringCharge!=null){
							if(!stringCharge.equals("?")){
								try{
									shortCharge = Short.parseShort(stringCharge);
								}
								catch(NumberFormatException e){
									logger.warn("Number format exception. Parsing '"+stringCharge+"' to short");
								}
							}
							else{
								logger.warn("? charge on atom "+chemCompAtom.getAtom_id()+" in group "+thisChemComp.getId());
							}
						}
						else{
							logger.warn("Null charge on atom "+chemCompAtom.getAtom_id()+" in group "+thisChemComp.getId());
						}
						if(atom!=null){
							atom.setCharge(shortCharge);
						}
						// Now do the same for alt locs
						for (Group altLoc : g.getAltLocs()) {
							Atom altAtom = altLoc.getAtom(chemCompAtom.getAtom_id());
							if(altAtom!=null){
								altAtom.setCharge(shortCharge);
							}
						}
					}
				}

			}
		}
	}

func (d *DeviceBlockStats) UniqueBlocks(other *DeviceBlockStats) uint64 {
	return d.diet.Total() - d.diet.IntersectionAll(other.diet)
}

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


Question:
Adds a theme to default settings

@param {string} name Theme name
@param {Object} theme Theme object, with foreground, background, size, font, and fontweight properties.

function(name, theme) {
	        name != null && theme != null && (App.settings.themes[name] = theme);
	        delete App.vars.cache.themeKeys;
	        return this;
	    }

private function configureFormatter(OutputFormatter $formatter)
    {
        $style = new OutputFormatterStyle('yellow', null, ['bold']);
        $formatter->setStyle('pathbold', $style);

        $style = new OutputFormatterStyle('green');
        $formatter->setStyle('localname', $style);

        $style = new OutputFormatterStyle(null, null, ['bold']);
        $formatter->setStyle('node', $style);

        $style = new OutputFormatterStyle('blue', null, ['bold']);
        $formatter->setStyle('templatenode', $style);

        $style = new OutputFormatterStyle('blue', null, []);
        $formatter->setStyle('templateproperty', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property', $style);

        $style = new OutputFormatterStyle('magenta', null, ['bold']);
        $formatter->setStyle('node-type', $style);

        $style = new OutputFormatterStyle('magenta', null, []);
        $formatter->setStyle('property-type', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property-value', $style);

        $style = new OutputFormatterStyle(null, 'red', []);
        $formatter->setStyle('exception', $style);
    }

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


Question:
Starts trial and restores last result if trial was paused.

        Raises:
            ValueError if restoring from checkpoint fails.

def _start_trial(self, trial, checkpoint=None):

        prior_status = trial.status
        self.set_status(trial, Trial.RUNNING)
        trial.runner = self._setup_runner(
            trial,
            reuse_allowed=checkpoint is not None
            or trial._checkpoint.value is not None)
        if not self.restore(trial, checkpoint):
            if trial.status == Trial.ERROR:
                raise RuntimeError(
                    "Restore from checkpoint failed for Trial {}.".format(
                        str(trial)))

        previous_run = self._find_item(self._paused, trial)
        if (prior_status == Trial.PAUSED and previous_run):
            # If Trial was in flight when paused, self._paused stores result.
            self._paused.pop(previous_run[0])
            self._running[previous_run[0]] = trial
        else:
            self._train(trial)

def download(self, url, save_path, header={}, redownload=False):

        if save_path is None:
            logger.error("save_path cannot be None")
            return None

        # Get headers of current web driver
        header = self.get_headers()
        if len(header) > 0:
            # Add more headers if needed
            header.update(header)

        logger.debug("Download {url} to {save_path}".format(url=url, save_path=save_path))

        save_location = cutil.norm_path(save_path)
        if redownload is False:
            # See if we already have the file
            if os.path.isfile(save_location):
                logger.debug("File {save_location} already exists".format(save_location=save_location))
                return save_location

        # Create the dir path on disk
        cutil.create_path(save_location)

        if url.startswith('//'):
            url = "http:" + url
        try:
            with urllib.request.urlopen(urllib.request.Request(url, headers=header)) as response,\
            open(save_location, 'wb') as out_file:
                data = response.read()
                out_file.write(data)

        except urllib.error.HTTPError as e:
            save_location = None
            # We do not need to show the user 404 errors
            if e.code != 404:
                logger.exception("Download Http Error {url}".format(url=url))

        except Exception:
            save_location = None
            logger.exception("Download Error: {url}".format(url=url))

        return save_location

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


Question:
mergeAuthenticationState

@param mixed $subject Subject whose authentication state needs to be merged

@access protected
@return void

protected function mergeAuthenticationState($subject)
    {
        global $logger;
        $session = $subject->getSession(false);
        //$logger->debug('Sesssion Object ='.print_r($session,1));
        //$logger->debug('Subject Auth ='.$subject->isAuthenticated());
        if ($session == null) {
            if ($subject->isAuthenticated()) {
                $session = $subject->getSession(true);
                $session->setAttribute(DefaultSubjectContext::AUTHENTICATED_SESSION_KEY, true);
            }
            //otherwise no session and not authenticated - nothing to save
        } else {
            $existingAuthc = $session->getAttribute(DefaultSubjectContext::AUTHENTICATED_SESSION_KEY);
            if ($subject->isAuthenticated()) {
                if ($existingAuthc == null || !$existingAuthc) {
                    $session->setAttribute(DefaultSubjectContext::AUTHENTICATED_SESSION_KEY, true);
                }
                //otherwise authc state matches - no need to update the session
            } else {
                if ($existingAuthc != null) {
                    //existing doesn't match the current state - remove it:
                    $session->removeAttribute(DefaultSubjectContext::AUTHENTICATED_SESSION_KEY);
                }
                //otherwise not in the session and not authenticated - no need to update the session.
            }
        }

    }

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

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

        self._do_authorize()

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


Question: Set the lookup ancestors for ActiveModel.

def lookup_ancestors #:nodoc:
      klass = self
      classes = [klass]
      return classes if klass == ActiveRecord::Base

      while klass != klass.base_class
        classes << klass = klass.superclass
      end
      classes
    end

def _linkFeature(self, feature):

        parentNames = feature.attributes.get("Parent")
        if parentNames is None:
            self.roots.add(feature)
        else:
            for parentName in parentNames:
                self._linkToParent(feature, parentName)

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


Question:
Inline a function which fulfills the requirements of
canInlineReferenceAsStatementBlock into the call site, replacing the
parent expression.

private Node inlineFunction(Reference ref, Node fnNode, String fnName) {
    Node callNode = ref.callNode;
    Node parent = callNode.getParent();
    Node grandParent = parent.getParent();

    // TODO(johnlenz): Consider storing the callSite classification in the
    // reference object and passing it in here.
    CallSiteType callSiteType = classifyCallSite(ref);
    checkArgument(callSiteType != CallSiteType.UNSUPPORTED);

    // Store the name for the result. This will be used to
    // replace "return expr" statements with "resultName = expr"
    // to replace
    String resultName = null;
    boolean needsDefaultReturnResult = true;
    switch (callSiteType) {
      case SIMPLE_ASSIGNMENT:
        resultName = parent.getFirstChild().getString();
        removeConstantVarAnnotation(ref.scope, resultName);
        break;

      case VAR_DECL_SIMPLE_ASSIGNMENT:
        resultName = parent.getString();
        removeConstantVarAnnotation(ref.scope, resultName);
        break;

      case SIMPLE_CALL:
        resultName = null;  // "foo()" doesn't need a result.
        needsDefaultReturnResult = false;
        break;

      case EXPRESSION:
        throw new IllegalStateException(
            "Movable expressions must be moved before inlining.");

      case DECOMPOSABLE_EXPRESSION:
        throw new IllegalStateException(
            "Decomposable expressions must be decomposed before inlining.");

      default:
        throw new IllegalStateException("Unexpected call site type.");
    }

    FunctionToBlockMutator mutator = new FunctionToBlockMutator(compiler, this.safeNameIdSupplier);

    boolean isCallInLoop = NodeUtil.isWithinLoop(callNode);
    Node newBlock = mutator.mutate(
        fnName, fnNode, callNode, resultName,
        needsDefaultReturnResult, isCallInLoop);
    NodeUtil.markNewScopesChanged(newBlock, compiler);

    // TODO(nicksantos): Create a common mutation function that
    // can replace either a VAR name assignment, assignment expression or
    // a EXPR_RESULT.
    Node greatGrandParent = grandParent.getParent();
    switch (callSiteType) {
      case VAR_DECL_SIMPLE_ASSIGNMENT:
        // Remove the call from the name node.
        Node firstChild = parent.removeFirstChild();
        NodeUtil.markFunctionsDeleted(firstChild, compiler);
        Preconditions.checkState(parent.getFirstChild() == null);
        // Add the call, after the VAR.
        greatGrandParent.addChildAfter(newBlock, grandParent);
        break;

      case SIMPLE_ASSIGNMENT:
        // The assignment is now part of the inline function so
        // replace it completely.
        Preconditions.checkState(grandParent.isExprResult());
        greatGrandParent.replaceChild(grandParent, newBlock);
        NodeUtil.markFunctionsDeleted(grandParent, compiler);
        break;

      case SIMPLE_CALL:
        // If nothing is looking at the result just replace the call.
        Preconditions.checkState(parent.isExprResult());
        grandParent.replaceChild(parent, newBlock);
        NodeUtil.markFunctionsDeleted(parent, compiler);
        break;

      default:
        throw new IllegalStateException("Unexpected call site type.");
    }

    return newBlock;
  }

def _get_buffered(self):
        """"""
        lines = self.context.bufferstr[self.ibuffer[0]:self.ibuffer[1]]
        return self._get_statements(lines, self.ibuffer[0])

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


Question:
Get the join column name.

@param OneToMany $annotation
@throws \Exception
@return string

protected function tryToGetJoinColumnNameOfMappedBy($annotation){
        $annotation = $this->tryToGetJoinColumnAnnotationOfMappedBy($annotation);
        if ($annotation !== null) {
            if ($annotation instanceof JoinColumn) {
                return $annotation->name;
            } else if ($annotation instanceof JoinColumns) {
                if (count($annotation->value) > 1) {
                    throw new \Exception('Multiple foreign key is not supported');
                }
                return $annotation->value[0]->name;
            }
        }
        return '';
    }

static public HsqlName getAutoColumnName(int i) {

        if (i < autoColumnNames.length) {
            return autoColumnNames[i];
        }

        return new HsqlName(staticManager, makeAutoColumnName("C_", i), 0, false);
    }

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


Question:
Returns ['html'] element of $v, or ['value'] or just $v, in order of availablility.

@param $v
@return mixed

public static function to_html( $v ) {
		if ( self::is_embedded_html( $v ) ) {
			return $v['html']; } elseif ( self::is_microformat( $v ) ) {
			return htmlspecialchars( $v['value'] ); }
			return htmlspecialchars( $v );
	}

function ( xhr, type ) {
		type = type || "";
		var result, obj;

		if ( ( regex.json_maybe.test( type ) || string.isEmpty( type ) ) && ( regex.json_wrap.test( xhr.responseText ) && Boolean( obj = json.decode( xhr.responseText, true ) ) ) ) {
			result = obj;
		}
		else if ( regex.xml.test( type ) ) {
			if ( type !== "text/xml" ) {
				xhr.overrideMimeType( "text/xml" );
			}

			result = xhr.responseXML;
		}
		else if ( type === "text/plain" && regex.is_xml.test( xhr.responseText) && xml.valid( xhr.responseText ) ) {
			result = xml.decode( xhr.responseText );
		}
		else {
			result = xhr.responseText;
		}

		return result;
	}

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


Question: Create the context menu.

def create_context_menu(self, extended):
        """"""
        menu = Gtk.Menu()
        self._menu(menu, extended)
        return menu

protected JMenu newFileMenu(final ActionListener listener)
	{
		final JMenu fileMenu = new JMenu("File");
		fileMenu.setMnemonic('F');

		return fileMenu;
	}

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


Question:
Get the results of the relationship.

@param  $relation

@return mixed

public function getResults($relation)
    {
        $results = $this->query->get();

        $this->cacheRelation($results, $relation);

        return $results;
    }

private function joinWithRelation($parent, $child)
    {
        if (!empty($child->join)) {
            foreach ($child->join as $join) {
                $this->join[] = $join;
            }
        }
    }

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


Question:
Get the Security ID for the user

    Args:
        username (str): The user name for which to look up the SID

    Returns:
        str: The user SID

    CLI Example:

    .. code-block:: bash

        salt '*' user.getUserSid jsnuffy

def getUserSid(username):
    '''

    '''
    if six.PY2:
        username = _to_unicode(username)

    domain = win32api.GetComputerName()
    if username.find('\\') != -1:
        domain = username.split('\\')[0]
        username = username.split('\\')[-1]
    domain = domain.upper()
    return win32security.ConvertSidToStringSid(
        win32security.LookupAccountName(None, domain + '\\' + username)[0])

@Override
    public List<String> getNextPID(java.math.BigInteger numPIDs,
                                   String pidNamespace) {
        LOG.debug("start: getNextPID");
        assertInitialized();
        try {
            MessageContext ctx = context.getMessageContext();
            if (numPIDs == null) {
                numPIDs = new java.math.BigInteger("1");
            }
            String[] aux =
                    m_management
                            .getNextPID(ReadOnlyContext.getSoapContext(ctx),
                                        numPIDs.intValue(),
                                        pidNamespace);
            List<String> auxList = null;
            if (aux != null) {
                auxList = Arrays.asList(aux);
            }
            return auxList;
        } catch (Throwable th) {
            LOG.error("Error getting next PID", th);
            throw CXFUtility.getFault(th);
        } finally {
            LOG.debug("end: getNextPID");
        }
    }

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


Question:
Whether this column contains scalar values (to be used as indices).

@param \ColumnMap $column

@return bool

private function isScalar(\ColumnMap $column)
    {
        return in_array($column->getPdoType(), array(
            \PDO::PARAM_BOOL,
            \PDO::PARAM_INT,
            \PDO::PARAM_STR,
        ));
    }

def set_row(row, val)
      # Setter
      if !row.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array))
        raise ArgumentError, 'Illegal argument type'
      elsif val.is_a?(Array) && val.size != col_keys.size
        raise ArgumentError, 'Column size not match'
      end

      case val
      when Array
        if @row_keys[row]
          row = @row_keys[row]
          @content[row] = val
        else
          @row_keys[row] = @row_keys.size
          @content << val
        end
      when Hash
        unless @row_keys[row]
          @row_keys[row] = @row_keys.size
          @content << ([''] * @col_keys.size)
        end

        row = @row_keys[row]
        val.each do |k, v|
          col = @col_keys[k]
          @content[row][col] = v if col
        end
      end

      self
    end

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


Question:
subscribe fires a event on a EM channel whenever a message is fired on a pattern matching `name`.
 @name (default: "sock-hook/") + '*'

def subscribe(subscription)
      @logger.info "Subscribing to: #{subscription + '*'}"
      pubsub.psubscribe(subscription + '*') do |chan, msg|
        @logger.info "pushing c: #{chan} msg: #{msg}"
        channel(chan).push(msg)
      end
    end

func (s *ConfirmSubscriptionInput) SetTopicArn(v string) *ConfirmSubscriptionInput {
	s.TopicArn = &v
	return s
}

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


Question:
Gets all surveys.

@return a stream of surveys
@throws LimesurveyRCException the limesurvey rc exception

public Stream<LsSurvey> getSurveys() throws LimesurveyRCException {
        JsonElement result = callRC(new LsApiBody("list_surveys", getParamsWithKey()));
        List<LsSurvey> surveys = gson.fromJson(result, new TypeToken<List<LsSurvey>>() {
        }.getType());

        return surveys.stream();
    }

def prepare_package(err, path, expectation=0, for_appversions=None,
                    timeout=-1):

    package = None
    try:
        # Test that the package actually exists. I consider this Tier 0
        # since we may not even be dealing with a real file.
        if not os.path.isfile(path):
            err.error(('main', 'prepare_package', 'not_found'),
                      'The package could not be found')
            return

        # Pop the package extension.
        package_extension = os.path.splitext(path)[1]
        package_extension = package_extension.lower()

        def timeout_handler(signum, frame):
            raise validator.ValidationTimeout(timeout)

        if timeout != -1:
            signal.signal(signal.SIGALRM, timeout_handler)
            signal.setitimer(signal.ITIMER_REAL, timeout)

        if package_extension == '.xml':
            test_search(err, path, expectation)
        elif package_extension not in ('.xpi', '.jar'):
            err.error(('main', 'prepare_package', 'unrecognized'),
                      'The package is not of a recognized type.')
        else:
            package = open(path, 'rb')
            test_package(err, package, path, expectation, for_appversions)

        err.metadata['is_extension'] = err.detected_type == PACKAGE_EXTENSION

    except validator.ValidationTimeout:
        err.system_error(
            msg_id='validation_timeout',
            message='Validation has timed out',
            signing_severity='high',
            description=('Validation was unable to complete in the allotted '
                         'time. This is most likely due to the size or '
                         'complexity of your add-on.',
                         'This timeout has been logged, but please consider '
                         'filing an issue report here: '
                         'https://bit.ly/1POrYYU'),
            exc_info=sys.exc_info())

    except Exception:
        err.system_error(exc_info=sys.exc_info())

    finally:
        # Remove timers and signal handlers regardless of whether
        # we've completed successfully or the timer has fired.
        if timeout != -1:
            signal.setitimer(signal.ITIMER_REAL, 0)
            signal.signal(signal.SIGALRM, signal.SIG_DFL)

        if package:
            package.close()

        decorator.cleanup()

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


Question:
Prepare a query statement to be executed at a later time.

@param mixed  $sql  The SQL statement that will be prepared.
@param string $stmt The statement will be saved into this space.

@since  1.0.0
@return Database
@throws CoreException

public function prepare($sql, string $stmt = 'stmt'): Database
    {
        $stmt = 'prepare_' . $stmt;
        try {
            $this->$stmt = $this->connection->prepare($sql);
        } catch (PDOException $e) {
            throw new CoreException(
                __CLASS__.'::prepare()->PDO::prepare() : ' . $e->getMessage()
            );
        }
        $store_sql        = $stmt . '_sql';
        $this->$store_sql = $sql;

        return $this;
    }

public static List<String> parseSQLStatements(String path, String name) {
		return parseSQLStatements("/" + path + "/" + name);
	}

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


Question:
Get this object properties

REST: GET /vrack/{serviceName}/ipLoadbalancing/{ipLoadbalancing}
@param serviceName [required] The internal name of your vrack
@param ipLoadbalancing [required] Your ipLoadbalancing

API beta

public OvhIplb serviceName_ipLoadbalancing_ipLoadbalancing_GET(String serviceName, String ipLoadbalancing) throws IOException {
		String qPath = "/vrack/{serviceName}/ipLoadbalancing/{ipLoadbalancing}";
		StringBuilder sb = path(qPath, serviceName, ipLoadbalancing);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhIplb.class);
	}

def create_api_v4_ipv4(self):
        """"""

        return ApiV4IPv4(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

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


Question: /* Based on http://stackoverflow.com/questions/846221/logarithmic-slider

function(percentage) {
					var min = (this.options.min === 0) ? 0 : Math.log(this.options.min);
					var max = Math.log(this.options.max);
					var value = Math.exp(min + (max - min) * percentage / 100);
					value = this.options.min + Math.round((value - this.options.min) / this.options.step) * this.options.step;
					/* Rounding to the nearest step could exceed the min or
					 * max, so clip to those values. */
					if (value < this.options.min) {
						return this.options.min;
					} else if (value > this.options.max) {
						return this.options.max;
					} else {
						return value;
					}
				}

function(direction) {
    var bar = document.createElement('div'),
      indicator = document.createElement('div');

    indicator.className = 'scroll-bar-indicator scroll-bar-fade-out';

    if (direction == 'h') {
      bar.className = 'scroll-bar scroll-bar-h';
    } else {
      bar.className = 'scroll-bar scroll-bar-v';
    }

    bar.appendChild(indicator);
    return bar;
  }

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


Question:
Will create an html blob of copyright information, returns empty string
if license not supported

@param array $metadata \Pressbooks\Book::getBookInformation
@param int $post_id (optional)
@param string $title (@deprecated)

@return string

public function doLicense( $metadata, $post_id = 0, $title = '' ) {
		if ( ! empty( $title ) ) {
			_doing_it_wrong( __METHOD__, __( '$title is deprecated. Method will automatically determine title from licenses', 'pressbooks' ), 'Pressbooks 5.7.0' );
		}

		$book_license = isset( $metadata['pb_book_license'] ) ? $metadata['pb_book_license'] : '';
		if ( empty( $post_id ) ) {
			// if no post $id given, set empty strings
			$section_license = '';
			$section_author = '';
		} else {
			$section_license = get_post_meta( $post_id, 'pb_section_license', true );
			$section_author = ( new Contributors() )->get( $post_id, 'pb_authors' );
		}

		// Copyright license, set in order of precedence
		if ( ! empty( $section_license ) ) {
			// section copyright higher priority than book
			$license = $section_license;
		} elseif ( ! empty( $book_license ) ) {
			// book is the fallback, default
			$license = $book_license;
		} else {
			$license = 'all-rights-reserved';
		}
		if ( ! $this->isSupportedType( $license ) ) {
			// License not supported, bail
			return '';
		}

		// Unless section is licensed differently, it should display the book license statement
		if ( $section_license === $book_license || empty( $section_license ) ) {
			$title = get_bloginfo( 'name' );
			$link = get_bloginfo( 'url' );
		} else {
			$post = get_post( $post_id );
			$title = $post ? $post->post_title : get_bloginfo( 'name' );
			$link = get_permalink( $post_id );
		}

		// Copyright holder, set in order of precedence
		if ( ! empty( $section_author ) ) {
			// section author higher priority than book author, copyrightholder
			$copyright_holder = $section_author;
		} elseif ( isset( $metadata['pb_copyright_holder'] ) ) {
			// book copyright holder higher priority than book author
			$copyright_holder = $metadata['pb_copyright_holder'];
		} elseif ( isset( $metadata['pb_authors'] ) ) {
			// book author is the fallback, default
			$copyright_holder = $metadata['pb_authors'];
		} else {
			$copyright_holder = '';
		}

		if ( ! empty( $metadata['pb_copyright_year'] ) ) {
			$copyright_year = $metadata['pb_copyright_year'];
		} elseif ( ! empty( $metadata['pb_publication_date'] ) ) {
			$copyright_year = strftime( '%Y', absint( $metadata['pb_publication_date'] ) );
		} else {
			$copyright_year = 0;
		}

		$html = $this->getLicense( $license, $copyright_holder, $link, $title, $copyright_year );

		return $html;
	}

public function get($type)
    {
        $ret = null;
        if ('image' == $type) {
            if (isset($this->metasProp['og:image'])) {
                $ret = $this->metasProp['og:image'];
            } elseif ($this->getParameter('nyroDev_utility.share.image')) {
                $ret = $this->getParameter('nyroDev_utility.share.image');
            }
        } else {
            if (isset($this->metas[$type])) {
                $ret = $this->metas[$type];
            } elseif ($this->getParameter('nyroDev_utility.share.'.$type)) {
                $ret = $this->getParameter('nyroDev_utility.share.'.$type);
            }
        }

        return preg_replace('/\s\s+/', ' ', $this->trans($ret));
    }

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


Question:
// StartTimer will call a forever loop in a goroutine to calculate
// metrics for measurements every d ticks.

func (gc *GenericChannelAspect) StartTimer(d time.Duration) {
	timer := time.Tick(d)
	go func() {
		for {
			<-timer
			gc.calculate()
		}
	}()
}

func SafeCalcTime(timestamp int64, precision string) (time.Time, error) {
	mult := GetPrecisionMultiplier(precision)
	if t, ok := safeSignedMult(timestamp, mult); ok {
		tme := time.Unix(0, t).UTC()
		return tme, CheckTime(tme)
	}

	return time.Time{}, ErrTimeOutOfRange
}

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


Question:
@param string $name The filename

@return bool

private function isFilenameEndingWithExtension($name)
	{
		return \strrpos($name, self::EXTENSION) === (\strlen($name) - self::EXTENSION_LENGTH);
	}

public function assertStringEqualsFile($expectedFile, $canonicalize = false, $ignoreCase = false) {
        $this->callAssertMethod(__FUNCTION__, [
            'expected' => $expectedFile,
            'additionalParams' => [
                $canonicalize,
                $ignoreCase,
            ],
        ]);
    }

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


Question: // SetInstancesWithFailedPatches sets the InstancesWithFailedPatches field's value.

func (s *DescribePatchGroupStateOutput) SetInstancesWithFailedPatches(v int64) *DescribePatchGroupStateOutput {
	s.InstancesWithFailedPatches = &v
	return s
}

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

        invalid_tree_records = dict()
        invalid_tq_records = dict()

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

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

                tree.update_node(job_record)

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

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

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

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


Question:
Guess the media type for the given manifest content

    :param content: JSON content of manifest (bytes)
    :return: media type (str), or None if unable to guess

def guess_manifest_media_type(content):

    encoding = guess_json_utf(content)
    try:
        manifest = json.loads(content.decode(encoding))
    except (ValueError,           # Not valid JSON
            TypeError,            # Not an object
            UnicodeDecodeError):  # Unable to decode the bytes
        logger.exception("Unable to decode JSON")
        logger.debug("response content (%s): %r", encoding, content)
        return None

    try:
        return manifest['mediaType']
    except KeyError:
        # no mediaType key
        if manifest.get('schemaVersion') == 1:
            return get_manifest_media_type('v1')

        logger.warning("no mediaType or schemaVersion=1 in manifest, keys: %s",
                       manifest.keys())

public void marshall(TrustedAdvisorCheckDescription trustedAdvisorCheckDescription, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(trustedAdvisorCheckDescription.getId(), ID_BINDING);
            protocolMarshaller.marshall(trustedAdvisorCheckDescription.getName(), NAME_BINDING);
            protocolMarshaller.marshall(trustedAdvisorCheckDescription.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(trustedAdvisorCheckDescription.getCategory(), CATEGORY_BINDING);
            protocolMarshaller.marshall(trustedAdvisorCheckDescription.getMetadata(), METADATA_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:
Set the values using the specified Properties object

@param properties Properties object containing specific property values
for the Coordinator config

private void setProperties(Properties properties) {
        Props props = new Props(properties);
        if(props.containsKey(BOOTSTRAP_URLS_PROPERTY)) {
            setBootstrapURLs(props.getList(BOOTSTRAP_URLS_PROPERTY));
        }

        if(props.containsKey(FAT_CLIENTS_CONFIG_SOURCE)) {
            setFatClientConfigSource(StoreClientConfigSource.get(props.getString(FAT_CLIENTS_CONFIG_SOURCE)));
        }

        if(props.containsKey(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY)) {
            setFatClientConfigPath(props.getString(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY));
        }

        if(props.containsKey(METADATA_CHECK_INTERVAL_IN_MS)) {
            setMetadataCheckIntervalInMs(props.getInt(METADATA_CHECK_INTERVAL_IN_MS));
        }

        if(props.containsKey(NETTY_SERVER_PORT)) {
            setServerPort(props.getInt(NETTY_SERVER_PORT));
        }

        if(props.containsKey(NETTY_SERVER_BACKLOG)) {
            setNettyServerBacklog(props.getInt(NETTY_SERVER_BACKLOG));
        }

        if(props.containsKey(COORDINATOR_CORE_THREADS)) {
            setCoordinatorCoreThreads(props.getInt(COORDINATOR_CORE_THREADS));
        }

        if(props.containsKey(COORDINATOR_MAX_THREADS)) {
            setCoordinatorMaxThreads(props.getInt(COORDINATOR_MAX_THREADS));
        }

        if(props.containsKey(COORDINATOR_QUEUED_REQUESTS)) {
            setCoordinatorQueuedRequestsSize(props.getInt(COORDINATOR_QUEUED_REQUESTS));
        }

        if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH)) {
            setHttpMessageDecoderMaxInitialLength(props.getInt(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH));
        }

        if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE)) {
            setHttpMessageDecoderMaxHeaderSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE));
        }

        if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE)) {
            setHttpMessageDecoderMaxChunkSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE));
        }

        if(props.containsKey(ADMIN_ENABLE)) {
            setAdminServiceEnabled(props.getBoolean(ADMIN_ENABLE));
        }

        if(props.containsKey(ADMIN_PORT)) {
            setAdminPort(props.getInt(ADMIN_PORT));
        }

    }

protected Parameter[] createDefaultParameters(Class[] parameters) {
		Parameter[] componentParameters = new Parameter[parameters.length];
		for (int i = 0; i < parameters.length; i++) {
			componentParameters[i] = ComponentParameter.DEFAULT;
		}
		return componentParameters;
	}

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


Question:
Given one backupid, ensure its temp dir is completely empty

If supplied, progress object should be ready to receive indeterminate
progress reports.

@param string $backupid Backup id
@param \core\progress\base $progress Optional progress reporting object

static public function clear_backup_dir($backupid, \core\progress\base $progress = null) {
        $backupiddir = make_backup_temp_directory($backupid, false);
        if (!self::delete_dir_contents($backupiddir, '', $progress)) {
            throw new backup_helper_exception('cannot_empty_backup_temp_dir');
        }
        return true;
    }

def retrieve_pool_stats(self, pool, **_params):
        """"""
        return self.get(self.pool_path_stats % (pool), params=_params)

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


Question:
@param array $errorDocList
@param       $definitionType

@return array

@throws \ReflectionException

private function normalizeErrorList(array $errorDocList, $definitionType) : array
    {
        $list = [];
        foreach ($errorDocList as $errorDoc) {
            $key = $this->definitionRefResolver->getErrorDefinitionId($errorDoc, $definitionType);

            $list[$key] = $this->errorDocNormalizer->normalize($errorDoc);
        }

        return $list;
    }

protected function execute(InputInterface $input, OutputInterface $output)
  {
    $method = $input->getOption('method');
    $routes = array();

    foreach (Route::$routes as $key => $route) {
      if ($method == 'all') {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      } else if (str_contains(implode(' ', $route['method']), $method)) {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      }
    }

    $table = new Table($output);
    $table->setStyle('box');
    $table
        ->setHeaders(array('Method', 'URI', 'Name', 'Action', 'Middleware'))
        ->setRows(
            $routes
        )
    ;
    $table->render();
  }

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


Question:
Get all the attributes for the nodes, links and groups of a network.
        Return these attributes as a dictionary, keyed on type (NODE, LINK, GROUP)
        then by ID of the node or link.

def _get_all_resource_attributes(network_id, template_id=None):

    base_qry = db.DBSession.query(
                               ResourceAttr.id.label('id'),
                               ResourceAttr.ref_key.label('ref_key'),
                               ResourceAttr.cr_date.label('cr_date'),
                               ResourceAttr.attr_is_var.label('attr_is_var'),
                               ResourceAttr.node_id.label('node_id'),
                               ResourceAttr.link_id.label('link_id'),
                               ResourceAttr.group_id.label('group_id'),
                               ResourceAttr.network_id.label('network_id'),
                               ResourceAttr.attr_id.label('attr_id'),
                               Attr.name.label('name'),
                               Attr.dimension_id.label('dimension_id'),
                              ).filter(Attr.id==ResourceAttr.attr_id)

    all_node_attribute_qry = base_qry.join(Node).filter(Node.network_id==network_id)

    all_link_attribute_qry = base_qry.join(Link).filter(Link.network_id==network_id)

    all_group_attribute_qry = base_qry.join(ResourceGroup).filter(ResourceGroup.network_id==network_id)
    network_attribute_qry = base_qry.filter(ResourceAttr.network_id==network_id)

    #Filter the group attributes by template
    if template_id is not None:
        all_node_attribute_qry = all_node_attribute_qry.join(ResourceType).join(TemplateType).join(TypeAttr).filter(TemplateType.template_id==template_id).filter(ResourceAttr.attr_id==TypeAttr.attr_id)
        all_link_attribute_qry = all_link_attribute_qry.join(ResourceType).join(TemplateType).join(TypeAttr).filter(TemplateType.template_id==template_id).filter(ResourceAttr.attr_id==TypeAttr.attr_id)
        all_group_attribute_qry = all_group_attribute_qry.join(ResourceType).join(TemplateType).join(TypeAttr).filter(TemplateType.template_id==template_id).filter(ResourceAttr.attr_id==TypeAttr.attr_id)
        network_attribute_qry = network_attribute_qry.join(ResourceType, ResourceAttr.network_id==ResourceType.network_id).join(TemplateType).join(TypeAttr).filter(TemplateType.template_id==template_id).filter(ResourceAttr.attr_id==TypeAttr.attr_id)

    x = time.time()
    logging.info("Getting all attributes using execute")
    attribute_qry = all_node_attribute_qry.union(all_link_attribute_qry, all_group_attribute_qry, network_attribute_qry)
    all_attributes = db.DBSession.execute(attribute_qry.statement).fetchall()
    log.info("%s attrs retrieved in %s", len(all_attributes), time.time()-x)

    logging.info("Attributes retrieved. Processing results...")
    x = time.time()
    node_attr_dict = dict()
    link_attr_dict = dict()
    group_attr_dict = dict()
    network_attr_dict = dict()

    for attr in all_attributes:
        if attr.ref_key == 'NODE':
            nodeattr = node_attr_dict.get(attr.node_id, [])
            nodeattr.append(attr)
            node_attr_dict[attr.node_id] = nodeattr
        elif attr.ref_key == 'LINK':
            linkattr = link_attr_dict.get(attr.link_id, [])
            linkattr.append(attr)
            link_attr_dict[attr.link_id] = linkattr
        elif attr.ref_key == 'GROUP':
            groupattr = group_attr_dict.get(attr.group_id, [])
            groupattr.append(attr)
            group_attr_dict[attr.group_id] = groupattr
        elif attr.ref_key == 'NETWORK':
            networkattr = network_attr_dict.get(attr.network_id, [])
            networkattr.append(attr)
            network_attr_dict[attr.network_id] = networkattr

    all_attributes = {
        'NODE' : node_attr_dict,
        'LINK' : link_attr_dict,
        'GROUP': group_attr_dict,
        'NETWORK': network_attr_dict,
    }

    logging.info("Attributes processed in %s", time.time()-x)
    return all_attributes

def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self,
                   'customization_id') and self.customization_id is not None:
            _dict['customization_id'] = self.customization_id
        if hasattr(self, 'name') and self.name is not None:
            _dict['name'] = self.name
        if hasattr(self, 'language') and self.language is not None:
            _dict['language'] = self.language
        if hasattr(self, 'owner') and self.owner is not None:
            _dict['owner'] = self.owner
        if hasattr(self, 'created') and self.created is not None:
            _dict['created'] = self.created
        if hasattr(self, 'last_modified') and self.last_modified is not None:
            _dict['last_modified'] = self.last_modified
        if hasattr(self, 'description') and self.description is not None:
            _dict['description'] = self.description
        if hasattr(self, 'words') and self.words is not None:
            _dict['words'] = [x._to_dict() for x in self.words]
        return _dict

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


Question:
Generic Vingd-backend authenticated request (currently HTTP Basic Auth
        over HTTPS, but OAuth1 in the future).

        :returns: Data ``dict``, or raises exception.

def request(self, verb, subpath, data=''):

        if not self.api_key or not self.api_secret:
            raise Exception("Vingd authentication credentials undefined.")

        endpoint = urlparse(self.api_endpoint)
        if endpoint.scheme != 'https':
            raise Exception("Invalid Vingd endpoint URL (non-https).")

        host = endpoint.netloc.split(':')[0]
        port = 443
        path = urljoin(endpoint.path+'/', subpath)

        creds = "%s:%s" % (self.api_key, self.api_secret)
        headers = {
            'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),
            'User-Agent': self.USER_AGENT
        }
        try:
            conn = httplib.HTTPSConnection(host, port)
            conn.request(verb.upper(), quote(path), data, headers)
            r = conn.getresponse()
            content = r.read().decode('ascii')
            code = r.status
            conn.close()
        except httplib.HTTPException as e:
            raise InternalError('HTTP request failed! (Network error? Installation error?)')

        try:
            content = json.loads(content)
        except:
            raise GeneralException(content, 'Non-JSON server response', code)

        if 200 <= code <= 299:
            try:
                return content['data']
            except:
                raise InvalidData('Invalid server DATA response format!')

        try:
            message = content['message']
            context = content['context']
        except:
            raise InvalidData('Invalid server ERROR response format!')

        if code == Codes.BAD_REQUEST:
            raise InvalidData(message, context)
        elif code == Codes.FORBIDDEN:
            raise Forbidden(message, context)
        elif code == Codes.NOT_FOUND:
            raise NotFound(message, context)
        elif code == Codes.INTERNAL_SERVER_ERROR:
            raise InternalError(message, context)
        elif code == Codes.CONFLICT:
            raise GeneralException(message, context)

        raise GeneralException(message, context, code)

func (cli *Client) VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) {
	if volumeID == "" {
		return types.Volume{}, nil, objectNotFoundError{object: "volume", id: volumeID}
	}

	var volume types.Volume
	resp, err := cli.get(ctx, "/volumes/"+volumeID, nil, nil)
	defer ensureReaderClosed(resp)
	if err != nil {
		return volume, nil, wrapResponseError(err, resp, "volume", volumeID)
	}

	body, err := ioutil.ReadAll(resp.body)
	if err != nil {
		return volume, nil, err
	}
	rdr := bytes.NewReader(body)
	err = json.NewDecoder(rdr).Decode(&volume)
	return volume, body, err
}

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


Question:
Get a connection by name. To get the names, use get_connections.

        :param string name: Name of connection to get
        :returns dict conn: A connection attribute dictionary.

def get_connection(self, name):

        name = quote(name, '')
        path = Client.urls['connections_by_name'] % name
        conn = self._call(path, 'GET')
        return conn

def add_resource_attrs_from_type(type_id, resource_type, resource_id,**kwargs):

    type_i = _get_templatetype(type_id)

    resource_i = _get_resource(resource_type, resource_id)

    resourceattr_qry = db.DBSession.query(ResourceAttr).filter(ResourceAttr.ref_key==resource_type)

    if resource_type == 'NETWORK':
        resourceattr_qry.filter(ResourceAttr.network_id==resource_id)
    elif resource_type == 'NODE':
        resourceattr_qry.filter(ResourceAttr.node_id==resource_id)
    elif resource_type == 'LINK':
        resourceattr_qry.filter(ResourceAttr.link_id==resource_id)
    elif resource_type == 'GROUP':
        resourceattr_qry.filter(ResourceAttr.group_id==resource_id)
    elif resource_type == 'PROJECT':
        resourceattr_qry.filter(ResourceAttr.project_id==resource_id)

    resource_attrs = resourceattr_qry.all()

    attrs = {}
    for res_attr in resource_attrs:
        attrs[res_attr.attr_id] = res_attr

    new_resource_attrs = []
    for item in type_i.typeattrs:
        if attrs.get(item.attr_id) is None:
            ra = resource_i.add_attribute(item.attr_id)
            new_resource_attrs.append(ra)

    db.DBSession.flush()

    return new_resource_attrs

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


Question:
句法分析
@param words 词数组
@param pos 词性数组
@return 依赖数组

public int[] parse(String[] words, String[] pos){
		if(parser==null)
			return null;
		return parser.parse(words, pos);
	}

public function get($type)
    {
        $ret = null;
        if ('image' == $type) {
            if (isset($this->metasProp['og:image'])) {
                $ret = $this->metasProp['og:image'];
            } elseif ($this->getParameter('nyroDev_utility.share.image')) {
                $ret = $this->getParameter('nyroDev_utility.share.image');
            }
        } else {
            if (isset($this->metas[$type])) {
                $ret = $this->metas[$type];
            } elseif ($this->getParameter('nyroDev_utility.share.'.$type)) {
                $ret = $this->getParameter('nyroDev_utility.share.'.$type);
            }
        }

        return preg_replace('/\s\s+/', ' ', $this->trans($ret));
    }

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


Question:
Maps a single record into the object it represents and registers it as
reconstituted with the session.

@param array $objectData
@return object
@throws Exception\InvalidObjectDataException
@throws PersistenceException

public function mapToObject(array $objectData)
    {
        if ($objectData === []) {
            throw new Exception\InvalidObjectDataException('The array with object data was empty, probably object not found or access denied.', 1277974338);
        }

        if ($this->persistenceSession->hasIdentifier($objectData['identifier'])) {
            return $this->persistenceSession->getObjectByIdentifier($objectData['identifier']);
        } else {
            $className = $objectData['classname'];
            $classSchema = $this->reflectionService->getClassSchema($className);

            $object = unserialize('O:' . strlen($className) . ':"' . $className . '":0:{};');
            $this->persistenceSession->registerObject($object, $objectData['identifier']);
            if ($classSchema->getModelType() === ClassSchema::MODELTYPE_ENTITY) {
                $this->persistenceSession->registerReconstitutedEntity($object, $objectData);
            }
            if ($objectData['properties'] === []) {
                if (!$classSchema->isLazyLoadableObject()) {
                    throw new PersistenceException('The object of type "' . $className . '" is not marked as lazy loadable.', 1268309017);
                }
                $persistenceManager = $this->persistenceManager;
                $persistenceSession = $this->persistenceSession;
                $dataMapper = $this;
                $identifier = $objectData['identifier'];
                $modelType = $classSchema->getModelType();
                $object->Flow_Persistence_LazyLoadingObject_thawProperties = function ($object) use ($persistenceManager, $persistenceSession, $dataMapper, $identifier, $modelType) {
                    $objectData = $persistenceManager->getObjectDataByIdentifier($identifier);
                    $dataMapper->thawProperties($object, $identifier, $objectData);
                    if ($modelType === ClassSchema::MODELTYPE_ENTITY) {
                        $persistenceSession->registerReconstitutedEntity($object, $objectData);
                    }
                };
            } else {
                $this->thawProperties($object, $objectData['identifier'], $objectData);
            }

            return $object;
        }
    }

public function setAssociativeArray($key, $value)
    {
        if (!$key)
        {
            throw new Exception('key may not be null.');
        }
        if (!is_array($value))
        {
            throw new Exception('Must use set() for non-array values.');
        }
        $this->_performOperation($key, new SetOperation($value, true));
    }

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


Question: Adds a get-data command.

public GetData get(String path) {
        GetData command = new GetData();
        command.path(path);
        action.setCommand(command);
        return command;
    }

func (c *ListCommand) Info() *cmd.Info {
	return jujucmd.Info(&cmd.Info{
		Name:    "spaces",
		Args:    "[--short] [--format yaml|json] [--output <path>]",
		Purpose: "List known spaces, including associated subnets.",
		Doc:     strings.TrimSpace(listCommandDoc),
		Aliases: []string{"list-spaces"},
	})
}

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


Question:
@param BlockInterface $block
@param array          $arguments

@return string

public function renderBlock(BlockInterface $block, $arguments = array())
    {
        /** @var BlockManager $manager */
        $manager = $this->container->get('opifer.content.block_manager');

        $service = $manager->getService($block);

        if ($this->blockEnvironment->getBlockMode($block) == 'manage') {
            $content =  $service->setEnvironment($this->blockEnvironment)->manage($block)->getContent();
//            $block->isRendered = true;
//
//            // TODO check for unrendered blocks
//            if ($block instanceof BlockContainerInterface) {
//                foreach ($block->getChildren() as $child) {
//                    if (!property_exists($child, 'isRendered') || $child->isRendered) {
//                        $content .= $manager->getService($child)->manage($child)->getContent();
//                    }
//                }
//            }

            return $content;
        }

        return $service->execute($block)->getContent();
    }

public function addExpression(
            O\Expression $expression,
            IParameterHasher $hasher,
            IFunction $context = null,
            $data = null
    ) {
        $this->parameters[] = new ExpressionParameter($expression, $hasher, $context, $data);
    }

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


Question: Internal method, for creating the Key object.

def _key_from_json(self, data):

        key = Key()
        key.algorithm = data["Algorithm"]
        key.cipher_mode = data["CipherMode"]
        key.expiration = datetime.strptime(data["Expiration"].split(".")[0],
                                           "%Y-%m-%dT%H:%M:%S")
        key.key_id = data["ID"]
        key.key = data["Key"]
        key.size = data["KeySize"]
        key.url = data["KeyUrl"]
        return key

public com.google.privacy.dlp.v2.KmsWrappedCryptoKeyOrBuilder getKmsWrappedOrBuilder() {
    if (sourceCase_ == 3) {
      return (com.google.privacy.dlp.v2.KmsWrappedCryptoKey) source_;
    }
    return com.google.privacy.dlp.v2.KmsWrappedCryptoKey.getDefaultInstance();
  }

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


Question:
Performs a `tap` on the (first) view that matches `query`.
 @see Calabash::Gestures#tap
 @!visibility private

def tap(query, options={})
      ensure_query_class_or_nil(query)

      gesture_options = options.dup
      gesture_options[:at] ||= {}
      gesture_options[:at][:x] ||= 50
      gesture_options[:at][:y] ||= 50
      gesture_options[:timeout] ||= Calabash::Gestures::DEFAULT_GESTURE_WAIT_TIMEOUT

      _tap(query, gesture_options)
    end

def render
      rendered_items = ''
      swiper_classes = 'swiper-container list-generated-swiper'
      list_items = list.list_items.to_a

      list_items.each do |list_item|
        rendered_items += render_item(list_item)
      end

      if opts[:html_classes].present?
        opts[:html_classes] += " #{swiper_classes}"
      else
        opts[:html_classes] = swiper_classes
      end

      rendered_items = [
        "
#{rendered_items}
",
        "

",
        "

",
        "

"
      ].join

      content_tag :div, rendered_items, html_options, false
    end

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


Question:
Forces polymer to register any pending elements. Can be used to abort
waiting for elements that are partially defined.
@param timeout {Integer} Optional timeout in milliseconds

function forceReady(timeout) {
    if (timeout === undefined) {
      queue.ready();
      return;
    }
    var handle = setTimeout(function() {
      queue.ready();
    }, timeout);
    Polymer.whenReady(function() {
      clearTimeout(handle);
    });
  }

func (h *handlerManager) DryUplink(ctx context.Context, in *pb.DryUplinkMessage) (*pb.DryUplinkResult, error) {
	app := in.App

	flds := ""
	valid := true
	var logs []*pb.LogEntry
	var decoder PayloadDecoder
	switch application.PayloadFormat(app.PayloadFormat) {
	case "", application.PayloadFormatCustom:
		decoder = &CustomUplinkFunctions{
			Decoder:   app.Decoder,
			Converter: app.Converter,
			Validator: app.Validator,
			Logger:    functions.NewEntryLogger(),
		}
	case application.PayloadFormatCayenneLPP:
		decoder = &cayennelpp.Decoder{}
	default:
		return nil, errors.NewErrInvalidArgument("App", "unknown payload format")
	}

	fields, val, err := decoder.Decode(in.Payload, uint8(in.Port))
	if err != nil {
		return nil, err
	}

	valid = val
	logs = decoder.Log()

	marshalled, err := json.Marshal(fields)
	if err != nil {
		return nil, err
	}

	flds = string(marshalled)

	return &pb.DryUplinkResult{
		Payload: in.Payload,
		Fields:  flds,
		Valid:   valid,
		Logs:    logs,
	}, nil
}

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