Question:
// NewPerHost returns a PerHost Dialer that directs connections to either
// defaultDialer or bypass, depending on whether the connection matches one of
// the configured rules.

func NewPerHost(defaultDialer, bypass Dialer) *PerHost {
	return &PerHost{
		def:    defaultDialer,
		bypass: bypass,
	}
}

func addBgp(ctx *cli.Context) {
	if len(ctx.Args()) < 1 {
		errExit(ctx, exitHelp, "Host name required", true)
	}

	hostname := ctx.Args()[0]
	routerip := ctx.String("router-ip")
	asid := ctx.String("as")
	neighboras := ctx.String("neighbor-as")
	neighbor := ctx.String("neighbor")

	//Error checks
	_, _, err := net.ParseCIDR(routerip)
	if err != nil {
		errExit(ctx, exitHelp, "Wrong CIDR format. Enter in x.x.x.x/len format", true)
	}

	ip := net.ParseIP(neighbor)
	if ip == nil {
		errExit(ctx, exitHelp, "Wrong IP format. Enter in x.x.x.x format", true)
	}

	if routerip == "" || asid == "" || neighbor == "" || neighboras == "" {
		errExit(ctx, exitHelp, "Missing attributes", true)
	}

	errCheck(ctx, getClient(ctx).BgpPost(&contivClient.Bgp{
		As:         asid,
		Hostname:   hostname,
		Neighbor:   neighbor,
		NeighborAs: neighboras,
		Routerip:   routerip,
	}))

}

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


Question: // SetReportName sets the ReportName field's value.

func (s *DeleteReportDefinitionInput) SetReportName(v string) *DeleteReportDefinitionInput {
	s.ReportName = &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:
Run the migrations.

@return void

public function up()
    {
        Schema::create('hc_menu_groups', function (Blueprint $table) {
            $table->integer('count', true);
            $table->string('id', 36)->unique('id_UNIQUE');
            $table->timestamps();
            $table->softDeletes();

            $table->string('language_code', 36);
            $table->string('name', 191);
            $table->integer('sequence')->nullable();
        });

        Schema::table('hc_menu_groups', function (Blueprint $table) {
            $table->foreign('language_code')->references('iso_639_1')->on('hc_languages')->onUpdate('NO ACTION')->onDelete('NO ACTION');
        });
    }

func (md *RootMetadataV2) ClearForV4Migration() {
	md.WKeys = nil
	md.RKeys = nil
	md.Extra.UnresolvedWriters = nil
	md.UnresolvedReaders = nil
}

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


function(list, delim) {
            return new Anonymous(!isArray(list.value)
                ? list.toCSS()
                : list.value.map(function(a) {
                    return toString(a, "", "");
                }).join(delim ? delim.value : ", "));
        }

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

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

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

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

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

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


Question:
This method will take a MutableSet and wrap it directly in a SynchronizedMutableSet.  It will
take any other non-GS-collection and first adapt it will a SetAdapter, and then return a
SynchronizedMutableSet that wraps the adapter.

public static <E, S extends Set<E>> SynchronizedMutableSet<E> of(S set)
    {
        return new SynchronizedMutableSet<E>(SetAdapter.adapt(set));
    }

public static final Iterator createIterator(Object object) {
        LOGGER.debug("Create an iterator for class: " + (object == null ? "null" : object.getClass().getName()));

        if(object == null)
            return null;

        if(object instanceof Iterator) {
            return (Iterator)object;
        } else if(object instanceof Collection) {
            Collection collection = (Collection)object;
            return collection.iterator();
        } else if(object instanceof Map) {
            return new MapIterator((Map)object);
        } else if(object.getClass().isArray()) {
            return new ArrayIterator(object);
        } else if(object instanceof Enumeration)
            return new EnumerationIterator((Enumeration)object);
        else if(object instanceof ResultSet && !(object instanceof RowSet))
            return new ResultSetIterator((ResultSet)object);

        // check to see if there is a registered IteratorPlant that can handle this type
        Iterator ret = null;
        Iterator factories = ITERATOR_FACTORIES.keySet().iterator();
        while(factories.hasNext()) {
            IteratorPlant plant = (IteratorPlant)ITERATOR_FACTORIES.get(factories.next());
            ret = plant.createIterator(object);

            if(ret != null) return ret;
        }

        return new AtomicObjectIterator(object);
    }

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


Question:
This method pops the latest node from the trace
fragment hierarchy.

@param cls The type of node to pop
@param uri The optional uri to match
@return The node

public Node popNode(Class<? extends Node> cls, String uri) {

        synchronized (nodeStack) {
            // Check if fragment is in suppression mode
            if (suppress) {
                if (!suppressedNodeStack.isEmpty()) {

                    // Check if node is on the suppressed stack
                    Node suppressed = popNode(suppressedNodeStack, cls, uri);
                    if (suppressed != null) {
                        // Popped node from suppressed stack
                        return suppressed;
                    }
                } else {
                    // If suppression parent popped, then cancel the suppress mode
                    suppress = false;
                }
            }

            return popNode(nodeStack, cls, uri);
        }
    }

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

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


Question: As part of parse_line(), checks for new executable declarations in the statement.

def _rt_parse_execs(self, statement, element, mode, lineparser):
        """"""
        #This is the same deal as with _rt_parse_types() below.
        if mode == "insert":
            enew, start, end = self.xparser.parse_signature(statement, element, element)
            if enew is not None:
                enew.start, enew.end = lineparser.absolute_charindex(statement, start, end)
                enew.incomplete = True
                element.executables[enew.name.lower()] = enew
                lineparser.additions.append((enew, element))

def make_ready_all(self):

        T = self.tm.trace
        if T: T.write(self.trace_message('Task.make_ready_all()', self.node))

        self.out_of_date = self.targets[:]
        for t in self.targets:
            t.disambiguate().set_state(NODE_EXECUTING)
            for s in t.side_effects:
                # add disambiguate here to mirror the call on targets above
                s.disambiguate().set_state(NODE_EXECUTING)

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


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

@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case AfplibPackage.BSU__LID:
				setLID(LID_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

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

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

            config.script = wrapped_script

        return Container(config)

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


Question:
Return the schema for the given tableName.

@param datasetName tableName
@return Schema as JSON

@Override
    @GraphTransaction
    public String getSchema(String datasetName) throws AtlasException {
        datasetName = ParamChecker.notEmpty(datasetName, "table name");
        LOG.info("Fetching schema for tableName={}", datasetName);
        TypeUtils.Pair<String, String> typeIdPair = validateDatasetNameExists(datasetName);

        return getSchemaForId(typeIdPair.left, typeIdPair.right);
    }

private void populateMetaData() throws SQLException
   {
      m_meta.clear();

      ResultSetMetaData meta = m_rs.getMetaData();
      int columnCount = meta.getColumnCount() + 1;
      for (int loop = 1; loop < columnCount; loop++)
      {
         String name = meta.getColumnName(loop);
         Integer type = Integer.valueOf(meta.getColumnType(loop));
         m_meta.put(name, type);
      }
   }

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


Question:
Binding for {@link java.lang.Math#abs(int)}

@param   a   the argument whose absolute value is to be determined
@return  the absolute value of the argument.

public static IntegerBinding abs(final ObservableIntegerValue a) {
        return createIntegerBinding(() -> Math.abs(a.get()), a);
    }

public static Short min(Short a, Short b) {
		return a <= b ? a : b;
	}

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


Question:
Get a acl for application by id

@param int $appId
@param int $aclId
@param array $queryParams
@return AclResponse

public function getById($appId, $aclId, array $queryParams = [])
    {
        $response = $this->api->applications()->acls()->getById($appId, $aclId, $queryParams);

        return new AclResponse($response);
    }

protected function prepareCurl()
    {
        $this->curl = curl_init();
        $this->complete = Complete::factory(function() {
            if ($this->curl) {
                curl_close($this->curl);
            }
            $this->curl     = null;
            $this->complete = null;
        });

        foreach(self::$curlOptions as $option => $value) {
            curl_setopt($this->curl, $option, $value);
        }
        if ($this->method === HttpMethods::POST) {
            curl_setopt($this->curl, CURLOPT_POST, true);
        }
        if (!empty($this->auth)) {
            curl_setopt($this->curl, CURLOPT_USERPWD, sprintf(
                "%s:%s",
                $this->auth["user"],
                $this->auth["pass"]
            ));
        }
    }

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


Question:
Add a date range aggregate.

@param $alias
@param $field
@param $format
@param array $ranges

@internal param null $from
@internal param null $to

public function dateRange($alias, $field, $format, array $ranges)
    {
        $aggregation = new DateRangeAggregation($alias, $field, $format, $ranges);

        $this->append($aggregation);
    }

private function convertJoinColumnAnnotationToJoinColumnMetadata(
        Annotation\JoinColumn $joinColumnAnnot
    ) : Mapping\JoinColumnMetadata {
        $joinColumn = new Mapping\JoinColumnMetadata();

        // @todo Remove conditionals for name and referencedColumnName once naming strategy is brought into drivers
        if (! empty($joinColumnAnnot->name)) {
            $joinColumn->setColumnName($joinColumnAnnot->name);
        }

        if (! empty($joinColumnAnnot->referencedColumnName)) {
            $joinColumn->setReferencedColumnName($joinColumnAnnot->referencedColumnName);
        }

        $joinColumn->setNullable($joinColumnAnnot->nullable);
        $joinColumn->setUnique($joinColumnAnnot->unique);

        if (! empty($joinColumnAnnot->fieldName)) {
            $joinColumn->setAliasedName($joinColumnAnnot->fieldName);
        }

        if (! empty($joinColumnAnnot->columnDefinition)) {
            $joinColumn->setColumnDefinition($joinColumnAnnot->columnDefinition);
        }

        if ($joinColumnAnnot->onDelete) {
            $joinColumn->setOnDelete(strtoupper($joinColumnAnnot->onDelete));
        }

        return $joinColumn;
    }

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


Question: Restore the original cursor position because the user hit abort.

def qteAbort(self, msgObj):

        self.qteWidget.setCursorPosition(*self.cursorPosOrig)
        self.qteMain.qtesigAbort.disconnect(self.qteAbort)

def save_excursion
      old_point = new_mark
      old_mark = @mark&.dup
      old_column = @goal_column
      begin
        yield
      ensure
        point_to_mark(old_point)
        old_point.delete
        if old_mark
          @mark.location = old_mark.location
          old_mark.delete
        end
        @goal_column = old_column
      end
    end

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


Question: Marshall the given parameter object.

public void marshall(StartTaskRequest startTaskRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(startTaskRequest.getCluster(), CLUSTER_BINDING);
            protocolMarshaller.marshall(startTaskRequest.getTaskDefinition(), TASKDEFINITION_BINDING);
            protocolMarshaller.marshall(startTaskRequest.getOverrides(), OVERRIDES_BINDING);
            protocolMarshaller.marshall(startTaskRequest.getContainerInstances(), CONTAINERINSTANCES_BINDING);
            protocolMarshaller.marshall(startTaskRequest.getStartedBy(), STARTEDBY_BINDING);
            protocolMarshaller.marshall(startTaskRequest.getGroup(), GROUP_BINDING);
            protocolMarshaller.marshall(startTaskRequest.getNetworkConfiguration(), NETWORKCONFIGURATION_BINDING);
            protocolMarshaller.marshall(startTaskRequest.getTags(), TAGS_BINDING);
            protocolMarshaller.marshall(startTaskRequest.getEnableECSManagedTags(), ENABLEECSMANAGEDTAGS_BINDING);
            protocolMarshaller.marshall(startTaskRequest.getPropagateTags(), PROPAGATETAGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
Builds a component package based on a component.json file.
Will install packages if they don't exist locally.
Validate each component before returning built files

function buildComponentAndCheckConformance(filepath) {
  var componentDir = path.join(process.cwd(), path.dirname(filepath));
  var deferred = Q.defer();

  resolve(componentDir, options.resolveOpts, function(err, tree) {
    if (err) {
      return deferred.reject(err);
    }

    var build = Build(flatten(tree));

    build.stylePlugins = function(build) {
      build.use('styles', function(file, done) {
        file.read(function(err, string) {
          if (err) {
            return deferred.reject(err);
          }

          if (options.conform) {
            try {
              file.string = conform(string);
            } catch (e) {
              return deferred.reject(e);
            }
          }

          done();
        });
      });
    };

    build.styles(function(err, builtCSS) {
      if (err) {
        return deferred.reject(err);
      }

      deferred.resolve(builtCSS);
    });
  });

  return deferred.promise;
}

function compileValidator( attributes ) {
	if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) {
		throw new TypeError( "definition of attributes must be object" );
	}

	const attributeNames = Object.keys( attributes );
	const numAttributes = attributeNames.length;
	const validation = [];

	for ( let ai = 0; ai < numAttributes; ai++ ) {
		const attributeName = attributeNames[ai];
		const attribute = attributes[attributeName];

		const handler = Types.selectByName( attribute.type );

		const { args, body } = extractBody( handler.isValid );
		if ( args.length < 4 ) {
			throw new TypeError( `isValid() of ModelType for handling ${attribute.type} values must accept four arguments` );
		}

		validation[ai] = `
{
	const ${args[0]} = "${attributeName}";
	let ${args[1]} = __props["${attributeName}"];
	const ${args[2]} = __attrs["${attributeName}"];
	const ${args[3]} = __errors;

	{
		${body}
	}
}
		`;
	}

	// eslint-disable-next-line no-new-func
	return new Function( `
const __attrs = this.constructor.schema.attributes;
const __props = this.properties;
const __errors = [];

${validation.join( "" )}

return __errors;
` );
}

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


Question: Calculate the overall test score using the configuration.

def compute_score(self):
        """"""
        # LOGGER.info("Begin scoring")
        cases = self.get_configured_tests() | set(self.result.cases)
        scores = DataFrame({"score": 0.0, "max": 1.0},
                           index=sorted(cases))
        self.result.setdefault("score", dict())
        self.result["score"]["sections"] = list()
        # Calculate the scores for each test individually.
        for test, result in iteritems(self.result.cases):
            # LOGGER.info("Calculate score for test: '%s'.", test)
            # Test metric may be a dictionary for a parametrized test.
            metric = result["metric"]
            if hasattr(metric, "items"):
                result["score"] = test_score = dict()
                total = 0.0
                for key, value in iteritems(metric):
                    value = 1.0 - value
                    total += value
                    test_score[key] = value
                # For some reason there are parametrized tests without cases.
                if len(metric) == 0:
                    metric = 0.0
                else:
                    metric = total / len(metric)
            else:
                metric = 1.0 - metric
            scores.at[test, "score"] = metric
            scores.loc[test, :] *= self.config["weights"].get(test, 1.0)
        score = 0.0
        maximum = 0.0
        # Calculate the scores for each section considering the individual test
        # case scores.
        for section_id, card in iteritems(
            self.config['cards']['scored']['sections']
        ):
            # LOGGER.info("Calculate score for section: '%s'.", section_id)
            cases = card.get("cases", None)
            if cases is None:
                continue
            card_score = scores.loc[cases, "score"].sum()
            card_total = scores.loc[cases, "max"].sum()
            # Format results nicely to work immediately with Vega Bar Chart.
            section_score = {"section": section_id,
                             "score": card_score / card_total}
            self.result["score"]["sections"].append(section_score)
            # Calculate the final score for the entire model.
            weight = card.get("weight", 1.0)
            score += card_score * weight
            maximum += card_total * weight
        self.result["score"]["total_score"] = score / maximum

public static void write(final Iterable<HighScoringPair> hsps, final PrintWriter writer) {
        checkNotNull(hsps);
        checkNotNull(writer);
        for (HighScoringPair hsp : hsps) {
            writer.println(hsp.toString());
        }
    }

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


Question:
Survey source synchronization check function

@param string $sourceSurveyId
@param int $surveyId
@param int $userId
@return mixed message string or array of messages

public function checkSurvey($sourceSurveyId, $surveyId, $userId)
    {
        $messages = array();
        $survey   = $this->tracker->getSurvey($surveyId);

        if (null === $sourceSurveyId) {
            // Was removed
            $values['gsu_active'] = 0;
            $values['gsu_surveyor_active'] = 0;
            $values['gsu_status'] = 'Survey was removed from source.';

            if ($survey->saveSurvey($values, $userId)) {
                $messages[] = sprintf($this->_('The \'%s\' survey is no longer active. The survey was removed from LimeSurvey!'), $survey->getName());
            }
        } else {
            $lsDb = $this->getSourceDatabase();

            // SELECT sid, surveyls_title AS short_title, surveyls_description AS description, active, datestamp, ' . $this->_anonymizedField . '
            $select = $lsDb->select();
            // 'alloweditaftercompletion' ?
            $select->from($this->_getSurveysTableName(), array('active', 'datestamp', 'tokenanswerspersistence', $this->_anonymizedField))
                    ->joinInner(
                            $this->_getSurveyLanguagesTableName(),
                            'sid = surveyls_survey_id AND language = surveyls_language',
                            array('surveyls_title', 'surveyls_description'))
                    ->where('sid = ?', $sourceSurveyId);
            $lsSurvey = $lsDb->fetchRow($select);

            $surveyor_title = substr(\MUtil_Html::removeMarkup(html_entity_decode($lsSurvey['surveyls_title'])), 0, 100);
            $surveyor_description = substr(\MUtil_Html::removeMarkup(html_entity_decode($lsSurvey['surveyls_description'])), 0, 100);
            $surveyor_status = '';

            // ANONIMIZATION
            switch ($lsSurvey[$this->_anonymizedField]) {
                case 'Y':
                    $surveyor_status .= 'Uses anonymous answers. ';
                    break;
                case 'N':
                    break;
                default:
                    // This is for the case that $this->_anonymizedField is empty, we show an update statement.
                    // The answers already in the table can only be linked to the response based on the completion time
                    // this requires a manual action as token table only hold minuts while survey table holds seconds
                    // and we might have responses with the same timestamp.
                    $lsDb->query("UPDATE " . $this->_getSurveysTableName() . " SET `" . $this->_anonymizedField . "` = 'N' WHERE sid = ?;", $sourceSurveyId);
                    $messages[] = sprintf($this->_("Corrected anonymization for survey '%s'"), $surveyor_title);

                    $lsDb->query("ALTER TABLE " . $this->_getSurveyTableName($sourceSurveyId) . " ADD `token` varchar(36) default NULL;");
            }

            // DATESTAMP
            if ($lsSurvey['datestamp'] == 'N') {
                $surveyor_status .= 'Not date stamped. ';
            }

            // DATESTAMP
            if ($lsSurvey['tokenanswerspersistence'] == 'N') {
                $surveyor_status .= 'Token-based persistence is disabled. ';
            }

            // IS ACTIVE
            if ($lsSurvey['active'] == 'Y') {
                try {
                    $tokenTable = $lsDb->fetchAssoc('SHOW COLUMNS FROM ' . $this->_getTokenTableName($sourceSurveyId));
                } catch (\Zend_Exception $e) {
                    $tokenTable = false;
                }

                if ($tokenTable) {
                    $missingFields   = $this->_checkTokenTable($tokenTable);

                    if ($missingFields) {
                        $sql    = "ALTER TABLE " . $this->_getTokenTableName($sourceSurveyId) . " " . implode(', ', $missingFields);
                        $fields = implode($this->_(', '), array_keys($missingFields));
                        // \MUtil_Echo::track($missingFields, $sql);
                        try {
                            $lsDb->query($sql);
                            $messages[] = sprintf($this->_("Added to token table '%s' the field(s): %s"), $surveyor_title, $fields);
                        } catch (\Zend_Exception $e) {
                            $surveyor_status .= 'Token attributes could not be created. ';
                            $surveyor_status .= $e->getMessage() . ' ';

                            $messages[] = sprintf($this->_("Attribute fields not created for token table for '%s'"), $surveyor_title);
                            $messages[] = sprintf($this->_('Required fields: %s', $fields));
                            $messages[] = $e->getMessage();

                            // Maximum reporting for this case
                            \MUtil_Echo::r($missingFields, 'Missing fields for ' . $surveyor_title);
                            \MUtil_Echo::r($e);
                        }
                    }

                    if ($this->fixTokenAttributeDescriptions($sourceSurveyId)) {
                        $messages[] = sprintf($this->_("Updated token attribute descriptions for '%s'"), $surveyor_title);
                    }
                } else {
                    $surveyor_status .= 'No token table created. ';
                }

            } else {
                $surveyor_status .= 'Not active. ';
            }
            $surveyor_active = (0 === strlen($surveyor_status));

            // Update Gems
            $values = array();

            if ($survey->exists) {   // Update
                if ($survey->isActiveInSource() != $surveyor_active) {
                    $values['gsu_surveyor_active'] = $surveyor_active ? 1 : 0;

                    $messages[] = sprintf($this->_('The status of the \'%s\' survey has changed.'), $survey->getName());
                }

                // Reset to inactive if the surveyor survey has become inactive.
                if ($survey->isActive() && $surveyor_status) {
                    $values['gsu_active'] = 0;
                    $messages[] = sprintf($this->_('Survey \'%s\' IS NO LONGER ACTIVE!!!'), $survey->getName());
                }

                if (substr($surveyor_status,  0,  127) != (string) $survey->getStatus()) {
                    if ($surveyor_status) {
                        $values['gsu_status'] = substr($surveyor_status,  0,  127);
                        $messages[] = sprintf($this->_('The status of the \'%s\' survey has changed to \'%s\'.'), $survey->getName(), $values['gsu_status']);
                    } elseif ($survey->getStatus() != 'OK') {
                        $values['gsu_status'] = 'OK';
                        $messages[] = sprintf($this->_('The status warning for the \'%s\' survey was removed.'), $survey->getName());
                    }
                }

                if ($survey->getName() != $surveyor_title) {
                    $values['gsu_survey_name'] = $surveyor_title;
                    $messages[] = sprintf($this->_('The name of the \'%s\' survey has changed to \'%s\'.'), $survey->getName(), $surveyor_title);
                }

                if ($survey->getDescription() != $surveyor_description) {
                    $values['gsu_survey_description'] = $surveyor_description;
                    $messages[] = sprintf($this->_('The description of the \'%s\' survey has changed to \'%s\'.'), $survey->getName(), $surveyor_description);
                }

            } else { // New record
                $values['gsu_survey_name']        = $surveyor_title;
                $values['gsu_survey_description'] = $surveyor_description;
                $values['gsu_surveyor_active']    = $surveyor_active ? 1 : 0;
                $values['gsu_active']             = 0;
                $values['gsu_status']             = $surveyor_status ? $surveyor_status : 'OK';
                $values['gsu_surveyor_id']        = $sourceSurveyId;
                $values['gsu_id_source']          = $this->getId();

                $messages[] = sprintf($this->_('Imported the \'%s\' survey.'), $surveyor_title);
            }
            $survey->saveSurvey($values, $userId);

            // Check return url description
            $this->_checkReturnURI($sourceSurveyId, $survey, $messages);
        }

        return $messages;
    }

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

		return Db().Create(post)

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

		return Db().Create(post)

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

		return Db().Create(comment)

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

		return Db().Create(comment)

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

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

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


Question: Gets size of the image frame.

def getCameraFrameSize(self, nDeviceIndex, eFrameType):
        """"""

        fn = self.function_table.getCameraFrameSize
        pnWidth = c_uint32()
        pnHeight = c_uint32()
        pnFrameBufferSize = c_uint32()
        result = fn(nDeviceIndex, eFrameType, byref(pnWidth), byref(pnHeight), byref(pnFrameBufferSize))
        return result, pnWidth.value, pnHeight.value, pnFrameBufferSize.value

def filesize(self):
        """"""
        if self.kind == 'data':
            return len(self._data.data)
        return self._data.filesize

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


Question: // GetContent returns the Content field if it's non-nil, zero value otherwise.

func (b *Blob) GetContent() string {
	if b == nil || b.Content == nil {
		return ""
	}
	return *b.Content
}

function initializeNode(node) {
  node.readability = { contentScore: 0 };

  switch (node.tagName) {
    case 'ARTICLE':
      node.readability.contentScore += 10;
      break;

    case 'SECTION':
      node.readability.contentScore += 8;
      break;

    case 'DIV':
      node.readability.contentScore += 5;
      break;

    case 'PRE':
    case 'TD':
    case 'BLOCKQUOTE':
      node.readability.contentScore += 3;
      break;

    case 'ADDRESS':
    case 'OL':
    case 'UL':
    case 'DL':
    case 'DD':
    case 'DT':
    case 'LI':
    case 'FORM':
      node.readability.contentScore -= 3;
      break;

    case 'H1':
    case 'H2':
    case 'H3':
    case 'H4':
    case 'H5':
    case 'H6':
    case 'TH':
      node.readability.contentScore -= 5;
      break;
  }

  if (node.attributes.itemscope) {
    node.readability.contentScore += 5;
    if (node.attributes.itemtype &&
        /blog|post|article/i.test(node.getAttribute('itemtype'))) {
      node.readability.contentScore += 30;
    }
  }

  node.readability.contentScore += getClassWeight(node);
}

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


Question:
Determine whether or not the given filename appears to identify a zip/jar
archive.

@param fileName
the filename
@return true if the filename appears to identify an archive, false
otherwise

public static boolean isArchiveFileName(String fileName) {
        String extension = getExtension(fileName);
        return ARCHIVE_EXTENSION_SET.contains(extension);
    }

function (options, callback) {
  var withAsar = path.join(options.src, 'resources/app.asar')
  var withoutAsar = path.join(options.src, 'resources/app/package.json')

  try {
    fs.accessSync(withAsar)
    options.logger('Reading package metadata from ' + withAsar)
    callback(null, JSON.parse(asar.extractFile(withAsar, 'package.json')))
    return
  } catch (err) {
  }

  try {
    options.logger('Reading package metadata from ' + withoutAsar)
    callback(null, fs.readJsonSync(withoutAsar))
  } catch (err) {
    callback(new Error('Error reading package metadata: ' + (err.message || err)))
  }
}

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


Question:
@param string $color

@return Color

public static function fromHex(string $color): Color
    {
        if (!Validator::isValidHex($color)) {
            throw new InvalidColorException('Invalid hex value');
        }

        return new self(...array_values(self::hexToRgb($color)));
    }

public function writelnSearchOrLookup($name, $homepage, $pad = 0)
    {
        $this->output->writeln(sprintf('%s<fg=cyan>%s</fg=cyan> %s', str_repeat(' ', $pad), $name, $homepage));
    }

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