Question: Each subdir in {@link DatasetsFinder#inputDir} is considered a dataset, if it satisfies blacklist and whitelist.

@Override
  public Set<Dataset> findDistinctDatasets() throws IOException {
    Set<Dataset> datasets = Sets.newHashSet();
    for (FileStatus datasetsFileStatus : this.fs.globStatus(new Path(inputDir, subDirPattern))) {
      log.info("Scanning directory : " + datasetsFileStatus.getPath().toString());
      if (datasetsFileStatus.isDirectory()) {
        String datasetName = getDatasetName(datasetsFileStatus.getPath().toString(), inputDir);
        if (DatasetFilterUtils.survived(datasetName, this.blacklist, this.whitelist)) {
          log.info("Found dataset: " + datasetName);
          Path inputPath = new Path(this.inputDir, new Path(datasetName, this.inputSubDir));
          Path inputLatePath = new Path(this.inputDir, new Path(datasetName, this.inputLateSubDir));
          Path outputPath = new Path(this.destDir, new Path(datasetName, this.destSubDir));
          Path outputLatePath = new Path(this.destDir, new Path(datasetName, this.destLateSubDir));
          Path outputTmpPath = new Path(this.tmpOutputDir, new Path(datasetName, this.destSubDir));
          double priority = this.getDatasetPriority(datasetName);

          String folderStructure = getFolderStructure();
          for (FileStatus status : this.fs.globStatus(new Path(inputPath, folderStructure))) {
            Path jobInputPath = status.getPath();
            DateTime folderTime = null;
            try {
              folderTime = getFolderTime(jobInputPath, inputPath);
            } catch (RuntimeException e) {
              log.warn("{} is not a valid folder. Will be skipped due to exception.", jobInputPath, e);
              continue;
            }

            if (folderWithinAllowedPeriod(jobInputPath, folderTime)) {
              Path jobInputLatePath = appendFolderTime(inputLatePath, folderTime);
              Path jobOutputPath = appendFolderTime(outputPath, folderTime);
              Path jobOutputLatePath = appendFolderTime(outputLatePath, folderTime);
              Path jobOutputTmpPath = appendFolderTime(outputTmpPath, folderTime);

              Dataset timeBasedDataset = new Dataset.Builder().withPriority(priority)
                  .withDatasetName(datasetName)
                  .addInputPath(this.recompactDatasets ? jobOutputPath : jobInputPath)
                  .addInputLatePath(this.recompactDatasets ? jobOutputLatePath : jobInputLatePath)
                  .withOutputPath(jobOutputPath).withOutputLatePath(jobOutputLatePath)
                  .withOutputTmpPath(jobOutputTmpPath).build();
              // Stores the extra information for timeBasedDataset
              timeBasedDataset.setJobProp(MRCompactor.COMPACTION_JOB_DEST_PARTITION,
                  folderTime.toString(this.timeFormatter));
              timeBasedDataset.setJobProp(MRCompactor.COMPACTION_INPUT_PATH_TIME, folderTime.getMillis());
              datasets.add(timeBasedDataset);
            }
          }
        }
      }
    }
    return datasets;
  }

def handle_import(self, name, compilation, rule):

        original_path = PurePath(name)

        search_exts = list(compilation.compiler.dynamic_extensions)
        if original_path.suffix and original_path.suffix in search_exts:
            basename = original_path.stem
        else:
            basename = original_path.name

        if original_path.is_absolute():
            # Remove the beginning slash
            search_path = original_path.relative_to('/').parent
        elif rule.source_file.origin:
            search_path = rule.source_file.origin
            if original_path.parent:
                search_path = os.path.normpath(str(search_path / original_path.parent))
        else:
            search_path = original_path.parent

        for prefix, suffix in product(('_', ''), search_exts):
            filename = PurePath(prefix + basename + suffix)

            full_filename, storage = get_file_and_storage(str(search_path / filename))

            if full_filename:
                with storage.open(full_filename) as f:
                    return SourceFile.from_file(f, origin=search_path, relpath=filename)

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


Question: // StringNotEmpty checks to ensure the given string is not empty.

func StringNotEmpty(obtained, paramName string) Checker {
	return func() (isNotEmpty bool, errMsg string) {
		isNotEmpty = obtained != ""
		errMsg = fmt.Sprintf("Parameter is an empty string: %s", paramName)
		return
	}
}

def isemptyfile(filepath):

    exists = os.path.exists(safepath(filepath))
    if exists:
        filesize = os.path.getsize(safepath(filepath))
        return filesize == 0
    else:
        return False

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


Question:
Assign display group to a display group.

@param array|int $displayGroupId The Display Group ID to assign
@return XiboDisplayGroup

public function assignDisplayGroup($displayGroupId)
    {
        $this->getLogger()->info('Assigning display Group ID ' . json_encode($displayGroupId) . ' To display Group ID ' . $this->displayGroupId);
        $this->doPost('/displaygroup/' . $this->displayGroupId . '/displayGroup/assign', [
        'displayGroupId' => $displayGroupId
        ]);
        return $this;
    }

protected function marshall(QtiComponent $component)
    {
        $element = parent::marshall($component);

        $this->setDOMElementAttribute($element, 'href', $component->getHref());

        // Deal with categories.
        $categories = $component->getCategories();
        if (count($categories) > 0) {
            $this->setDOMElementAttribute($element, 'category', implode("\x20", $categories->getArrayCopy()));
        }

        // Deal with variableMappings.
        $variableMappings = $component->getVariableMappings();
        foreach ($variableMappings as $mapping) {
            $marshaller = $this->getMarshallerFactory()->createMarshaller($mapping);
            $element->appendChild($marshaller->marshall($mapping));
        }

        // Deal with weights.
        $weights = $component->getWeights();
        foreach ($weights as $weight) {
            $marshaller = $this->getMarshallerFactory()->createMarshaller($weight);
            $element->appendChild($marshaller->marshall($weight));
        }

        // Deal with templateDefaults.
        $templateDefaults = $component->getTemplateDefaults();
        foreach ($templateDefaults as $default) {
            $marshaller = $this->getMarshallerFactory()->createMarshaller($default);
            $element->appendChild($marshaller->marshall($default));
        }

        return $element;
    }

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


Question:
// newTerminalPrompter creates a liner based user input prompter working off the
// standard input and output streams.

func newTerminalPrompter() *terminalPrompter {
	p := new(terminalPrompter)
	// Get the original mode before calling NewLiner.
	// This is usually regular "cooked" mode where characters echo.
	normalMode, _ := liner.TerminalMode()
	// Turn on liner. It switches to raw mode.
	p.State = liner.NewLiner()
	rawMode, err := liner.TerminalMode()
	if err != nil || !liner.TerminalSupported() {
		p.supported = false
	} else {
		p.supported = true
		p.normalMode = normalMode
		p.rawMode = rawMode
		// Switch back to normal mode while we're not prompting.
		normalMode.ApplyMode()
	}
	p.SetCtrlCAborts(true)
	p.SetTabCompletionStyle(liner.TabPrints)
	p.SetMultiLineMode(true)
	return p
}

def _endpoint_from_socksport_line(reactor, socks_config):

    if socks_config.startswith('unix:'):
        # XXX wait, can SOCKSPort lines with "unix:/path" still
        # include options afterwards? What about if the path has a
        # space in it?
        return UNIXClientEndpoint(reactor, socks_config[5:])

    # options like KeepAliveIsolateSOCKSAuth can be appended
    # to a SocksPort line...
    if ' ' in socks_config:
        socks_config = socks_config.split()[0]
    if ':' in socks_config:
        host, port = socks_config.split(':', 1)
        port = int(port)
    else:
        host = '127.0.0.1'
        port = int(socks_config)
    return TCP4ClientEndpoint(reactor, host, port)

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


Question:
Filters the bundle to render

@param bundles
the list of bundles
@return the list of filtered bundle

protected List<JoinableResourceBundle> filterBundlesToRender(List<JoinableResourceBundle> bundles) {
		List<JoinableResourceBundle> filteredBundles = new ArrayList<>();
		for (JoinableResourceBundle bundle : bundles) {
			if (!bundle.getInclusionPattern().isIncludeOnlyOnDebug()) {
				filteredBundles.add(bundle);
			}
		}
		return filteredBundles;
	}

def notes(element_key)
      parameter = { basic_auth: @auth }

      response = self.class.get("/elements/#{element_key}/notes", parameter)
      if response.success?
        search_response_header = SearchResponseHeader.new(response)
        search_response_header.elementList
      end
    end

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


Question:
Copy of all values of the root object.

@param pvRootObject Source object, that will be copy.
@return The copy of the source object.

public Object copy(final Object pvRootObject) {
		Object lvSimple = makeSimple(pvRootObject);
		Object lvComplex = makeComplex(lvSimple);
		return lvComplex;
	}

public void marshall(DescribeRootFoldersRequest describeRootFoldersRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeRootFoldersRequest.getAuthenticationToken(), AUTHENTICATIONTOKEN_BINDING);
            protocolMarshaller.marshall(describeRootFoldersRequest.getLimit(), LIMIT_BINDING);
            protocolMarshaller.marshall(describeRootFoldersRequest.getMarker(), MARKER_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:
// NewDefault builds a new report indexing the last sample value
// available.

func NewDefault(prof *profile.Profile, options Options) *Report {
	index := len(prof.SampleType) - 1
	o := &options
	if o.Title == "" && len(prof.Mapping) > 0 && prof.Mapping[0].File != "" {
		o.Title = filepath.Base(prof.Mapping[0].File)
	}
	o.SampleType = prof.SampleType[index].Type
	o.SampleUnit = strings.ToLower(prof.SampleType[index].Unit)
	o.SampleValue = func(v []int64) int64 {
		return v[index]
	}
	return New(prof, o)
}

def _init_metadata(self):
        """"""

        # pylint: disable=attribute-defined-outside-init
        # this method is called from descendent __init__
        self._mdata.update(default_mdata.get_osid_form_mdata())
        update_display_text_defaults(self._mdata['journal_comment'], self._locale_map)
        for element_name in self._mdata:
            self._mdata[element_name].update(
                {'element_id': Id(self._authority,
                                  self._namespace,
                                  element_name)})
        self._journal_comment_default = self._mdata['journal_comment']['default_string_values'][0]
        self._validation_messages = {}

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


Question: Return the given template string rendered using the given context.

def render(template, context=None, **kwargs):

    renderer = Renderer()
    return renderer.render(template, context, **kwargs)

protected function compileTemplate($fileName)
    {
        try {
            $this->
                twigView->
                getTwig()->
                loadTemplate($fileName);
            $this->out('<success>' . $fileName . '</success>');
        } catch (\Exception $exception) {
            $this->out('<error>' . $fileName . '</error>');
            $this->out('<error>' . $exception->getMessage() . '</error>');
        }
    }

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


Question:
Select a fresh range of date including first day and last day.

@param firstDay first day of the range to select
@param lastDay last day of the range to select

public void selectRange(final CalendarDay firstDay, final CalendarDay lastDay) {
    if (firstDay == null || lastDay == null) {
      return;
    } else if (firstDay.isAfter(lastDay)) {
      adapter.selectRange(lastDay, firstDay);
      dispatchOnRangeSelected(adapter.getSelectedDates());
    } else {
      adapter.selectRange(firstDay, lastDay);
      dispatchOnRangeSelected(adapter.getSelectedDates());
    }
  }

private function addSelectionMethod(QueryBuilderResult $query, $methodName)
    {
        $findMethod = function () use ($query, $methodName) {

            $sth = $this->pdo->prepare($query->getSql());
            /** @noinspection PhpMethodParametersCountMismatchInspection */
            $sth->setFetchMode(\PDO::FETCH_CLASS, $this->entityClass->getName());
            try {
                $sth->execute(func_get_args());
            } catch (PDOException $e) {
                throw new DslSyntaxException('Failed to run query [' . $methodName . '] with parameters ' . print_r(func_get_args(), true));
            }

            switch ($query->getResultMode()) {
                case QueryBuilderResult::RESULT_SELECT_SINGLE:
                    return $sth->fetch();
                case QueryBuilderResult::RESULT_SELECT_MULTIPLE:
                    return $sth->fetchAll();
            }

            throw new DslSyntaxException('Result Mode ' . $query->getResultMode() . ' is not implemented', DATADO_ILLEGAL_RESULT_MODE);

        };

        $this->methods[$methodName] = \Closure::bind($findMethod, $this, get_class());
    }

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


Question: // hasUserDefinedIPAddress returns whether the passed IPAM configuration contains IP address configuration

func hasUserDefinedIPAddress(ipamConfig *networktypes.EndpointIPAMConfig) bool {
	return ipamConfig != nil && (len(ipamConfig.IPv4Address) > 0 || len(ipamConfig.IPv6Address) > 0)
}

def stop_accepting_passive_host_checks(self):

        if self.my_conf.accept_passive_host_checks:
            self.my_conf.modified_attributes |= DICT_MODATTR["MODATTR_PASSIVE_CHECKS_ENABLED"].value
            self.my_conf.accept_passive_host_checks = False
            self.my_conf.explode_global_conf()
            self.daemon.update_program_status()

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


Question: Load library by searching possible path.

def _load_lib():
    """"""
    lib_path = libinfo.find_lib_path()
    lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL)
    # DMatrix functions
    lib.MXGetLastError.restype = ctypes.c_char_p
    return lib

public static function getKnownLanguages($basePath = JPATH_ROOT)
	{
		$dir = self::getLanguagePath($basePath);
		$knownLanguages = self::parseLanguageFiles($dir);

		return $knownLanguages;
	}

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


Question: Отключить модуль

public function disable()
    {
		$a = Application::getInstance();
		$md = $a->getVar('module_disable');
		$md[$this->name] = 1;
		$a->setVar('module_disable', $md);
    }

public function boot() {
		$this->emitter = new Emitter;
		$this->query = new QueryRepository();
		//Busca las acciones definidas en el plugin y las agrega como acciones de Wordpress
		$this->add_actions();
		add_action('cmb2_admin_init', array($this, 'add_metaboxes'), 1000);
	}

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


Question:
Returns the position of the element in the set. Execute a binary search since the elements are always ordered.

@param iElement
element to find
@return The position of the element if found, otherwise false

public int indexOf(final OIdentifiable iElement) {
		if (delegate.isEmpty())
			return -1;

		final boolean prevConvert = delegate.isAutoConvertToRecord();
		if (prevConvert)
			delegate.setAutoConvertToRecord(false);

		final int pos = Collections.binarySearch(delegate, iElement);

		if (prevConvert)
			// RESET PREVIOUS SETTINGS
			delegate.setAutoConvertToRecord(true);

		return pos;
	}

public static void configureQueryOptions(DatabaseClient client)
    throws FailedRequestException, ForbiddenUserException, ResourceNotFoundException, ResourceNotResendableException
  {
    // create a manager for writing query options
    QueryOptionsManager optionsMgr = client.newServerConfigManager().newQueryOptionsManager();

    // create the query options
    String options =
      "<search:options "+
        "xmlns:search='http://marklogic.com/appservices/search'>"+
        "<search:constraint name='industry'>"+
        "<search:value>"+
        "<search:element name='industry' ns=''/>"+
        "</search:value>"+
        "</search:constraint>"+
        "<search:return-aggregates>false</search:return-aggregates>"+
        "<search:return-constraints>false</search:return-constraints>"+
        "<search:return-facets>false</search:return-facets>"+
        "<search:return-frequencies>false</search:return-frequencies>"+
        "<search:return-metrics>false</search:return-metrics>"+
        "<search:return-plan>false</search:return-plan>"+
        "<search:return-qtext>false</search:return-qtext>"+
        "<search:return-query>false</search:return-query>"+
        "<search:return-similar>true</search:return-similar>"+
        "<search:return-values>false</search:return-values>"+
        "<search:return-results>false</search:return-results>"+
        "<search:transform-results apply='empty-snippet'/>"+
        "</search:options>";

    // create a handle to send the query options
    StringHandle writeHandle = new StringHandle(options);

    // write the query options to the database
    optionsMgr.writeOptions(OPTIONS_NAME, writeHandle);

    System.out.println("Configured the query options on the server");
  }

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


Question: minutes : {epoch => minute object}

def schedule_cycles(minutes,location_id,conditions = {})

			products = Auth.configuration.product_class.constantize.all if conditions.blank?

			products = Auth.configuration.product_class.constantize.where(conditions) if !conditions.blank?

			minutes.keys.each do |epoch|

				products.each do |product|

					all_cycles_valid = true
					product.cycles.each do |cycle|

						all_cycles_valid = cycle.requirements_satisfied(epoch + cycle.time_since_prev_cycle.minutes*60,location_id)

					end

					## just because the cycles are valid, it means we have workers, but how many?
					## that also has to be returned by the cycle validity statements

					if all_cycles_valid == true
						cycle_chain = []
						product.cycles.each do |cycle|
							epoch_at_which_to_add = epoch + cycle.time_since_prev_cycle.minutes*60
							cycle_to_add = cycle.dup
							cycle_to_add.start_time = epoch_at_which_to_add
							cycle_to_add.end_time = cycle_to_add.start_time + cycle_to_add.duration
							cycle_to_add.cycle_chain = cycle_chain
							if minutes[epoch_at_which_to_add]

								add_to_previous_rolling_n_minutes(minutes,epoch_at_which_to_add,cycle_to_add)

								minutes[epoch_at_which_to_add].cycles << cycle_to_add

								cycle_chain << cycle_to_add.id.to_s
							else
								#raise "necessary minute not in range."
							end
						end
					end
				end
			end
			minutes
		end

def archive_sciobj(pid):

    sciobj_model = d1_gmn.app.model_util.get_sci_model(pid)
    sciobj_model.is_archived = True
    sciobj_model.save()
    _update_modified_timestamp(sciobj_model)

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


Question:
// Options mocks base method
// nolint

func (m *MockRuntimeReader) Options() policy.OptionsType {
	ret := m.ctrl.Call(m, "Options")
	ret0, _ := ret[0].(policy.OptionsType)
	return ret0
}

func NotMultipleOf(name, in string, multiple interface{}) *Validation {
	var msg string
	if in == "" {
		msg = fmt.Sprintf(multipleOfFailNoIn, name, multiple)
	} else {
		msg = fmt.Sprintf(multipleOfFail, name, in, multiple)
	}
	return &Validation{
		code:    MultipleOfFailCode,
		Name:    name,
		In:      in,
		Value:   multiple,
		message: msg,
	}
}

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


Question: Decide if we should launch a browser

def launch_browser(attempt_launch_browser=True):
    """"""
    _DISPLAY_VARIABLES = ['DISPLAY', 'WAYLAND_DISPLAY', 'MIR_SOCKET']
    _WEBBROWSER_NAMES_BLACKLIST = [
        'www-browser', 'lynx', 'links', 'elinks', 'w3m']

    import webbrowser

    launch_browser = attempt_launch_browser
    if launch_browser:
        if ('linux' in sys.platform and
                not any(os.getenv(var) for var in _DISPLAY_VARIABLES)):
            launch_browser = False
        try:
            browser = webbrowser.get()
            if (hasattr(browser, 'name')
                    and browser.name in _WEBBROWSER_NAMES_BLACKLIST):
                launch_browser = False
        except webbrowser.Error:
            launch_browser = False

    return launch_browser

def detect_firefox_o_s_phone()

      if (detect_ios() || detect_android() || detect_sailfish())
        return false
      end

      if ((user_agent.include?(ENGINE_FIREFOX)) && (user_agent.include?(MOBILE)))
        return true
      end

      return false
    end

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


Question: draw a string in bold

def bold_print(text)
      text.split(//).each do |ch|
        print ch, BS, ch
      end
    end

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.


Question: Set the value of a variable

def set_value(self, name, value, PY2_frontend):
        """"""
        import cloudpickle
        ns = self._get_reference_namespace(name)

        # We send serialized values in a list of one element
        # from Spyder to the kernel, to be able to send them
        # at all in Python 2
        svalue = value[0]

        # We need to convert svalue to bytes if the frontend
        # runs in Python 2 and the kernel runs in Python 3
        if PY2_frontend and not PY2:
            svalue = bytes(svalue, 'latin-1')

        # Deserialize and set value in namespace
        dvalue = cloudpickle.loads(svalue)
        ns[name] = dvalue
        self.log.debug(ns)

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: // OnStop implements cmn.Service by unsubscribing from all transactions.

func (is *IndexerService) OnStop() {
	if is.eventBus.IsRunning() {
		_ = is.eventBus.UnsubscribeAll(context.Background(), subscriber)
	}
}

def _cleanup(self):
        '''

        '''
        self._pending_consumers = None
        self._consumer_cb = None
        self._get_cb = None
        self._recover_cb = None
        self._cancel_cb = None
        self._return_listener = None
        super(BasicClass, self)._cleanup()

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


Question: Helper to get the log messages from the shader compiler.

private static boolean printLogInfo(int obj) {
        IntBuffer iVal = BufferUtils.createIntBuffer(1);
        ARBShaderObjects.glGetObjectParameterARB(obj,
                ARBShaderObjects.GL_OBJECT_INFO_LOG_LENGTH_ARB, iVal);

        int length = iVal.get();
        if (length > 1) {
            // We have some info we need to output.
            ByteBuffer infoLog = BufferUtils.createByteBuffer(length);
            iVal.flip();
            ARBShaderObjects.glGetInfoLogARB(obj, iVal, infoLog);
            byte[] infoBytes = new byte[length];
            infoLog.get(infoBytes);
            String out = new String(infoBytes);
            System.out.println("Info log:\n" + out);
        } else {
            return true;
        }
        return false;
    }

public static br_configuresyslog[] configuresyslog(nitro_service client, br_configuresyslog[] resources) throws Exception
	{
		if(resources == null)
			throw new Exception("Null resource array");

		if(resources.length == 1)
			return ((br_configuresyslog[]) resources[0].perform_operation(client, "configuresyslog"));

		return ((br_configuresyslog[]) perform_operation_bulk_request(client, resources, "configuresyslog"));
	}

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


Question:
delete(filething)

    Arguments:
        filething (filething)
    Raises:
        mutagen.MutagenError

    Remove tags from a file.

def delete(filething):

    t = OggOpus(filething)
    filething.fileobj.seek(0)
    t.delete(filething)

def _write_wiki_pages(
            self):

        self.log.debug('starting the ``_write_wiki_pages`` method')

        pathToWriteFile = self.settings[
            "sherlock wiki root"] + "/Crossmatch-Catalogue Tables.md"
        writeFile = codecs.open(pathToWriteFile, encoding='utf-8', mode='w')
        now = datetime.now()
        now = now.strftime("%Y-%m-%d %H:%M")
        lastUpdated = """Last Updated %(now)s
""" % locals()

        writeFile.write(lastUpdated + self.mdTables)
        writeFile.close()

        pathToWriteFile = self.settings[
            "sherlock wiki root"] + "/Crossmatch-Catalogue Views.md"
        writeFile = codecs.open(pathToWriteFile, encoding='utf-8', mode='w')
        now = datetime.now()
        now = now.strftime("%Y-%m-%d %H:%M")
        lastUpdated = """Last Updated %(now)s
""" % locals()

        writeFile.write(lastUpdated + self.mdViews)
        writeFile.close()

        pathToWriteFile = self.settings[
            "sherlock wiki root"] + "/Crossmatch-Catalogue Streams.md"
        writeFile = codecs.open(pathToWriteFile, encoding='utf-8', mode='w')
        now = datetime.now()
        now = now.strftime("%Y-%m-%d %H:%M")
        lastUpdated = """Last Updated %(now)s
""" % locals()

        writeFile.write(lastUpdated + self.mdStreams)
        writeFile.close()

        self.log.debug('completed the ``_write_wiki_pages`` method')
        return None

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


Question:
Add a service to this server.

@param serviceDefinition the service definition of new service
@return an updated instance of this {@link GrpcServerBuilder}

public GrpcServerBuilder addService(GrpcService serviceDefinition) {
    ServerServiceDefinition service = serviceDefinition.getServiceDefinition();
    if (SecurityUtils.isAuthenticationEnabled(mConfiguration)
        && serviceDefinition.isAuthenticated()) {
      // Intercept the service with authenticated user injector.
      service = ServerInterceptors.intercept(service,
          new AuthenticatedUserInjector(mAuthenticationServer));
    }
    mNettyServerBuilder = mNettyServerBuilder.addService(service);
    return this;
  }

public function start($argument, $metadata, $options)
    {
        $channel_ref = $this->_rpcPreProcess($argument);
        $real_channel = $channel_ref->getRealChannel($this->gcp_channel->credentials);
        $this->createRealCall($real_channel);
        $this->real_call->start($argument, $metadata, $options);
    }

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


Question: // SetUser sets the User field's value.

func (s *DescribeUserOutput) SetUser(v *DescribedUser) *DescribeUserOutput {
	s.User = 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:
findPostingsForAccount

@author Tom Haskins-Vaughan <tom@harvestcloud.com>
@since  2013-02-06

@param  Account $account

@return array

public function findPostingsForAccount(Account $account)
    {
        $q = $this->getEntityManager()->createQuery('

            SELECT     p
            FROM       HarvestCloudCoreBundle:Posting p
            WHERE      p.account = :account

        ')->setParameter('account', $account);

        return $q->getResult();
    }

def create_user(username, password)
      new_action = { 'UserName' => username, 'Password' => password, 'Oem' => { 'Hp' => { 'LoginName' => username } } }
      response = rest_post('/redfish/v1/AccountService/Accounts/', body: new_action)
      response_handler(response)
      true
    end

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


Question: Parses relative to Easter Sunday holidays.

public void parse (final int nYear, final HolidayMap aHolidayMap, final Holidays aConfig)
  {
    for (final RelativeToEasterSunday aDay : aConfig.getRelativeToEasterSunday ())
    {
      if (!isValid (aDay, nYear))
        continue;
      final ChronoLocalDate aEasterSunday = getEasterSunday (nYear, aDay.getChronology ());
      aEasterSunday.plus (aDay.getDays (), ChronoUnit.DAYS);
      final String sPropertiesKey = "christian." + aDay.getDescriptionPropertiesKey ();
      addChrstianHoliday (aEasterSunday,
                          sPropertiesKey,
                          XMLHolidayHelper.getType (aDay.getLocalizedType ()),
                          aHolidayMap);
    }
  }

def hamsterday_time_to_datetime(hamsterday, time):

    # work around cyclic imports
    from hamster.lib.configuration import conf

    if time < conf.day_start:
        # early morning, between midnight and day_start
        # => the hamster day is the previous civil day
        civil_date = hamsterday + dt.timedelta(days=1)
    else:
        civil_date = hamsterday
    return dt.datetime.combine(civil_date, time)

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


Question: Save Github settings.

public function github()
    {
        $this->requireAdmin();

        $this->settings['phpci']['github']['id']     = $this->getParam('githubid', '');
        $this->settings['phpci']['github']['secret'] = $this->getParam('githubsecret', '');
        $error                                       = $this->storeSettings();

        $response = new b8\Http\Response\RedirectResponse();

        if ($error) {
            $response->setHeader('Location', PHPCI_URL . 'settings?saved=2');
        } else {
            $response->setHeader('Location', PHPCI_URL . 'settings?saved=1');
        }

        return $response;
    }

func GetConfig(project string) ([]byte, error) {
	var path string
	if runtime.GOOS == "windows" {
		path = os.Getenv("HOMEPATH")
	} else {
		path = os.Getenv("HOME")
	}
	path = path + string(filepath.Separator) + "." + project
	fileandpath := path + string(filepath.Separator) + "config.json"
	file, err := os.Open(fileandpath)
	if err != nil {
		return []byte{}, err
	}
	return ioutil.ReadAll(file)
}

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


Question: // Print returns an array of strings suitable for printing the store limits.

func (sl *StoreLimits) Print() []string {
	sublist := util.NewSublist()
	for cn, cl := range sl.PerChannel {
		sublist.Insert(cn, &channelLimitInfo{
			name:      cn,
			limits:    cl,
			isLiteral: util.IsChannelNameLiteral(cn),
		})
	}
	maxLevels := sublist.NumLevels()
	txt := []string{}
	title := "---------- Store Limits ----------"
	txt = append(txt, title)
	txt = append(txt, fmt.Sprintf("Channels:        %s",
		getLimitStr(true, int64(sl.MaxChannels),
			int64(DefaultStoreLimits.MaxChannels),
			limitCount)))
	maxLen := len(title)
	txt = append(txt, "--------- Channels Limits --------")
	txt = append(txt, getGlobalLimitsPrintLines(&sl.ChannelLimits)...)
	if len(sl.PerChannel) > 0 {
		channels := sublist.Subjects()
		channelLines := []string{}
		for _, cn := range channels {
			r := sublist.Match(cn)
			var prev *channelLimitInfo
			for i := 0; i < len(r); i++ {
				channel := r[i].(*channelLimitInfo)
				if channel.name == cn {
					var parentLimits *ChannelLimits
					if prev == nil {
						parentLimits = &sl.ChannelLimits
					} else {
						parentLimits = prev.limits
					}
					channelLines = append(channelLines,
						getChannelLimitsPrintLines(i, maxLevels, &maxLen, channel.name, channel.limits, parentLimits)...)
					break
				}
				prev = channel
			}
		}
		title := " List of Channels "
		numberDashesLeft := (maxLen - len(title)) / 2
		numberDashesRight := maxLen - len(title) - numberDashesLeft
		title = fmt.Sprintf("%s%s%s",
			repeatChar("-", numberDashesLeft),
			title,
			repeatChar("-", numberDashesRight))
		txt = append(txt, title)
		txt = append(txt, channelLines...)
	}
	txt = append(txt, repeatChar("-", maxLen))
	return txt
}

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.


Question:
Evaluate the limits corresponding to a C.L. of (1-alpha)%.

        Parameters
        ----------
        alpha :  limit confidence level.
        upper :  upper or lower limits.

def getLimit(self, alpha, upper=True):

        dlnl = onesided_cl_to_dlnl(1.0 - alpha)
        return self.getDeltaLogLike(dlnl, upper=upper)

def compute_stability_classification(self, predicted_data, record, dataframe_record):
        ''''''
        stability_classification, stability_classication_x_cutoff, stability_classication_y_cutoff = None, self.stability_classication_x_cutoff, self.stability_classication_y_cutoff
        if record['DDG'] != None:
            stability_classification = fraction_correct([record['DDG']], [predicted_data[self.ddg_analysis_type]], x_cutoff = stability_classication_x_cutoff, y_cutoff = stability_classication_y_cutoff)
            stability_classification = int(stability_classification)
            assert(stability_classification == 0 or stability_classification == 1)
        dataframe_record['StabilityClassification'] = stability_classification

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


Question: // title gives a backup generated title for a page

func title(p string) string {
	return strings.TrimRight(path.Base(p), path.Ext(p))
}

def sitemap_meta_description
      return controller.sitemap_meta_data[:description].blank? ? nil : tag(:meta, {name: :description, content: controller.sitemap_meta_data[:description]}, false, false)
    end

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


Question: Used by {@link solutions.siren.join.action.terms.TransportTermsByQueryAction}

public static TermsSet newTermsSet(long expectedElements, TermsByQueryRequest.TermsEncoding termsEncoding, CircuitBreaker breaker) {
    switch (termsEncoding) {
      case LONG:
        return new LongTermsSet(expectedElements, breaker);
      case INTEGER:
        return new IntegerTermsSet(expectedElements, breaker);
      case BLOOM:
        return new BloomFilterTermsSet(expectedElements, breaker);
      case BYTES:
        return new BytesRefTermsSet(breaker);
      default:
        throw new IllegalArgumentException("[termsByQuery] Invalid terms encoding: " + termsEncoding.name());
    }
  }

public function loadAction(Request $request)
    {
        $repository = $this->get('phlexible_media_template.template_manager');

        $templateKey = $request->get('template_key');

        $template = $repository->find($templateKey);
        $parameters = $template->getParameters();

        if (isset($parameters['method'])) {
            $parameters['xmethod'] = $parameters['method'];
            unset($parameters['method']);
        }

        return new JsonResponse(['success' => true, 'data' => $parameters]);
    }

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


Question:
// ruleParser parses protobuf L7 rules to enforcement objects
// May panic

func ruleParser(rule *cilium.PortNetworkPolicyRule) []proxylib.L7NetworkPolicyRule {
	l7Rules := rule.GetL7Rules()
	var rules []proxylib.L7NetworkPolicyRule
	if l7Rules == nil {
		return rules
	}
	for _, l7Rule := range l7Rules.GetL7Rules() {
		var rr r2d2Rule
		for k, v := range l7Rule.Rule {
			switch k {
			case "cmd":
				rr.cmdExact = v
			case "file":
				if v != "" {
					rr.fileRegexCompiled = regexp.MustCompile(v)
				}
			default:
				proxylib.ParseError(fmt.Sprintf("Unsupported key: %s", k), rule)
			}
		}
		if rr.cmdExact != "" &&
			rr.cmdExact != "READ" &&
			rr.cmdExact != "WRITE" &&
			rr.cmdExact != "HALT" &&
			rr.cmdExact != "RESET" {
			proxylib.ParseError(fmt.Sprintf("Unable to parse L7 r2d2 rule with invalid cmd: '%s'", rr.cmdExact), rule)
		}
		if (rr.fileRegexCompiled != nil) && !(rr.cmdExact == "" || rr.cmdExact == "READ" || rr.cmdExact == "WRITE") {
			proxylib.ParseError(fmt.Sprintf("Unable to parse L7 r2d2 rule, cmd '%s' is not compatible with 'file'", rr.cmdExact), rule)
		}
		regexStr := ""
		if rr.fileRegexCompiled != nil {
			regexStr = rr.fileRegexCompiled.String()
		}
		log.Infof("Parsed rule '%s' '%s'", rr.cmdExact, regexStr)
		rules = append(rules, &rr)
	}
	return rules
}

public void marshall(Sunglasses sunglasses, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(sunglasses.getValue(), VALUE_BINDING);
            protocolMarshaller.marshall(sunglasses.getConfidence(), CONFIDENCE_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: TODO: This method is boilerplate code also contained in eu.seaclouds.platform.dashboard.util.ObjectMapperHelpers

private <T> T xmlToObject(String xml, Class<T> type) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(type);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

        T obj = (T) jaxbUnmarshaller.unmarshal(new StringReader(xml));
        return obj;
    }

private static function init_templating()
    {
        // If no templating strategy has already been registered.
        if (!static::$container->has(Templating_Interface::class)) {
            // Add the default rendering engine.
            static::$container->add_singleton(
                \Snap\Templating\Standard\Standard_Strategy::class,
                function () {
                    return new \Snap\Templating\Standard\Standard_Strategy;
                }
            );

            static::$container->bind(\Snap\Templating\Standard\Standard_Strategy::class, Templating_Interface::class);

            static::$container->add(
                \Snap\Templating\Standard\Partial::class,
                function (Container $hodl) {
                    return $hodl->resolve(\Snap\Templating\Standard\Partial::class);
                }
            );
        }
    }

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


Question:
/*
reference:
"Cartographic Projection Procedures for the UNIX Environment-
A User's Manual" by Gerald I. Evenden,
USGS Open File Report 90-284and Release 4 Interim Reports (2003)

function init$16() {
        //no-op
        if (!this.sphere) {
            this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
        }
    }

def primary_deployment(cluster)
      # Try to describe the existing service.
      description = begin
        Ecs.describe_services(cluster.name, [@name])
      rescue => e
        puts "Error: #{e}"
        nil
      end

      missing_service_warning = <<-STR
Can't find an existing service '#{name}'.  You'll probably need to
register one manually using the AWS console and set up any load balancers
you might need.
      STR

      if description.nil?
        puts missing_service_warning
        return nil
      end

      unless service = description.fetch("services")[0]
        puts missing_service_warning
        return nil
      end

      # Find the primary deployment.
      deployment = service.fetch("deployments").find do |d|
        d["status"] == "PRIMARY"
      end
      return nil if deployment.nil?

      # Extract a task definition `name:revision`.
      arn = deployment.fetch("taskDefinition")
      arn.split('/').last
    end

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


Question: Sort an array of django versions low to high.

function sortDjangoVersions(versions) {
  return versions.sort((a, b) => {
    if (
      parseDjangoVersionString(a).major === parseDjangoVersionString(b).major
    ) {
      return (
        parseDjangoVersionString(a).minor - parseDjangoVersionString(b).minor
      )
    } else {
      return (
        parseDjangoVersionString(a).major - parseDjangoVersionString(b).major
      )
    }
  })
}

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

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


Question:
Get the index for a namespace entry in the extension namespace Vector, -1 if
no such entry yet exists.

public int namespaceIndex(String namespace, Vector extensions)
  {
    for (int i = 0; i < extensions.size(); i++)
    {
      if (((ExtensionNamespaceSupport)extensions.get(i)).getNamespace().equals(namespace))
        return i;
    }
    return -1;
  }

function(matrix) {
    var M = matrix.elements || matrix;
    if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; }
    if (this.elements.length != M.length ||
        this.elements[0].length != M[0].length) { return false; }
    var ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j;
    do { i = ki - ni;
      nj = kj;
      do { j = kj - nj;
        if (Math.abs(this.elements[i][j] - M[i][j]) > Sylvester.precision) { return false; }
      } while (--nj);
    } while (--ni);
    return true;
  }

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


Question:
Convenience Function: Hash from String to String Hex representation

@param input
@return
@throws NoSuchAlgorithmException

public static String hashSHA256asStringHex(String input, int salt) throws NoSuchAlgorithmException {
		byte[] in = input.getBytes();
		ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + in.length);
		bb.putInt(salt);
		bb.put(input.getBytes());
		byte[] output = Hash.hashSHA256(bb.array());
		StringBuilder sb = new StringBuilder("0x");
		 for (byte b : output) {
		    sb.append(hexDigit[(b >> 4) & 0x0f]);
		    sb.append(hexDigit[b & 0x0f]);
		 }
		 return sb.toString();
	}

def kdf_hmac(self):

        encryption_algo = self['algorithm'].native

        if encryption_algo == 'pbes2':
            return self['parameters']['key_derivation_func']['parameters']['prf']['algorithm'].native

        if encryption_algo.find('.') == -1:
            if encryption_algo.find('_') != -1:
                _, hmac_algo, _ = encryption_algo.split('_', 2)
                return hmac_algo

            raise ValueError(unwrap(
                '''
                Encryption algorithm "%s" does not have a registered key
                derivation function
                ''',
                encryption_algo
            ))

        raise ValueError(unwrap(
            '''
            Unrecognized encryption algorithm "%s", can not determine key
            derivation hmac algorithm
            ''',
            encryption_algo
        ))

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


Question: Returns dotted-decimal reperesentation

def dotted(self):
        "  "
        obj = libcrypto.OBJ_nid2obj(self.nid)
        buf = create_string_buffer(256)
        libcrypto.OBJ_obj2txt(buf, 256, obj, 1)
        if pyver == 2:
            return buf.value
        else:
            return buf.value.decode('ascii')

public RosettaDF<T> out(Data.TYPE type) {
		outType = type;
		defaultOut = getOut(type==Data.TYPE.DEFAULT?Data.TYPE.JSON:type);
		return this;
	}

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


Question:
踢掉某个客户端，并以$message通知被踢掉客户端

@param int $client_id
@param string $message
@return void

public static function closeClient($client_id, $message = null)
    {
        if ($client_id === Context::$client_id) {
            return static::closeCurrentClient($message);
        } // 不是发给当前用户则使用存储中的地址
        else {
            $address_data = Context::clientIdToAddress($client_id);
            if (!$address_data) {
                return false;
            }
            $address      = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
            return static::kickAddress($address, $address_data['connection_id'], $message);
        }
    }

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:
@param mixed $request

@return $this
@throws InvalidArgumentException

public function add($request)
    {
        if (is_array($request)) {
            array_walk($request, [$this, __METHOD__]);

            return $this;
        }

        if (!$request instanceof Request) {
            throw new InvalidArgumentException('Argument for add() must be of type array or Request.');
        }

        $this->requests[] = $request;

        return $this;
    }

public SassValue invoke(List<?> arguments) {
    try {
      ArrayList<Object> values = new ArrayList<>(argumentConverters.size());

      for (ArgumentConverter argumentConverter : argumentConverters) {
        Object value = argumentConverter.convert(arguments, importStack, context);
        values.add(value);
      }

      Object result = method.invoke(object, values.toArray());

      return TypeUtils.convertToSassValue(result);
    } catch (Throwable throwable) {
      StringWriter stringWriter = new StringWriter();
      PrintWriter printWriter = new PrintWriter(stringWriter);

      String message = throwable.getMessage();
      if (StringUtils.isNotEmpty(message)) {
        printWriter.append(message).append(System.lineSeparator());
      }
      throwable.printStackTrace(printWriter);

      return new SassError(stringWriter.toString());
    }
  }

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


Question: Reads an approval request object with a given id.

def ReadApprovalRequest(self, requestor_username, approval_id, cursor=None):
    """"""

    query = ("""
        SELECT
            ar.approval_id,
            UNIX_TIMESTAMP(ar.timestamp),
            ar.approval_request,
            u.username,
            UNIX_TIMESTAMP(ag.timestamp)
        FROM approval_request ar
        LEFT JOIN approval_grant ag USING (username_hash, approval_id)
        LEFT JOIN grr_users u ON u.username_hash = ag.grantor_username_hash
        WHERE ar.approval_id = %s AND ar.username_hash = %s
        """)

    cursor.execute(
        query,
        [_ApprovalIDToInt(approval_id),
         mysql_utils.Hash(requestor_username)])
    res = cursor.fetchall()
    if not res:
      raise db.UnknownApprovalRequestError("Approval '%s' not found." %
                                           approval_id)

    approval_id_int, timestamp, approval_request_bytes, _, _ = res[0]

    approval_request = mysql_utils.StringToRDFProto(rdf_objects.ApprovalRequest,
                                                    approval_request_bytes)
    approval_request.approval_id = _IntToApprovalID(approval_id_int)
    approval_request.timestamp = mysql_utils.TimestampToRDFDatetime(timestamp)

    for _, _, _, grantor_username, timestamp in res:
      if not grantor_username:
        continue

      # Note: serialized approval_request objects are guaranteed to not
      # have any grants.
      approval_request.grants.append(
          rdf_objects.ApprovalGrant(
              grantor_username=grantor_username,
              timestamp=mysql_utils.TimestampToRDFDatetime(timestamp)))

    return approval_request

def _get_future_devices(self, context):
        """"""
        monitor = Monitor.from_netlink(context)
        monitor.filter_by("hidraw")
        monitor.start()

        self._scanning_log_message()
        for device in iter(monitor.poll, None):
            if device.action == "add":
                # Sometimes udev rules has not been applied at this point,
                # causing permission denied error if we are running in user
                # mode. With this sleep this will hopefully not happen.
                sleep(1)

                yield device
                self._scanning_log_message()

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


Question:
Create a user
 @param [String, Symbol] username
 @param [String, Symbol] password
 @raise [RuntimeError] if the request failed
 @return true

def create_user(username, password)
      new_action = { 'UserName' => username, 'Password' => password, 'Oem' => { 'Hp' => { 'LoginName' => username } } }
      response = rest_post('/redfish/v1/AccountService/Accounts/', body: new_action)
      response_handler(response)
      true
    end

def create_node(**kwargs):
    '''

    '''
    name = kwargs['name']
    size = kwargs['size']
    image = kwargs['image']
    location = kwargs['location']
    networks = kwargs.get('networks')
    tag = kwargs.get('tag')
    locality = kwargs.get('locality')
    metadata = kwargs.get('metadata')
    firewall_enabled = kwargs.get('firewall_enabled')

    create_data = {
        'name': name,
        'package': size['name'],
        'image': image['name'],
    }
    if networks is not None:
        create_data['networks'] = networks

    if locality is not None:
        create_data['locality'] = locality

    if metadata is not None:
        for key, value in six.iteritems(metadata):
            create_data['metadata.{0}'.format(key)] = value

    if tag is not None:
        for key, value in six.iteritems(tag):
            create_data['tag.{0}'.format(key)] = value

    if firewall_enabled is not None:
        create_data['firewall_enabled'] = firewall_enabled

    data = salt.utils.json.dumps(create_data)

    ret = query(command='my/machines', data=data, method='POST',
                location=location)
    if ret[0] in VALID_RESPONSE_CODES:
        return ret[1]
    else:
        log.error('Failed to create node %s: %s', name, ret[1])

    return {}

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


Question:
// UpdateActualOrg updates current organization.
// It reflects PUT /api/org API call.

func (r *Client) UpdateActualOrg(org Org) (StatusMessage, error) {
	var (
		raw  []byte
		resp StatusMessage
		err  error
	)
	if raw, err = json.Marshal(org); err != nil {
		return StatusMessage{}, err
	}
	if raw, _, err = r.put("api/org", nil, raw); err != nil {
		return StatusMessage{}, err
	}
	if err = json.Unmarshal(raw, &resp); err != nil {
		return StatusMessage{}, err
	}
	return resp, nil
}

func (up UnitPayloads) SetStatus(name, status string) error {
	if err := payload.ValidateState(status); err != nil {
		return errors.Trace(err)
	}

	change := payloadSetStatusChange{
		Unit:   up.unit,
		Name:   name,
		Status: status,
	}
	if err := Apply(up.db, change); err != nil {
		return errors.Trace(err)
	}
	return nil
}

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


Question:
Scale an envelope to have a given width.

@param original the envelope.
@param newWidth the new width to use.
@return the scaled envelope placed in the original lower left corner position.

public static Envelope scaleToWidth( Envelope original, double newWidth ) {
        double width = original.getWidth();
        double factor = newWidth / width;

        double newHeight = original.getHeight() * factor;

        return new Envelope(original.getMinX(), original.getMinX() + newWidth, original.getMinY(),
                original.getMinY() + newHeight);
    }

def LayoutChildren( self, dc, children, parent, x,y,w,h, hot_map, depth=0, node_sum=None ):

        if node_sum is None:
            nodes = [ (self.adapter.value(node,parent),node) for node in children ]
            nodes.sort(key=operator.itemgetter(0))
            total = self.adapter.children_sum( children,parent )
        else:
            nodes = children
            total = node_sum
        if total:
            if self.square_style and len(nodes) > 5:
                # new handling to make parents with large numbers of parents a little less
                # "sliced" looking (i.e. more square)
                (head_sum,head),(tail_sum,tail) = split_by_value( total, nodes )
                if head and tail:
                    # split into two sub-boxes and render each...
                    head_coord,tail_coord = split_box( head_sum/float(total), x,y,w,h )
                    if head_coord:
                        self.LayoutChildren(
                            dc, head, parent, head_coord[0],head_coord[1],head_coord[2],head_coord[3],
                            hot_map, depth,
                            node_sum = head_sum,
                        )
                    if tail_coord and coord_bigger_than_padding( tail_coord, self.padding+self.margin ):
                        self.LayoutChildren(
                            dc, tail, parent, tail_coord[0],tail_coord[1],tail_coord[2],tail_coord[3],
                            hot_map, depth,
                            node_sum = tail_sum,
                        )
                    return

            (firstSize,firstNode) = nodes[-1]
            fraction = firstSize/float(total)
            head_coord,tail_coord = split_box( firstSize/float(total), x,y,w,h )
            if head_coord:
                self.DrawBox(
                    dc, firstNode, head_coord[0],head_coord[1],head_coord[2],head_coord[3],
                    hot_map, depth+1
                )
            else:
                return # no other node will show up as non-0 either

            if len(nodes) > 1 and tail_coord and coord_bigger_than_padding( tail_coord, self.padding+self.margin ):
                self.LayoutChildren(
                    dc, nodes[:-1], parent,
                    tail_coord[0],tail_coord[1],tail_coord[2],tail_coord[3],
                    hot_map, depth,
                    node_sum = total - firstSize,
                )

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


Question:
// isPathShadowedInFlatMap makes sure the given path is not shadowed somewhere
// in a sub-path of the map.
// e.g., if "foo.bar" has a value in the given map, it “shadows”
//       "foo.bar.baz" in a lower-priority map

func (v *Viper) isPathShadowedInFlatMap(path []string, mi interface{}) string {
	// unify input map
	var m map[string]interface{}
	switch mi.(type) {
	case map[string]string, map[string]FlagValue:
		m = cast.ToStringMap(mi)
	default:
		return ""
	}

	// scan paths
	var parentKey string
	for i := 1; i < len(path); i++ {
		parentKey = strings.Join(path[0:i], v.keyDelim)
		if _, ok := m[parentKey]; ok {
			return parentKey
		}
	}
	return ""
}

public function softIncrement($route, array $routes)
    {

        // flat the route array
        $flatten = array_map(function($route) {
            return $route->getRoute();
        }, $routes);

        $i = 0;

        array_walk($routes, function($_route) use($route, &$i) {

            $search = "#".addcslashes(preg_replace('/\([0-9]+\)*$/', "", $route),'()').'(\([0-9]+\))*$#';

            if(preg_match($search, $_route->getRoute(), $matches)) {
                if(count($matches) == 2) {
                    $i = (int)$matches[1] == $i ? (int)$matches[1] + 1 : $i;
                } else {
                    $i++;
                }
            };
        });

        return ($i ? "($i)" : '');
    }

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


Question:
Removes whitespace at beginning and end of block so:
 x
 ->
x

function trim(rootBlockNode) {
            if (rootBlockNode) {
              node = rootBlockNode.firstChild;
              if (node && node.type == 3) {
                node.value = node.value.replace(startWhiteSpaceRegExp, '');
              }

              node = rootBlockNode.lastChild;
              if (node && node.type == 3) {
                node.value = node.value.replace(endWhiteSpaceRegExp, '');
              }
            }
          }

func FodderEnsureCleanNewline(fodder *Fodder) {
	if !FodderHasCleanEndline(*fodder) {
		FodderAppend(fodder, MakeFodderElement(FodderLineEnd, 0, 0, []string{}))
	}
}

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


Question: regardless of class position

public static String getNominalValueString(InstancesHeader context,
            int attIndex, int valIndex) {
        if (context != null) {
            int instAttIndex = attIndex < context.classIndex() ? attIndex
                    : attIndex + 1;
            if ((instAttIndex < context.numAttributes())
                    && (valIndex < context.attribute(instAttIndex).numValues())) {
                return "{val " + (valIndex + 1) + ":"
                        + context.attribute(instAttIndex).value(valIndex) + "}";
            }
        }
        return "{val " + (valIndex + 1) + "}";
    }

public function setByPosition($pos, $value)
    {
        switch ($pos) {
            case 0:
                $this->setSkillId($value);
                break;
            case 1:
                $this->setGroupId($value);
                break;
        } // switch()

        return $this;
    }

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


Question: // SetConfigValue sets and saves gopm configuration.

func SetConfigValue(section, key, val string) error {
	Cfg.SetValue(section, key, val)
	if err := goconfig.SaveConfigFile(Cfg, ConfigFile); err != nil {
		return fmt.Errorf("fail to set config value(%s:%s=%s): %v", section, key, val, err)
	}
	return nil
}

public function init(array $params = array()) {
        if (count($params) !== count($this->_config)) {
            throw new Garp_Browsebox_Exception('Number of parameters does not match the number of required parameters in filter "'.$this->getId().'"');
        }
        $this->_values = $params;
    }

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


Question:
// parseTabletType parses the string tablet type and verifies
// it is an accepted one

func parseTabletType(param string, types []topodatapb.TabletType) (topodatapb.TabletType, error) {
	tabletType, err := topoproto.ParseTabletType(param)
	if err != nil {
		return topodatapb.TabletType_UNKNOWN, fmt.Errorf("invalid tablet type %v: %v", param, err)
	}
	if !topoproto.IsTypeInList(topodatapb.TabletType(tabletType), types) {
		return topodatapb.TabletType_UNKNOWN, fmt.Errorf("type %v is not one of: %v", tabletType, strings.Join(topoproto.MakeStringTypeList(types), " "))
	}
	return tabletType, nil
}

public function setAllowReview($allowReview)
    {
        if (is_bool($allowReview)) {
            $this->allowReview = $allowReview;
        } else {
            $msg = "AllowReview must be a boolean, '" . gettype($allowReview) . "' given.";
            throw new InvalidArgumentException($msg);
        }
    }

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


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

@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case AfplibPackage.GSCOL__COL:
				return getCOL();
		}
		return super.eGet(featureID, resolve, coreType);
	}

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:
Returns ``True`` if you can expect multiple chunks.

        NB: If a particular file representation is in memory, subclasses should
        always return ``False`` -- there's no good reason to read from memory in
        chunks.

def multiple_chunks(self, chunk_size=None):

        if not chunk_size:
            chunk_size = self.DEFAULT_CHUNK_SIZE
        return self.size > chunk_size

public void setChannelPosition(long dataOffset, boolean startWithPartialChunk)
      throws IOException {
    long channelSize = blockDataWriter.getChannelSize();
    if (channelSize < dataOffset) {
      String msg = "Trying to change block file offset of block "
          + block
          + "file "
          + ((blockDataFile.getFile() != null) ? blockDataFile.getFile()
              : "unknown") + " to " + dataOffset
          + " but actual size of file is " + blockDataWriter.getChannelSize();
      throw new IOException(msg);
    }
    if (dataOffset > channelSize) {
      throw new IOException("Set position over the end of the data file.");
    }

    if (startWithPartialChunk && channelSize != dataOffset + checksumSize) {
      DFSClient.LOG.warn("Inline Checksum Block " + block + " channel size "
          + channelSize + " but packet needs to start from " + dataOffset);
    }

    // This flush should be a no-op since we always flush at the end of
    // writePacket() and hence the buffer should be empty.
    // However we do this just to be extra careful so that the
    // channel.position() doesn't mess up things with respect to the
    // buffered dataOut stream.
    blockDataWriter.flush();
    blockDataWriter.position(dataOffset);
  }

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


Question:
Redislize an array (key, valueToRedislize).

@param array $data

@return array

public function redislizeArray(array $data)
    {
        $result = [];
        foreach ($data as $key => $value) {
            if (!is_array($value)) {
                $result[$key] = $this->redislize($value);
            }
        }

        return $result;
    }

protected function describeProcedures($names, $refresh = false)
    {
        $names = static::validateAsArray(
            $names,
            ',',
            true,
            'The request contains no valid procedure names or properties.'
        );

        $out = [];
        foreach ($names as $name) {
            $out[] = $this->describeProcedure($name, $refresh);
        }

        return $out;
    }

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


Question:
Write the beginning of the DOM source for the section container
@param {aria.templates.MarkupWriter} out

function (out) {
                if (this.domType) {
                    // if domType is empty, we do not output anything for the section
                    // (used in the tooltip)
                    var attributeList = this.attributes ? ariaUtilsHtml.buildAttributeList(this.attributes) : '';
                    var h = ['<', this.domType, attributeList, ' id="', this._domId, '" ',
                            ariaUtilsDelegate.getMarkup(this.delegateId), '>'];
                    out.write(h.join(''));// opening the section
                }
            }

def _parse(self):

        responses = []
        for child in self._element:
            weight = int_attribute(child, 'weight', 1)
            self._log.debug('Parsing random entry with weight {weight}: {entry}'
                            .format(weight=weight, entry=child.text))

            # If the random element doesn't contain any tags, just store the text and return
            if not len(child):
                responses.append((child.text, weight))
                continue

            # Otherwise, parse all the available tags
            responses.append((tuple(self.trigger.agentml.parse_tags(child, self.trigger)), weight))
        self._responses = tuple(responses)

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


Question:
Return the category of this SimMemory instance. It can be one of the three following categories: reg, mem,
        or file.

def category(self):

        if self.id in ('reg', 'mem'):
            return self.id

        elif self._abstract_backer:
            return 'mem'

        elif self.id.startswith('file'):
            return 'file'

        else:
            raise SimMemoryError('Unknown SimMemory category for memory_id "%s"' % self.id)

def write_tmp_i3status_config(self, tmpfile):

        # order += ...
        for module in self.py3_config["i3s_modules"]:
            self.write_in_tmpfile('order += "%s"\n' % module, tmpfile)
        self.write_in_tmpfile("\n", tmpfile)
        # config params for general section and each module
        for section_name in ["general"] + self.py3_config["i3s_modules"]:
            section = self.py3_config[section_name]
            self.write_in_tmpfile("%s {\n" % section_name, tmpfile)
            for key, value in section.items():
                # don't include color values except in the general section
                if key.startswith("color"):
                    if (
                        section_name.split(" ")[0] not in I3S_COLOR_MODULES
                        or key not in I3S_ALLOWED_COLORS
                    ):
                        continue
                # Set known fixed format for time and tztime so we can work
                # out the timezone
                if section_name.split()[0] in TIME_MODULES:
                    if key == "format":
                        value = TZTIME_FORMAT
                    if key == "format_time":
                        continue
                if isinstance(value, bool):
                    value = "{}".format(value).lower()
                self.write_in_tmpfile('    %s = "%s"\n' % (key, value), tmpfile)
            self.write_in_tmpfile("}\n\n", tmpfile)
        tmpfile.flush()

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


Question:
We could use addList recursively here, but sometimes we produce
very deeply nested operators and run out of stack space, so we
just unroll the recursion when possible.

We assume nodes are left-recursive.

private void unrollBinaryOperator(
      Node n, Token op, String opStr, Context context,
      Context rhsContext, int leftPrecedence, int rightPrecedence) {
    Node firstNonOperator = n.getFirstChild();
    while (firstNonOperator.getToken() == op) {
      firstNonOperator = firstNonOperator.getFirstChild();
    }

    addExpr(firstNonOperator, leftPrecedence, context);

    Node current = firstNonOperator;
    do {
      current = current.getParent();
      cc.addOp(opStr, true);
      addExpr(current.getSecondChild(), rightPrecedence, rhsContext);
    } while (current != n);
  }

def find(self, path, mode='node'):

        path = path.split('.') if isinstance(path, str) else list(path)
        item = self

        for child in path:
            escaped_child = sanitize_identifier(child, escape=False)
            matching_children = [c for c in item.children
                                 if child.endswith(c) or escaped_child.endswith(c)]
            matching_children = sorted(matching_children, key=lambda x: -len(x))
            if matching_children:
                item = item[matching_children[0]]
            else:
                continue
        return item if mode == 'node' else item.path

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


Question:
// Start starts Caddy with the given Caddyfile.
//
// This function blocks until all the servers are listening.

func Start(cdyfile Input) (*Instance, error) {
	defer func() {
		// notify systemd that startup is complete
		_, err := daemon.SdNotify(true, "READY=1")
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error sending systemd ready notification %s\n", err.Error())
		}
	}()
	writePidFile()
	inst := &Instance{serverType: cdyfile.ServerType(), wg: new(sync.WaitGroup)}
	return inst, startWithListenerFds(cdyfile, inst, nil)
}

def get_banks_by_item(self, *args, **kwargs):
        """"""
        # Implemented from kitosid template for -
        # osid.resource.ResourceBinSession.get_bins_by_resource
        catalogs = self._get_provider_session('item_bank_session').get_banks_by_item(*args, **kwargs)
        cat_list = []
        for cat in catalogs:
            cat_list.append(Bank(self._provider_manager, cat, self._runtime, self._proxy))
        return BankList(cat_list)

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


Question: Cleanup and exit.

public function cleanup()
    {
        $this->saveState();

        if (null === $this->current_job) {
            $this->logger->debug('received cleanup call on worker ['.$this->id.'], no job is currently processing, exit now', [
                'category' => get_class($this),
                'pm' => $this->process,
            ]);

            $this->exit();

            return null;
        }

        $this->logger->debug('received cleanup call on worker ['.$this->id.'], reschedule current processing job ['.$this->current_job['_id'].']', [
            'category' => get_class($this),
            'pm' => $this->process,
        ]);

        $this->updateJob($this->current_job, JobInterface::STATUS_CANCELED);

        $this->db->{$this->scheduler->getEventQueue()}->insertOne([
            'job' => $this->current_job['_id'],
            'worker' => $this->id,
            'status' => JobInterface::STATUS_CANCELED,
            'timestamp' => new UTCDateTime(),
        ]);

        $options = $this->current_job['options'];
        $options['at'] = 0;

        $result = $this->scheduler->addJob($this->current_job['class'], $this->current_job['data'], $options)->getId();
        $this->exit();

        return $result;
    }

def R(self):
        ''
        self._check_estimated()
        if not self._estimation_finished:
            self._finish_estimation()
        return self._R

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


Question:
Sets the active migration if none is set and returns {@code null}, otherwise returns the currently set active migration.
Acquires the partition service lock.

public MigrationInfo setActiveMigration(MigrationInfo migrationInfo) {
        partitionServiceLock.lock();
        try {
            if (activeMigrationInfo == null) {
                activeMigrationInfo = migrationInfo;
                return null;
            }
            if (!activeMigrationInfo.equals(migrationInfo)) {
                if (logger.isFineEnabled()) {
                    logger.fine("Active migration is not set: " + migrationInfo
                            + ". Existing active migration: " + activeMigrationInfo);
                }
            }
            return activeMigrationInfo;
        } finally {
            partitionServiceLock.unlock();
        }
    }

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;
        $configurationPath = $input->getOption('configurationPath');
        $deploymentName = $input->getArgument('deploymentName');
        $deployment = $this->factory->getDeployment($deploymentName, $configurationPath);
        $workflow = $deployment->getWorkflow();

        if (! $deployment instanceof FailedDeployment) {
            $output->writeln('<success>Deployment ' . $deployment->getName() . '</success>');
            $output->writeln('');
            $output->writeln('Workflow: <success>' . $workflow->getName() . '</success>');

            if ($workflow instanceof SimpleWorkflow) {
                $value = $workflow->isEnableRollback() ? 'true' : 'false';
                $output->writeln('    <comment>Rollback enabled:</comment> <info>' . $value . '</info>');
            }

            $output->writeln('');

            $this->printNodes($deployment->getNodes());

            $this->printApplications($deployment->getApplications(), $deployment->getWorkflow());
        }
    }

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


Question:
// GroupTransactionsIntoBundles groups the given transactions into groups of bundles.
// Note that the same bundle can exist in the return slice multiple times, though they
// are reattachments of the same transfer.

func GroupTransactionsIntoBundles(txs transaction.Transactions) Bundles {
	bundles := Bundles{}

	for i := range txs {
		tx := &txs[i]
		if tx.CurrentIndex != 0 {
			continue
		}

		bundle := Bundle{*tx}
		lastIndex := int(tx.LastIndex)
		current := tx
		for x := 1; x <= lastIndex; x++ {
			// get all txs belonging into this bundle
			found := false
			for j := range txs {
				if current.Bundle != txs[j].Bundle ||
					txs[j].CurrentIndex != current.CurrentIndex+1 ||
					current.TrunkTransaction != txs[j].Hash {
					continue
				}
				found = true
				bundle = append(bundle, txs[j])
				current = &txs[j]
				break
			}
			if !found {
				break
			}
		}
		bundles = append(bundles, bundle)
	}

	return bundles
}

private Map<String, PipelineCommit> getCommitsAfterStage(PipelineStage stage, Pipeline pipeline, Dashboard dashboard,List<PipelineStage> pipelineStageList,Map<String,String> orderMap){
        Map<String, PipelineCommit> unionOfAllSets = new HashMap<>();
        // get key(ordinal) for stage name
        List<String> list = getKeysByValue(orderMap,stage.getName());
        int ordinal = Integer.parseInt(list.get(0));
        for (int systemStageOrdinal = ordinal+1; systemStageOrdinal < pipelineStageList.size(); ++systemStageOrdinal) {
            PipelineStage systemStage = null;
            for (Map.Entry<String, String> entry : orderMap.entrySet()) {
                String stageOrder = entry.getKey();
                String stageName = entry.getValue();
                if(Integer.parseInt(stageOrder) == systemStageOrdinal){
                    for(PipelineStage currentStage : pipelineStageList){
                        if(stageName.equalsIgnoreCase(currentStage.getName())){
                             systemStage = currentStage;
                        }
                    }
                }
            }
            Map<String, PipelineCommit> commits = findCommitsForStage(dashboard, pipeline, systemStage);
            unionOfAllSets.putAll(commits);
        }
        return unionOfAllSets;
    }

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


Question:
The Collections for the CurrentMetricResult object.

@param collections
The Collections for the CurrentMetricResult object.

public void setCollections(java.util.Collection<CurrentMetricData> collections) {
        if (collections == null) {
            this.collections = null;
            return;
        }

        this.collections = new java.util.ArrayList<CurrentMetricData>(collections);
    }

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

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


Question: // Sum returns the sum of the vector.

func (x Vector) Sum() float64 {
	s := 0.0
	for _, v := range x {
		s += v
	}
	return s
}

def run(self, *args):

        if self.source is None:
            self.model.summary()
        else:
            x_data, y_data = next(iter(self.source.train_loader()))
            self.model.summary(input_size=x_data.shape[1:])

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


Question:
// public API, executes a command on leader, returns chan which will
// block until command has been replicated to our local replica

func (s *server) Command(cmd string, args [][]byte) <-chan Result {

	if s.IsLeader() {
		cb := s.state.newCommand()
		cmdBytes := bytesForCommand(cb.originAddr, cb.reqNo, cmd, args)
		s.raft.Apply(cmdBytes, commandTimeout)
		return cb.result
	}
	// couldn't exec as leader, fallback to forwarding
	cb, err := s.dispatchToLeader(cmd, args)
	if err != nil {
		if cb != nil {
			cb.cancel()
		}
		ret := make(chan Result, 1)
		ret <- Result{nil, err}
		return ret
	}
	return cb.result
}

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: // getCellsForEdge populates the cells field to the set of index cells intersected by an edge AB.

func (c *CrossingEdgeQuery) getCellsForEdge(a, b Point) {
	c.cells = nil

	segments := FaceSegments(a, b)
	for _, segment := range segments {
		c.a = segment.a
		c.b = segment.b

		// Optimization: rather than always starting the recursive subdivision at
		// the top level face cell, instead we start at the smallest S2CellId that
		// contains the edge (the edge root cell). This typically lets us skip
		// quite a few levels of recursion since most edges are short.
		edgeBound := r2.RectFromPoints(c.a, c.b)
		pcell := PaddedCellFromCellID(CellIDFromFace(segment.face), 0)
		edgeRoot := pcell.ShrinkToFit(edgeBound)

		// Now we need to determine how the edge root cell is related to the cells
		// in the spatial index (cellMap). There are three cases:
		//
		//  1. edgeRoot is an index cell or is contained within an index cell.
		//     In this case we only need to look at the contents of that cell.
		//  2. edgeRoot is subdivided into one or more index cells. In this case
		//     we recursively subdivide to find the cells intersected by AB.
		//  3. edgeRoot does not intersect any index cells. In this case there
		//     is nothing to do.
		relation := c.iter.LocateCellID(edgeRoot)
		if relation == Indexed {
			// edgeRoot is an index cell or is contained by an index cell (case 1).
			c.cells = append(c.cells, c.iter.IndexCell())
		} else if relation == Subdivided {
			// edgeRoot is subdivided into one or more index cells (case 2). We
			// find the cells intersected by AB using recursive subdivision.
			if !edgeRoot.isFace() {
				pcell = PaddedCellFromCellID(edgeRoot, 0)
			}
			c.computeCellsIntersected(pcell, edgeBound)
		}
	}
}

def _get_ref(data, position, obj_end, opts, element_name):
    """"""
    collection, position = _get_string(
        data, position, obj_end, opts, element_name)
    oid, position = _get_oid(data, position, obj_end, opts, element_name)
    return DBRef(collection, oid), position

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


Question:
Populates a resource.

@param resource resource instance
@param record MPX record
@throws MPXJException

private void populateResource(Resource resource, Record record) throws MPXJException
   {
      String falseText = LocaleData.getString(m_locale, LocaleData.NO);

      int length = record.getLength();
      int[] model = m_resourceModel.getModel();

      for (int i = 0; i < length; i++)
      {
         int mpxFieldType = model[i];
         if (mpxFieldType == -1)
         {
            break;
         }

         String field = record.getString(i);

         if (field == null || field.length() == 0)
         {
            continue;
         }

         ResourceField resourceField = MPXResourceField.getMpxjField(mpxFieldType);
         switch (resourceField)
         {
            case OBJECTS:
            {
               resource.set(resourceField, record.getInteger(i));
               break;
            }

            case ID:
            {
               resource.setID(record.getInteger(i));
               break;
            }

            case UNIQUE_ID:
            {
               resource.setUniqueID(record.getInteger(i));
               break;
            }

            case MAX_UNITS:
            {
               resource.set(resourceField, record.getUnits(i));
               break;
            }

            case PERCENT_WORK_COMPLETE:
            case PEAK:
            {
               resource.set(resourceField, record.getPercentage(i));
               break;
            }

            case COST:
            case COST_PER_USE:
            case COST_VARIANCE:
            case BASELINE_COST:
            case ACTUAL_COST:
            case REMAINING_COST:
            {
               resource.set(resourceField, record.getCurrency(i));
               break;
            }

            case OVERTIME_RATE:
            case STANDARD_RATE:
            {
               resource.set(resourceField, record.getRate(i));
               break;
            }

            case REMAINING_WORK:
            case OVERTIME_WORK:
            case BASELINE_WORK:
            case ACTUAL_WORK:
            case WORK:
            case WORK_VARIANCE:
            {
               resource.set(resourceField, record.getDuration(i));
               break;
            }

            case ACCRUE_AT:
            {
               resource.set(resourceField, record.getAccrueType(i));
               break;
            }

            case LINKED_FIELDS:
            case OVERALLOCATED:
            {
               resource.set(resourceField, record.getBoolean(i, falseText));
               break;
            }

            default:
            {
               resource.set(resourceField, field);
               break;
            }
         }
      }

      if (m_projectConfig.getAutoResourceUniqueID() == true)
      {
         resource.setUniqueID(Integer.valueOf(m_projectConfig.getNextResourceUniqueID()));
      }

      if (m_projectConfig.getAutoResourceID() == true)
      {
         resource.setID(Integer.valueOf(m_projectConfig.getNextResourceID()));
      }

      //
      // Handle malformed MPX files - ensure we have a unique ID
      //
      if (resource.getUniqueID() == null)
      {
         resource.setUniqueID(resource.getID());
      }
   }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


Question:
Reads Citrus internal mail message model object from message payload. Either payload is actually a mail message object or
XML payload String is unmarshalled to mail message object.

@param message
@param endpointConfiguration
@return

private KubernetesCommand<?> getCommand(Message message, KubernetesEndpointConfiguration endpointConfiguration) {
        Object payload = message.getPayload();

        KubernetesCommand<?> command;
        if (message instanceof KubernetesMessage) {
            command = createCommandFromRequest(message.getPayload(KubernetesRequest.class));
        } else if (message.getHeaders().containsKey(KubernetesMessageHeaders.COMMAND) &&
                (payload == null || !StringUtils.hasText(payload.toString()))) {
            command = getCommandByName(message.getHeader(KubernetesMessageHeaders.COMMAND).toString());
        } else if (payload instanceof KubernetesCommand) {
            command = (KubernetesCommand) payload;
        } else {
            try {
                KubernetesRequest request = endpointConfiguration.getObjectMapper()
                        .readValue(message.getPayload(String.class), KubernetesRequest.class);
                command = createCommandFromRequest(request);
            } catch (IOException e) {
                throw new CitrusRuntimeException("Failed to read kubernetes request from payload", e);
            }
        }

        if (command == null) {
            throw new CitrusRuntimeException("Unable to create proper Kubernetes command from payload: " + payload);
        }

        return command;
    }

private static CEMI create(final int msgCode, final IndividualAddress src,
		final KNXAddress dst, final byte[] data, final CEMILData original, final boolean ext,
		final boolean repeat)
	{
		final int mc = msgCode != 0 ? msgCode : original.getMessageCode();
		final IndividualAddress s = src != null ? src : original.getSource();
		final KNXAddress d = dst != null ? dst : original.getDestination();
		final byte[] content = data != null ? data : original.getPayload();
		if (original instanceof CEMILDataEx) {
			final CEMILDataEx f = (CEMILDataEx) original;
			final CEMILDataEx copy = new CEMILDataEx(mc, s, d, content, f.getPriority(), repeat,
					f.isDomainBroadcast(), f.isAckRequested(), f.getHopCount());
			copy.ctrl2 |= original.ctrl2 & 0x0f;
			// copy additional info
			copy.additionalInfo().addAll(f.additionalInfo());
			return copy;
		}
		if (ext)
			return new CEMILDataEx(mc, s, d, content, original.getPriority(), repeat, original.getHopCount());
		return new CEMILData(mc, s, d, content, original.getPriority(), repeat, original.getHopCount());
	}

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


Question: // SetRun sets the Run field's value.

func (s *StopRunOutput) SetRun(v *Run) *StopRunOutput {
	s.Run = v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question:
// podFieldSelectorRuntimeValue returns the runtime value of the given
// selector for a pod.

func (kl *Kubelet) podFieldSelectorRuntimeValue(fs *v1.ObjectFieldSelector, pod *v1.Pod, podIP string) (string, error) {
	internalFieldPath, _, err := podshelper.ConvertDownwardAPIFieldLabel(fs.APIVersion, fs.FieldPath, "")
	if err != nil {
		return "", err
	}
	switch internalFieldPath {
	case "spec.nodeName":
		return pod.Spec.NodeName, nil
	case "spec.serviceAccountName":
		return pod.Spec.ServiceAccountName, nil
	case "status.hostIP":
		hostIP, err := kl.getHostIPAnyWay()
		if err != nil {
			return "", err
		}
		return hostIP.String(), nil
	case "status.podIP":
		return podIP, nil
	}
	return fieldpath.ExtractFieldPathAsString(pod, internalFieldPath)
}

def _generate_union_class_variant_creators(self, ns, data_type):

        for field in data_type.fields:
            if not is_void_type(field.data_type):
                field_name = fmt_func(field.name)
                field_name_reserved_check = fmt_func(field.name, check_reserved=True)
                if is_nullable_type(field.data_type):
                    field_dt = field.data_type.data_type
                else:
                    field_dt = field.data_type
                self.emit('@classmethod')
                self.emit('def {}(cls, val):'.format(field_name_reserved_check))
                with self.indent():
                    self.emit('"""')
                    self.emit_wrapped_text(
                        'Create an instance of this class set to the ``%s`` '
                        'tag with value ``val``.' % field_name)
                    self.emit()
                    self.emit(':param {} val:'.format(
                        self._python_type_mapping(ns, field_dt)))
                    self.emit(':rtype: {}'.format(
                        self._python_type_mapping(ns, data_type)))
                    self.emit('"""')
                    self.emit("return cls('{}', val)".format(field_name))
                self.emit()

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


Question:
Returns the table name of the model.

@return string

public function getTable(): string
	{
		if(empty($this->tableName))
		{
			$this->tableName = Str::pluralize(Str::camel2underscored($this->getClassShortName()));
		}

		return $this->tableName;
	}

public function saveTableToSession(Request $request, TableModel $table)
    {
        $request->getSession()->set(TableModel::buildSessionPath($request), serialize($table));
    }

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


Question:
Exclude object from result

@param   ChildPicture $picture Object to remove from the list of results

@return $this|ChildPictureQuery The current query, for fluid interface

public function prune($picture = null)
    {
        if ($picture) {
            $this->addUsingAlias(PictureTableMap::COL_ID, $picture->getId(), Criteria::NOT_EQUAL);
        }

        return $this;
    }

def get_delete_api(self, resource):

        parameters = self.delete_item_parameters(resource)

        get_item_api = {
            'path': '/%s/{id}/' % resource.get_api_name(),
            'description': 'Operations on %s' % resource.model.__name__,
            "responseClass": "void",
            'operations': [
                {
                    'httpMethod': 'DELETE',
                    'nickname': 'delete%s' % resource.model.__name__,
                    'summary': 'Delete %s by its unique ID' %
                               resource.model.__name__,
                    'parameters': parameters,
                }
            ]
        }

        return get_item_api

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