Question:
Add a point symbolizer definition to the rule.

@param styleJson The old style.

@Nullable
    public PointSymbolizer createPointSymbolizer(final PJsonObject styleJson) {

        if (this.allowNullSymbolizer && !(
                styleJson.has(JSON_EXTERNAL_GRAPHIC) || styleJson.has(JSON_GRAPHIC_NAME) ||
                        styleJson.has(JSON_POINT_RADIUS))) {
            return null;
        }

        Graphic graphic = this.styleBuilder.createGraphic();
        graphic.graphicalSymbols().clear();
        if (styleJson.has(JSON_EXTERNAL_GRAPHIC)) {
            String externalGraphicUrl = validateURL(styleJson.getString(JSON_EXTERNAL_GRAPHIC));

            try {
                final URI uri = URI.create(externalGraphicUrl);
                if (uri.getScheme().startsWith("http")) {
                    final ClientHttpRequest request = this.requestFactory.createRequest(uri, HttpMethod.GET);
                    externalGraphicUrl = request.getURI().toString();
                }
            } catch (IOException ignored) {
                // ignored
            }

            final String graphicFormat = getGraphicFormat(externalGraphicUrl, styleJson);
            ExternalGraphic externalGraphic = null;
            if (externalGraphicUrl.startsWith("data:")) {
                try {
                    externalGraphic = this.styleBuilder.createExternalGraphic(
                            new URL(null, externalGraphicUrl, new Handler()),
                            graphicFormat
                    );
                } catch (MalformedURLException e) {
                    // ignored
                }
            } else {
                externalGraphic =
                        this.styleBuilder.createExternalGraphic(externalGraphicUrl, graphicFormat);
            }
            if (externalGraphic != null) {
                graphic.graphicalSymbols().add(externalGraphic);
            }
        }

        if (styleJson.has(JSON_GRAPHIC_NAME)) {
            Expression graphicName =
                    parseProperty(styleJson.getString(JSON_GRAPHIC_NAME), input -> input);
            Fill fill = createFill(styleJson);
            Stroke stroke = createStroke(styleJson, false);

            final Mark mark = this.styleBuilder.createMark(graphicName, fill, stroke);
            graphic.graphicalSymbols().add(mark);
        }

        if (graphic.graphicalSymbols().isEmpty()) {
            Fill fill = createFill(styleJson);
            Stroke stroke = createStroke(styleJson, false);

            final Mark mark = this.styleBuilder.createMark(DEFAULT_POINT_MARK, fill, stroke);
            graphic.graphicalSymbols().add(mark);
        }

        graphic.setOpacity(
                parseExpression(null, styleJson, JSON_GRAPHIC_OPACITY, Double::parseDouble));

        if (!StringUtils.isEmpty(styleJson.optString(JSON_POINT_RADIUS))) {
            Expression size =
                    parseExpression(null, styleJson, JSON_POINT_RADIUS,
                                    (final String input) -> Double.parseDouble(input) * 2);
            graphic.setSize(size);
        } else if (!StringUtils.isEmpty(styleJson.optString(JSON_GRAPHIC_WIDTH))) {
            Expression size =
                    parseExpression(null, styleJson, JSON_GRAPHIC_WIDTH, Double::parseDouble);
            graphic.setSize(size);
        }

        if (!StringUtils.isEmpty(styleJson.optString(JSON_GRAPHIC_Y_OFFSET)) &&
                !StringUtils.isEmpty(styleJson.optString(JSON_GRAPHIC_X_OFFSET))) {
            Expression dy =
                    parseExpression(null, styleJson, JSON_GRAPHIC_Y_OFFSET, Double::parseDouble);
            Expression dx =
                    parseExpression(null, styleJson, JSON_GRAPHIC_X_OFFSET, Double::parseDouble);
            Displacement offset = this.styleBuilder.createDisplacement(dx, dy);
            graphic.setDisplacement(offset);
        }

        if (!StringUtils.isEmpty(styleJson.optString(JSON_ROTATION))) {
            final Expression rotation =
                    parseExpression(null, styleJson, JSON_ROTATION, Double::parseDouble);
            graphic.setRotation(rotation);
        }

        return this.styleBuilder.createPointSymbolizer(graphic);
    }

def run(self):

        # read inputs
        indent = int(self.tcex.playbook.read(self.args.indent))
        json_data = self.tcex.playbook.read(self.args.json_data)

        # get the playbook variable type
        json_data_type = self.tcex.playbook.variable_type(self.args.json_data)

        # convert string input to dict
        if json_data_type in ['String']:
            json_data = json.loads(json_data)

        # generate the new "pretty" json (this will be used as an option variable)
        try:
            self.pretty_json = json.dumps(json_data, indent=indent, sort_keys=self.args.sort_keys)
        except Exception:
            self.tcex.exit(1, 'Failed parsing JSON data.')

        # set the App exit message
        self.exit_message = 'JSON prettified.'

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


Question:
Render the prompt to a `Screen` instance.

        :param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class
            to which the output has to be written.

def write_to_screen(self, cli, screen, mouse_handlers, write_position):

        if not self.children:
            return

        sizes = self._divide_widths(cli, write_position.width)

        if self.report_dimensions_callback:
            self.report_dimensions_callback(cli, sizes)

        # If there is not enough space.
        if sizes is None:
            self.window_too_small.write_to_screen(
                cli, screen, mouse_handlers, write_position)
            return

        # Calculate heights, take the largest possible, but not larger than write_position.extended_height.
        heights = [child.preferred_height(cli, width, write_position.extended_height).preferred
                   for width, child in zip(sizes, self.children)]
        height = max(write_position.height, min(write_position.extended_height, max(heights)))

        # Draw child panes.
        ypos = write_position.ypos
        xpos = write_position.xpos

        for s, c in zip(sizes, self.children):
            c.write_to_screen(cli, screen, mouse_handlers, WritePosition(xpos, ypos, s, height))
            xpos += s

def prt_tsv_dat(prt, data_nts, **kws):
    """"""
    sep = "\t" if 'sep' not in kws else kws['sep']
    fld2fmt = None if 'fld2fmt' not in kws else kws['fld2fmt']
    if 'sort_by' in kws:
        data_nts = sorted(data_nts, key=kws['sort_by'])
    prt_if = kws['prt_if'] if 'prt_if' in kws else None
    prt_flds = kws['prt_flds'] if 'prt_flds' in kws else data_nts[0]._fields
    items = 0
    for nt_data_row in data_nts:
        if prt_if is None or prt_if(nt_data_row):
            if fld2fmt is not None:
                row_fld_vals = [(fld, getattr(nt_data_row, fld)) for fld in prt_flds]
                row_vals = _fmt_fields(row_fld_vals, fld2fmt)
            else:
                row_vals = [getattr(nt_data_row, fld) for fld in prt_flds]
            prt.write("{}\n".format(sep.join(str(d) for d in row_vals)))
            items += 1
    return items

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


Question: // SetStateReason sets the StateReason field's value.

func (s *MetricAlarm) SetStateReason(v string) *MetricAlarm {
	s.StateReason = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question:
Overrule this function if you want to perform a different
action than deleting when the user choose 'yes'.

protected function performAction()
    {
        $count = $this->db->delete("gems__appointments", $this->getWhere());

        $this->addMessage(sprintf($this->plural(
                '%d appointment deleted.',
                '%d appointments deleted.',
                $count
                ), $count));

        $this->setAfterCleanupRoute();
    }

void handleRemove(SimpleTest test, Conjunction selector,
                    MatchTarget object, InternTable subExpr, OrdinalPosition parentId) throws MatchingException
  {
    if (tc.isEntryEnabled())
	    tc.entry(this,cclass, "handleRemove","test: "+test+ ",selector: "+selector+", object: "+object);

    if (test.getKind() == SimpleTest.ID)
      trueChild = trueChild.remove(selector, object, subExpr, ordinalPosition);
    else if (test.getKind() == SimpleTest.NOTID)
      falseChild = falseChild.remove(selector, object, subExpr, ordinalPosition);
    else
      throw new IllegalStateException();

    if (tc.isEntryEnabled())
	    tc.exit(this,cclass, "handleRemove");
  }

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


Question: // NewManager returns a new plugin manager.

func NewManager(config ManagerConfig) (*Manager, error) {
	if config.RegistryService != nil {
		config.RegistryService = pluginRegistryService{config.RegistryService}
	}
	manager := &Manager{
		config: config,
	}
	for _, dirName := range []string{manager.config.Root, manager.config.ExecRoot, manager.tmpDir()} {
		if err := os.MkdirAll(dirName, 0700); err != nil {
			return nil, errors.Wrapf(err, "failed to mkdir %v", dirName)
		}
	}
	var err error
	manager.executor, err = config.CreateExecutor(manager)
	if err != nil {
		return nil, err
	}

	manager.blobStore, err = newBasicBlobStore(filepath.Join(manager.config.Root, "storage/blobs"))
	if err != nil {
		return nil, err
	}

	manager.cMap = make(map[*v2.Plugin]*controller)
	if err := manager.reload(); err != nil {
		return nil, errors.Wrap(err, "failed to restore plugins")
	}

	manager.publisher = pubsub.NewPublisher(0, 0)
	return manager, nil
}

public function jpegoptim($quality = null)
    {
        return $quality === null ? $this->addItem('q', 'jpegoptim') : $this->addItem('q', 'jpegoptim', $quality);
    }

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


Question:
Function to remove link to waitch list

@returns {undefined}

function(link, cb){
            var id = Math.abs(crc32.str(md5(link)));

            var options = {
                host: urlArr.hostname,
                port: urlArr.port,
                path: "/delete/"+id,
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            };

            var deleteRequest = protocol.request(options, function(res){
                var result = "";

                if(res.statusCode === 200){
                    res.on('error', function(error){
                        if(typeof cb === "function")
                            cb(error);
                    });

                    res.on('data', function(chunk){
                        result += chunk;
                    });

                    res.on('end', function(chunk){
                        if(typeof cb === "function"){
                            var resultObj = JSON.parse(result);
                            var err = (resultObj.status === "error") ? resultObj["msg"] : null
                            cb(err, resultObj);
                        }
                    });
                }
                else{
                    if(typeof cb === "function")
                        cb("Request return HTTP "+res.statusCode);
                }
            });

            deleteRequest.end();
        }

func (w *Weavebox) SetNotFoundHandler(h http.Handler) {
	w.router.NotFound = h
}

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


Question: Method for sending the registration Email to the user

def send_email(self, register_user):

        try:
            from flask_mail import Mail, Message
        except Exception:
            log.error("Install Flask-Mail to use User registration")
            return False
        mail = Mail(self.appbuilder.get_app)
        msg = Message()
        msg.subject = self.email_subject
        url = url_for(
            ".activation",
            _external=True,
            activation_hash=register_user.registration_hash,
        )
        msg.html = self.render_template(
            self.email_template,
            url=url,
            username=register_user.username,
            first_name=register_user.first_name,
            last_name=register_user.last_name,
        )
        msg.recipients = [register_user.email]
        try:
            mail.send(msg)
        except Exception as e:
            log.error("Send email exception: {0}".format(str(e)))
            return False
        return True

public function render_login_signup_form($form) {
        global $SITE;

        $context = $form->export_for_template($this);
        $url = $this->get_logo_url();
        if ($url) {
            $url = $url->out(false);
        }
        $context['logourl'] = $url;
        $context['sitename'] = format_string($SITE->fullname, true,
                ['context' => context_course::instance(SITEID), "escape" => false]);

        return $this->render_from_template('core/signup_form_layout', $context);
    }

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


Question:
//ModifyInstanceChargeType  modify instance charge type
//
// You can read doc at https://www.alibabacloud.com/help/doc-detail/25504.htm

func (client *Client) ModifyInstanceChargeType(args *ModifyInstanceChargeTypeArgs) (*ModifyInstanceChargeTypeResponse, error) {
	response := &ModifyInstanceChargeTypeResponse{}
	if err := client.Invoke("ModifyInstanceChargeType", args, response); err != nil {
		return response, err
	}
	return response, nil
}

func NewTfaChangePolicyType(Description string) *TfaChangePolicyType {
	s := new(TfaChangePolicyType)
	s.Description = Description
	return s
}

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


Question:
Get the provider info which is really opts from the config plus the
profile function which sets the values which we will store in the
user table in the database

@param providerName
@param providerConfig
@returns {*}

function getProvider(providerName, providerConfig) {
        return _.extend({}, providerConfig.opts, {
            profile: function profile(credentials, params, get, callback) {
                var proof = null;

                /* eslint camelcase:0 */
                if (providerConfig.useProof) {
                    proof = {
                        appsecret_proof: crypto
                            .createHmac('sha256', this.clientSecret)
                            .update(credentials.token)
                            .digest('hex')
                    };
                }

                get(providerConfig.url, proof, function (data) {
                    credentials.profile = {
                        authType:           providerName,
                        email:              data.email,
                        emailLower:         data.email && data.email.toLowerCase(),
                        emailConfirmed:     data.verified,
                        name: {
                            firstName:      data.given_name || '',
                            lastName:       data.family_name || '',
                            displayName:    data.name || ''
                        }
                    };

                    if (providerName === 'google') {
                        credentials.profile.profileImg = data.picture;
                        credentials.profile.googleAuthData = data;
                    }
                    else if (providerName === 'facebook') {
                        credentials.profile.profileImg = 'https://graph.facebook.com/' +
                            data.id + '/picture?width=80&height=80';
                        credentials.profile.fbAuthData = data;
                    }

                    return callback();
                });
            }
        });
    }

func NewLoginController(service *goa.Service, auth *login.KeycloakOAuthProvider, configuration loginConfiguration, identityRepository account.IdentityRepository) *LoginController {
	return &LoginController{Controller: service.NewController("login"), auth: auth, configuration: configuration, identityRepository: identityRepository}
}

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


Question:
returns the AligSeq (0 or 1) for a point
returns -1 if not over an alig seq.
@param point
@return which of the two sequences a point on the panel corresponds to

public int getAligSeq(Point point) {

		int i1 = getSeqPos(0, point);

		Point t1 = getPanelPos(0,i1);

		if ( Math.abs(t1.x - point.x) <= DEFAULT_CHAR_SIZE &&
				Math.abs(t1.y-point.y) < DEFAULT_CHAR_SIZE ) {
			return 0;
		}

		int i2   = getSeqPos(1,point);
		Point t2 = getPanelPos(1,i2);

		if ( Math.abs(t2.x - point.x) < DEFAULT_CHAR_SIZE &&
				Math.abs(t2.y-point.y) < DEFAULT_CHAR_SIZE ) {
			return 1;
		}

		//System.out.println(" i1: " + i1 +" t1 : " + Math.abs(t1.x - point.x) + " " + Math.abs(t1.y-point.y));
		//System.out.println(i2);

		return -1;
	}

def add_quality_score_vs_no_of_observations_section(self):

        sample_data = []
        data_labels = []
        for rt_type_name, rt_type in recal_table_type._asdict().items():
            sample_tables = self.gatk_base_recalibrator[rt_type]['quality_quantization_map']
            if len(sample_tables) == 0:
                continue

            sample_data.append({
                sample: {int(x): int(y) for x, y in zip(table['QualityScore'], table['Count'])}
                for sample, table in sample_tables.items()
            })

            sample_y_sums = {
                sample: sum(int(y) for y in table['Count'])
                for sample, table
                in sample_tables.items()
            }

            sample_data.append({
                sample: {
                    int(x): float(y) / sample_y_sums[sample]
                    for x, y in zip(table['QualityScore'], table['Count'])
                }
                for sample, table in sample_tables.items()
            })

            flat_proportions = [float(y) / sample_y_sums[sample]
                                for sample, table in sample_tables.items()
                                for y in table['Count']]
            prop_ymax = max(flat_proportions)
            data_labels.append({'name': "{} Count".format(rt_type_name.capitalize().replace('_', '-')),
                                'ylab': 'Count'})
            data_labels.append({'ymax': prop_ymax,
                                'name': "{} Percent".format(rt_type_name.capitalize().replace('_', '-')),
                                'ylab': 'Percent'})

        plot = linegraph.plot(
            sample_data,
            pconfig={
                'title': "Observed Quality Score Counts",
                'id': 'gatk-base-recalibrator-quality-score-vs-number-of-observations',
                'xlab': 'Observed Quality Score',
                'ylab': 'Count',
                'xDecimals': False,
                'data_labels': data_labels,
            })

        # Reported vs empirical quality scores
        self.add_section(
            name='Observed Quality Scores',
            description=(
                'This plot shows the distribution of base quality scores in each sample before and '
                'after base quality score recalibration (BQSR). Applying BQSR should broaden the '
                'distribution of base quality scores.'
            ),
            helptext=(
                'For more information see '
                '[the Broad\'s description of BQSR]'
                '(https://gatkforums.broadinstitute.org/gatk/discussion/44/base-quality-score-recalibration-bqsr)'
                '.'
            ),
            plot=plot,
        )

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


Question:
Return 16-bit signed int from buffer. (big-endian)

@see mysql-5.6.10/include/myisampack.h - mi_sint2korr

public final int getBeInt16(final int pos) {
        final int position = origin + pos;

        if (pos + 1 >= limit || pos < 0) throw new IllegalArgumentException("limit excceed: "
                                                                            + (pos < 0 ? pos : (pos + 1)));

        byte[] buf = buffer;
        return (0xff & buf[position + 1]) | ((buf[position]) << 8);
    }

public static function vector($key, $cipher, $mode) {
        $keySize = mcrypt_get_key_size($cipher, $mode);
        $key = str_pad(static::hash('md5', $key), $keySize, mb_substr($cipher, -1), STR_PAD_BOTH);

        if (mb_strlen($key) > $keySize) {
            $key = mb_substr($key, 0, $keySize);
        }

        $ivSize = mcrypt_get_iv_size($cipher, $mode);
        $iv = str_pad(static::hash('md5', $key, $mode), $ivSize, mb_substr($cipher, 0, 1), STR_PAD_BOTH);

        if (mb_strlen($iv) > $ivSize) {
            $iv = mb_substr($iv, 0, $ivSize);
        }

        return array($key, $iv);
    }

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


Question:
// StringGetOk returns a flag indicating whether or not the key exists. The
// StringGet method can return an empty value for keys that do not have values,
// so it cannot be trusted to indicate the existence of a key.

func (v *OrderedValues) StringGetOk(key string) (string, bool) {
	if len(key) == 0 {
		return "", false
	}
	val, ok := v.GetOk([]byte(key))
	if !ok {
		return "", false
	}
	return string(val), true
}

@Override
	public void visitMethod(Method obj) {
		try {
			if (obj.isSynthetic()) {
				return;
			}

			if (Values.CONSTRUCTOR.equals(getMethodName()) && javaClass.getClassName().contains("$")) {
				return;
			}

			List<String> types = SignatureUtils.getParameterSignatures(obj.getSignature());
			if ((types.isEmpty()) || (types.size() > 2)) {
				return;
			}

			if ((obj.getAccessFlags() & Const.ACC_VARARGS) != 0) {
				return;
			}

			String lastParmSig = types.get(types.size() - 1);
			if (!lastParmSig.startsWith(Values.SIG_ARRAY_PREFIX)
					|| lastParmSig.startsWith(Values.SIG_ARRAY_OF_ARRAYS_PREFIX)) {
				return;
			}

			if (SignatureBuilder.SIG_BYTE_ARRAY.equals(lastParmSig)
					|| SignatureBuilder.SIG_CHAR_ARRAY.equals(lastParmSig)) {
				return;
			}

			if (hasSimilarParms(types)) {
				return;
			}

			if (obj.isStatic() && "main".equals(obj.getName()) && SIG_STRING_ARRAY_TO_VOID.equals(obj.getSignature())) {
				return;
			}

			if (!obj.isPrivate() && !obj.isStatic() && isInherited(obj)) {
				return;
			}

			super.visitMethod(obj);
			bugReporter.reportBug(new BugInstance(this, BugType.UVA_USE_VAR_ARGS.name(), LOW_PRIORITY).addClass(this)
					.addMethod(this));

		} catch (ClassNotFoundException cnfe) {
			bugReporter.reportMissingClass(cnfe);
		}
	}

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


Question:
Create default decision states.

@param flow the flow

protected void createDefaultDecisionStates(final Flow flow) {
        createServiceUnauthorizedCheckDecisionState(flow);
        createServiceCheckDecisionState(flow);
        createWarnDecisionState(flow);
        createGatewayRequestCheckDecisionState(flow);
        createHasServiceCheckDecisionState(flow);
        createRenewCheckActionState(flow);
    }

func (dust2 Dust2) Rate(rate int8) Input {
	CheckRate(rate)
	(&dust2).defaults()
	return NewInput("Dust2", rate, 0, 1, dust2.Density)
}

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


Question:
Gracefully stop the :class:`Actor`.

        Implemented by the :meth:`.Concurrency.stop` method of the
        :attr:`concurrency` attribute.

def stop(self, exc=None, exit_code=None):
        '''
        '''
        return self._concurrency.stop(self, exc, exit_code)

def _read_body_by_chunk(self, response, file, raw=False):
        '''
        '''
        reader = ChunkedTransferReader(self._connection)

        file_is_async = hasattr(file, 'drain')

        while True:
            chunk_size, data = yield from reader.read_chunk_header()

            self._data_event_dispatcher.notify_read(data)
            if raw:
                file.write(data)

            if not chunk_size:
                break

            while True:
                content, data = yield from reader.read_chunk_body()

                self._data_event_dispatcher.notify_read(data)

                if not content:
                    if raw:
                        file.write(data)

                    break

                content = self._decompress_data(content)

                if file:
                    file.write(content)

                    if file_is_async:
                        yield from file.drain()

        content = self._flush_decompressor()

        if file:
            file.write(content)

            if file_is_async:
                yield from file.drain()

        trailer_data = yield from reader.read_trailer()

        self._data_event_dispatcher.notify_read(trailer_data)

        if file and raw:
            file.write(trailer_data)

            if file_is_async:
                yield from file.drain()

        response.fields.parse(trailer_data)

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


Question: Reads from the socket.

public int read(byte []buffer, int offset, int length, long timeout)
    throws IOException
  {
    if (length == 0) {
      throw new IllegalArgumentException();
    }

    long requestExpireTime = _requestExpireTime;

    if (requestExpireTime > 0 && requestExpireTime < CurrentTime.currentTime()) {
      close();
      throw new ClientDisconnectException(L.l("{0}: request-timeout read",
                                              addressRemote()));
    }

    int result = 0;

    synchronized (_readLock) {
      long now = CurrentTime.getCurrentTimeActual();

      long expires;

      // gap is because getCurrentTimeActual() isn't exact
      long gap = 20;

      if (timeout >= 0)
        expires = timeout + now - gap;
      else
        expires = _socketTimeout + now - gap;

      do {
        result = readNative(_socketFd, buffer, offset, length, timeout);

        now = CurrentTime.getCurrentTimeActual();

        timeout = expires - now;
      } while (result == JniStream.TIMEOUT_EXN && timeout > 0);
    }

    return result;
  }

public ByteBuffer getBuffer() {
        assert(isDirect == false);
        assert(buffer.b().hasArray());
        assert(!buffer.b().isDirect());
        buffer.b().flip();
        return buffer.b().asReadOnlyBuffer();
    }

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


Question: Executes {@code op} and sets {@code target} to the result.

public <T> void op(UnaryOp op, Local<T> target, Local<T> source) {
        addInstruction(new PlainInsn(op.rop(source.type), sourcePosition,
                target.spec(), source.spec()));
    }

public function build() {
    $options_data = $this->buildOptionsData();

    $out_text =
      $this->buildUsageLine($this->arguments_spec->getUsage(), $options_data);

    $options_text = '';
    if ($options_data['lines']) {
      foreach($options_data['lines'] as $option_line_data) {
        $options_text .= $this->buildOptionLine($option_line_data, $options_data)."\n";
      }

      $out_text .=
        "\n".
        ConsoleFormat::applyformatToText('bold','cyan','Options:')."\n".
        $options_text;
    }

    return $out_text;
  }

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


Question:
Get the ID from the PEOPLES table

@param  int     $id      Users table ID
@return mixed

public function getPeopleIdForIndexListing($id) {
        // Does the PEOPLES table exist?
        if (Schema::hasTable('peoples')) {
            $person = DB::table('peoples')->where('user_id', '=', $id)->first();

            if (!$person) return "Not in LaSalleCRM";

            $full_url = route('admin.crmpeoples.edit', $person->id);

            $html  = '';
            $html .= 'Edit this LaSalle Customer';
            $html .= '';

            return $html;
        }

        return "LaSalleCRM is not installed";
    }

func ParsePersonaIDType(text string) PersonaIDType {
	switch {
	case strings.EqualFold(text, personaIDTypeUserStr):
		return PersonaIDTypeUser
	case strings.EqualFold(text, personaIDTypeGroupStr):
		return PersonaIDTypeGroup
	case strings.EqualFold(text, personaIDTypeSIDStr):
		return PersonaIDTypeSID
	case strings.EqualFold(text, personaIDTypeUIDStr):
		return PersonaIDTypeUID
	case strings.EqualFold(text, personaIDTypeGIDStr):
		return PersonaIDTypeGID
	}
	return PersonaIDTypeUnknown
}

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


Question: // Returns minimal value of two integers provided

func Min(a, b int) int {
	if a < b {
		return a
	} else if b < a {
		return b
	}
	return a
}

func (c *SQLiteContext) ResultInt(i int) {
	if i64 && (i > math.MaxInt32 || i < math.MinInt32) {
		C.sqlite3_result_int64((*C.sqlite3_context)(c), C.sqlite3_int64(i))
	} else {
		C.sqlite3_result_int((*C.sqlite3_context)(c), C.int(i))
	}
}

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


Question:
Subtract

@param mixed $arg1
@return \Object\Value\Math

public function subtract($arg1) : \Object\Value\Math {
		\Math::subtract2($this->result, $arg1, $this->scale);
		return $this;
	}

def _get_pv_array_construct(self):

        bus_no = integer.setResultsName("bus_no")
        s_rating = real.setResultsName("s_rating") # MVA
        v_rating = real.setResultsName("v_rating") # kV
        p = real.setResultsName("p") # p.u.
        v = real.setResultsName("v") # p.u.
        q_max = Optional(real).setResultsName("q_max") # p.u.
        q_min = Optional(real).setResultsName("q_min") # p.u.
        v_max = Optional(real).setResultsName("v_max") # p.u.
        v_min = Optional(real).setResultsName("v_min") # p.u.
        # Loss participation coefficient
        lp_coeff = Optional(real).setResultsName("lp_coeff")
        status = Optional(boolean).setResultsName("status")

        pv_data = bus_no + s_rating + v_rating + p + v + q_max + \
            q_min + v_max + v_min + lp_coeff + status + scolon

        pv_data.setParseAction(self.push_pv)

        pv_array = Literal("PV.con") + "=" + "[" + "..." + \
            ZeroOrMore(pv_data + Optional("]" + scolon))

        return pv_array

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


Question:
Gets called when a connection to the gateway is established.
        Initialise the protocol object.

def connection_made(self, transport):

        self.transport = transport
        self.loop = transport.loop
        self._cmd_lock = asyncio.Lock(loop=self.loop)
        self._wd_lock = asyncio.Lock(loop=self.loop)
        self._cmdq = asyncio.Queue(loop=self.loop)
        self._msgq = asyncio.Queue(loop=self.loop)
        self._updateq = asyncio.Queue(loop=self.loop)
        self._readbuf = b''
        self._update_cb = None
        self._received_lines = 0
        self._msg_task = self.loop.create_task(self._process_msgs())
        self._report_task = None
        self._watchdog_task = None
        self.status = {}
        self.connected = True

public function boot(): KernelInterface
    {
        if (! $this->isBooted) {
            foreach ($this->serviceProviders as $provider) {
                $this->bootProvider($provider);
            }
            $this->isBooted = true;
        }

        return $this;
    }

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


Question:
Given an error, returns a string for val formated to the appropriate
    number of significant figures.

def get_signum(val, err, max_sig=numpy.inf):

    coeff, pwr = ('%e' % err).split('e')
    if pwr.startswith('-'):
        pwr = int(pwr[1:])
        if round(float(coeff)) == 10.:
            pwr -= 1
        pwr = min(pwr, max_sig)
        tmplt = '%.' + str(pwr+1) + 'f'
        return tmplt % val
    else:
        pwr = int(pwr[1:])
        if round(float(coeff)) == 10.:
            pwr += 1
        # if the error is large, we can sometimes get 0;
        # adjust the round until we don't get 0 (assuming the actual
        # value isn't 0)
        return_val = round(val, -pwr+1)
        if val != 0.:
            loop_count = 0
            max_recursion = 100
            while return_val == 0.:
                pwr -= 1
                return_val = round(val, -pwr+1)
                loop_count += 1
                if loop_count > max_recursion:
                    raise ValueError("Maximum recursion depth hit! Input " +\
                        "values are: val = %f, err = %f" %(val, err))
        return drop_trailing_zeros(return_val)

public final void evalError() throws IOException {
    final List<EvaluationMonitor<SequenceLabelSample>> listeners = new LinkedList<EvaluationMonitor<SequenceLabelSample>>();
    listeners.add(new SequenceLabelerEvaluationErrorListener());
    final SequenceLabelerEvaluator evaluator = new SequenceLabelerEvaluator(this.corpusFormat,
        this.sequenceLabeler, listeners
            .toArray(new SequenceLabelerEvaluationMonitor[listeners.size()]));
    evaluator.evaluate(this.testSamples);
    System.out.println(evaluator.getFMeasure());
  }

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


Question:
Return the delivery charge of the Product

@param Product $product
@return Money

public function delivery(Product $product)
    {
        $delivery = $product->delivery->multiply($product->quantity);

        return $delivery;
    }

def store_pulse_jobs(pulse_job, exchange, routing_key):

    newrelic.agent.add_custom_parameter("exchange", exchange)
    newrelic.agent.add_custom_parameter("routing_key", routing_key)

    JobLoader().process_job(pulse_job)

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


Question: // SetCloudWatchLogGroupName sets the CloudWatchLogGroupName field's value.

func (s *CloudWatchOutputConfig) SetCloudWatchLogGroupName(v string) *CloudWatchOutputConfig {
	s.CloudWatchLogGroupName = &v
	return s
}

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

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

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


Question:
ダイナミックパス情報を得る。

@param string $path 対象のパス
@return string|bool 見つかった場合に、ダイナミックパスを、見つからない場合に `false` を返します。

public function get_dynamic_path_info( $path ){
		foreach( $this->sitemap_dynamic_paths as $sitemap_dynamic_path ){
			//ダイナミックパスを検索
			if( $sitemap_dynamic_path['path_original'] == $path ){
				return $sitemap_dynamic_path;
			}
			if( preg_match( $sitemap_dynamic_path['preg'] , $path ) ){
				return $sitemap_dynamic_path;
			}
		}
		return false;
	}

public function main()
    {
        if (null === $this->getRepository()) {
            throw new BuildException('"repository" is required parameter');
        }

        if (null === $this->getTargetPath()) {
            throw new BuildException('"targetPath" is required parameter');
        }

        $files = @scandir($this->getTargetPath());
        if (isset($files) && is_array($files) && (count($files) > 2)) {
            throw new BuildException(
                sprintf(
                    '"%s" target directory is not empty',
                    $this->getTargetPath()
                )
            );
        }

        try {
            $this->doClone($this->getGitClient(false, getcwd()));
        } catch (Exception $e) {
            throw new BuildException('The remote end hung up unexpectedly', $e);
        }

        $msg = 'git-clone: cloning '
            . ($this->isBare() ? '(bare) ' : '')
            . ($this->hasDepth() ? ' (depth="' . $this->getDepth() . '") ' : '')
            . '"' . $this->getRepository() . '" repository'
            . ' to "' . $this->getTargetPath() . '" directory';
        $this->log($msg, Project::MSG_INFO);
    }

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


Question:
Object to XML

@param object
object
@return xml

public static String convertToXML(Object object) {
		try {
			if (!JAXB_CONTEXT_MAP.containsKey(object.getClass())) {
				JAXB_CONTEXT_MAP.put(object.getClass(), JAXBContext.newInstance(object.getClass()));
			}
			Marshaller marshaller = JAXB_CONTEXT_MAP.get(object.getClass()).createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			// 设置CDATA输出字符
			marshaller.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() {
				public void escape(char[] ac, int i, int j, boolean flag, Writer writer) throws IOException {
					writer.write(ac, i, j);
				}
			});
			StringWriter stringWriter = new StringWriter();
			marshaller.marshal(object, stringWriter);
			return stringWriter.getBuffer().toString();
		} catch (Exception e) {
			logger.error("", e);
		}
		return null;
	}

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('TagList');
        $visitor->setHeader('Content-Type', $generator->getMediaType('TagList'));

        $generator->startAttribute('href', $data->path);
        $generator->endAttribute('href');

        $generator->startList('Tag');

        foreach ($data->tags as $restTag) {
            $generator->startObjectElement('Tag');
            $generator->startAttribute(
                'href',
                $this->router->generate(
                    'ezpublish_rest_eztags_loadTag',
                    ['tagPath' => trim($restTag->tag->pathString, '/')]
                )
            );
            $generator->endAttribute('href');
            $generator->endObjectElement('Tag');
        }

        $generator->endList('Tag');

        $generator->endObjectElement('TagList');
    }

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


Question:
/*[deutsch]
<p>Setzt eine Fehlerinformation. </p>

@param   errorIndex      error index in parsed text
@param   errorMessage    error message maybe empty
@throws  IllegalArgumentException if given error index is negative
@since   3.0

public void setError(
        int errorIndex,
        String errorMessage
    ) {

        if (errorIndex >= 0) {
            this.errorMessage = (
                ((errorMessage == null) || errorMessage.isEmpty())
                ? ("Error occurred at position: " + errorIndex)
                : errorMessage);
        } else {
            throw new IllegalArgumentException("Undefined error index: " + errorIndex);
        }

        this.pp.setErrorIndex(errorIndex);

    }

public function main()
    {
        if (null === $this->getFile()) {
            $msg = "JsonValidate: file is not defined.";
            $this->log($msg, Project::MSG_ERR);
            throw new \BuildException($msg);
        }

        if (!file_exists($this->getFile()) || is_dir($this->getFile())) {
            $msg = "JsonValidate: file not found " . $this->getFile();
            $this->log($msg, Project::MSG_ERR);
            throw new \BuildException($msg);
        }

        $decoded = json_decode(file_get_contents($this->getFile()));
        if (null === $decoded) {
            $msg = "JsonValidate: decoding " . $this->getFile() . " failed.";
            $this->log($msg, Project::MSG_ERR);
            throw new \BuildException($msg);
        }
        $this->log($this->getFile() . " is valid JSON", Project::MSG_INFO);
    }

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


Question: /* this function process selected time and return it parsed according to instance options

function(inst) {

            if (inst.hours == -1 && inst.minutes == -1) {
                return '';
            }

            // default to 0 AM if hours is not valid
            if ((inst.hours < inst.hours.starts) || (inst.hours > inst.hours.ends )) { inst.hours = 0; }
            // default to 0 minutes if minute is not valid
            if ((inst.minutes < inst.minutes.starts) || (inst.minutes > inst.minutes.ends)) { inst.minutes = 0; }

            var period = "",
                showPeriod = (this._get(inst, 'showPeriod') == true),
                showLeadingZero = (this._get(inst, 'showLeadingZero') == true),
                showHours = (this._get(inst, 'showHours') == true),
                showMinutes = (this._get(inst, 'showMinutes') == true),
                optionalMinutes = (this._get(inst, 'optionalMinutes') == true),
                amPmText = this._get(inst, 'amPmText'),
                selectedHours = inst.hours ? inst.hours : 0,
                selectedMinutes = inst.minutes ? inst.minutes : 0,
                displayHours = selectedHours ? selectedHours : 0,
                parsedTime = '';

            // fix some display problem when hours or minutes are not selected yet
            if (displayHours == -1) { displayHours = 0 }
            if (selectedMinutes == -1) { selectedMinutes = 0 }

            if (showPeriod) {
                if (inst.hours == 0) {
                    displayHours = 12;
                }
                if (inst.hours < 12) {
                    period = amPmText[0];
                }
                else {
                    period = amPmText[1];
                    if (displayHours > 12) {
                        displayHours -= 12;
                    }
                }
            }

            var h = displayHours.toString();
            if (showLeadingZero && (displayHours < 10)) { h = '0' + h; }

            var m = selectedMinutes.toString();
            if (selectedMinutes < 10) { m = '0' + m; }

            if (showHours) {
                parsedTime += h;
            }
            if (showHours && showMinutes && (!optionalMinutes || m != 0)) {
                parsedTime += this._get(inst, 'timeSeparator');
            }
            if (showMinutes && (!optionalMinutes || m != 0)) {
                parsedTime += m;
            }
            if (showHours) {
                if (period.length > 0) { parsedTime += this._get(inst, 'periodSeparator') + period; }
            }

            return parsedTime;
        }

func NewPartialStatement(pos int, line int) *PartialStatement {
	return &PartialStatement{
		NodeType: NodePartial,
		Loc:      Loc{pos, line},
	}
}

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


Question:
@param array $keys

@return array

@throws CacheException

public function getTtlMultiple(array $keys): array
    {
        if (!is_iterable($keys)) {
            throw new CacheException('Argument $keys is not iterable.');
        }
        if (!count($keys)) {
            return [];
        }
        $keys = array_unique($keys);
        $this->validateKeys($keys);
        $return = $this->client->evalsha(
            $this->scripts[self::SCRIPT_GET_TTL],
            count($keys),
            ...$keys,
            ...[
                self::PREFIX_KEY_VALUE,
            ]
        );
        return array_map(function ($value) {
            $value = (int)$value;
            if ($value === -1) {
                return 0;
            }
            if ($value === -2 || $value === 0) {
                return null;
            }
            return $value;
        }, array_combine($keys, $return));
    }

func (t *Template) GetAllAWSElastiCacheParameterGroupResources() map[string]*resources.AWSElastiCacheParameterGroup {
	results := map[string]*resources.AWSElastiCacheParameterGroup{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSElastiCacheParameterGroup:
			results[name] = resource
		}
	}
	return results
}

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


Question:
<p>
Releases the specified connection and returns it to the pool.
</p>

@param connection
A JDBC connection.

public void free(Connection connection) {
        try {
            if (!connection.isClosed()){
                // ensure connections returned to pool as read-only
                setConnectionReadOnly(connection, true);
                connection.close();
            } else {
                logger.debug("Ignoring attempt to close a previously closed connection");
            }
        } catch (SQLException sqle) {
            logger.warn("Unable to close connection", sqle);
        } finally {
            if (logger.isDebugEnabled()) {
                logger.debug("Returned connection to pool (" + toString() + ")");
            }
        }
    }

public void init(DatabaseOwner databaseOwner, String strDbName, int iDatabaseType, Map<String, Object> properties)
    {
        super.init(databaseOwner, strDbName, iDatabaseType, properties);

        if ((iDatabaseType & Constants.REMOTE_MEMORY) == 0)
        {   // Usually don't send messages (unless this is a remote copy, then I would)
            this.setProperty(DBParams.MESSAGES_TO_REMOTE, DBConstants.FALSE);   // Send by server version
            this.setProperty(DBParams.CREATE_REMOTE_FILTER, DBConstants.FALSE); // Create the remote filter
            this.setProperty(DBParams.UPDATE_REMOTE_FILTER, DBConstants.FALSE); // Updated by server version
        }
    }

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


Question:
Store the block help locally

@param  string $help       The help text
@param  array  $attributes Facultative attributes
@return $this

public function blockhelp($help, $attributes = [])
    {
        $this->blockhelp = $help;

        return parent::help($help, $attributes);
    }

def check_option!(name, definition)
      case name
      when :values
        raise AttributorException, "Allowed set of values requires an array. Got (#{definition})" unless definition.is_a? ::Array
      when :default
        raise AttributorException, "Default value doesn't have the correct attribute type. Got (#{definition.inspect})" unless type.valid_type?(definition) || definition.is_a?(Proc)
        options[:default] = load(definition) unless definition.is_a?(Proc)
      when :description
        raise AttributorException, "Description value must be a string. Got (#{definition})" unless definition.is_a? ::String
      when :required
        raise AttributorException, 'Required must be a boolean' unless definition == true || definition == false
        raise AttributorException, 'Required cannot be enabled in combination with :default' if definition == true && options.key?(:default)
      when :required_if
        raise AttributorException, 'Required_if must be a String, a Hash definition or a Proc' unless definition.is_a?(::String) || definition.is_a?(::Hash) || definition.is_a?(::Proc)
        raise AttributorException, 'Required_if cannot be specified together with :required' if options[:required]
      when :example
        unless definition.is_a?(::Regexp) || definition.is_a?(::String) || definition.is_a?(::Array) || definition.is_a?(::Proc) || definition.nil? || type.valid_type?(definition)
          raise AttributorException, "Invalid example type (got: #{definition.class.name}). It must always match the type of the attribute (except if passing Regex that is allowed for some types)"
        end
      when :custom_data
        raise AttributorException, "custom_data must be a Hash. Got (#{definition})" unless definition.is_a?(::Hash)
      else
        return :unknown # unknown option
      end

      :ok # passes
    end

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


Question: /* modify the addEdge function to attach random weights

function (from, to, edgeData) {
    edgeData = edgeData || {}
    edgeData.weight = Math.floor(Math.random() * 10) + 1;
    edgeData.label = edgeData.weight;
    edgeData.style = { 'pointer-events': 'none' }
    g.addEdge(from, to, edgeData);
  }

def get_edge(self, edge_id):
        """"""
        try:
            edge_object = self.edges[edge_id]
        except KeyError:
            raise NonexistentEdgeError(edge_id)
        return edge_object

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


Question:
Display a listing of page.

@param      $slug1
@param null $slug2
@param null $slug3
@return Response

public function index($slug1, $slug2 = null, $slug3 = null)
    {
        $url = $this->getCurrentUrl();

        $page = Page::with('components.component')->where('url', $url)->first();
        if (!$page) {
            throw new NotFoundHttpException();
        }

        // find out if its a 'main page' and get the children
        $children = $this->findChildrenPages($page);

        return $this->view('titan::pages.page')
            ->with('activePage', $page)
            ->with('childrenPages', $children);
    }

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

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

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

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


Question: ### @private viewAppByName (appName, callback, success) #### @callback {function} Continuation to respond to on error. #### @success {function} Continuation to respond to on success. Attempts to retrieve the application from Nodejitsu with the given name.

function viewAppByName(appName, callback, success) {
  jitsu.apps.view(appName, function (err, app) {
    return err ? callback(err) : success(null, app);
  });
}

func serviceWatch(params map[string]interface{}) (WatcherFunc, error) {
	stale := false
	if err := assignValueBool(params, "stale", &stale); err != nil {
		return nil, err
	}

	var (
		service string
		tags    []string
	)
	if err := assignValue(params, "service", &service); err != nil {
		return nil, err
	}
	if service == "" {
		return nil, fmt.Errorf("Must specify a single service to watch")
	}
	if err := assignValueStringSlice(params, "tag", &tags); err != nil {
		return nil, err
	}

	passingOnly := false
	if err := assignValueBool(params, "passingonly", &passingOnly); err != nil {
		return nil, err
	}

	fn := func(p *Plan) (BlockingParamVal, interface{}, error) {
		health := p.client.Health()
		opts := makeQueryOptionsWithContext(p, stale)
		defer p.cancelFunc()
		nodes, meta, err := health.ServiceMultipleTags(service, tags, passingOnly, &opts)
		if err != nil {
			return nil, nil, err
		}
		return WaitIndexVal(meta.LastIndex), nodes, err
	}
	return fn, nil
}

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


Question: // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RecreateDeploymentStrategyParams.

func (in *RecreateDeploymentStrategyParams) DeepCopy() *RecreateDeploymentStrategyParams {
	if in == nil {
		return nil
	}
	out := new(RecreateDeploymentStrategyParams)
	in.DeepCopyInto(out)
	return out
}

func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	path, err := pathFor(blobDataPathSpec{
		digest: dgst,
	})

	if err != nil {
		return distribution.Descriptor{}, err
	}

	fi, err := bs.driver.Stat(ctx, path)
	if err != nil {
		switch err := err.(type) {
		case driver.PathNotFoundError:
			return distribution.Descriptor{}, distribution.ErrBlobUnknown
		default:
			return distribution.Descriptor{}, err
		}
	}

	if fi.IsDir() {
		// NOTE(stevvooe): This represents a corruption situation. Somehow, we
		// calculated a blob path and then detected a directory. We log the
		// error and then error on the side of not knowing about the blob.
		dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path)
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	// TODO(stevvooe): Add method to resolve the mediatype. We can store and
	// cache a "global" media type for the blob, even if a specific repo has a
	// mediatype that overrides the main one.

	return distribution.Descriptor{
		Size: fi.Size(),

		// NOTE(stevvooe): The central blob store firewalls media types from
		// other users. The caller should look this up and override the value
		// for the specific repository.
		MediaType: "application/octet-stream",
		Digest:    dgst,
	}, nil
}

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


Question: // SetId sets the Id field's value.

func (s *Entity) SetId(v int64) *Entity {
	s.Id = &v
	return s
}

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

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

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


Question:
Adds the commerce shipment item to the database. Also notifies the appropriate model listeners.

@param commerceShipmentItem the commerce shipment item
@return the commerce shipment item that was added

public static com.liferay.commerce.model.CommerceShipmentItem addCommerceShipmentItem(
		com.liferay.commerce.model.CommerceShipmentItem commerceShipmentItem) {
		return getService().addCommerceShipmentItem(commerceShipmentItem);
	}

def save(self):

        LOGGER.debug("Cluster.save")
        post_payload = {}
        consolidated_containers_id = []

        if self.id is not None:
            post_payload['clusterID'] = self.id

        if self.name is not None:
            post_payload['clusterName'] = self.name

        if self.containers_id is not None:
            consolidated_containers_id = copy.deepcopy(self.containers_id)
        if self.containers_2_rm is not None:
            for container_2_rm in self.containers_2_rm:
                if container_2_rm.id is None:
                    container_2_rm.sync()
                consolidated_containers_id.remove(container_2_rm.id)
        if self.containers_2_add is not None:
            for container_2_add in self.containers_2_add:
                if container_2_add.id is None:
                    container_2_add.save()
                consolidated_containers_id.append(container_2_add.id)
        post_payload['clusterContainersID'] = consolidated_containers_id

        params = SessionService.complete_transactional_req({'payload': json.dumps(post_payload)})
        if MappingService.driver_type != DriverFactory.DRIVER_REST:
            params['OPERATION'] = 'createCluster'
            args = {'properties': params}
        else:
            args = {
                'http_operation': 'POST',
                'operation_path': '',
                'parameters': params
            }

        response = ClusterService.requester.call(args)

        if MappingService.driver_type != DriverFactory.DRIVER_REST:
            response = response.get()

        if response.rc != 0:
            LOGGER.warning('Cluster.save - Problem while saving cluster' + self.name +
                           '. Reason: ' + str(response.response_content) + ' - ' + str(response.error_message) +
                           " (" + str(response.rc) + ")")
            if response.rc == 500 and ArianeMappingOverloadError.ERROR_MSG in response.error_message:
                raise ArianeMappingOverloadError("Cluster.save", ArianeMappingOverloadError.ERROR_MSG)
            # traceback.print_stack()
        else:
            self.id = response.response_content['clusterID']
            if self.containers_2_add is not None:
                for container_2_add in self.containers_2_add:
                    container_2_add.sync()
            if self.containers_2_rm is not None:
                for container_2_rm in self.containers_2_rm:
                    container_2_rm.sync()
            self.sync(json_obj=response.response_content)
        self.containers_2_add.clear()
        self.containers_2_rm.clear()

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


Question: Wrap and return the given socket.

def bind(self, sock):
        """"""
        if self.context is None:
            self.context = self.get_context()
        conn = SSLConnection(self.context, sock)
        self._environ = self.get_environ()
        return conn

def raw_callback(self, raw_packet):
        """"""
        if not ';PONG;' in raw_packet:
            log.info('forwarding packet %s to clients', raw_packet)
        else:
            log.debug('forwarding packet %s to clients', raw_packet)
        writers = [i[1] for i in list(clients)]
        for writer in writers:
            writer.write(str(raw_packet).encode() + CRLF)

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


Question: Used in Dataset.__init__.

def merge_data_and_coords(data, coords, compat='broadcast_equals',
                          join='outer'):
    """"""
    objs = [data, coords]
    explicit_coords = coords.keys()
    indexes = dict(extract_indexes(coords))
    return merge_core(objs, compat, join, explicit_coords=explicit_coords,
                      indexes=indexes)

def default(self, obj):  # lint-amnesty, pylint: disable=arguments-differ, method-hidden

        if isinstance(obj, datetime):
            if obj.tzinfo is None:
                # Localize to UTC naive datetime objects
                obj = UTC.localize(obj)  # pylint: disable=no-value-for-parameter
            else:
                # Convert to UTC datetime objects from other timezones
                obj = obj.astimezone(UTC)
            return obj.isoformat()
        elif isinstance(obj, date):
            return obj.isoformat()

        return super(DateTimeJSONEncoder, self).default(obj)

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


Question:
Check for session.
@param strClassAndID
@return

public BaseSessionProxy checkForSession(String strClassAndID)
    {
        int iColon = strClassAndID.indexOf(CLASS_SEPARATOR);
        String strSessionClass = null;
        if (iColon != -1)
            strSessionClass = strClassAndID.substring(0, iColon);
        String strID = strClassAndID.substring(iColon + 1);
        if (REMOTE_SESSION.equals(strSessionClass))
            return new SessionProxy(this, strID);
        if (REMOTE_TABLE.equals(strSessionClass))
            return new TableProxy(this, strID);
        if (REMOTE_BASE_SESSION.equals(strSessionClass))
            return new BaseSessionProxy(this, strID);
        return null;    // Not a session
    }

public function login(Net_SSH2 &$ssh)
    {
        $this->validateAuthParams(
            $this->authParams,
            $acceptableParams = [
                'username' => 'is_string',
                'password' => 'is_string'
            ]
        );

        extract($this->authParams);

        if (!$ssh->login($username, $password)) {
            throw new \Exception(get_class().': Authentication failed');
        }
    }

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


Question:
// MaxDeterminizedStates represents the maximum automaton states allowed for regex expansion.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-suggesters-completion.html#regex
// for details.

func (o *RegexCompletionSuggesterOptions) MaxDeterminizedStates(max int) *RegexCompletionSuggesterOptions {
	o.maxDeterminizedStates = &max
	return o
}

def to_dict(self):

        return {
            'model_type': 'segmented_discretechoice',
            'name': self.name,
            'segmentation_col': self.segmentation_col,
            'sample_size': self.sample_size,
            'probability_mode': self.probability_mode,
            'choice_mode': self.choice_mode,
            'choosers_fit_filters': self.choosers_fit_filters,
            'choosers_predict_filters': self.choosers_predict_filters,
            'alts_fit_filters': self.alts_fit_filters,
            'alts_predict_filters': self.alts_predict_filters,
            'interaction_predict_filters': self.interaction_predict_filters,
            'estimation_sample_size': self.estimation_sample_size,
            'prediction_sample_size': self.prediction_sample_size,
            'choice_column': self.choice_column,
            'default_config': {
                'model_expression': self.default_model_expr,
            },
            'remove_alts': self.remove_alts,
            'fitted': self.fitted,
            'models': {
                yamlio.to_scalar_safe(name):
                    self._process_model_dict(m.to_dict())
                for name, m in self._group.models.items()
            }
        }

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


Question:
Reset VM statistics.

        in pattern of type str
            The selection pattern. A bit similar to filename globbing.

def reset_stats(self, pattern):

        if not isinstance(pattern, basestring):
            raise TypeError("pattern can only be an instance of type basestring")
        self._call("resetStats",
                     in_p=[pattern])

static Matcher head(Matcher matcher) {
    if (matcher instanceof SeqMatcher) {
      List<Matcher> ms = matcher.<SeqMatcher>as().matchers();
      return ms.get(0);
    } else {
      return matcher;
    }
  }

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


Question: Marshall the given parameter object.

public void marshall(Limit limit, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(limit.getType(), TYPE_BINDING);
            protocolMarshaller.marshall(limit.getMax(), MAX_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
@param string             $type
@param RuleInterface|null $next

@return RuleInterface

public static function toManyRelationship(string $type, RuleInterface $next = null): RuleInterface
    {
        $primary = new ToManyRelationshipTypeCheckerRule($type);

        return $next === null ? $primary : new AndOperator($primary, $next);
    }

def get_interface_detail_output_interface_ifHCInErrors(self, **kwargs):

        config = ET.Element("config")
        get_interface_detail = ET.Element("get_interface_detail")
        config = get_interface_detail
        output = ET.SubElement(get_interface_detail, "output")
        interface = ET.SubElement(output, "interface")
        interface_type_key = ET.SubElement(interface, "interface-type")
        interface_type_key.text = kwargs.pop('interface_type')
        interface_name_key = ET.SubElement(interface, "interface-name")
        interface_name_key.text = kwargs.pop('interface_name')
        ifHCInErrors = ET.SubElement(interface, "ifHCInErrors")
        ifHCInErrors.text = kwargs.pop('ifHCInErrors')

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

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


Question:
// reopenFDOnError determines whether we should reopen the file handle
// in readwrite mode and try again. This comes from util-linux/sys-utils/flock.c:
//  Since Linux 3.4 (commit 55725513)
//  Probably NFSv4 where flock() is emulated by fcntl().

func (f *Flock) reopenFDOnError(err error) (bool, error) {
	if err != syscall.EIO && err != syscall.EBADF {
		return false, nil
	}
	if st, err := f.fh.Stat(); err == nil {
		// if the file is able to be read and written
		if st.Mode()&0600 == 0600 {
			f.fh.Close()
			f.fh = nil

			// reopen in read-write mode and set the filehandle
			fh, err := os.OpenFile(f.path, os.O_CREATE|os.O_RDWR, os.FileMode(0600))
			if err != nil {
				return false, err
			}
			f.fh = fh
			return true, nil
		}
	}

	return false, nil
}

public function chmod($path, $perm)
	{
		if ( ! $this->_is_conn())
		{
			return false;
		}

		// Permissions can only be set when running PHP 5
		if ( ! function_exists('ftp_chmod'))
		{
			if ($this->_debug == true)
			{
				throw new \FtpFileAccessException('CHMOD function does not exist');
			}
			return false;
		}

		$result = @ftp_chmod($this->_conn_id, $perm, $path);

		if ($result === false)
		{
			if ($this->_debug == true)
			{
				throw new \FtpFileAccessException('Unable to CHMOD');
			}
			return false;
		}

		return true;
	}

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


Question: Generally used post training time to load a single sentence for predictions

public INDArray loadSingleSentence(String sentence) {
        List<String> tokens = tokenizeSentence(sentence);
        if(format == Format.CNN1D || format == Format.RNN){
            int[] featuresShape = new int[] {1, wordVectorSize, Math.min(maxSentenceLength, tokens.size())};
            INDArray features = Nd4j.create(featuresShape, (format == Format.CNN1D ? 'c' : 'f'));
            INDArrayIndex[] indices = new INDArrayIndex[3];
            indices[0] = NDArrayIndex.point(0);
            for (int i = 0; i < featuresShape[2]; i++) {
                INDArray vector = getVector(tokens.get(i));
                indices[1] = NDArrayIndex.all();
                indices[2] = NDArrayIndex.point(i);
                features.put(indices, vector);
            }
            return features;
        } else {
            int[] featuresShape = new int[] {1, 1, 0, 0};
            if (sentencesAlongHeight) {
                featuresShape[2] = Math.min(maxSentenceLength, tokens.size());
                featuresShape[3] = wordVectorSize;
            } else {
                featuresShape[2] = wordVectorSize;
                featuresShape[3] = Math.min(maxSentenceLength, tokens.size());
            }

            INDArray features = Nd4j.create(featuresShape);
            int length = (sentencesAlongHeight ? featuresShape[2] : featuresShape[3]);
            INDArrayIndex[] indices = new INDArrayIndex[4];
            indices[0] = NDArrayIndex.point(0);
            indices[1] = NDArrayIndex.point(0);
            for (int i = 0; i < length; i++) {
                INDArray vector = getVector(tokens.get(i));

                if (sentencesAlongHeight) {
                    indices[2] = NDArrayIndex.point(i);
                    indices[3] = NDArrayIndex.all();
                } else {
                    indices[2] = NDArrayIndex.all();
                    indices[3] = NDArrayIndex.point(i);
                }

                features.put(indices, vector);
            }

            return features;
        }
    }

func NewTracerWithEverything(options *Options, recorder SpanRecorder) ot.Tracer {
	InitSensor(options)
	ret := &tracerS{options: TracerOptions{
		Recorder:       recorder,
		ShouldSample:   shouldSample,
		MaxLogsPerSpan: MaxLogsPerSpan}}
	ret.textPropagator = &textMapPropagator{ret}

	return ret
}

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


Question:
function processURL()
This will process the URL and extract the parameters from it.

private function processURL(): void
    {
        $defaultPath = '';
        $basePath = explode('?', urldecode($_SERVER['REQUEST_URI']));
        $requestURI = explode('/', rtrim($basePath[0], '/'));
        $requestURI[0] = strtoupper($_SERVER['REQUEST_METHOD']);
        $scriptName = explode('/', $_SERVER['SCRIPT_NAME']);
        $sizeofRequestURI = sizeof($requestURI);
        $sizeofScriptName = sizeof($scriptName);
        for ($x = 0; $x < $sizeofRequestURI && $x < $sizeofScriptName; $x++) {
            if (strtolower($requestURI[$x]) == strtolower($scriptName[$x])) {
                $defaultPath .= '/' . $requestURI[$x];
                unset($requestURI[$x]);
            }
        }
        $this->default = $defaultPath . $this->default;
        if (!$this->isFullUrl($this->defaultMobileApp)) {
            $this->defaultMobileApp = $defaultPath . $this->defaultMobileApp;
        }
        $this->parameters = array_values($requestURI);
    }

func (s *CreateIntegrationOutput) SetRequestParameters(v map[string]*string) *CreateIntegrationOutput {
	s.RequestParameters = v
	return s
}

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


Question:
Runs the widget

@return string

public function run()
    {
        $this->registerAssets();

        if ($this->hasModel()) {
            echo Html::activeCheckbox($this->model, $this->attribute, $this->options);
        } else {
            $checked = ArrayHelper::remove($this->options, 'checked', false);
            echo Html::checkbox($this->name, $checked, $this->options);
        }
    }

def _push_cm_exit(self, cm, cm_exit):
        """"""
        _exit_wrapper = self._create_exit_wrapper(cm, cm_exit)
        self._push_exit_callback(_exit_wrapper, True)

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


Question:
// parseDuration takes a user's input as a string and attempts to convert it
// into a time.Duration. If not given as a go-style duration string, the input
// is assumed to be seconds as a float.

func parseDuration(input string) (time.Duration, error) {
	d, err := time.ParseDuration(input)
	if err != nil {
		n, err := strconv.ParseFloat(input, 64)
		if err != nil {
			return 0, err
		}
		d = time.Duration(n*1000) * time.Millisecond
	}
	return d, nil
}

def _resolved_type(self):
        """"""
        import datetime

        self.type_ratios = {test: (float(self.type_counts[test]) / float(self.count)) if self.count else None
                            for test, testf in tests + [(None, None)]}

        # If it is more than 5% str, it's a str

        try:
            if self.type_ratios.get(text_type,0) + self.type_ratios.get(binary_type,0) > .05:
                if self.type_counts[text_type] > 0:
                    return text_type, False

                elif self.type_counts[binary_type] > 0:
                    return binary_type, False
        except TypeError as e:
            # This is probably the result of the type being unknown
            pass

        if self.type_counts[datetime.datetime] > 0:
            num_type = datetime.datetime

        elif self.type_counts[datetime.date] > 0:
            num_type = datetime.date

        elif self.type_counts[datetime.time] > 0:
            num_type = datetime.time

        elif self.type_counts[float] > 0:
            num_type = float

        elif self.type_counts[int] > 0:
            num_type = int

        elif self.type_counts[text_type] > 0:
            num_type = text_type

        elif self.type_counts[binary_type] > 0:
            num_type = binary_type

        else:
            num_type = unknown

        if self.type_counts[binary_type] > 0 and num_type != binary_type:
            has_codes = True
        else:
            has_codes = False

        return num_type, has_codes

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


Question:
事件处理方法
@param EventParam $e
@return void

public function handle(WorkerStartEventParam $e)
    {
        // 随机数播种
        mt_srand();

        // 重新加载项目配置及组件
        foreach(Helper::getAppMains() as $main)
        {
            $main->loadConfig();
            $main->loadComponents();
        }

        if($e->server->getSwooleServer()->taskworker)
        {
            Imi::setProcessName('taskWorker');
        }
        else
        {
            // swoole 4.1.0 一键协程化
            if(method_exists('\Swoole\Runtime', 'enableCoroutine') && (Helper::getMain(App::getNamespace())->getConfig()['enableCoroutine'] ?? true))
            {
                \Swoole\Runtime::enableCoroutine(true);
            }
            Imi::setProcessName('worker');
        }

        $GLOBALS['WORKER_START_END_RESUME_COIDS'] = [];

        // 初始化 worker
        App::initWorker();
    }

func (daemon *Daemon) LogContainerEvent(container *container.Container, action string) {
	daemon.LogContainerEventWithAttributes(container, action, map[string]string{})
}

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


Question:
update the given group
@param \Symbb\Core\UserBundle\Entity\GroupInterface $group

public function update(GroupInterface $group)
    {
        $this->em->persist($group);
        $this->em->flush();
        return true;

    }

def changepassword(self, event):
        """"""

        old = event.data['old']
        new = event.data['new']
        uuid = event.user.uuid

        # TODO: Write email to notify user of password change

        user = objectmodels['user'].find_one({'uuid': uuid})
        if std_hash(old, self.salt) == user.passhash:
            user.passhash = std_hash(new, self.salt)
            user.save()

            packet = {
                'component': 'hfos.enrol.enrolmanager',
                'action': 'changepassword',
                'data': True
            }
            self.fireEvent(send(event.client.uuid, packet))
            self.log('Successfully changed password for user', uuid)
        else:
            packet = {
                'component': 'hfos.enrol.enrolmanager',
                'action': 'changepassword',
                'data': False
            }
            self.fireEvent(send(event.client.uuid, packet))
            self.log('User tried to change password without supplying old one', lvl=warn)

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


Question: get lookahead symbol.

protected final Token lookahead(int index) throws ScanException, ParseException {
		if (lookahead.isEmpty()) {
			lookahead = new LinkedList<LookaheadToken>();
		}
		while (index >= lookahead.size()) {
			lookahead.add(new LookaheadToken(scanner.next(), scanner.getPosition()));
		}
		return lookahead.get(index).token;
	}

func lexLabel(l *lexer) stateFn {
	l.acceptRun(Alpha + "_")

	l.emit(label)

	return lexLine
}

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


Question:
@param Record $record
@param Entity $entity
@param        $language

@return $this

public function deleteTranslation(Record $record, Entity $entity, $language)
    {
        (new DeleteRecord($record, $entity, $this))->setTable($entity->getTable() . '_i18n')
                                                   ->setData(
                                                       [
                                                           $entity->getTable() . '_i18n' => [
                                                               'language_id' => $language,
                                                           ],
                                                       ]
                                                   )->execute();

        return $this;
    }

private TSMeta parseTSMetaQS(final HttpQuery query) {
    final String tsuid = query.getQueryStringParam("tsuid");
    final TSMeta meta;
    if (tsuid != null && !tsuid.isEmpty()) {
      meta = new TSMeta(tsuid);
    } else {
      meta = new TSMeta();
    }

    final String display_name = query.getQueryStringParam("display_name");
    if (display_name != null) {
      meta.setDisplayName(display_name);
    }

    final String description = query.getQueryStringParam("description");
    if (description != null) {
      meta.setDescription(description);
    }

    final String notes = query.getQueryStringParam("notes");
    if (notes != null) {
      meta.setNotes(notes);
    }

    final String units = query.getQueryStringParam("units");
    if (units != null) {
      meta.setUnits(units);
    }

    final String data_type = query.getQueryStringParam("data_type");
    if (data_type != null) {
      meta.setDataType(data_type);
    }

    final String retention = query.getQueryStringParam("retention");
    if (retention != null && !retention.isEmpty()) {
      try {
        meta.setRetention(Integer.parseInt(retention));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'retention' value");
      }
    }

    final String max = query.getQueryStringParam("max");
    if (max != null && !max.isEmpty()) {
      try {
        meta.setMax(Float.parseFloat(max));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'max' value");
      }
    }

    final String min = query.getQueryStringParam("min");
    if (min != null && !min.isEmpty()) {
      try {
        meta.setMin(Float.parseFloat(min));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'min' value");
      }
    }

    return meta;
  }

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


Question:
Resolution by Sarrus method
@return string
@throws OperationNotAllowedException

public function forOrderThree()
    {
        if ($this->matrix->getNumRows()!==3) {
            throw new OperationNotAllowedException('determinantOrderThree only allowed on 3x3 matrix');
        }
        $additions = array(
            array(array(1,1), array(2,2), array(3,3)),
            array(array(1,2), array(2,3), array(3,1)),
            array(array(1,3), array(2,1), array(3,2)),
        );
        $subtractions = array(
            array(array(1,3), array(2,2), array(3,1)),
            array(array(1,2), array(2,1), array(3,3)),
            array(array(1,1), array(2,3), array(3,2)),
        );
        $result = $this->valueZero;
        foreach ($additions as $addition) {
            $partial = $this->valueOne;
            foreach ($addition as $point) {
                $partial = bcmul($partial, $this->matrix->getPoint($point[0], $point[1]), $this->precision);
            }
            $result = bcadd($result, $partial, $this->precision);
        }
        foreach ($subtractions as $subtraction) {
            $partial = $this->valueOne;
            foreach ($subtraction as $point) {
                $partial = bcmul($partial, $this->matrix->getPoint($point[0], $point[1]), $this->precision);
            }
            $result = bcsub($result, $partial, $this->precision);
        }
        return $result;
    }

func (md *MDServerRemote) OnDoCommandError(err error, wait time.Duration) {
	md.log.CWarningf(context.TODO(),
		"MDServerRemote: DoCommand error: %q; retrying in %s", err, wait)
	// Only push errors that should not be retried as connection status changes.
	if !md.ShouldRetry("", err) {
		md.config.KBFSOps().PushConnectionStatusChange(MDServiceName, err)
		md.config.Reporter().OnlineStatusChanged(context.Background(), false)
	}
}

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


Question: // merge combines the next set of blocks into merged blocks.

func (k *tsmBatchKeyIterator) mergeInteger() {
	// No blocks left, or pending merged values, we're done
	if len(k.blocks) == 0 && len(k.merged) == 0 && k.mergedIntegerValues.Len() == 0 {
		return
	}

	sort.Stable(k.blocks)

	dedup := k.mergedIntegerValues.Len() != 0
	if len(k.blocks) > 0 && !dedup {
		// If we have more than one block or any partially tombstoned blocks, we many need to dedup
		dedup = len(k.blocks[0].tombstones) > 0 || k.blocks[0].partiallyRead()

		// Quickly scan each block to see if any overlap with the prior block, if they overlap then
		// we need to dedup as there may be duplicate points now
		for i := 1; !dedup && i < len(k.blocks); i++ {
			dedup = k.blocks[i].partiallyRead() ||
				k.blocks[i].overlapsTimeRange(k.blocks[i-1].minTime, k.blocks[i-1].maxTime) ||
				len(k.blocks[i].tombstones) > 0
		}

	}

	k.merged = k.combineInteger(dedup)
}

protected function getDocBlock(Stmt $stmt, array $uses = []): ?array
    {
        $comments = $stmt->getAttribute('comments');

        if (is_array($comments)) {
            foreach ($comments as $comment) {
                if ($comment instanceof Doc) {
                    return $this->processDocBlock($comment->getText(), $uses);
                }
            }
        }

        return null;
    }

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


Question: Unit test code - run as Java application from your eclipse workspace

public static void main(String[] args) {
        final boolean testTimeout = true;
        final boolean testDeadlock = false;
        final boolean testShutdown = true;
        final long timeout = 1000;

        final Object lock1 = new Object();
        final Object lock2 = new Object();

        final Thread thread1 = new Thread() {
            @Override
            public void run() {
                synchronized (lock1) {
                    System.out.println("Thread1 has lock1");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    };
                    synchronized (lock2) {
                        System.out.println("Thread1 has both locks");
                    }
                }
            }
        };
        final Thread thread2 = new Thread() {
            @Override
            public void run() {
                synchronized (lock2) {
                    System.out.println("Thread2 has lock2");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    };
                    synchronized (lock1) {
                        System.out.println("Thread2 has both locks");
                    }
                }
            }
        };
        final Thread shutdownThread = new Thread() {
            @Override
            public void run() {
                System.out.println("Shutdown hook sleeping");
                try {
                    Thread.sleep(timeout * 3);
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                } finally {
                    System.out.println("Shutdown hook finished");
                }
            }
        };

        final TimedExitThread tet = new TimedExitThread();
        tet.setTimeout(timeout);

        if (testDeadlock) {
            thread1.start();
            thread2.start();
        }

        if (testShutdown) {
            Runtime.getRuntime().addShutdownHook(shutdownThread);
        }

        tet.start();

        if (testTimeout) {
            System.out.println("main() sleeping");
            try {
                Thread.sleep(timeout * 2);
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            } finally {
                System.out.println("main() finished");
            }
        }
    }

public void unexport_server(Database database, String deviceName)
            throws DevFailed {
        if (!database.isAccess_checked()) checkAccess(database);

        DeviceData argIn = new DeviceData();
        argIn.insert(deviceName);
        command_inout(database, "DbUnExportServer", argIn);
    }

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


Question:
This method initializes the Parse "SVN Entries" checkbox.

@return javax.swing.JCheckBox

private JCheckBox getChkParseSVNEntries() {
		if (parseSVNEntries == null) {
			parseSVNEntries = new JCheckBox();
			parseSVNEntries.setText(Constant.messages.getString("spider.options.label.svnentries"));
		}
		return parseSVNEntries;
	}

private JPanel getJPanel1() {
		if (jPanel1 == null) {
			jPanel1 = new JPanel();
			jPanel1.add(getBtnFind());
			jPanel1.add(getBtnCancel());
		}
		return jPanel1;
	}

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


Question:
Checks if a node is the "end" keyword.

    Args:
        node: AST node.

    Returns:
        True if the node is the "end" keyword, otherwise False.

def is_end_node(node):

    return (isinstance(node, ast.Expr) and
            isinstance(node.value, ast.Name) and
            node.value.id == 'end')

protected function seekTernaryElse(\Twig_TokenStream $tokens)
    {
        $i = 1;
        $depth = 0;
        $found = false;
        $token = null;

        while ($depth || !$found) {
            $token = $tokens->look($i);

            if (in_array($token->getType(), [\Twig_Token::BLOCK_END_TYPE, \Twig_Token::VAR_END_TYPE, \Twig_Token::INTERPOLATION_END_TYPE])) {
                return;
            }

            // End of hash value means end of short ternary (eg. "foo ? bar" syntax)
            if ($token->getType() === \Twig_Token::PUNCTUATION_TYPE && $token->getValue() === ',') {
                return;
            }

            if ($token->getType() === \Twig_Token::PUNCTUATION_TYPE && in_array($token->getValue(), ['(', '[', '{'])) {
                $depth++;
            }

            if ($depth && $token->getType() === \Twig_Token::PUNCTUATION_TYPE && in_array($token->getValue(), [')', ']', '}'])) {
                $depth--;
            }

            $found = $token->getType() === \Twig_Token::PUNCTUATION_TYPE && $token->getValue() === ':';
            $i++;
        }

        return $token;
    }

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


Question:
Build the final URL to be passed

@param array $queryParams an array of all the query parameters

@return string

private function buildUrl($queryParams = null)
    {
        $path = '/' . implode('/', $this->path);
        if (isset($queryParams)) {
            $path .= '?' . http_build_query($queryParams);
        }
        return sprintf('%s%s%s', $this->host, $this->version ?: '', $path);
    }

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

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

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


Question: Marshall the given parameter object.

public void marshall(DeleteDeviceRequest deleteDeviceRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(deleteDeviceRequest.getDeviceArn(), DEVICEARN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
/*
Highlight comment lines to matching end delimiter

private void commentLinesAfter( String content, int line )
  {
    int offset = _root.getElement( line ).getEndOffset();
    // End of comment not found, nothing to do
    int endDelimiter = indexOf( content, getEndDelimiter(), offset );
    if( endDelimiter < 0 )
    {
      return;
    }
    // Matching start/end of comment found, comment the lines
    int startDelimiter = lastIndexOf( content, getStartDelimiter(), endDelimiter );
    if( startDelimiter < 0 || startDelimiter <= offset )
    {
      setCharacterAttributes( offset, endDelimiter - offset + 1, _comment, false );
    }
  }

private function preIndent()
    {
        $prev = $this->tokens->getId($this->tokens->key() - 1);

        switch ($this->tokens->getId()) {
            case DocLexer::T_AT:
                if ($prev
                    && (DocLexer::T_COLON !== $prev)
                    && (DocLexer::T_COMMA !== $prev)
                    && (DocLexer::T_EQUALS !== $prev)
                    && (DocLexer::T_OPEN_CURLY_BRACES !== $prev)
                    && (DocLexer::T_OPEN_PARENTHESIS !== $prev)) {
                    $this->indent(true);
                }

                break;
            case DocLexer::T_CLOSE_CURLY_BRACES:
                $this->level--;

                if (DocLexer::T_OPEN_CURLY_BRACES !== $prev) {
                    $this->indent();
                }

                break;
            case DocLexer::T_CLOSE_PARENTHESIS:
                $this->level--;

                if (DocLexer::T_OPEN_PARENTHESIS !== $prev) {
                    $this->indent();
                }

                break;
        }
    }

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


Question: Fast scale operation that does not sample the results

def identity(self, surface):

        return self._pygame.transform.scale(surface, self._output_size)

func (o *OnlyOnce) GetSampleRate(key string) int {
	o.lock.Lock()
	defer o.lock.Unlock()
	if _, found := o.seen[key]; found {
		return 1000000000
	}
	o.seen[key] = true
	return 1
}

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


Question:
After loading the entity load file if any.

@param LifecycleEventArgs $eventArgs

public function postLoad(LifecycleEventArgs $eventArgs)
    {
        $entityManager = $eventArgs->getEntityManager();
        $object = $eventArgs->getEntity();
        $uploadableMeta = $this->getObjectExtendedMetadata($entityManager, $object);

        if ($uploadableMeta->hasUploadableProperties()) {
            $this->loadFiles($entityManager, $object, $uploadableMeta);
        }
    }

public function execute(TransactionData $transactionData, $argument = null)
    {
        foreach ($this->expectationBackup->listExpectations() as $expectation) {
            $this->expectationStorage->addExpectation($expectation);
        }
        $this->logger->debug('Pre-defined expectations are restored, scenarios and requests history are cleared.');

        $transactionData->setResponse(
            $transactionData->getResponse()->withStatus(200)
        );
    }

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


Question: // Build is part of the ModelOperation interface.

func (op *UpdateMachineOperation) Build(attempt int) ([]txn.Op, error) {
	if attempt > 0 {
		if err := op.m.Refresh(); err != nil {
			return nil, err
		}
	}

	var allOps []txn.Op

	if op.AgentVersion != nil {
		ops, _, err := op.m.setAgentVersionOps(*op.AgentVersion)
		if err != nil {
			return nil, errors.Annotate(err, "cannot set agent version")
		}
		allOps = append(allOps, ops...)
	}

	if op.Constraints != nil {
		ops, err := op.m.setConstraintsOps(*op.Constraints)
		if err != nil {
			return nil, errors.Annotate(err, "cannot set constraints")
		}
		allOps = append(allOps, ops...)
	}

	if op.HasVote != nil {
		ops, err := op.m.setHasVoteOps(*op.HasVote)
		if err != nil {
			return nil, errors.Annotate(err, "cannot set has-vote")
		}
		allOps = append(allOps, ops...)
	}

	if op.MachineAddresses != nil || op.ProviderAddresses != nil {
		ops, _, _, _, _, err := op.m.setAddressesOps(op.MachineAddresses, op.ProviderAddresses)
		if err != nil {
			return nil, errors.Annotate(err, "cannot set addresses")
		}
		allOps = append(allOps, ops...)
	}

	if op.PasswordHash != nil {
		ops, err := op.m.setPasswordHashOps(*op.PasswordHash)
		if err != nil {
			return nil, errors.Annotate(err, "cannot set password")
		}
		allOps = append(allOps, ops...)
	}

	return allOps, nil
}

func (c *Command) addHelpGroup(showHelp func() error) *Group {
	var help struct {
		ShowHelp func() error `short:"h" long:"help" description:"Show this help message"`
	}

	help.ShowHelp = showHelp
	ret, _ := c.AddGroup("Help Options", "", &help)
	ret.isBuiltinHelp = true

	return ret
}

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


Question:
pack up found items for search ctrl
            :param target: treectrl obj
            :param s_text: text to search, lower case
            return list of found items

def pack_found_items(self, s_text, target):

        all_children = self.all_children
        all_text = [target.GetItemText(i).lower() for i in all_children]

        found_items = [child for i, child in enumerate(all_children)
                       if s_text in all_text[i]]

        return found_items

def process(self, txt, mode):

        result = ''
        if mode == 'ADD':  # already in add mode, so add data
            if txt in self.all_commands['cmd'][0]:
                self.show_output('Returning to Command mode')
                mode = 'COMMAND'
                self.prompt = '> '
            else:
                self.show_output('Adding Text : ', txt)
                result = self.cmd_add(txt)
        elif mode == 'QUERY':
            if txt in self.all_commands['cmd'][0]:
                self.show_output('Returning to Command mode')
                mode = 'COMMAND'
                self.prompt = '> '
            else:
                self.show_output('Query : ', txt)
                result = self.cmd_query(txt)
        else:
            if txt in self.all_commands['exit'][0]:
                self.cmd_exit()

            elif txt in self.all_commands['help'][0]:
                self.cmd_help()

            elif txt in self.all_commands['cmd'][0]:
                result = 'Returning to Command mode'
                mode = 'COMMAND'
                self.prompt = '> '

            elif txt in self.all_commands['add'][0]:
                result = 'Entering Add mode'
                mode = 'ADD'
                self.prompt = 'ADD > '

            elif txt in self.all_commands['query'][0]:
                result = 'Entering Query mode'
                mode = 'QUERY'
                self.prompt = '?? > '
            else:
                result = 'Unknown command - type help for list of commands'

        return result, mode

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


Question:
Given a GraphQL source, parses it into a Document.
Throws GraphQLError if a syntax error is encountered.

@inheritdoc
@throws SyntaxErrorException
@throws \ReflectionException
@throws InvariantException

public function parse(Source $source, array $options = []): DocumentNode
    {
        $this->lexer = $this->createLexer($source, $options);

        return $this->lexDocument();
    }

public static function generate(string $typeName, array $typeFields): string
    {
        $mutationName = 'create' . $typeName;

        $arguments = RelationArgumentGenerator::generate($typeFields);
        $arguments = array_merge($arguments, InputFieldsArgumentGenerator::generate($typeFields));

        if (count($arguments) < 1) {
            return '';
        }

        $mutation = sprintf('    %s(%s)', $mutationName, implode(', ', $arguments));
        $mutation .= sprintf(': %1$s @create(model: "%1$s")', $typeName);

        if (config('lighthouse-utils.authorization')) {
            $permission = sprintf('create%1$s', $typeName);
            $mutation .= sprintf(' @can(if: "%1$s", model: "User")', $permission);
        }

        GraphQLSchema::register($mutationName, $typeName, 'mutation', $permission ?? null);

        return $mutation;
    }

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


Question:
Add an item to the cache only if it doesn't already exist

@param   string  $key
@param   mixed   $value
@param   int     $minutes
@return  void

public function add($key, $value, $minutes)
	{
		$key = $this->id($key);
		$seconds = $minutes * 60;

		return $this->apcu ? apcu_add($key, $value, $seconds) : apc_add($key, $value, $seconds);
	}

public function setQueryCacheLifetime($timeToLive)
    {
        if ($timeToLive !== null) {
            $timeToLive = (int) $timeToLive;
        }

        $this->_queryCacheTTL = $timeToLive;

        return $this;
    }

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


Question: Clear the RemoteBridge subsystem to its reset state.

def clear_to_reset(self, config_vars):
        """"""

        super(RemoteBridgeState, self).clear_to_reset(config_vars)
        self.status = BRIDGE_STATUS.IDLE
        self.error = 0

func (s *BaiduChannelResponse) SetPlatform(v string) *BaiduChannelResponse {
	s.Platform = &v
	return s
}

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


Question:
Helper to format a LogRecord in in Stackdriver fluentd format.

        :rtype: str
        :returns: JSON str to be written to the log file.

def format_stackdriver_json(record, message):

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

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

    return json.dumps(payload)

function writeFileData(file_path, time, size, sizes_data, sizes_file_path){
		var file_ext = path.extname(file_path).replace('.','');
		var file_name = path.basename(file_path);

		// create file type object if it doesnt exist
		if(sizes_data[file_ext] === undefined){
			sizes_data[file_ext] = {};
		}

		// create file array
		if(sizes_data[file_ext][file_name] === undefined){
			sizes_data[file_ext][file_name] = [];
		}
		var time_obj = {
			date: time,
			size: size
		};
		grunt.log.writeln(file_path + " .... " + size + "b");

		sizes_data[file_ext][file_name].push(time_obj);
		fs.writeFileSync(sizes_file_path, JSON.stringify(sizes_data), 'utf8');
	}

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