Question:
/*-------------------------------------------------------------------------
Output:
-------------------------------------------------------------------------

public function appendFormattedElement(XMLElement &$wrapper, $data, $encode = false, $mode = null, $entry_id = null)
    {
        $value = ($data['value'] === 'yes' ? 'Yes' : 'No');

        $wrapper->appendChild(new XMLElement($this->get('element_name'), ($encode ? General::sanitize($value) : $value)));
    }

def report(self):

        # make this prettier
        html = u'
\n' % self.name()

        # Intro
        html = html + "
 Plugin " + self.name() + "
\n"

        # Files
        if len(self.copied_files):
            html = html + "
Files copied:

\n"
            for afile in self.copied_files:
                html = html + '
%s' % \
                    (u'..' + _to_u(afile['dstpath']), _to_u(afile['srcpath']))
                if afile['symlink'] == "yes":
                    html = html + " (symlink to %s)" % _to_u(afile['pointsto'])
                html = html + '
\n'
            html = html + "

\n"

        # Command Output
        if len(self.executed_commands):
            html = html + "
Commands Executed:

\n"
            # convert file name to relative path from our root
            # don't use relpath - these are HTML paths not OS paths.
            for cmd in self.executed_commands:
                if cmd["file"] and len(cmd["file"]):
                    cmd_rel_path = u"../" + _to_u(self.commons['cmddir']) \
                        + "/" + _to_u(cmd['file'])
                    html = html + '
%s
\n' % \
                        (cmd_rel_path, _to_u(cmd['exe']))
                else:
                    html = html + '
%s
\n' % (_to_u(cmd['exe']))
            html = html + "

\n"

        # Alerts
        if len(self.alerts):
            html = html + "
Alerts:

\n"
            for alert in self.alerts:
                html = html + '
%s
\n' % _to_u(alert)
            html = html + "

\n"

        # Custom Text
        if self.custom_text != "":
            html = html + "
Additional Information:
\n"
            html = html + _to_u(self.custom_text) + "
\n"

        if six.PY2:
            return html.encode('utf8')
        else:
            return html

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


@Override
    protected void startNewPage()
    {
        super.startNewPage();
        pagebox = createBlock(body, curpage, false);
        pagebox.setStyle(createPageStyle());
        body.addSubBox(pagebox);
    }

public function preview()
	{
		$strPreview = '

' . $this->label . '

';

		if ($this->multiPage)
		{
			$strPreview .= '
 Articletitle1

 Articletitle2

 Articletitle3
';
		}
		else
		{
			$strPreview .= '
 Articletitle
';
		}

		$strPreview .= '

Change selection

' . $this->description . '

';

		return $strPreview;
	}

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


Question:
Simplified serialization.

@param java.io.DataOutputStream to write the serialized Object into.

public void writeObject(java.io.DataOutputStream dataOutputStream)
                    throws ObjectManagerException
    {
        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.entry(this, cclass, "writeObject"
                        , "dataOutputStream=" + dataOutputStream);

        try
        {
            dataOutputStream.writeByte(SimpleSerialVersion);
            dataOutputStream.writeLong(identifier);
            if (XID == null)
            {
                dataOutputStream.writeByte(0);
            }
            else
            { // Non null XID.
                dataOutputStream.writeByte(XID.length);
                dataOutputStream.write(XID);
            } // if (XID == null).

        } catch (java.io.IOException exception) {
            // No FFDC Code Needed.
            ObjectManager.ffdc.processException(this, cclass, "writeObject", exception, "1:177:1.9");

            if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
                trace.exit(this, cclass, "writeObject");
            throw new PermanentIOException(this, exception);
        } // catch (java.io.IOException exception).

        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.exit(this, cclass, "writeObject");
    }

private static List<ParameterFiller> parseParameters(List<String> parameters) {
    List<ParameterFiller> parameterFillers = new ArrayList<>(parameters.size());
    for (String parameter : parameters) {
      ParameterFiller parameterFiller = parseParameter(parameter);
      if (parameterFiller != null) {
        parameterFillers.add(parameterFiller);
      }
    }
    return parameterFillers;
  }

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


Question:
// Err waits for all previous calls to Go to complete and returns the
// first non-nil error, or nil.

func (g *Group) Err() error {
	g.wg.Wait()
	if len(g.errs) > 0 {
		return g.errs[0]
	}
	return nil
}

func goErrorHandler(code C.int, reason *C.char) {
	reasonHeader := reflect.StringHeader{
		Data: uintptr(unsafe.Pointer(reason)),
		Len:  int(C.strlen(reason)),
	}
	reasonString := (*string)(unsafe.Pointer(&reasonHeader))
	Log.Printf("%s -- %s", codeToString(int(code)), *reasonString)
}

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


Question: compare array or element for equivalence

def rights_equal(rights_attr)
      f_rights = Array.wrap(fedora.fetch('rights', {}).fetch(rights_attr, [])).sort
      b_rights = Array.wrap(bendo.fetch('rights', {}).fetch(rights_attr, [])).sort

      return 0 if f_rights == b_rights
      1
    end

function(name){
        for (var i = 0, len = _pluginList.length ; i < len ; i++){
            var plugin = _pluginList[i];
            if (name === plugin.name) {
                return true;
            }
        }
        return false;
    }

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


Question: Get the KERNINGRECORD structure.

def _get_struct_kerningrecord(self, font_flags_wide_codes):
        """"""
        getter = unpack_ui16 if font_flags_wide_codes else unpack_ui8
        data = {}
        data['FontKerningCode1'] = getter(self._src)
        data['FontKerningCode2'] = getter(self._src)
        data['FontKerningAdjustment'] = unpack_si16(self._src)
        return data

protected function evaluateConst()
    {

        common_Logger::d('CONSTANTE TYPE', array('Generis Term evaluateConst'));
	    $property = new core_kernel_classes_Property(RulesRdf::PROPERTY_TERM_VALUE);
	    return $this->getUniquePropertyValue($property);

    }

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


Question:
// These methods are used by ModelManager and Application facades
// when destroying models and applications/units.
// UnitStorage returns the storage instances attached to the specified unit.

func UnitStorage(st StorageAccess, unit names.UnitTag) ([]state.StorageInstance, error) {
	attachments, err := st.UnitStorageAttachments(unit)
	if err != nil {
		return nil, errors.Trace(err)
	}
	instances := make([]state.StorageInstance, 0, len(attachments))
	for _, attachment := range attachments {
		instance, err := st.StorageInstance(attachment.StorageInstance())
		if errors.IsNotFound(err) {
			continue
		} else if err != nil {
			return nil, errors.Trace(err)
		}
		instances = append(instances, instance)
	}
	return instances, nil
}

def actually_mount(self, client):
        """"""
        a_obj = self.config.copy()
        if 'description' in a_obj:
            del a_obj['description']

        try:
            m_fun = getattr(client, self.mount_fun)
            if self.description and a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description,
                      config=a_obj)
            elif self.description:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description)
            elif a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      config=a_obj)
            else:
                m_fun(self.backend,
                      mount_point=self.path)
        except hvac.exceptions.InvalidRequest as exception:
            match = re.match('existing mount at (?P<path>.+)', str(exception))
            if match:
                e_msg = "%s has a mountpoint conflict with %s" % \
                        (self.path, match.group('path'))
                raise aomi_excep.VaultConstraint(e_msg)
            else:
                raise

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


Question: // WithTimeout adds the timeout to the delete Json web key params

func (o *DeleteJSONWebKeyParams) WithTimeout(timeout time.Duration) *DeleteJSONWebKeyParams {
	o.SetTimeout(timeout)
	return o
}

func (c *Client) DeleteDomain(p *DeleteDomainParameter) (*Result, error) {
	obj, err := c.Request("deleteDomain", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Result), err
}

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


Question: Sets the status of this job to 'success' or 'failure'.

def finish(self, result, array_id = None):
    """"""
    # check if there is any array job still running
    new_status = 'success' if result == 0 else 'failure'
    new_result = result
    finished = True
    if array_id is not None:
      for array_job in self.array:
        if array_job.id == array_id:
          array_job.status = new_status
          array_job.result = result
          array_job.finish_time = datetime.now()
        if array_job.status not in ('success', 'failure'):
          finished = False
        elif new_result == 0:
          new_result = array_job.result

    if finished:
      # There was no array job, or all array jobs finished
      self.status = 'success' if new_result == 0 else 'failure'
      self.result = new_result
      self.finish_time = datetime.now()

      # update all waiting jobs
      for job in self.get_jobs_waiting_for_us():
        if job.status == 'waiting':
          job.queue()

private static boolean summarize( List<String> warnings, List<String> errors, boolean isNoWarn )
  {
    if( isNoWarn )
    {
      System.out.printf( "\ngosuc completed with %d errors. Warnings were disabled.\n", errors.size() );
    }
    else
    {
      System.out.printf( "\ngosuc completed with %d warnings and %d errors.\n", warnings.size(), errors.size() );
    }

    return errors.size() > 0;
  }

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


Question: will accumulate in a new list.

private List<Entry> getPendingWrites() {
    synchronized (this) {
      List<Entry> save = this.pendingWrites;
      this.pendingWrites = new LinkedList<>();
      return save;
    }
  }

def _collect_data(self):

        all_data = []
        for line in self.engine.run_engine():
            logging.debug("Adding {} to all_data".format(line))
            all_data.append(line.copy())
            logging.debug("all_data is now {}".format(all_data))

        return all_data

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


Question:
/* (non-Javadoc)
@see com.oath.cyclops.types.MonadicValue#flatMapP(java.util.function.Function)

public <R> ValueTransformer<W,R> mergeMap(Function<? super T, ? extends Publisher<? extends R>> mapper) {
        return unitAnyM(this.transformerStream().map(v->v.mergeMap(mapper)));
    }

public static <K, V> List<Tuple<K, V>> object(final List<K> keys, final List<V> values) {
        return map(keys, new Function<K, Tuple<K, V>>() {
            private int index;

            @Override
            public Tuple<K, V> apply(K key) {
                return Tuple.create(key, values.get(index++));
            }
        });
    }

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


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

public EClass getMPGRG() {
		if (mpgrgEClass == null) {
			mpgrgEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(420);
		}
		return mpgrgEClass;
	}

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: // SetVolumesPerInstance sets the VolumesPerInstance field's value.

func (s *EbsBlockDeviceConfig) SetVolumesPerInstance(v int64) *EbsBlockDeviceConfig {
	s.VolumesPerInstance = &v
	return s
}

def parse_record(self, node):

        if self.current_simulation == None:
            self.raise_error('<Record> must be only be used inside a ' +
                             'simulation specification')

        if 'quantity' in node.lattrib:
            quantity = node.lattrib['quantity']
        else:
            self.raise_error('<Record> must specify a quantity.')

        scale = node.lattrib.get('scale', None)
        color  = node.lattrib.get('color', None)
        id  = node.lattrib.get('id', None)

        self.current_simulation.add_record(Record(quantity, scale, color, id))

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


Question: handle xlim change requests from queue

def xlim_change_check(self, idx):
        ''''''
        if not self.xlim_pipe[1].poll():
            return
        xlim = self.xlim_pipe[1].recv()
        if xlim is None:
            return
        #print("recv: ", self.graph_num, xlim)
        if self.ax1 is not None and xlim != self.xlim:
            self.xlim = xlim
            self.fig.canvas.toolbar.push_current()
            #print("setting: ", self.graph_num, xlim)
            self.ax1.set_xlim(xlim)
            # trigger the timer, this allows us to setup a v slow animation,
            # which saves a lot of CPU
            self.ani.event_source._on_timer()

function(xmlElement) {
    this.arguments_ = [];
    for (var i = 0, childNode; childNode = xmlElement.childNodes[i]; i++) {
      if (childNode.nodeName.toLowerCase() == 'arg') {
        this.arguments_.push(childNode.getAttribute('name'));
      }
    }
    this.updateParams_();
    Blockly.Procedures.mutateCallers(this);

    // Show or hide the statement input.
    this.setStatements_(xmlElement.getAttribute('statements') !== 'false');
  }

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


Question:
Removes the value of the image element if any. It is safe to call this
method regardless of if an image has been set or not.

public JQMListItem removeImage() {
        if (imageElem != null) {
            imageElem.removeFromParent();
            imageElem = null;
        }
        getElement().removeClassName(STYLE_UI_LI_HAS_THUMB);
        return this;
    }

def clear_provider_links(self):

        # Implemented from template for osid.learning.ActivityForm.clear_assets_template
        if (self.get_provider_links_metadata().is_read_only() or
                self.get_provider_links_metadata().is_required()):
            raise errors.NoAccess()
        self._my_map['providerLinkIds'] = self._provider_links_default

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


Question:
Required to back the priority queue for scheduled tasks.

@param a the first Task
@param b the second Task
@return 0 if equal, < 0 if a < b, > 0 if a > b

public int compare(final Object a, final Object b) {

        final long awhen = ((Task) (a)).getNextScheduled();
        final long bwhen = ((Task) (b)).getNextScheduled();

        return (awhen < bwhen) ? -1
                               : (awhen == bwhen) ? 0
                                                  : 1;
    }

public function query(string $query)
    {
        if (self::$monitorQueries) {
            $queryStartTime   = microtime(true);
            self::$strQueries .= $query . "\n";
        }

        $result = $this->sendQuery($query);

        if (self::$monitorQueries) {
            global $time;
            $queryEndTime  = microtime(true);
            $curScriptTime = $queryEndTime - $time;
            /** @var int $queryStartTime */
            $queryExecTime    = $queryEndTime - $queryStartTime;
            self::$strQueries .= '  Script time: ' . round($curScriptTime, 8) . "\n";
            self::$strQueries .= '  Query  time: ' . round($queryExecTime, 8) . "\n";
        }

        return $result;
    }

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


Question: Limit row passing a value or detect limits making the best effort.

def row_csv_limiter(rows, limits=None):

    limits = [None, None] if limits is None else limits

    if len(exclude_empty_values(limits)) == 2:
        upper_limit = limits[0]
        lower_limit = limits[1]
    elif len(exclude_empty_values(limits)) == 1:
        upper_limit = limits[0]
        lower_limit = row_iter_limiter(rows, 1, -1, 1)
    else:
        upper_limit = row_iter_limiter(rows, 0, 1, 0)
        lower_limit = row_iter_limiter(rows, 1, -1, 1)

    return rows[upper_limit: lower_limit]

private int minLimit(int input, int min) {
        if (input < min) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Config: " + input + " too small.");
            }
            return min;
        }
        return input;
    }

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


Question:
Add a participant to a tournament (up until it is started).

@param array $params

public function addParticipant($params = [])
    {
        $response = Guzzle::post("tournaments/{$this->id}/participants", $params);

        $participant = new Participant($response->participant);
        $participant->tournament_slug = $this->id;

        return $participant;
    }

public function register($username, $password)
    {
        $userData = [
            'auth' => [
                'type' => 'm.login.dummy'
            ],
            'bind_email' => false,
            'bind_msisdn' => false,
            'password' => $password,
            'x_show_msisdn' => false
        ];

        if ($username) {
            $userData['username'] = $username;
        }

        $data = $this->matrix()->request('POST', $this->endpoint('register'), $userData, [
            'kind' => 'user'
        ]);
        $this->setData($data);
        return $this->data;
    }

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


Question: // MonthNarrow returns the locales narrow month given the 'month' provided

func (rof *rof) MonthNarrow(month time.Month) string {
	return rof.monthsNarrow[month]
}

public InternalLocaleBuilder setLanguageTag(LanguageTag langtag) {
        clear();
        if (langtag.getExtlangs().size() > 0) {
            _language = langtag.getExtlangs().get(0);
        } else {
            String language = langtag.getLanguage();
            if (!language.equals(LanguageTag.UNDETERMINED)) {
                _language = language;
            }
        }
        _script = langtag.getScript();
        _region = langtag.getRegion();

        List<String> bcpVariants = langtag.getVariants();
        if (bcpVariants.size() > 0) {
            StringBuilder var = new StringBuilder(bcpVariants.get(0));
            for (int i = 1; i < bcpVariants.size(); i++) {
                var.append(BaseLocale.SEP).append(bcpVariants.get(i));
            }
            _variant = var.toString();
        }

        setExtensions(langtag.getExtensions(), langtag.getPrivateuse());

        return this;
    }

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


Question:
Returns array of relevant context capability records.

@return array

public function get_capabilities() {
        global $DB;

        $sort = 'ORDER BY contextlevel,component,name';   // To group them sensibly for display

        $params = array();
        $sql = "SELECT *
                  FROM {capabilities}
                 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";

        return $DB->get_records_sql($sql.' '.$sort, $params);
    }

protected function fireAfterResolvingCallbacks($abstract, $object)
    {
        $this->fireCallbackArray($object, $this->globalAfterResolvingCallbacks);

        $this->fireCallbackArray(
            $object, $this->getCallbacksForType($abstract, $object, $this->afterResolvingCallbacks)
        );
    }

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


Question:
// GetBinaryName checks if useBinary is in binDir and returns it. If
// useBinary is empty it returns a binary name if there is only one
// such in binDir. Otherwise it returns an error.

func GetBinaryName(binDir, useBinary string) (string, error) {
	fi, err := ioutil.ReadDir(binDir)
	if err != nil {
		return "", err
	}

	switch {
	case len(fi) < 1:
		return "", fmt.Errorf("No binaries found in %q", binDir)
	case len(fi) == 1:
		name := fi[0].Name()
		if useBinary != "" && name != useBinary {
			return "", fmt.Errorf("No such binary found in %q: %q. There is only %q", binDir, useBinary, name)
		}
		Debug("found binary: ", name)
		return name, nil
	case len(fi) > 1:
		names := []string{}
		for _, v := range fi {
			names = append(names, v.Name())
		}
		if useBinary == "" {
			return "", fmt.Errorf("Found multiple binaries in %q, but no specific binary is preferred. Please specify which binary to pick up. Following binaries are available: %q", binDir, strings.Join(names, `", "`))
		}
		for _, v := range names {
			if v == useBinary {
				return v, nil
			}
		}
		return "", fmt.Errorf("No such binary found in %q: %q. There are following binaries available: %q", binDir, useBinary, strings.Join(names, `", "`))
	}
	panic("Reaching this point shouldn't be possible.")
}

func (c *Custom) Parse(files *map[string]*file.File, dirs **dir.Dir, config *SharedConfig) error {
	to := *files
	dirList := *dirs

	var newList []string
	for _, customFile := range c.Files {
		// get files from glob
		list, err := doublestar.Glob(customFile)
		if err != nil {
			return err
		}

		// insert files from glob into the new list
		newList = append(newList, list...)
	}

	// copy new list
	c.Files = newList

	// 0 files in the list
	if len(c.Files) == 0 {
		return errors.New("No files found")
	}

	// loop through files from glob
	for _, customFile := range c.Files {
		// gives error when file doesn't exist
		if !utils.Exists(customFile) {
			return fmt.Errorf("File [%s] doesn't exist", customFile)
		}

		cb := func(fpath string, d *godirwalk.Dirent) error {
			if config.Updater.Empty && !config.Updater.IsUpdating {
				log.Println("empty mode")
				return nil
			}

			// only files will be processed
			if d != nil && d.IsDir() {
				return nil
			}

			originalPath := fpath
			fpath = utils.FixPath(fpath)

			var fixedPath string
			if c.Prefix != "" || c.Base != "" {
				c.Base = strings.TrimPrefix(c.Base, "./")

				if strings.HasPrefix(fpath, c.Base) {
					fixedPath = c.Prefix + fpath[len(c.Base):]
				} else {
					if c.Base != "" {
						fixedPath = c.Prefix + fpath
					}
				}

				fixedPath = utils.FixPath(fixedPath)
			} else {
				fixedPath = utils.FixPath(fpath)
			}

			// check for excluded files
			for _, excludedFile := range c.Exclude {
				m, err := doublestar.Match(c.Prefix+excludedFile, fixedPath)
				if err != nil {
					return err
				}

				if m {
					return nil
				}
			}

			info, err := os.Stat(fpath)
			if err != nil {
				return err
			}

			if info.Name() == config.Output {
				return nil
			}

			// get file's content
			content, err := ioutil.ReadFile(fpath)
			if err != nil {
				return err
			}

			replaced := false

			// loop through replace list
			for _, r := range c.Replace {
				// check if path matches the pattern from property: file
				matched, err := doublestar.Match(c.Prefix+r.File, fixedPath)
				if err != nil {
					return err
				}

				if matched {
					for pattern, word := range r.Replace {
						content = []byte(strings.Replace(string(content), pattern, word, -1))
						replaced = true
					}
				}
			}

			// compress the content
			if config.Compression.Options != nil {
				content, err = config.Compression.Compress(content)
				if err != nil {
					return err
				}
			}

			dst := make([]byte, len(content)*4)
			for i := 0; i < len(content); i++ {
				dst[i*4] = byte('\\')
				dst[i*4+1] = byte('x')
				dst[i*4+2] = hextable[content[i]>>4]
				dst[i*4+3] = hextable[content[i]&0x0f]
			}

			f := file.NewFile()
			f.OriginalPath = originalPath
			f.ReplacedText = replaced
			f.Data = `[]byte("` + string(dst) + `")`
			f.Name = info.Name()
			f.Path = fixedPath
			f.Tags = c.Tags
			f.Base = c.Base
			f.Prefix = c.Prefix
			f.Modified = info.ModTime().String()

			if _, ok := to[fixedPath]; ok {
				f.Tags = to[fixedPath].Tags
			}

			// insert dir to dirlist so it can be created on b0x's init()
			dirList.Insert(path.Dir(fixedPath))

			// insert file into file list
			to[fixedPath] = f
			return nil
		}

		customFile = utils.FixPath(customFile)

		// unlike filepath.walk, godirwalk will only walk dirs
		f, err := os.Open(customFile)
		if err != nil {
			return err
		}

		defer f.Close()

		fs, err := f.Stat()
		if err != nil {
			return err
		}

		if fs.IsDir() {
			if err := godirwalk.Walk(customFile, &godirwalk.Options{
				Unsorted: true,
				Callback: cb,
			}); err != nil {
				return err
			}

		} else {
			if err := cb(customFile, nil); err != nil {
				return err
			}
		}
	}

	return nil
}

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


Question:
Internal method to escape special attribute name characters, to handle things like name spaces.
@param str The string to escape the characters in.

private String escapeStringSpecialCharacters(String str)
    {
        if (logger.isLoggable(Level.FINER)) logger.exiting(className, "escapeStringSpecialCharacters(String)");

        if (str != null)
        {
            StringBuffer strBuf = new StringBuffer("");

            for (int i = 0; i < str.length(); i++)
            {
                char strChar = str.charAt(i);

                switch (strChar)
                {
                    case '"':
                        {
                            strBuf.append("\\\"");
                            break;
                        }
                    case '\t':
                        {
                            strBuf.append("\\t");
                            break;
                        }
                    case '\b':
                        {
                            strBuf.append("\\b");
                            break;
                        }
                    case '\\':
                        {
                            strBuf.append("\\\\");
                            break;
                        }
                    case '\f':
                        {
                            strBuf.append("\\f");
                            break;
                        }
                    case '\r':
                        {
                            strBuf.append("\\r");
                            break;
                        }
                    case '/':
                        {
                            strBuf.append("\\/");
                            break;
                        }
                    default:
                        {
                            if ((strChar >= 32) && (strChar <= 126) )
                            {
                                strBuf.append(strChar);
                            }
                            else if (strChar > 126)
                            {
                              if ((escapeNonAsciiChars))
                              {
                                  strBuf.append("\\u");
                                  StringBuffer sb = new StringBuffer(Integer.toHexString(strChar));
                                  while (sb.length() < 4)
                                  {
                                      sb.insert(0,'0');
                                  }
                                  strBuf.append(sb.toString());
                              }
                              else {
                                strBuf.append(strChar);
                              }
                            }
                            else
                            {
                                strBuf.append("\\u");
                                StringBuffer sb = new StringBuffer(Integer.toHexString(strChar));
                                while (sb.length() < 4)
                                {
                                    sb.insert(0,'0');
                                }
                                strBuf.append(sb.toString());
                            }

                            break;
                        }
                }
            }
            str = strBuf.toString();
        }
        if (logger.isLoggable(Level.FINER)) logger.exiting(className, "escapeStringSpecialCharacters(String)");
        return str;
    }

def normalized_query(*flags)
      return nil unless self.query
      return @normalized_query if defined?(@normalized_query)
      @normalized_query ||= begin
        modified_query_class = Addressable::URI::CharacterClasses::QUERY.dup
        # Make sure possible key-value pair delimiters are escaped.
        modified_query_class.sub!("\\&", "").sub!("\\;", "")
        pairs = (self.query || "").split("&", -1)
        pairs.sort! if flags.include?(:sorted)
        component = pairs.map do |pair|
          Addressable::URI.normalize_component(pair, modified_query_class, "+")
        end.join("&")
        component == "" ? nil : component
      end
      # All normalized values should be UTF-8
      @normalized_query.force_encoding(Encoding::UTF_8) if @normalized_query
      @normalized_query
    end

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


Question: Detects react file changes

public function detectChanges()
    {
        $this->signalDispatcher->connect(FlowFileMonitor::class, 'filesHaveChanged', function (string $fileMonitorIdentifier, array $changedFiles) {
            if ($fileMonitorIdentifier === static::FILE_MONITOR_IDENTIFIER) {
                foreach ($changedFiles as $changedFile => $status) {
                    if ($status === ChangeDetectionStrategyInterface::STATUS_DELETED) {
                        $this->unmonitorFile($changedFile);
                        $this->emitFileHasChanged($changedFile);
                    }

                    if ($status === ChangeDetectionStrategyInterface::STATUS_CHANGED) {
                        $this->emitFileHasChanged($changedFile);
                    }
                }
            }
        });

        $fileMonitor = new FlowFileMonitor(static::FILE_MONITOR_IDENTIFIER);
        $files = $this->cache->getByTag('file');

        foreach ($files as $file) {
            $fileMonitor->monitorFile($file);
        }

        $fileMonitor->detectChanges();
        $fileMonitor->shutdownObject();
    }

public function setLastModifiedTime(PhingFile $f, $time)
    {
        $path = $f->getPath();
        $success = @touch($path, $time);
        if (!$success) {
            throw new IOException("Could not touch '" . $path . "' due to: $php_errormsg");
        }
    }

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


Question: // RunCommand defines the libcompose run subcommand.

func RunCommand(factory app.ProjectFactory) cli.Command {
	return cli.Command{
		Name:   "run",
		Usage:  "Run a one-off command",
		Action: app.WithProject(factory, app.ProjectRun),
		Flags: []cli.Flag{
			cli.BoolFlag{
				Name:  "d",
				Usage: "Detached mode: Run container in the background, print new container name.",
			},
		},
	}
}

def _local(self, args):
        '''

        '''
        args.pop(0)
        command = args[0]
        if command == 'install':
            self._local_install(args)
        elif command == 'files':
            self._local_list_files(args)
        elif command == 'info':
            self._local_info(args)
        else:
            raise SPMInvocationError('Invalid local command \'{0}\''.format(command))

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


Question: // Gt creates a > comparison expression.

func (b ValExprBuilder) Gt(val interface{}) BoolExprBuilder {
	return b.makeComparisonExpr(astGT, makeValExpr(val))
}

function isGoogCallExpression(node, name) {
  const callee = node.callee;
  return callee && callee.type === 'MemberExpression' &&
      callee.object.type === 'Identifier' && callee.object.name === 'goog' &&
      callee.property.type === 'Identifier' && !callee.property.computed &&
      callee.property.name === name;
}

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


Question:
:rtype: core.BunqModel
        :raise: BunqException

def get_referenced_object(self):

        if self._UserPerson is not None:
            return self._UserPerson

        if self._UserCompany is not None:
            return self._UserCompany

        raise exception.BunqException(self._ERROR_NULL_FIELDS)

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

        invalid_tree_records = dict()
        invalid_tq_records = dict()

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

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

                tree.update_node(job_record)

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

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

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

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


Question: Qiita記法を独自フォーマットに変換

function(page) {
			var regixAll = /([^\S]```.*)(:(.+))[\s\S]+?```/g;
			var regix = /([^\S]```.*)(:(.+))[\s\S]+?```/;
			var matchAll = page.content.match(regixAll);

			for(var i = 0; matchAll && i < matchAll.length; i++){
				var match = matchAll[i].match(regix);
				var input = match.input.replace(match[2], "");
				var replace = input.replace(match[1], "\n\n!FILENAME " + match[3] + match[1]);
				page.content = page.content.replace(match.input, replace);
			}

			return page;
		}

def get_options():

    #already imported Qt somewhere. Use that
    loaded = loaded_api()
    if loaded is not None:
        return [loaded]

    mpl = sys.modules.get('matplotlib', None)

    if mpl is not None and not check_version(mpl.__version__, '1.0.2'):
        #1.0.1 only supports PyQt4 v1
        return [QT_API_PYQT_DEFAULT]

    if os.environ.get('QT_API', None) is None:
        #no ETS variable. Ask mpl, then use either
        return matplotlib_options(mpl) or [QT_API_PYQT_DEFAULT, QT_API_PYSIDE, QT_API_PYQT5]

    #ETS variable present. Will fallback to external.qt
    return None

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


Question: get a list of all of the files in the repository

def list(self, path=None, with_metadata=False, include_partitions=False):
        ''''''
        return self.upstream.list(
            path,
            with_metadata=with_metadata,
            include_partitions=include_partitions)

def get_branches(self, local=True, remote_branches=True):
        """"""

        if not self.repo.remotes:
            remote_branches = False

        branches = []

        if remote_branches:

            # Remote refs.
            try:
                for b in self.remote.refs:
                    name = '/'.join(b.name.split('/')[1:])

                    if name not in legit_settings.forbidden_branches:
                        branches.append(Branch(name, is_published=True))
            except (IndexError, AssertionError):
                pass

        if local:

            # Local refs.
            for b in [h.name for h in self.repo.heads]:

                if (not remote_branches) or (b not in [br.name for br in branches]):
                    if b not in legit_settings.forbidden_branches:
                        branches.append(Branch(b, is_published=False))

        return sorted(branches, key=attrgetter('name'))

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


Question:
Load includes.

@param array $results Loaded records

protected function loadIncludes(array $results): void
	{
		$includes = $this->parseIncludes();

		foreach($includes['this'] as $include => $criteria)
		{
			$forward = $includes['forward'][$include] ?? [];

			$results[0]->$include()->eagerLoad($results, $include, $criteria, $forward);
		}
	}

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:
/*
(non-Javadoc)
@see javax.slee.resource.ResourceAdaptor#setResourceAdaptorContext(javax.slee.resource.ResourceAdaptorContext)

public void setResourceAdaptorContext(javax.slee.resource.ResourceAdaptorContext raContext) {
		this.raContext = raContext;
		this.tracer = raContext.getTracer("XCAPClientResourceAdaptor");
		sbbInterface = new XCAPClientResourceAdaptorSbbInterfaceImpl(this);
        this.sleeEndpoint = raContext.getSleeEndpoint();
        this.eventLookupFacility = raContext.getEventLookupFacility();

        try {
        	this.getResponseEvent = eventLookupFacility.getFireableEventType(new EventTypeID("GetResponseEvent", "org.restcomm", "2.0"));
        	this.putResponseEvent = eventLookupFacility.getFireableEventType(new EventTypeID("PutResponseEvent", "org.restcomm", "2.0"));
        	this.deleteResponseEvent = eventLookupFacility.getFireableEventType(new EventTypeID("DeleteResponseEvent", "org.restcomm", "2.0"));
        }
        catch(Exception e) {
        	if(tracer.isWarningEnabled())
        		tracer.warning("Could not look up Response Event",e);
        }
	}

public base_response save_config() throws Exception
	{
		nsconfig resource = new nsconfig();
		options option = new options();
		option.set_action("save");
		base_response result = resource.perform_operation(this, option);
		return result;
	}

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


Question: // SetSortingEntities sets the SortingEntities field's value.

func (s *DescribeClusterSnapshotsInput) SetSortingEntities(v []*SnapshotSortingEntity) *DescribeClusterSnapshotsInput {
	s.SortingEntities = v
	return s
}

protected function _resolveBundle(EntityInterface $entity)
    {
        $bundle = $this->config('bundle');
        if (is_callable($bundle)) {
            $callable = $this->config('bundle');
            $bundle = $callable($entity);
        }

        return (string)$bundle;
    }

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


Question:
Connect to the bus Redis instance

@param {Object} busModule

function connect(busModule) {
  if (busModule) {
    module.exports.client = busModule.connect();
    BUS_MODULE = true;
  } else {
    log('info', `Connecting to default Redis event bus at ${process.env.CLAY_BUS_HOST}`);
    module.exports.client = new Redis(process.env.CLAY_BUS_HOST);
  }
}

def get_component_types(topic_id, remoteci_id, db_conn=None):
    """"""

    db_conn = db_conn or flask.g.db_conn
    rconfiguration = remotecis.get_remoteci_configuration(topic_id,
                                                          remoteci_id,
                                                          db_conn=db_conn)

    # if there is no rconfiguration associated to the remoteci or no
    # component types then use the topic's one.
    if (rconfiguration is not None and
            rconfiguration['component_types'] is not None):
        component_types = rconfiguration['component_types']
    else:
        component_types = get_component_types_from_topic(topic_id,
                                                         db_conn=db_conn)

    return component_types, rconfiguration

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


Question:
Allow the defaults to be specified via the `lockerProvider`

@param {Object}  value  The defaults to override

function (value) {
                if (! _defined(value)) return defaults;

                angular.forEach(value, function (val, key) {
                    if (defaults.hasOwnProperty(key)) defaults[key] = val;
                });
            }

protected function substituteImplicitBindings( $route )
	{
		$parameters = $route->parameters();

		foreach ( $route->signatureParameters( Model::class ) as $parameter )
		{
			$class = $parameter->getClass();

			if ( array_key_exists( $parameter->name, $parameters ) && !$route->getParameter( $parameter->name ) instanceof Model )
			{
				$method = $parameter->isDefaultValueAvailable() ? 'first' : 'firstOrFail';

				$model = $class->newInstance();

				$route->setParameter( $parameter->name, $model->where( $model->getRouteKeyName(), $parameters[$parameter->name] )->{$method()} );
			}
		}
	}

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


Question:
Update the specified resource in storage.

@param \Illuminate\Http\Request   $request
@param \Laralum\Users\Models\User $user

@return \Illuminate\Http\Response

public function update(Request $request, User $user)
    {
        $this->authorize('update', $user);
        $this->validate($request, [
            'name'     => 'required|max:255',
        ]);

        $user->update([
            'name' => $request->name,
        ]);

        return redirect()->route('laralum::users.index');
    }

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

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


Question:
checks if property which is checked via has$PROPERTYNAME() is set

@param   string  $propertyName
@return  bool

protected function hasProperty(string $propertyName): bool
    {
        if (count($this->values) === 1
          && isset($this->values['__value'])
          && 'value' === $propertyName) {
            return isset($this->values['__value']);
        }

        return isset($this->values[$propertyName]);
    }

function() {
      var designSet = this._designSet;

      if (this.type in designSet.value) {
        var designType = designSet.value[this.type];

        if ('decorate' in designSet.value[this.type]) {
          this.isDecorated = true;
        } else {
          this.isDecorated = false;
        }

        if (this.name in designSet.property) {
          this.isMultiValue = ('multiValue' in designSet.property[this.name]);
          this.isStructuredValue = ('structuredValue' in designSet.property[this.name]);
        }
      }
    }

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


Question:
`-webkit-gradient`转`radial-gradient`或`linear-gradient`
@param  {Array} args      修正前的参数
@param  {Node}  gradient  原始的node对象
@return {Array}           修正后的参数

function fixOldGradient (args, gradient) {
	const type = args[0][0];
	let colorStops = [];
	let from;
	let to;

	// 将参数中的`color-stop`,`from`,`to`三种信息剔除出args并单独存放，剩下的存起来
	args = args.slice(1).filter((arg) => {
		const fnName = arg.value;
		if (fnName === "from") {
			from = arg;
		} else if (fnName === "to") {
			to = arg;
		} else if (fnName === "color-stop") {
			colorStops.push(arg);
		} else {
			return true;
		}
		return false;
	});

	if (from) {
		// 将from信息放入colorStops头部
		colorStops.unshift(from);
	}
	if (to) {
		// 将from信息放入colorStops尾部
		colorStops.push(to);
	}

	// 将数组colorStops中的元素都转换为标准形式
	colorStops = colorStops.map((colorStop, i) => {
		// 获取colorStop的参数
		colorStop = colorStop.nodes;
		// 如果不知一个参数
		if (colorStop.length > 1) {
			// 计算位置信息的浏览器默认值
			const posVal = i * 100 / (colorStops.length - 1);
			colorStop = colorStop.filter((val) => {
				// 如果位置信息与浏览器默认值相同，去除它
				return parseFloat(val) !== posVal;
			});

			if (colorStop.length > 1) {
				// 参数重新排列，位置信息放在后面，以便符合新语法
				colorStop.sort((word) => {
					return isNaN(parseFloat(word)) ? -1 : 1;
				});
			}
		}
		return colorStop;
	});

	if (type === "radial") {
		// 按照圆形渐变语法处理剩下的参数
		args = fixOldRadialGradient(args);
	} else {
		// 按照线性渐变语法处理剩下的参数
		args = fixOldLinearGradient(args);
	}

	if (args && args.length) {
		// 将`fixOldRadialGradient`或`fixOldLinearGradient`的返回结果插入colorStops
		colorStops.unshift(args);
	}
	// 将css属性名名称转换为标准的
	gradient.value = type + "-gradient";
	return colorStops;
}

def unfuse(self):

        stack = SequentialRNNCell()
        get_cell = {'rnn_relu': lambda cell_prefix: RNNCell(self._num_hidden,
                                                            activation='relu',
                                                            prefix=cell_prefix),
                    'rnn_tanh': lambda cell_prefix: RNNCell(self._num_hidden,
                                                            activation='tanh',
                                                            prefix=cell_prefix),
                    'lstm': lambda cell_prefix: LSTMCell(self._num_hidden,
                                                         prefix=cell_prefix),
                    'gru': lambda cell_prefix: GRUCell(self._num_hidden,
                                                       prefix=cell_prefix)}[self._mode]
        for i in range(self._num_layers):
            if self._bidirectional:
                stack.add(BidirectionalCell(
                    get_cell('%sl%d_'%(self._prefix, i)),
                    get_cell('%sr%d_'%(self._prefix, i)),
                    output_prefix='%sbi_l%d_'%(self._prefix, i)))
            else:
                stack.add(get_cell('%sl%d_'%(self._prefix, i)))

            if self._dropout > 0 and i != self._num_layers - 1:
                stack.add(DropoutCell(self._dropout, prefix='%s_dropout%d_'%(self._prefix, i)))

        return stack

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


Question: Auto Generated Code

def copy_config_input_target_config_target_url_url(self, **kwargs):

        config = ET.Element("config")
        copy_config = ET.Element("copy_config")
        config = copy_config
        input = ET.SubElement(copy_config, "input")
        target = ET.SubElement(input, "target")
        config_target = ET.SubElement(target, "config-target")
        url = ET.SubElement(config_target, "url")
        url = ET.SubElement(url, "url")
        url.text = kwargs.pop('url')

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

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

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

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


Question:
export

@return mixed|string

public function export()
    {
        $tables = $this->db->getDatabase()->getTables(true);

        $sql = [];

        foreach ($tables as $table) {
            // Table
            $sql[] = MysqlGrammar::dropTable($table, true);
            $sql[] = $this->getCreateTable($table);

            // Data
            $inserts = $this->getInserts($table);

            if ($inserts) {
                $sql[] = $inserts;
            }
        }

        return implode(";\n\n", $sql);
    }

def text_result(text: str,
                extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None,
                filename: str = None) -> WSGI_TUPLE_TYPE:

    extraheaders = extraheaders or []
    if filename:
        extraheaders.append(
            ('content-disposition', 'inline; filename="{}"'.format(filename))
        )
    contenttype = 'text/plain; charset=utf-8'
    if filename:
        contenttype += '; filename="{}"'.format(filename)
    return contenttype, extraheaders, text.encode("utf-8")

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


Question:
return SEO URL for the requested response.

@param $sResponseName string

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

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

protected function _singleMeta($name, $content)
    {
        if( stripos($name, 'http:') === 0 )
        {
            $name = ' http-equiv="'.str_ireplace('http:', NULL, $name).'"';
        }
        elseif( stripos($name, 'property:') === 0 )
        {
            $name = ' property="'.str_ireplace('property:', NULL, $name).'"';
        }
        else
        {
            $name = ' name="'.str_ireplace('name:', NULL, $name).'"';
        }

        if( ! empty($content) )
        {
            $content = ' content="'.$content.'"';
        }
        else
        {
            $content = '';
        }

        return '<meta' . $name . $content . ' />' . EOL;
    }

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


Question: Calculate the height for bar type charts

function (d, chart, series) {
            var returnHeight = 0;
            if (series.y._hasTimeField()) {
                returnHeight = series.y.floatingBarWidth;
            } else if (series.y.measure !== null && series.y.measure !== undefined) {
                returnHeight = Math.abs(series.y._scale(d.y) - series.y._scale((d.y <= 0 ? d.y + d.height : d.y - d.height)));
            } else {
                returnHeight = d.height * ((chart._heightPixels() / series.y._max) - (dimple._helpers.yGap(chart, series) * 2)) - (dimple._helpers.yClusterGap(d, chart, series) * 2);
            }
            return returnHeight;
        }

public float getCharHeight(char c, FontOptions options)
	{
		return getCharData(c).getCharHeight() / fontGeneratorOptions.fontSize * (options != null ? options.getFontScale() : 1) * 9;
	}

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


Question:
Returns the template variables in key value format

@param array data
@return array

public function getVariables()
	{
		$pages 	= ceil($this->total / $this->range);
		$page 	= floor($this->start / $this->range) + 1;

		$min 	= $page - $this->show;
		$max 	= $page + $this->show;

		if($min < 1) {
			$min = 1;
		}

		if($max > $pages) {
			$max = $pages;
		}

		return array(
			'class'	=> $this->class,
			'url'	=> $this->url,
			'query' => $this->query,
			'start' => $this->start,
			'range' => $this->range,
			'total' => $this->total,
			'show'	=> $this->show,
			'min'	=> $min,
			'max'	=> $max,
			'pages' => $pages,
			'page'	=> $page);
	}

public static function SelectValuesWithParamAndResolver( $xpath, $resolver, $vars )
	{
		/**
		 * @var XPath2NodeIterator $iter
		 */
		$iter = XPath2NodeIterator::Create( Compile( $xpath, $resolver )->EvaluateWithVars( null, $vars ) );
		while ( $iter->MoveNext() )
		{
			yield $iter->getCurrent()->GetTypedValue();
		}
	}

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


Question: Retrieves the messages from any direct message in the server

def im_messages_others(self, room_id, **kwargs):
        """"""
        return self.__call_api_get('im.messages.others', roomId=room_id, kwargs=kwargs)

public function getRawMessage(): string
    {
        if (null === $this->rawMessage) {
            $this->rawMessage = $this->doGetContent('');
        }

        return $this->rawMessage;
    }

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


Question: Reference counted wrapper for a plugin object

function (options, completion) {
    var Proto = function PluginProxy() {},
        api = new Proto(),
        waitForReadySignal = pluginEventingBehaviour(api);

    refCountBehaviour(api);

    // Assign +plugin+ to this object and setup all the public
    // accessors that relate to the DOM Object.
    //
    var setPlugin = function setPlugin (plugin) {
          if (plugin) {
            api._ = plugin;
            api.parentElement = plugin.parentElement;
            api.$ = $(plugin);
          }
          else {
            api._ = null;
            api.parentElement = null;
            api.$ = $();
          }
        };

    api.uuid = generateCallbackID();

    api.isValid = function() {
      return api._.valid;
    };

    api.destroy = function() {
      api.removeAllRefs();
      setPlugin(null);

      // Let listeners know that they should do any final book keeping
      // that relates to us.
      api.emit('destroy');
    };

    /// Initialise

    // The next statement creates the raw plugin object accessor on the Proxy.
    // This is null until we actually have created the Object.
    setPlugin(null);

    waitOnGlobalCallback(api.uuid, function(err) {
      if (err) {
        completion('The plugin with the mimeType of ' +
                        options.mimeType + ' timed out while loading: ' + err);

        api.destroy();
        return;
      }

      api._.setAttribute('id', 'tb_plugin_' + api._.uuid);
      api._.removeAttribute('tb_callback_id');
      api.uuid = api._.uuid;
      api.id = api._.id;

      waitForReadySignal(function(err) {
        if (err) {
          completion('Error while starting up plugin ' + api.uuid + ': ' + err);
          api.destroy();
          return;
        }

        completion(void 0, api);
      });
    });

    createObject(api.uuid, options, function(err, plugin) {
      setPlugin(plugin);
    });

    return api;
  }

func (obj *Doc) CloneBookmark(ctx context.Context, id string) (string, error) {
	result := &struct {
		CloneId string	`json:"qCloneId"`
	} {}
	err := obj.rpc(ctx, "CloneBookmark", result, id)
	return result.CloneId, err
}

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


Question:
Returns the scroll bar state of the window. Helper for hasScrollbar().

@param {Object} query
@param {Object} context

@returns {{vertical: boolean, horizontal: boolean}}

function _windowHasScrollbar ( query, context ) {

        var windowInnerHeight, windowInnerWidth, windowProps,
            scrollbarWidth = $.scrollbarWidth(),
            result = {},
            doneX = ! query.getHorizontal,
            doneY = ! query.getVertical;

        // We may be able to take a shortcut. The window.innerWidth and -Height report the dimensions of the viewport
        // including scroll bars, and documentElement.clientWidth and -Height report them without scroll bars. That
        // gives the presence of a scroll bar away, as long as
        //
        // - the scroll bars actually take up space (width > 0)
        // - the browser supports window.innerWidth/Height (IE8, for instance, does not)
        // - the browser doesn't report a buggy value. FF has a bug which as only been fixed in FF25 (released 29 Oct
        //   2013). It manifests itself in a fictional return value of 10 for these properties. See
        //   * https://developer.mozilla.org/en-US/docs/Web/API/Window.innerWidth
        //   * https://developer.mozilla.org/en-US/docs/Web/API/Window.innerHeight
        //   * https://bugzilla.mozilla.org/show_bug.cgi?id=641188

        if ( query.getHorizontal && scrollbarWidth > 0 ) {
            windowInnerHeight = context.window.innerHeight;
            if ( windowInnerHeight > 10 ) {
                result.horizontal = windowInnerHeight > context.documentElement.clientHeight;
                doneX = true;
            }
        }

        if ( query.getVertical && scrollbarWidth > 0 ) {
            windowInnerWidth = context.window.innerWidth;
            if ( windowInnerWidth > 10 ) {
                result.vertical = windowInnerWidth > context.documentElement.clientWidth;
                doneY = true;
            }
        }

        if ( ! doneX || ! doneY ) {

            // Shortcut didn't work. We have to evaluate overflow settings, window and document size.

            windowProps = _getViewportOverflows( query, context ).window;

            // Handle the trivial cases first: window set to overflow: scroll or to overflow: hidden.
            if ( ! doneX && windowProps.overflowScrollX ) result.horizontal = doneX = true;
            if ( ! doneY && windowProps.overflowScrollY ) result.vertical = doneY = true;

            if ( ! doneX && windowProps.overflowHiddenX ) {
                result.horizontal = false;
                doneX = true;
            }

            if ( ! doneY && windowProps.overflowHiddenY ) {
                result.vertical = false;
                doneY = true;
            }

            // Handle the remaining overflow: auto case
            //
            // (There is no actual overflow: visible case for the viewport, see getAppliedViewportOverflows.)
            if ( ! doneX ) result.horizontal = context.documentElement.clientWidth < $.documentWidth( context.document );
            if ( ! doneY ) result.vertical = context.documentElement.clientHeight < $.documentHeight( context.document );

        }

        return result;

    }

public function tailable($tail = true)
    {
        $tail = (boolean) $tail;
        $this->tailable = $tail;
        $this->riakCursor->tailable($tail);
        return $this;
    }

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


Question:
Register bindings in the container.

@return void

public function register()
    {
        $this->app->bind('soda.field.repository', function ($app) {
            return new FieldRepository(new Field);
        });

        $this->registerAliases($this->aliases);
    }

func (n *EndpointSelector) AddMatch(key, value string) {
	if n.MatchLabels == nil {
		n.MatchLabels = map[string]string{}
	}
	n.MatchLabels[key] = value
	n.requirements = labelSelectorToRequirements(n.LabelSelector)
}

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


Question:
Reinstate volume.

        Args:
            fade (bool): Whether volume should be faded up on restore.

def _restore_volume(self, fade):

        self.device.mute = self.mute

        # Can only change volume on device with fixed volume set to False
        # otherwise get uPnP error, so check first. Before issuing a network
        # command to check, fixed volume always has volume set to 100.
        # So only checked fixed volume if volume is 100.
        if self.volume == 100:
            fixed_vol = self.device.renderingControl.GetOutputFixed(
                [('InstanceID', 0)])['CurrentFixed']
        else:
            fixed_vol = False

        # now set volume if not fixed
        if not fixed_vol:
            self.device.bass = self.bass
            self.device.treble = self.treble
            self.device.loudness = self.loudness

            if fade:
                # if fade requested in restore
                # set volume to 0 then fade up to saved volume (non blocking)
                self.device.volume = 0
                self.device.ramp_to_volume(self.volume)
            else:
                # set volume
                self.device.volume = self.volume

function (name, value) {
        var self = this, elm = self.getEl(self.ariaTarget);

        if (typeof value === "undefined") {
          return self._aria[name];
        }

        self._aria[name] = value;

        if (self.state.get('rendered')) {
          elm.setAttribute(name == 'role' ? name : 'aria-' + name, value);
        }

        return self;
      }

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


Question:
Init file header for DBF File
@param dbfFile DBF File path
@param forceEncoding File encoding to use, null will use the file encoding provided in the file header
@throws IOException

public void initDriverFromFile(File dbfFile, String forceEncoding) throws IOException {
        // Read columns from files metadata
        this.dbfFile = dbfFile;
        FileInputStream fis = new FileInputStream(dbfFile);
        dbaseFileReader = new DbaseFileReader(fis.getChannel(), forceEncoding);
    }

def parse_args():
    """"""
    parser = argparse.ArgumentParser(
        description='Check kafka current status',
    )
    parser.add_argument(
        "--cluster-type",
        "-t",
        dest='cluster_type',
        required=True,
        help='Type of cluster',
        default=None,
    )
    parser.add_argument(
        "--cluster-name",
        "-c",
        dest='cluster_name',
        help='Name of the cluster',
    )
    parser.add_argument(
        '--discovery-base-path',
        dest='discovery_base_path',
        type=str,
        help='Path of the directory containing the <cluster_type>.yaml config',
    )
    parser.add_argument(
        "--broker-id",
        help='The broker id where the check is running. Set to -1 if you use automatic '
        'broker ids, and it will read the id from data-path instead. This parameter is '
        'required only in case controller-only or first-broker-only are used.',
        type=convert_to_broker_id,
    )
    parser.add_argument(
        "--data-path",
        help='Path to the Kafka data folder.',
    )
    parser.add_argument(
        '--controller-only',
        action="store_true",
        help='If this parameter is specified, it will do nothing and succeed on '
        'non-controller brokers. Default: %(default)s',
    )
    parser.add_argument(
        '--first-broker-only',
        action='store_true',
        help='If specified, the command will only perform the check if '
        'broker_id is the lowest broker id in the cluster. If it is not the lowest, '
        'it will not perform any check and succeed immediately. '
        'Default: %(default)s',
    )
    parser.add_argument(
        '-v',
        '--verbose',
        help='print verbose execution information. Default: %(default)s',
        action="store_true",
        default=False,
    )
    parser.add_argument(
        '-j',
        '--json',
        help='Print output in json format. Default: %(default)s',
        action="store_true",
        default=False,
    )

    subparsers = parser.add_subparsers()
    MinIsrCmd().add_subparser(subparsers)
    ReplicaUnavailabilityCmd().add_subparser(subparsers)
    ReplicationFactorCmd().add_subparser(subparsers)
    OfflineCmd().add_subparser(subparsers)

    return parser.parse_args()

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


Question:
Write out an image map area line with the coordinates passed to this
    function
    <area shape="rect" coords="tlx,tly,brx,bry" href="#chr7" title="chr7:100001..500001">

def write_ImageMapLine(tlx, tly, brx, bry, w, h, dpi, chr, segment_start, segment_end):

    tlx, brx = [canvas2px(x, w, dpi) for x in (tlx, brx)]
    tly, bry = [canvas2px(y, h, dpi) for y in (tly, bry)]
    chr, bac_list = chr.split(':')
    return '<area shape="rect" coords="' + \
           ",".join(str(x) for x in (tlx, tly, brx, bry)) \
           + '" href="#' + chr + '"' \
           + ' title="' + chr + ':' + str(segment_start) + '..' + str(segment_end) + '"' \
           + ' />'

func (obj *Doc) CloneBookmark(ctx context.Context, id string) (string, error) {
	result := &struct {
		CloneId string	`json:"qCloneId"`
	} {}
	err := obj.rpc(ctx, "CloneBookmark", result, id)
	return result.CloneId, err
}

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


Question: // Specifies the application name.

func (h *Client) ApplicationName(applicationName string) *Client {
	h.applicationName = applicationName
	h.applicationNameSet = true
	return h
}

protected function GenerateApplicationFile($files) {
        $filePath = $this->GenerateConstantsClass($files);
        array_push($this->filesGenerated, $filePath);
        return $filePath;
    }

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


Question:
// CreateExecutableCopy makes a temporary copy of a plugin binary and makes it
// executable.
//
// config.PluginHome() + /temp is used as the temp dir instead of the system
// temp for security reasons.

func (actor Actor) CreateExecutableCopy(path string, tempPluginDir string) (string, error) {
	tempFile, err := makeTempFile(tempPluginDir)
	if err != nil {
		return "", err
	}

	// add '.exe' to the temp file if on Windows
	executablePath := generic.ExecutableFilename(tempFile.Name())
	err = os.Rename(tempFile.Name(), executablePath)
	if err != nil {
		return "", err
	}

	err = fileutils.CopyPathToPath(path, executablePath)
	if err != nil {
		return "", err
	}

	err = os.Chmod(executablePath, 0700)
	if err != nil {
		return "", err
	}

	return executablePath, nil
}

public function execute() {
        global $CFG;

        // The directories hosting the candidate stale temp files eventually are $CFG->tempdir and $CFG->backuptempdir.

        // Do the job on each of the directories above.
        // Let's start with $CFG->tempdir.
        $this->execute_on($CFG->tempdir);

        // Run on $CFG->backuptempdir too, if different from the default one, '$CFG->tempdir/backup'.
        if (realpath(dirname($CFG->backuptempdir)) !== realpath($CFG->tempdir)) {
            // The $CFG->backuptempdir setting is different from the default '$CFG->tempdir/backup'.
            $this->execute_on($CFG->backuptempdir);
        }
    }

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


Question:
获取CDN域名访问日志的下载链接，具体下载操作请自行根据链接下载
参考文档：日志下载

@param domains 待获取日志下载信息的域名列表
@param logDate 待获取日志的具体日期，格式为：2017-02-18
@return 获取日志下载链接的回复

public CdnResult.LogListResult getCdnLogList(String[] domains, String logDate) throws QiniuException {
        HashMap<String, String> req = new HashMap<>();
        req.put("domains", StringUtils.join(domains, ";"));
        req.put("day", logDate);

        byte[] body = Json.encode(req).getBytes(Constants.UTF_8);
        String url = server + "/v2/tune/log/list";
        StringMap headers = auth.authorizationV2(url, "POST", body, Client.JsonMime);
        Response response = client.post(url, body, headers, Client.JsonMime);
        return response.jsonToObject(CdnResult.LogListResult.class);
    }

public function request($url, array $options = array())
    {
        $options += array(
            'data' => null,
            'timeout' => 30,
            'context' => null,
            'method' => 'GET',
            'headers' => array()
        );

        if ($options['method'] === 'POST' && empty($options['headers'])) {
            $options['headers'] = array('Content-Type' => 'application/x-www-form-urlencoded');
        }

        if (!empty($options['query'])) {
            $url = strtok($url, '?') . '?' . http_build_query($options['query']);
        }

        return $this->setUri($url)
            ->setHeaders($options['headers'])
            ->setMethod($options['method'])
            ->setData($options['data'])
            ->setTimeOut($options['timeout'])
            ->setContext($options['context'])
            ->setSocket()
            ->exec()
            ->getFormattedResponse();
    }

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


Question: // SetExpression sets the Expression field's value.

func (s *SelectObjectContentInput) SetExpression(v string) *SelectObjectContentInput {
	s.Expression = &v
	return s
}

public <T> T getField(String locale, String key) {
    return localize(locale).getField(key);
  }

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


Question:
Restore the model from the model identifier instance.

@param  \Illuminate\Contracts\Database\ModelIdentifier  $value
@return \Illuminate\Database\Eloquent\Model

public function restoreModel($value)
    {
        return $this->getQueryForModelRestoration(
            (new $value->class)->setConnection($value->connection), $value->id
        )->useWritePdo()->firstOrFail()->load($value->relations ?? []);
    }

public function track(array $queries)
    {
        if (count($queries) == 0)
            return null;

        $data = [
            'query'     => $this->prepareQuery($queries),
            'arguments' => $this->prepareArguments($queries),
        ];

        return $this->getModel()
            ->newQuery()
            ->firstOrCreate(Arr::only($data, ['query']), $data)
            ->getKey();
    }

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


Question:
Creates a session using available authentication type.

        Auth priority:
        1. Token Auth
        2. Tenant Auth
        3. Azure CLI Auth

def _initialize_session(self):

        # Only run once
        if self.credentials is not None:
            return

        tenant_auth_variables = [
            constants.ENV_TENANT_ID, constants.ENV_SUB_ID,
            constants.ENV_CLIENT_ID, constants.ENV_CLIENT_SECRET
        ]

        token_auth_variables = [
            constants.ENV_ACCESS_TOKEN, constants.ENV_SUB_ID
        ]

        msi_auth_variables = [
            constants.ENV_USE_MSI, constants.ENV_SUB_ID
        ]

        if self.authorization_file:
            self.credentials, self.subscription_id = self.load_auth_file(self.authorization_file)
            self.log.info("Creating session with authorization file")

        elif all(k in os.environ for k in token_auth_variables):
            # Token authentication
            self.credentials = BasicTokenAuthentication(
                token={
                    'access_token': os.environ[constants.ENV_ACCESS_TOKEN]
                })
            self.subscription_id = os.environ[constants.ENV_SUB_ID]
            self.log.info("Creating session with Token Authentication")
            self._is_token_auth = True

        elif all(k in os.environ for k in tenant_auth_variables):
            # Tenant (service principal) authentication
            self.credentials = ServicePrincipalCredentials(
                client_id=os.environ[constants.ENV_CLIENT_ID],
                secret=os.environ[constants.ENV_CLIENT_SECRET],
                tenant=os.environ[constants.ENV_TENANT_ID],
                resource=self.resource_namespace)
            self.subscription_id = os.environ[constants.ENV_SUB_ID]
            self.tenant_id = os.environ[constants.ENV_TENANT_ID]
            self.log.info("Creating session with Service Principal Authentication")

        elif all(k in os.environ for k in msi_auth_variables):
            # MSI authentication
            if constants.ENV_CLIENT_ID in os.environ:
                self.credentials = MSIAuthentication(
                    client_id=os.environ[constants.ENV_CLIENT_ID],
                    resource=self.resource_namespace)
            else:
                self.credentials = MSIAuthentication(
                    resource=self.resource_namespace)

            self.subscription_id = os.environ[constants.ENV_SUB_ID]
            self.log.info("Creating session with MSI Authentication")
        else:
            # Azure CLI authentication
            self._is_cli_auth = True
            (self.credentials,
             self.subscription_id,
             self.tenant_id) = Profile().get_login_credentials(
                resource=self.resource_namespace)
            self.log.info("Creating session with Azure CLI Authentication")

        # Let provided id parameter override everything else
        if self.subscription_id_override is not None:
            self.subscription_id = self.subscription_id_override

        self.log.info("Session using Subscription ID: %s" % self.subscription_id)

        if self.credentials is None:
            self.log.error('Unable to locate credentials for Azure session.')

func (s *Scheme) SetVersionPriority(versions ...schema.GroupVersion) error {
	groups := sets.String{}
	order := []string{}
	for _, version := range versions {
		if len(version.Version) == 0 || version.Version == APIVersionInternal {
			return fmt.Errorf("internal versions cannot be prioritized: %v", version)
		}

		groups.Insert(version.Group)
		order = append(order, version.Version)
	}
	if len(groups) != 1 {
		return fmt.Errorf("must register versions for exactly one group: %v", strings.Join(groups.List(), ", "))
	}

	s.versionPriority[groups.List()[0]] = order
	return nil
}

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


Question:
Construction from a string, raise a TypeError if not
        possible

def construct_from_string(cls, string):

        if string == cls.name:
            return cls()
        raise TypeError("Cannot construct a '{}' from "
                        "'{}'".format(cls, string))

def from_config(self, k, v):

        if k == "setup":
            return from_commandline(v, classname=to_commandline(datagen.DataGenerator()))
        return super(DataGenerator, self).from_config(k, v)

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


Question:
Simple implementation of Zambretti forecaster algorithm.
    Inspired by beteljuice.com Java algorithm, as converted to Python by
    honeysucklecottage.me.uk, and further information
    from http://www.meteormetrics.com/zambretti.htm

def zambretti_code(params, hourly_data):
    """"""
    north = literal_eval(params.get('Zambretti', 'north', 'True'))
    baro_upper = float(params.get('Zambretti', 'baro upper', '1050.0'))
    baro_lower = float(params.get('Zambretti', 'baro lower', '950.0'))
    if not hourly_data['rel_pressure']:
        return ''
    if hourly_data['wind_ave'] is None or hourly_data['wind_ave'] < 0.3:
        wind = None
    else:
        wind = hourly_data['wind_dir']
    if hourly_data['pressure_trend'] is None:
        trend = 0.0
    else:
        trend = hourly_data['pressure_trend'] / 3.0
    # normalise pressure
    pressure = 950.0 + (
        (1050.0 - 950.0) * (hourly_data['rel_pressure'] - baro_lower) /
        (baro_upper - baro_lower))
    # adjust pressure for wind direction
    if wind is not None:
        if not isinstance(wind, int):
            wind = int(wind + 0.5) % 16
        if not north:
            # southern hemisphere, so add 180 degrees
            wind = (wind + 8) % 16
        pressure += (  5.2,  4.2,  3.2,  1.05, -1.1, -3.15, -5.2, -8.35,
                     -11.5, -9.4, -7.3, -5.25, -3.2, -1.15,  0.9,  3.05)[wind]
    # compute base forecast from pressure and trend (hPa / hour)
    summer = north == (hourly_data['idx'].month >= 4 and
                       hourly_data['idx'].month <= 9)
    if trend >= 0.1:
        # rising pressure
        if summer:
            pressure += 3.2
        F = 0.1740 * (1031.40 - pressure)
        LUT = ('A', 'B', 'B', 'C', 'F', 'G', 'I', 'J', 'L', 'M', 'M', 'Q', 'T',
               'Y')
    elif trend <= -0.1:
        # falling pressure
        if summer:
            pressure -= 3.2
        F = 0.1553 * (1029.95 - pressure)
        LUT = ('B', 'D', 'H', 'O', 'R', 'U', 'V', 'X', 'X', 'Z')
    else:
        # steady
        F = 0.2314 * (1030.81 - pressure)
        LUT = ('A', 'B', 'B', 'B', 'E', 'K', 'N', 'N', 'P', 'P', 'S', 'W', 'W',
               'X', 'X', 'X', 'Z')
    # clip to range of lookup table
    F = min(max(int(F + 0.5), 0), len(LUT) - 1)
    # convert to letter code
    return LUT[F]

def __save_output(self):

        out = zipfile.ZipFile(self.outputfilename, 'w')

        for info_zip in self.infile.infolist():

            if info_zip.filename in self.templated_files:
                # Template file - we have edited these.

                # get a temp file
                streamout = open(get_secure_filename(), "w+b")
                fname, output_stream = self.output_streams[
                    self.templated_files.index(info_zip.filename)
                ]

                transformer = get_list_transformer(self.namespaces)
                remapped_stream = output_stream | transformer

                # write the whole stream to it
                for chunk in remapped_stream.serialize():
                    streamout.write(chunk.encode('utf-8'))
                    yield True

                # close the temp file to flush all data and make sure we get
                # it back when writing to the zip archive.
                streamout.close()

                # write the full file to archive
                out.write(streamout.name, fname)

                # remove temp file
                os.unlink(streamout.name)

            else:
                # Copy other files straight from the source archive.
                out.writestr(info_zip, self.infile.read(info_zip.filename))

        # Save images in the "Pictures" sub-directory of the archive.
        for identifier, data in self.images.items():
            out.writestr(PY3O_IMAGE_PREFIX + identifier, data)

        # close the zipfile before leaving
        out.close()
        yield True

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


Question: // SetTotalCount sets the TotalCount field's value.

func (s *SearchUsersOutput) SetTotalCount(v int64) *SearchUsersOutput {
	s.TotalCount = &v
	return s
}

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

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


Question:
/*
Returns Placeholders with different salutations

$recipient contains recipient row
$language contains in which lanuage the Placeholders should be translated

public static function getPlaceholders(Kwc_Mail_Recipient_Interface $recipient, $language)
    {
        $ret = array();
        $trl = Kwf_Trl::getInstance();
        $ret['firstname'] = $recipient->getMailFirstname();
        $ret['lastname'] = $recipient->getMailLastname();
        if ($recipient instanceof Kwc_Mail_Recipient_TitleInterface) {
            $replace = array(
                $recipient->getMailTitle(),
                $recipient->getMailLastname()
            );
            $politeM = $trl->trlKwf('Dear Mr. {0} {1}', $replace, $language);
            $politeF = $trl->trlKwf('Dear Mrs. {0} {1}', $replace, $language);
            if ($recipient->getMailGender() == 'male' && $recipient->getMailLastname()) {
                $t = $trl->trlKwf('Dear Mr. {0} {1}', $replace, $language);
            } else if ($recipient->getMailGender() == 'female' && $recipient->getMailLastname()) {
                $t = $trl->trlKwf('Dear Mrs. {0} {1}', $replace, $language);
            } else {
                $t = $trl->trlKwf('Dear Mrs./Mr. {0} {1}', $replace, $language);
            }
            $ret['salutation_polite'] = trim(str_replace('  ', ' ', $t));

            if ($recipient->getMailGender() == 'male') {
                $t = $trl->trlKwf('Mr. {0}', $recipient->getMailTitle(), $language);
            } else if ($recipient->getMailGender() == 'female') {
                $t = $trl->trlKwf('Mrs. {0}', $recipient->getMailTitle(), $language);
            } else {
                $t = $recipient->getMailTitle();
            }
            $ret['salutation_title'] = trim(str_replace('  ', ' ', $t));

            $ret['title'] = $recipient->getMailTitle();
        }
        if ($recipient instanceof Kwc_Mail_Recipient_GenderInterface) {
            $replace = array($recipient->getMailLastname());
            if ($recipient->getMailGender() == 'male') {
                $ret['salutation_polite_notitle'] = $trl->trlKwf('Dear Mr. {0}', $replace, $language);
                $ret['salutation_hello'] = $trl->trlKwf('Hello Mr. {0}', $replace, $language);
                $ret['salutation'] = $trl->trlKwf('Mr.', array(), $language);
                $ret['salutation_firstname'] = $trl->trlcKwf('salutation firstname male', 'Dear {0}', array($recipient->getMailFirstname()), $language);
            } else if ($recipient->getMailGender() == 'female') {
                $ret['salutation_polite_notitle'] = $trl->trlKwf('Dear Mrs. {0}', $replace, $language);
                $ret['salutation_hello'] = $trl->trlKwf('Hello Mrs. {0}', $replace, $language);
                $ret['salutation'] = $trl->trlKwf('Mrs.', array(), $language);
                $ret['salutation_firstname'] = $trl->trlcKwf('salutation firstname female', 'Dear {0}', array($recipient->getMailFirstname()), $language);
            } else {
                $replace = array(
                    $recipient->getMailFirstname(),
                    $recipient->getMailLastname()
                );
                if ($recipient->getMailFirstname() && $recipient->getMailLastname()) {
                    $ret['salutation_polite_notitle'] = trim($trl->trlKwf('Dear {0} {1}', $replace, $language));
                } else {
                    $ret['salutation_polite_notitle'] = $trl->trlKwf('Dear Sir or Madam', array(), $language);
                }
                $ret['salutation_hello'] = trim($trl->trlKwf('Hello {0} {1}', $replace, $language));
                $ret['salutation_firstname'] = $trl->trlcKwf('salutation firstname unknown gender', 'Dear {0}', array($recipient->getMailFirstname()), $language);
                $ret['salutation'] = '';
            }
        }
        return $ret;
    }

function unexpectedTokenError(token, message) {
        var value, msg = message || Messages.UnexpectedToken;

        if (token) {
            if (!message) {
                msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
                    (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
                    (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
                    (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
                    (token.type === Token.Template) ? Messages.UnexpectedTemplate :
                    Messages.UnexpectedToken;

                if (token.type === Token.Keyword) {
                    if (isFutureReservedWord(token.value)) {
                        msg = Messages.UnexpectedReserved;
                    } else if (strict && isStrictModeReservedWord(token.value)) {
                        msg = Messages.StrictReservedWord;
                    }
                }
            }

            value = (token.type === Token.Template) ? token.value.raw : token.value;
        } else {
            value = 'ILLEGAL';
        }

        msg = msg.replace('%0', value);

        return (token && typeof token.lineNumber === 'number') ?
            createError(token.lineNumber, token.start, msg) :
            createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
    }

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


Question:
Retrieves a lexicographical comparator for the given type.

@param elemComp
the comparator to use for comparing the elements.

@return a comparator for comparing objects of type T based on lexicographical ordering.

public static <T extends Iterable<U>, U> Comparator<T> lexComparator(Comparator<U> elemComp) {
        return new LexComparator<>(elemComp);
    }

@Override
	protected List<OUT> executeOnCollections(List<IN1> inputData1, List<IN2> inputData2, RuntimeContext ctx, ExecutionConfig executionConfig) throws Exception {
		CrossFunction<IN1, IN2, OUT> function = this.userFunction.getUserCodeObject();

		FunctionUtils.setFunctionRuntimeContext(function, ctx);
		FunctionUtils.openFunction(function, this.parameters);

		ArrayList<OUT> result = new ArrayList<OUT>(inputData1.size() * inputData2.size());

		TypeSerializer<IN1> inSerializer1 = getOperatorInfo().getFirstInputType().createSerializer(executionConfig);
		TypeSerializer<IN2> inSerializer2 = getOperatorInfo().getSecondInputType().createSerializer(executionConfig);
		TypeSerializer<OUT> outSerializer = getOperatorInfo().getOutputType().createSerializer(executionConfig);

		for (IN1 element1 : inputData1) {
			for (IN2 element2 : inputData2) {
				IN1 copy1 = inSerializer1.copy(element1);
				IN2 copy2 = inSerializer2.copy(element2);
				OUT o = function.cross(copy1, copy2);
				result.add(outSerializer.copy(o));
			}
		}

		FunctionUtils.closeFunction(function);
		return result;
	}

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


Question:
/*
@description
Multiplies an integer n by a standard group element and
returns the resulting group element.

public static byte [] scalseMult_base(byte [] n) {
            if (!(n.length==scalarLength))
                return null;

            byte [] q = new byte [scalarLength];

            crypto_scalarmult_base(q, n);

            return q;
        }

def unfuse(self):

        stack = SequentialRNNCell()
        get_cell = {'rnn_relu': lambda cell_prefix: RNNCell(self._num_hidden,
                                                            activation='relu',
                                                            prefix=cell_prefix),
                    'rnn_tanh': lambda cell_prefix: RNNCell(self._num_hidden,
                                                            activation='tanh',
                                                            prefix=cell_prefix),
                    'lstm': lambda cell_prefix: LSTMCell(self._num_hidden,
                                                         prefix=cell_prefix),
                    'gru': lambda cell_prefix: GRUCell(self._num_hidden,
                                                       prefix=cell_prefix)}[self._mode]
        for i in range(self._num_layers):
            if self._bidirectional:
                stack.add(BidirectionalCell(
                    get_cell('%sl%d_'%(self._prefix, i)),
                    get_cell('%sr%d_'%(self._prefix, i)),
                    output_prefix='%sbi_l%d_'%(self._prefix, i)))
            else:
                stack.add(get_cell('%sl%d_'%(self._prefix, i)))

            if self._dropout > 0 and i != self._num_layers - 1:
                stack.add(DropoutCell(self._dropout, prefix='%s_dropout%d_'%(self._prefix, i)))

        return stack

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


Question:
// put returns an allocated big int to the pool to be later reused by get calls.
// Note, the values as saved as is; neither put nor get zeroes the ints out!

func (p *intPool) put(is ...*big.Int) {
	if len(p.pool.data) > poolLimit {
		return
	}
	for _, i := range is {
		// verifyPool is a build flag. Pool verification makes sure the integrity
		// of the integer pool by comparing values to a default value.
		if verifyPool {
			i.Set(checkVal)
		}
		p.pool.push(i)
	}
}

public void set_point( int point, int tick, int ampl ) {
		if( point >= 0 && point < ticks.length ) {
			if( point == 0 ) {
				tick = 0;
			}
			if( point > 0 ) {
				if( tick < ticks[ point - 1 ] ) {
					/* Simple guess at where the point is supposed to be.*/
					tick += 256;
				}
				if( tick <= ticks[ point - 1 ] ) {
					System.out.println( "Envelope: Point not valid (" + tick + " <= " + ticks[ point - 1 ] + ")");
					tick = ticks[ point - 1 ] + 1;
				}
			}
			ticks[ point ] = tick;
			ampls[ point ] = ampl;
			point += 1;
			while( point < ticks.length ) {
				ticks[ point ] = ticks[ point - 1 ] + 1;
				ampls[ point ] = 0;
				point += 1;
			}
		}
	}

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


Question: // DecodeMsg implements msgp.Decodable

func (z *Archive) DecodeMsg(dc *msgp.Reader) (err error) {
	var field []byte
	_ = field
	var zb0001 uint32
	zb0001, err = dc.ReadMapHeader()
	if err != nil {
		err = msgp.WrapError(err)
		return
	}
	for zb0001 > 0 {
		zb0001--
		field, err = dc.ReadMapKeyPtr()
		if err != nil {
			err = msgp.WrapError(err)
			return
		}
		switch msgp.UnsafeString(field) {
		case "MetricDefinition":
			err = z.MetricDefinition.DecodeMsg(dc)
			if err != nil {
				err = msgp.WrapError(err, "MetricDefinition")
				return
			}
		case "SchemaId":
			z.SchemaId, err = dc.ReadUint16()
			if err != nil {
				err = msgp.WrapError(err, "SchemaId")
				return
			}
		case "AggId":
			z.AggId, err = dc.ReadUint16()
			if err != nil {
				err = msgp.WrapError(err, "AggId")
				return
			}
		case "IrId":
			z.IrId, err = dc.ReadUint16()
			if err != nil {
				err = msgp.WrapError(err, "IrId")
				return
			}
		case "LastSave":
			z.LastSave, err = dc.ReadUint32()
			if err != nil {
				err = msgp.WrapError(err, "LastSave")
				return
			}
		default:
			err = dc.Skip()
			if err != nil {
				err = msgp.WrapError(err)
				return
			}
		}
	}
	return
}

def _json_from_message(message):

    try:
        return json.loads(message.payload_utf8)
    except ValueError:
        logger = logging.getLogger(__name__)
        logger.warning("Ignoring invalid json in namespace %s: %s",
                       message.namespace, message.payload_utf8)
        return {}

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


Question: actually creates the action buttons

def make_buttons names
      @action_buttons = []
      $log.debug "XXX: came to NTP make buttons FORM= #{@form.name} names #{names}  "
      total = names.inject(0) {|total, item| total + item.length + 4}
      bcol = center_column total

      # this craps out when height is zero
      brow = @row + @height-2
      brow = FFI::NCurses.LINES-2 if brow < 0
      $log.debug "XXX: putting buttons :on #{brow} : #{@row} , #{@height} "
      button_ct=0
      tpp = self
      names.each_with_index do |bname, ix|
        text = bname
        #underline = @underlines[ix] if !@underlines.nil?

        button = Button.new nil do
          text text
          name bname
          row brow
          col bcol
          #underline underline
          highlight_bgcolor $reversecolor
          color $datacolor
          bgcolor $datacolor
        end
        @action_buttons << button
        button.form = @form
        button.override_graphic  @graphic
        index = button_ct
        tpp = self
        button.command { |form| @selected_index = index; @stop = true;
          # ActionEvent has source event and action_command
          fire_handler :PRESS, ActionEvent.new(tpp, index, button.text)
          #throw(:close, @selected_index)
        }
        button_ct += 1
        bcol += text.length+6
      end
    end

public static function oneAction(ResourceListInterface $resources)
    {
        $resources->get(0)->getErrors()->addAll($resources->getErrors());

        return $resources->get(0);
    }

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


Question:
Capitalise the first letter of the sentence and add a full stop.
@param sentence
@param exciting

function sentenceCase(sentence) {
  var exciting = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];

  // uppercase the first letter
  sentence = sentence[0].toUpperCase() + sentence.slice(1);

  if (['.', '!', '?'].indexOf(sentence.slice(-1)) > -1) {
    return sentence;
  } else if (exciting) {
    return sentence + "!";
  } else {
    return sentence + ".";
  }
}

public function parse($story, $actor = null)
    {
        $options = array();

        $this->getService('anahita:language')->load($story->component);

        static $commands;

        $commands = $commands ? clone $commands : new LibBaseTemplateObjectContainer();

        $commands->reset();

        $data = array(
            'commands' => $commands,
            'actor' => $actor,
            'helper' => $this,
            'story' => $story,
            'subject' => $story->subject,
            'target' => $story->target,
            'object' => $story->object,
            'comment' => $story->comment,
            'type' => $story->getIdentifier()->name,
        );

        $path[] = ANPATH_ROOT.'/components/'.$story->component.'/templates/stories/'.$story->name.'.php';

        $output = $this->_render($story, $path, $data);
        $data = $this->_parseData($output);

        $data['commands'] = $commands;

        return $data;
    }

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


Question:
Normalize data to zero mean and unit variance
substract by the mean and divide by the standard deviation

@param toNormalize the ndarray to normalize
@return the normalized ndarray

public static INDArray normalizeZeroMeanAndUnitVariance(INDArray toNormalize) {
        INDArray columnMeans = toNormalize.mean(0);
        INDArray columnStds = toNormalize.std(0);

        toNormalize.subiRowVector(columnMeans);
        //padding for non zero
        columnStds.addi(Nd4j.EPS_THRESHOLD);
        toNormalize.diviRowVector(columnStds);
        return toNormalize;
    }

def __normalize_name(self, name):

        if not name.startswith(self.__root_namespace):
            name = foundations.namespace.set_namespace(self.__root_namespace,
                                                       foundations.namespace.set_namespace(self.__default_namespace,
                                                                                name))
            LOGGER.debug("> Normalized name: '{0}'.".format(name))
            return name
        else:
            LOGGER.debug("> Name '{0}' is already normalized!".format(name))
            return name

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


Question: Order is defined by the current state of sorting

def sort(self, section: int, order=None):
        """"""
        attr = self.header[section]
        old_i, old_sort = self.sort_state
        self.beginResetModel()
        if section == old_i:
            self.collection.sort(attr, not old_sort)
            self.sort_state = (section, not old_sort)
        else:
            self.collection.sort(attr, True)
            self.sort_state = (section, True)
        self.endResetModel()

func SelectOrder(i int, slice []int) int {
	rand.Seed(time.Now().Unix())
	cslice := make([]int, len(slice)) // copy
	copy(cslice, slice[:])
	return selectOrder(i, cslice)
}

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


Question: Returns a function for registering options on the given scope.

def registration_function_for_optionable(self, optionable_class):
    """"""
    self._assert_not_frozen()
    # TODO(benjy): Make this an instance of a class that implements __call__, so we can
    # docstring it, and so it's less weird than attatching properties to a function.
    def register(*args, **kwargs):
      kwargs['registering_class'] = optionable_class
      self.register(optionable_class.options_scope, *args, **kwargs)
    # Clients can access the bootstrap option values as register.bootstrap.
    register.bootstrap = self.bootstrap_option_values()
    # Clients can access the scope as register.scope.
    register.scope = optionable_class.options_scope
    return register

func (c *Config) Service(client *api.Client, logger *log.Logger) (*connect.Service, error) {
	return connect.NewServiceWithLogger(c.ProxiedServiceName, client, logger)
}

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