Question:
// GetRefreshTokenLifespan sets how long a refresh token is going to be valid. Defaults to 30 days. Set to -1 for
// refresh tokens that never expire.

func (c *Config) GetRefreshTokenLifespan() time.Duration {
	if c.RefreshTokenLifespan == 0 {
		return time.Hour * 24 * 30
	}
	return c.RefreshTokenLifespan
}

function Cellar(name, mongoose, schema, options) {
	// connect to mongodb if they pass credentials
	if(mongoose.constructor.name === 'Object') {
		var mongoUrl = 'mongodb://' + mongoose.user + ':' + mongoose.pass + '@' + mongoose.host + ':' + mongoose.port + '/' + mongoose.name;
		mongoose = _mongoose.connect(mongoUrl);
	}
	// create a schema instance if they pass the literal
	schema = schema instanceof mongoose.Schema ? schema : new mongoose.Schema(schema);

	options = options || {};
	//default maxAge is 1 day, -1 means no expiration
	var maxAge = (typeof options.maxAge === undefined ? 1 : options.maxAge);
	// initialize lastChecked as a long time ago
	var lastChecked = new Date(0);
	// add an `updated_at` field to track when the document was last touched
	schema.add({updated_at: {type: Date, required:true, "default": Date.now}});

	// instantiate the model
	var mongoose_model = mongoose.model(name, schema);

	// prune

	// Private
	// Remove expired documents from the collection

	// ### Arguments
	// None

	// ### Returns
	// None

	function prune() {
		//check if this database is meant to be pruned
		if(~maxAge) {
			var d = new Date();
			d.setDate(d.getDate() - maxAge);

			if(lastChecked < d) { // make sure we're not trying to prune more often than at least maxAge since the last time we did
				mongoose_model.remove()
					.where('updated_at').lt(d)
					.exec(function(error, numAffected) {
						lastChecked = new Date(); //update our lastChecked to reflect our touching the database
						if(error) {
							console.log("Error while removing docs from database", error);
						} else {
							if(options.verbose) {
								console.log("Removed "+numAffected+" old docs from the database.");
							}
						}
					});
			}
		}
	}

	// Cellar#store

	// Public
	// Create or update a document in the collection

	// ### Arguments
	// * `where` - Optional Object describing criteria by which to update the document (see http://www.mongodb.org/display/DOCS/Querying)
	// * `data` - Object of data to update or create the document
	// * `callback` - Function to be evaluated upon completion of the insert/update
	//		- Arguments
	//			1. Error
	//			2. Mongoose document created or updated

	// ### Returns
	// * Instance of Cellar

	this.store = function(where, data, callback) {
		if(arguments.length < 3) {
			callback = data;
			data = where;
			where = null;
		}

		if(where) {
			//update
			data.updated_at = Date.now();
			for(var p in where) {
				if(where.hasOwnProperty(p)) {
					if(typeof data[p] === 'undefined') {
						// add all the `where` properties to the replacement doc (where there are no conflicts) in case this document gets upserted
						data[p] = where[p];
					}
				}
			}
			mongoose_model.findOneAndUpdate(where, data, {upsert:true}, callback);
		} else {
			//insert
			var store = new mongoose_model(data);
			store.save(callback);
		}
		//prune the db
		prune();
		return this;
    };

    // Cellar#retrieve

	// Public
	// Find a document in the collection

	// ### Arguments
	// * `where` - Object of criteria by which to find the document (see http://www.mongodb.org/display/DOCS/Querying)
	// * `fields` - Optional Array of String field names to retrieve on the document
	// * `callback` - Function to be evaluated upon completion of the find operation
	//		- Arguments
	//			1. Error
	//			2. Mongoose document that matched the criteria or null if no document matched

	// ### Returns
	// * Instance of Cellar

    this.retrieve = function(where, fields, callback) {
		if(arguments.length < 3 || fields === undefined || fields === null) {
			fields = [];
		}
		var args = [where];
		if(fields.length) {
			args.push(fields.join(" "));
		}
		args.push(callback);
		mongoose_model.findOne.apply(mongoose_model, args);
		return this;
    };

    // Cellar#retrieve_field

	// Public
	// Find the contents of one field on a document in the collection

	// ### Arguments
	// * `where` - Object of criteria by which to find the document where the field is (see http://www.mongodb.org/display/DOCS/Querying)
	// * `field` - String name of field desired
	// * `callback` - Function to be evaluated after the find is completed
	//		- Arguments
	//			1. Error - will also return an error if looking for a field on a document which does not have the field
	//			2. Contents of `field` in a matching document, or null if no document matched

	// ### Returns
	// * Instance of Cellar

    this.retrieve_field = function(where, field, callback) {
		this.retrieve(where, [field], function(error, doc) {
			if(error || !doc) {
				callback(error);
				return;
			}
			if(!doc[field]) {
				callback(new Error(field+" does not exist in this document"));
				return;
			}
			callback(null, doc[field]);
		});
		return this;
    };

    return this;
}

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


Question:
Convert this encoded string back to a Java Object.
@param string The string to convert.
@return The java object.

public Object stringToObject(String string)
    {
        string = Base64.decode(string);
        Object obj = super.stringToObject(string);
        return obj;
    }

public PrivateKey unwrapPrivateKeyByKey(byte[] key,Key unwrapKey)
	{
		try {
    		if(key==null || key.length<=0 || unwrapKey==null)
    		{
    			return null;
    		}
			Cipher cipher=Cipher.getInstance(algorithm);
			//使用私钥包裹模式
			cipher.init(Cipher.UNWRAP_MODE,unwrapKey);
			return (PrivateKey) cipher.unwrap(key, algorithm,Cipher.PRIVATE_KEY);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
    	return null;
	}

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


Question:
Return a sub

@param string $name
@param string $attrs
@param string $ns

public function sub($name, $attrs = null, $ns = null)
    {
        //@TODO: attrs is ignored
        foreach ($this->subs as $sub) {
            if ($sub->name === $name and ($ns === null or $sub->ns === $ns)) {
                return $sub;
            }
        }
        return null;
    }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


Question:
Format the date/time value as a string based on the current locale

@param string|false $format  'short', 'medium', 'long', 'full', 'none' or false
@return int|null

protected function getFormat($format)
    {
        if ($format === false) {
            $format = 'none';
        }

        $types = [
            'none' => \IntlDateFormatter::NONE,
            'short' => \IntlDateFormatter::SHORT,
            'medium' => \IntlDateFormatter::MEDIUM,
            'long' => \IntlDateFormatter::LONG,
            'full' => \IntlDateFormatter::FULL
        ];

        return isset($types[$format]) ? $types[$format] : null;
    }

public function setType($type)
    {
        $this->type = $type;
        if ($this->type == "xml") {
            $this->formatter = new XMLPDOResultFormatter();
        } elseif ($this->type == "plain") {
            $this->formatter = new PlainPDOResultFormatter();
        } else {
            throw new BuildException("Formatter '" . $this->type . "' not implemented");
        }
    }

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


Question: Return common prefix length of IPv6 addresses a and b.

def in6_get_common_plen(a, b):

    def matching_bits(byte1, byte2):
        for i in range(8):
            cur_mask = 0x80 >> i
            if (byte1 & cur_mask) != (byte2 & cur_mask):
                return i
        return 8

    tmpA = inet_pton(socket.AF_INET6, a)
    tmpB = inet_pton(socket.AF_INET6, b)
    for i in range(16):
        mbits = matching_bits(orb(tmpA[i]), orb(tmpB[i]))
        if mbits != 8:
            return 8 * i + mbits
    return 128

public function getNextAddress()
    {
        $overflow = false;
        $bytes = $this->getBytes();
        for ($i = count($bytes) - 1; $i >= 0; --$i) {
            if ($bytes[$i] === 255) {
                if ($i === 0) {
                    $overflow = true;
                    break;
                }
                $bytes[$i] = 0;
            } else {
                ++$bytes[$i];
                break;
            }
        }

        return $overflow ? null : static::fromBytes($bytes);
    }

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


Question: Transform Swagger spec.

function transform(value, options) {
  options = options || {};

  return traverse(value, {
    beforeObject: function(v) {
      if (options.removeFormats &&
          typeof v.format === 'string' &&
          typeof v.type === 'string' &&
          v.type !== 'string') {
        delete v.format;
      }

      return v;
    },
    afterObject: function(v) {
      if (options.convertRefs &&
          typeof v.type === 'string' &&
          constants.notModel.indexOf(v.type) < 0) {
        return { $ref: v.type };
      }

      return v;
    },
  });
}

@Override
    public StreamT<W,T> takeRight(final int num) {

        return (StreamT<W,T>) FoldableTransformerSeq.super.takeRight(num);
    }

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


Question: Update the prompt-toolkit Layout and FocusStack.

def sync_with_prompt_toolkit(self):

        # After executing a command, make sure that the layout of
        # prompt-toolkit matches our WindowArrangement.
        self.editor_layout.update()

        # Make sure that the focus stack of prompt-toolkit has the current
        # page.
        window = self.window_arrangement.active_pt_window
        if window:
            self.application.layout.focus(window)

func (m *OutgoingMessage) SetKeyboard(k KeyboardMarkup, selective bool) *OutgoingMessage {
	m.Keyboard = true
	m.KeyboardMarkup = k.Keyboard()
	m.Selective = selective
	//todo: here is workaround for QT version. Keyboard with selective is not working
	return m
}

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


Question:
Fetch router data from the routing plugin in chunks.

                :param router_ids: List of router_ids of routers to fetch
                :return: List of router dicts of format:
                         [ {router_dict1}, {router_dict2},.....]

def _fetch_router_chunk_data(self, router_ids=None):

        curr_router = []
        if len(router_ids) > self.sync_routers_chunk_size:
            # fetch routers by chunks to reduce the load on server and
            # to start router processing earlier
            for i in range(0, len(router_ids),
                           self.sync_routers_chunk_size):
                routers = self.plugin_rpc.get_routers(
                                self.context, (router_ids[i:i +
                                               self.sync_routers_chunk_size]))
                LOG.debug('Processing :%r', routers)
                for r in routers:
                    curr_router.append(r)
        else:
            curr_router = self.plugin_rpc.get_routers(
                self.context, router_ids=router_ids)
        return curr_router

def _get_vrfs(self):

        vrfs = []
        ios_cfg = self._get_running_config()
        parse = HTParser(ios_cfg)
        vrfs_raw = parse.find_lines("^vrf definition")
        for line in vrfs_raw:
            #  raw format ['ip vrf <vrf-name>',....]
            vrf_name = line.strip().split(' ')[2]
            vrfs.append(vrf_name)
        LOG.info("VRFs:%s", vrfs)
        return vrfs

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


Question:
Model Factory.

@throws \Exception

@return mixed

public function getModel()
    {
        $namePath = $this->getModelClass();
        $model = new $namePath();

        if (!($model instanceof EntityDataModel)) {
            throw new \Exception($this->valueClass.' is not an instance of EntityModel.');
        }

        return $model;
    }

private function _addError($relationModel, $owner, $relationName, $prettyRelationName)
    {
        foreach ($relationModel->errors as $attribute => $attributeErrors) {
            foreach ($attributeErrors as $error) {
                $owner->addError($relationName, "{$prettyRelationName}: {$error}");
            }
        }
    }

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


Question:
ステートメント初期化。

@param sqlContext SQLコンテキスト
@return PreparedStatement
@throws SQLException SQL例外

protected PreparedStatement getPreparedStatement(final SqlContext sqlContext) throws SQLException {
		PreparedStatement stmt = ((LocalTransactionManager) transactionManager).getPreparedStatement(sqlContext);
		// プロパティ設定
		applyProperties(stmt);
		return stmt;
	}

HashMap<String, byte[]> getExplainPlans(Catalog catalog) {
        HashMap<String, byte[]> retval = new HashMap<>();
        Database db = getCatalogDatabase(m_catalog);
        assert(db != null);
        for (Procedure proc : db.getProcedures()) {
            for (Statement stmt : proc.getStatements()) {
                String s = "SQL: " + stmt.getSqltext() + "\n";
                s += "COST: " + Integer.toString(stmt.getCost()) + "\n";
                s += "PLAN:\n\n";
                s += Encoder.hexDecodeToString(stmt.getExplainplan()) + "\n";
                byte[] b = s.getBytes(Constants.UTF8ENCODING);
                retval.put(proc.getTypeName() + "_" + stmt.getTypeName() + ".txt", b);
            }
        }
        return retval;
    }

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


Question:
Check for unclosed statements.
@return Were any statements unclosed?

private boolean closeStatements() {

      // JDBC API says...
      // Calling the method close on a Statement object that is already closed has no effect.
      // Note: When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

      boolean hasUnclosed = false;

      if(openStatements.size() > 0) {
         for(Statement stmt : openStatements) {
            try {
               if(!stmt.isClosed()) {
                  stmt.close();
                  hasUnclosed = true;
               }
            } catch(SQLException e) {
               hasUnclosed = true;
               setLogicalCloseException(e);
            } catch(Throwable t) {
               hasUnclosed = true;
               if(logicalCloseException == null) {
                  if(Util.isRuntimeError(t)) {
                     setLogicalCloseException(t);
                  } else {
                     setLogicalCloseException(new SQLException(t));
                  }
               }
            }
         }

         openStatements.clear();
      }

      return hasUnclosed;
   }

public static int parseBlockComment(final char[] query, int offset) {
    if (offset + 1 < query.length && query[offset + 1] == '*') {
      // /* /* */ */ nest, according to SQL spec
      int level = 1;
      for (offset += 2; offset < query.length; ++offset) {
        switch (query[offset - 1]) {
          case '*':
            if (query[offset] == '/') {
              --level;
              ++offset; // don't parse / in */* twice
            }
            break;
          case '/':
            if (query[offset] == '*') {
              ++level;
              ++offset; // don't parse * in /*/ twice
            }
            break;
          default:
            break;
        }

        if (level == 0) {
          --offset; // reset position to last '/' char
          break;
        }
      }
    }
    return offset;
  }

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


Question:
Execute consumer when the string is empty

@param str      string value
@param consumer consumer

public static void isBlankThen(String str, Consumer<String> consumer) {
        if (isBlank(str)) {
            consumer.accept(str);
        }
    }

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

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


Question:
Reapplies order-addresses on submit

@param ApiOrderInterface $cart

private function reApplyOrderAddresses($cart, $user)
    {
        // validate addresses
        $this->validateOrCreateAddresses($cart, $user);

        // reapply invoice address of cart
        if ($cart->getInvoiceAddress()->getContactAddress()) {
            $this->orderAddressManager->getAndSetOrderAddressByContactAddress(
                $cart->getInvoiceAddress()->getContactAddress(),
                null,
                null,
                $cart->getInvoiceAddress()
            );
        }

        // reapply delivery address of cart
        if ($cart->getDeliveryAddress()->getContactAddress()) {
            $this->orderAddressManager->getAndSetOrderAddressByContactAddress(
                $cart->getDeliveryAddress()->getContactAddress(),
                null,
                null,
                $cart->getDeliveryAddress()
            );
        }

        // reapply delivery-addresses of every item
        foreach ($cart->getItems() as $item) {
            if ($item->getDeliveryAddress() &&
                $item->getDeliveryAddress()->getContactAddress()
            ) {
                $this->orderAddressManager->getAndSetOrderAddressByContactAddress(
                    $item->getDeliveryAddress()->getContactAddress(),
                    null,
                    null,
                    $item->getDeliveryAddress()
                );
            }
        }
    }

public function create($customerId, $parameters = [])
    {
        if (is_array($parameters) && isset($parameters['source'])) {
            $parameters['source']['object'] = 'bank_account';
        } elseif (is_string($parameters)) {
            $parameters = ['source' => $parameters];
        }

        return $this->_post("customers/{$customerId}/sources", $parameters);
    }

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


Question:
Execute.

@param string $packageName    package to inspect
@param string $textConstraint Optional version constraint
@param bool   $onlyLocal

@return Dependency[]|null

public function execute($packageName, $textConstraint = '*', $onlyLocal = true)
    {
        // Find packages that are or provide the requested package first
        $pool = $this->getRequiredPool($packageName, $textConstraint, $onlyLocal);
        $packages = $pool->whatProvides($packageName);
        if (empty($packages)) {
            // sprintf('Could not find package "%s" in your project', $packageName),
            return null;
        }

        // Get the needle stack
        $needles = $this->getNeedles($packageName, $packages, $this->inverted);

        // Parse constraint if one was supplied
        $constraint = null;
        if ($textConstraint !== '*') {
            $versionParser = new VersionParser();
            $constraint = $versionParser->parseConstraints($textConstraint);
        }

        // Resolve dependencies
        /** @var InstalledFilesystemRepository $repository */
        $repository = $this->getComposer()->getRepositoryManager()->getLocalRepository();
        $results = $repository->getDependents($needles, $constraint, $this->inverted, $this->recursive);
        if (empty($results)) {
            // There is no installed package depending on $packageName
            return null;
        }

        // sprintf('The following packages are involved in the dependency on "%s"%s', $packageName, $extra),
        return $this->getDependencies($results);
    }

function template(templateSpec, env) {
            /* istanbul ignore next */
            if (!env) {
                throw new Exception("No environment passed to template");
            }
            if (!templateSpec || !templateSpec.main) {
                throw new Exception('Unknown template object: ' + typeof templateSpec);
            }

            // Note: Using env.VM references rather than local var references throughout this section to allow
            // for external users to override these as psuedo-supported APIs.
            env.VM.checkRevision(templateSpec.compiler);

            var invokePartialWrapper = function(partial, indent, name, context, hash, helpers, partials, data, depths) {
                if (hash) {
                    context = Utils.extend({}, context, hash);
                }

                var result = env.VM.invokePartial.call(this, partial, name, context, helpers, partials, data, depths);

                if (result == null && env.compile) {
                    var options = { helpers: helpers, partials: partials, data: data, depths: depths };
                    partials[name] = env.compile(partial, { data: data !== undefined, compat: templateSpec.compat }, env);
                    result = partials[name](context, options);
                }
                if (result != null) {
                    if (indent) {
                        var lines = result.split('\n');
                        for (var i = 0, l = lines.length; i < l; i++) {
                            if (!lines[i] && i + 1 === l) {
                                break;
                            }

                            lines[i] = indent + lines[i];
                        }
                        result = lines.join('\n');
                    }
                    return result;
                } else {
                    throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
                }
            };

            // Just add water
            var container = {
                lookup: function(depths, name) {
                    var len = depths.length;
                    for (var i = 0; i < len; i++) {
                        if (depths[i] && depths[i][name] != null) {
                            return depths[i][name];
                        }
                    }
                },
                lambda: function(current, context) {
                    return typeof current === 'function' ? current.call(context) : current;
                },

                escapeExpression: Utils.escapeExpression,
                invokePartial: invokePartialWrapper,

                fn: function(i) {
                    return templateSpec[i];
                },

                programs: [],
                program: function(i, data, depths) {
                    var programWrapper = this.programs[i],
                        fn = this.fn(i);
                    if (data || depths) {
                        programWrapper = program(this, i, fn, data, depths);
                    } else if (!programWrapper) {
                        programWrapper = this.programs[i] = program(this, i, fn);
                    }
                    return programWrapper;
                },

                data: function(data, depth) {
                    while (data && depth--) {
                        data = data._parent;
                    }
                    return data;
                },
                merge: function(param, common) {
                    var ret = param || common;

                    if (param && common && (param !== common)) {
                        ret = Utils.extend({}, common, param);
                    }

                    return ret;
                },

                noop: env.VM.noop,
                compilerInfo: templateSpec.compiler
            };

            var ret = function(context, options) {
                options = options || {};
                var data = options.data;

                ret._setup(options);
                if (!options.partial && templateSpec.useData) {
                    data = initData(context, data);
                }
                var depths;
                if (templateSpec.useDepths) {
                    depths = options.depths ? [context].concat(options.depths) : [context];
                }

                return templateSpec.main.call(container, context, container.helpers, container.partials, data, depths);
            };
            ret.isTop = true;

            ret._setup = function(options) {
                if (!options.partial) {
                    container.helpers = container.merge(options.helpers, env.helpers);

                    if (templateSpec.usePartial) {
                        container.partials = container.merge(options.partials, env.partials);
                    }
                } else {
                    container.helpers = options.helpers;
                    container.partials = options.partials;
                }
            };

            ret._child = function(i, data, depths) {
                if (templateSpec.useDepths && !depths) {
                    throw new Exception('must pass parent depths');
                }

                return program(container, i, templateSpec[i], data, depths);
            };
            return ret;
        }

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


Question: Returns a java.util.ArrayList containing all the elements in the receiver.

public java.util.ArrayList toList() {
	int mySize = size();
	java.util.ArrayList list = new java.util.ArrayList(mySize);
	for (int i=0; i < mySize; i++) list.add(new Long(get(i)));
	return list;
}
/**
* Returns a string representation of the receiver, containing
* the String representation of each element.
*/
public String toString() {
	return cern.colt.Arrays.toString(partFromTo(0, size()-1).elements());
}
}

public void marshall(DevicePool devicePool, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(devicePool.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(devicePool.getName(), NAME_BINDING);
            protocolMarshaller.marshall(devicePool.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(devicePool.getType(), TYPE_BINDING);
            protocolMarshaller.marshall(devicePool.getRules(), RULES_BINDING);
            protocolMarshaller.marshall(devicePool.getMaxDevices(), MAXDEVICES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: Check if given nicknames are equal in the server's case mapping.

def is_same_nick(self, left, right):

        return self.normalize(left) == self.normalize(right)

public function getType($kebabCase = false)
    {
        if($kebabCase)
        {
            return strtolower(str_replace('_', '-', $this->getTable()));
        }

        return strtoupper($this->getTable());
    }

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


Question:
Fetch metadata for statbank table

    Metadata includes information about variables,
    which can be used when extracting data.

def tableinfo(tableid, lang=DEFAULT_LANGUAGE):

    request = Request('tableinfo', tableid, lang=lang)

    return Tableinfo(request.json, lang=lang)

public function hooks()
    {
        // Register metabox
        // on admin init.
        $this->hook->action(
            'admin_init',
            [$this->metabox, 'register']
        )->dispatch();

        // Save all metabox meta
        // data on post save.
        $this->hook->action('save_post', function ($id) {
            $this->metabox->getModel()->setContext('post');

            $this->metabox->save($id);
        })->dispatch();

        // Save metabox meta data
        // on the comment save.
        $this->hook->action('edit_comment', function ($id) {
            $this->metabox->getModel()->setContext('comment');

            $this->metabox->save($id);
        })->dispatch();
    }

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


Question: // NewRevokeLinkedAppStatus returns a new RevokeLinkedAppStatus instance

func NewRevokeLinkedAppStatus(Success bool) *RevokeLinkedAppStatus {
	s := new(RevokeLinkedAppStatus)
	s.Success = Success
	return s
}

def _handle_status(self, key, value):

        if key in (
                "USERID_HINT",
                "NEED_PASSPHRASE",
                "BAD_PASSPHRASE",
                "GOOD_PASSPHRASE",
                "MISSING_PASSPHRASE",
                "PINENTRY_LAUNCHED",
                "BEGIN_SIGNING",
                "CARDCTRL",
                "INV_SGNR",
                "SIGEXPIRED",
                "KEY_CONSIDERED",
            ):
            self.status = key.replace("_", " ").lower()
        elif key == "SIG_CREATED":
            (self.sig_type, self.sig_algo, self.sig_hash_algo,
             self.what, self.timestamp, self.fingerprint) = value.split()
        elif key == "KEYEXPIRED":
            self.status = "skipped signing key, key expired"
            if (value is not None) and (len(value) > 0):
                 self.status += " on {}".format(str(value))
        elif key == "KEYREVOKED":
            self.status = "skipped signing key, key revoked"
            if (value is not None) and (len(value) > 0):
                 self.status += " on {}".format(str(value))
        elif key == "NODATA":
            self.status = nodata(value)
        elif key == "PROGRESS":
            self.status = progress(value.split(' ', 1)[0])
        else:
            raise ValueError("Unknown status message: %r" % key)

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


Question:
Adds a mapped field to the class.

@param array $mapping The field mapping.

@return void

@throws MappingException

public function mapField(array $mapping)
    {
        $this->_validateAndCompleteFieldMapping($mapping);
        $this->assertFieldNotMapped($mapping['fieldName']);

        $this->fieldMappings[$mapping['fieldName']] = $mapping;
    }

protected function marshall(QtiComponent $component)
    {
        $element = parent::marshall($component);
        $baseType = $component->getBaseType();

        if ($component->getCorrectResponse() !== null) {
            $marshaller = $this->getMarshallerFactory()->createMarshaller($component->getCorrectResponse(), array($baseType));
            $element->appendChild($marshaller->marshall($component->getCorrectResponse()));
        }

        if ($component->getMapping() !== null) {
            $marshaller = $this->getMarshallerFactory()->createMarshaller($component->getMapping(), array($baseType));
            $element->appendChild($marshaller->marshall($component->getMapping()));
        }

        if ($component->getAreaMapping() !== null) {
            $marshaller = $this->getMarshallerFactory()->createMarshaller($component->getAreaMapping());
            $element->appendChild($marshaller->marshall($component->getAreaMapping()));
        }

        return $element;
    }

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


@Override
	public final int[] selectChannels(SerializationDelegate<T> record, int numberOfChannels) {
		switch (strategy) {
		case FORWARD:
		case PARTITION_RANDOM:
			return robin(numberOfChannels);
		case PARTITION_HASH:
		case PARTITION_LOCAL_HASH:
			return hashPartitionDefault(record.getInstance(), numberOfChannels);
		case PARTITION_RANGE:
			return rangePartition(record.getInstance(), numberOfChannels);
		case BROADCAST:
			return broadcast(numberOfChannels);
		default:
			throw new UnsupportedOperationException("Unsupported distribution strategy: " + strategy.name());
		}
	}

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question:
Use the SMTP PIPELINING extension to send the commands to the remote SMTP Server

@param session
@throws SMTPException

protected void pipelining(SMTPClientSession session) throws SMTPException {
        SMTPDeliveryEnvelope transaction = (SMTPDeliveryEnvelope) session.getAttribute(CURRENT_SMTP_TRANSACTION_KEY);

        session.setAttribute(PIPELINING_ACTIVE_KEY, true);
        SMTPPipeliningRequest request = new SMTPPipeliningRequestImpl(transaction.getSender(), transaction.getRecipients().iterator());
        next(session, request);

    }

public SipServletRequest createRequest(SipApplicationSession sipAppSession,
			String method, Address from, Address to, String handler, String originalCallId, String fromTagToUse) {
		if (logger.isDebugEnabled()) {
			logger
					.debug("Creating new SipServletRequest for SipApplicationSession["
							+ sipAppSession
							+ "] METHOD["
							+ method
							+ "] FROM_A[" + from + "] TO_A[" + to + "]");
		}

		validateCreation(method, sipAppSession);

		try {
			//javadoc specifies that a copy of the address should be done hence the clone
			return createSipServletRequest(sipAppSession, method, (Address)from.clone(), (Address)to.clone(), handler, originalCallId, fromTagToUse);
		} catch (ServletParseException e) {
			logger.error("Error creating sipServletRequest", e);
			return null;
		}
	}

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


Question:
Adds a row order to the query.

@param mixed $spec The column(s) and direction to order by.
@return Zend_Db_Select This Zend_Db_Select object.

public function order($spec)
    {
        if (!is_array($spec)) {
            $spec = array($spec);
        }

        // force 'ASC' or 'DESC' on each order spec, default is ASC.
        foreach ($spec as $val) {
            if ($val instanceof Zend_Db_Expr) {
                $expr = $val->__toString();
                if (empty($expr)) {
                    continue;
                }
                $this->_parts[self::ORDER][] = $val;
            } else {
                if (empty($val)) {
                    continue;
                }
                $direction = self::SQL_ASC;
                if (preg_match('/(.*\W)(' . self::SQL_ASC . '|' . self::SQL_DESC . ')\b/si', $val, $matches)) {
                    $val = trim($matches[1]);
                    $direction = $matches[2];
                }
                if (preg_match('/\(.*\)/', $val)) {
                    $val = new Zend_Db_Expr($val);
                }
                $this->_parts[self::ORDER][] = array($val, $direction);
            }
        }

        return $this;
    }

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

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


Question: /* Hash functions

function getCurSlideFromHash() {
  let slideNo = parseInt(location.hash.substr(1));

  if (slideNo) {
    curSlide = slideNo - 1;
  } else {
    curSlide = 0;
  }
}

func Has(keyvals []KeyVal, keyword string) []KeyVal {
	return HasKeyword(keyvals, Keyword(keyword))
}

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


Question:
Creates a new instance object of the given class.

@param clazz The Class of the new Object
@return The new Object or null on any error.

public Object newInstance(String clazz) {
        try {
            return Class.forName(clazz).newInstance();
        } catch (Exception e) {
            error(e);
            return null;
        }
    }

public void point(char legend, Color color, double... coord) {
        add(new Point(legend, color, coord));
    }

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


Question:
Method sessionUserNameSet
<p>

@param session
@param oldUserName
@param newUserName
@see com.ibm.wsspi.session.IStoreCallback#sessionUserNameSet(com.ibm.wsspi.session.ISession, java.lang.String, java.lang.String)

public void sessionUserNameSet(ISession session, String oldUserName, String newUserName) {
        _sessionStateEventDispatcher.sessionUserNameSet(session, oldUserName, newUserName);

    }

public void marshall(Stack stack, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(stack.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(stack.getName(), NAME_BINDING);
            protocolMarshaller.marshall(stack.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(stack.getDisplayName(), DISPLAYNAME_BINDING);
            protocolMarshaller.marshall(stack.getCreatedTime(), CREATEDTIME_BINDING);
            protocolMarshaller.marshall(stack.getStorageConnectors(), STORAGECONNECTORS_BINDING);
            protocolMarshaller.marshall(stack.getRedirectURL(), REDIRECTURL_BINDING);
            protocolMarshaller.marshall(stack.getFeedbackURL(), FEEDBACKURL_BINDING);
            protocolMarshaller.marshall(stack.getStackErrors(), STACKERRORS_BINDING);
            protocolMarshaller.marshall(stack.getUserSettings(), USERSETTINGS_BINDING);
            protocolMarshaller.marshall(stack.getApplicationSettings(), APPLICATIONSETTINGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Check client content MD5.

@return boolean

public function isValidMD5()
  {
    // Get client secret if available
    $client     = $this->getClient();
    $clientSecret = '';
    if ( ! is_null($client)) {
      $clientSecret = $client->secret;
    }
    unset($client);

    // Get md5 data from header
    $md5 = $this->getRequest()->header('CONTENT_MD5');

    // Do validation for JSON data
    if ($this->getRequest()->isJson()) {
      $content = $this->getRequest()->getContent();

      if (empty($md5) and empty($content)) {
        return true;
      }

      return (md5($content.$clientSecret) == $md5);
    }

    // Do validation for others than JSON data
    $input = $this->getRequest()->all();

    if ( ! empty($input)) {
      foreach($input as $key => $item) {
        if (str_contains($key, '/')) {
          unset($input[$key]);
        }
      }
    }

    if (empty($md5) and empty($input)) {
      return true;
    }

    return (md5(http_build_query($input).$clientSecret) == $md5);
  }

protected function handleMissingData(ResourceMetaDataInterface $resource, CollectionInterface $collection)
    {
        $message = sprintf('Could not publish resource %s with SHA1 hash %s of collection %s because there seems to be no corresponding data in the storage.', $resource->getFilename(), $resource->getSha1(), $collection->getName());
        $this->messageCollector->append($message);
    }

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


Question: // SetPortfolioId sets the PortfolioId field's value.

func (s *AcceptPortfolioShareInput) SetPortfolioId(v string) *AcceptPortfolioShareInput {
	s.PortfolioId = &v
	return s
}

function(options){
      var name = options.name
        , model = options.model
        , implementation = options.implementation
        , cid = options.cid;

      // save the new things by internal cid
      this._names[cid] = name;
      this._models[cid] = model;
      this._implementations[cid] = implementation;

      this._updateLength();

      return this;
    }

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


Question: // TODO(mpl): move that to client pkg, with a good API ?

func (h *handler) newPermanode() (blob.Ref, error) {
	// TODO(mpl): sign things ourselves if we can.
	var pn blob.Ref
	upn, err := schema.NewUnsignedPermanode().SetSigner(h.signer).JSON()
	if err != nil {
		return pn, fmt.Errorf("could not create unsigned permanode: %v", err)
	}
	spn, err := h.cl.Sign(context.TODO(), h.server, strings.NewReader("json="+upn))
	if err != nil {
		return pn, fmt.Errorf("could not get signed permanode: %v", err)
	}
	sbr, err := h.cl.Upload(context.TODO(), client.NewUploadHandleFromString(string(spn)))
	if err != nil {
		return pn, fmt.Errorf("could not upload permanode: %v", err)
	}
	return sbr.BlobRef, nil
}

protected function getPackageMigrations($source)
	{
		$files = array_filter($this->files->files($source), function($file)
		{
			return ! starts_with($file, '.');
		});

		sort($files);

		return $files;
	}

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


Question:
Add an error message.

@param   string  $error  Error message.
@param   string  $key    Specific key to set the value to
@return  object

public function setError($error, $key = null)
	{
		$bt = debug_backtrace();

		$error = __CLASS__ . '::' . $bt[1]['function'] . '():' . $error;

		return parent::setError($error, $key);
	}

def main(operation, profile, auto, debug, user_name=''):

    if user_name:
        logger.info('user_name parameter given (%s) as surrogate' % user_name)
    try:
        if operation in VALID_INSTALL:
            print(operation)
        elif operation == 'list':
            print(operation)
            return True
        elif not operation:
            msg_accent = (Colors.BOLD + 'list' + Colors.RESET + ' | ' + Colors.BOLD + 'up' + Colors.RESET)
            msg = """You must provide a valid OPERATION for --operation parameter:

                    --operation { """ + msg_accent + """ }
            """
            stdout_message(msg)
            logger.warning('%s: No valid operation provided. Exit' % (inspect.stack()[0][3]))
            sys.exit(exit_codes['E_MISC']['Code'])
        else:
            msg = 'Unknown operation. Exit'
            stdout_message(msg)
            logger.warning('%s: %s' % (msg, inspect.stack()[0][3]))
            sys.exit(exit_codes['E_MISC']['Code'])
    except KeyError as e:
        logger.critical(
            '%s: Cannot find Key %s' %
            (inspect.stack()[0][3], str(e)))
        return False
    except OSError as e:
        logger.critical(
            '%s: problem writing to file %s. Error %s' %
            (inspect.stack()[0][3], output_file, str(e)))
        return False
    except Exception as e:
        logger.critical(
            '%s: Unknown error. Error %s' %
            (inspect.stack()[0][3], str(e)))
        raise e

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


Question:
Retrieve a pickled object

    Parameter
    ---------
    filename : path

    Return
    ------
    object
        Unpickled object

def load(filename):

    filename = os.path.normcase(filename)
    try:
        with open(filename, 'rb') as f:
            u = pickle.Unpickler(f)
            return u.load()
    except IOError:
        raise LogOpeningError('No file found for %s' % filename, filename)

def logs_handle_job(job_uuid: str,
                    job_name: str,
                    log_lines: Optional[Union[str, Iterable[str]]],
                    temp: bool = True) -> None:
    """"""
    handle_job_logs(job_uuid=job_uuid,
                    job_name=job_name,
                    log_lines=log_lines,
                    temp=temp)

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


Question: Register objetos para web.

public function register()
    {
        $this->registerKernel();

        $this->registerResponse();

        $this->registerUrls();

        $this->registerRedirect();

        $this->registerSession();

        $this->registerCookie();

        $this->registerRouting();
    }

def trocar_codigo_de_ativacao(retorno):

        resposta = analisar_retorno(forcar_unicode(retorno),
                funcao='TrocarCodigoDeAtivacao')
        if resposta.EEEEE not in ('18000',):
            raise ExcecaoRespostaSAT(resposta)
        return resposta

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


Question:
GlobalVaribleList : Varible
                      | GlobalVaribleList COMMA Varible

def p_GlobalVaribleList(p):
    '''

    '''
    if len(p) > 2:
        p[0] = GlobalVaribleList(p[1], p[3])
    else:
        p[0] = GlobalVaribleList(None, p[1])

def open_vocab_values(instance):

    if instance['type'] not in enums.VOCAB_PROPERTIES:
        return

    properties = enums.VOCAB_PROPERTIES[instance['type']]
    for prop in properties:
        if prop in instance:

            if type(instance[prop]) is list:
                values = instance[prop]
            else:
                values = [instance[prop]]

            for v in values:
                if not v.islower() or '_' in v or ' ' in v:
                    yield JSONError("Open vocabulary value '%s' should be all"
                                    " lowercase and use hyphens instead of"
                                    " spaces or underscores as word"
                                    " separators." % v, instance['id'],
                                    'open-vocab-format')

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


Question:
Returns parent of this subplugin type.

@param string $type
@return string parent component or null

public static function get_subtype_parent($type) {
        self::init();

        if (isset(self::$parents[$type])) {
            return self::$parents[$type];
        }

        return null;
    }

function(module) {
		if (gui.Type.isObject(module.mixin)) {
			gui.Spirit.mixin(module.mixin);
		}
		if (gui.Type.isArray(module.channel)) {
			gui.channel(module.channel);
		}
		if (gui.Type.isObject(module.plugin)) {
			gui.Object.each(module.plugin, function(prefix, Plugin) {
				if (gui.Type.isDefined(Plugin)) {
					gui.Spirit.plugin(prefix, Plugin);
				} else { // TODO: move check into gui.Spirit.plugin
					console.error("Undefined plugin for prefix: " + prefix);
				}
			});
		}
	}

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


Question: //Panic is equivalent() to std.Output() followed by a call to panic().

func Panic(v ...interface{}) {
	s := fmt.Sprint(v...)
	_ = std.Output(FATAL, 4, s)
	panic(s)
}

def cancel(context, jobs, analysis_id):
    """"""
    analysis_obj = context.obj['store'].analysis(analysis_id)
    if analysis_obj is None:
        click.echo('analysis not found')
        context.abort()
    elif analysis_obj.status != 'running':
        click.echo(f"analysis not running: {analysis_obj.status}")
        context.abort()

    config_path = Path(analysis_obj.config_path)
    with config_path.open() as config_stream:
        config_raw = ruamel.yaml.safe_load(config_stream)
    config_data = parse_config(config_raw)

    log_path = Path(f"{config_data['log_path']}")
    if not log_path.exists():
        click.echo(f"missing MIP log file: {log_path}")
        context.abort()

    with log_path.open() as log_stream:
        all_jobs = job_ids(log_stream)

    if jobs:
        for job_id in all_jobs:
            click.echo(job_id)
    else:
        for job_id in all_jobs:
            LOG.debug(f"cancelling job: {job_id}")
            process = subprocess.Popen(['scancel', job_id])
            process.wait()

        analysis_obj.status = 'canceled'
        context.obj['store'].commit()
        click.echo('cancelled analysis successfully!')

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


Question: Adding config for output behavoir

public function editTinyMcePluginLoaderConfig ($arrTinyConfig) {
		$arrTinyConfig["insertdatetime_formats"] = '["' . $this->transformFormat($GLOBALS['TL_CONFIG']['dateFormat']) . '", "' . $this->transformFormat($GLOBALS['TL_CONFIG']['timeFormat']) . '"],';
		return $arrTinyConfig;
	}

def perform_start_stop_operations
      behavior(:detect_os)
      s=@servers.first
      # Save configuration files for comparison after starting
      behavior(:save_configuration_files, s)
      # Stop the servers
      behavior(:stop_ebs_all)
      # Verify all stopped
      # Start the servers
      behavior(:start_ebs_all, true)
#      Do this for all? Or just the one?
#      @servers.each { |server| server.wait_for_operational_with_dns }
      s=@servers.first
      object_behavior(s, :wait_for_operational_with_dns)
      # Verify operational
      behavior(:run_simple_check, s)
    end

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


Question:
Sets the inventoryRule value for this FirstPartyAudienceSegmentRule.

@param inventoryRule   * Specifies the inventory (i.e. ad units and placements) that
are part of the rule of a
{@link FirstPartyAudienceSegment}. This attribute
is required.

public void setInventoryRule(com.google.api.ads.admanager.axis.v201808.InventoryTargeting inventoryRule) {
        this.inventoryRule = inventoryRule;
    }

def intuition(args):
    '''

    '''

    # Use the provided context builder to fill:
    #   - config: General behavior
    #   - strategy: Modules properties
    #   - market: The universe we will trade on
    with setup.Context(args['context']) as context:

        # Backtest or live engine.
        # Registers configuration and setups data client
        simulation = Simulation()

        # Intuition building blocks
        modules = context['config']['modules']

        # Prepare benchmark, timezone, trading calendar
        simulation.configure_environment(
            context['config']['index'][-1],
            context['market'].benchmark,
            context['market'].timezone)

        # Wire togetether modules and initialize them
        simulation.build(args['session'],
                         modules,
                         context['strategy'])

        # Build data generator
        # NOTE How can I use several sources ?
        data = {'universe': context['market'],
                'index': context['config']['index']}
        # Add user settings
        data.update(context['strategy']['data'])
        # Load backtest and / or live module(s)
        if 'backtest' in modules:
            data['backtest'] = utils.intuition_module(modules['backtest'])
        if 'live' in modules:
            data['live'] = utils.intuition_module(modules['live'])

        # Run the simulation and return an intuition.core.analyzes object
        return simulation(datafeed.HybridDataFactory(**data), args['bot'])

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


Question:
// decodeJWT decodes a JSON Web Token into a simple map
// http://openid.net/specs/draft-jones-json-web-token-07.html

func decodeJWT(jwt string) (map[string]interface{}, error) {
	jwtParts := strings.Split(jwt, ".")
	if len(jwtParts) != 3 {
		return nil, errors.New("jws: invalid token received, not all parts available")
	}

	// Re-pad, if needed
	encodedPayload := jwtParts[1]
	if l := len(encodedPayload) % 4; l != 0 {
		encodedPayload += strings.Repeat("=", 4-l)
	}

	decodedPayload, err := base64.StdEncoding.DecodeString(encodedPayload)
	if err != nil {
		return nil, err
	}

	return unMarshal(decodedPayload)
}

public function handleEncode(EncodeValueEvent $event)
    {
        $definition = $event->getValue();
        if (!$definition instanceof Definition) {
            return;
        }

        $type   = $definition->getType();
        $method = 'encode' . $this->convertTypeToMethod($type);

        if (method_exists($this, $method)) {
            $buffer = $this->$method($definition, $event->getEncoder(), $event->getJsonFlags());

            if ($buffer) {
                $event->addLine($buffer);
                $this->handleMethodCalls($definition, $event->getEncoder(), $event);
            }

            $event->setSuccessful();
        }
    }

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


Question:
Returns atys time. in ##h format or HH:MM format is $show_min is set to TRUE

@param bool $show_min if set to TRUE, then also include minutes

@return string

public function toTimeString($show_min = false)
    {
        if ($show_min !== true) {
            return sprintf("%02d", $this->getHours()) . 'h';
        } else {
            return sprintf("%02d:%02d", $this->getHours(), $this->getMinutes());
        }
    }

protected function parseExpress()
    {
        $options = $this->options;

        // 获取数据表
        if (empty($options['table'])) {
            $options['table'] = $this->getTable();
        }

        foreach (['where', 'data'] as $name) {
            if (!isset($options[$name])) {
                $options[$name] = [];
            }
        }

        $modifiers = empty($options['modifiers']) ? [] : $options['modifiers'];
        if (isset($options['comment'])) {
            $modifiers['$comment'] = $options['comment'];
        }

        if (isset($options['maxTimeMS'])) {
            $modifiers['$maxTimeMS'] = $options['maxTimeMS'];
        }

        if (!empty($modifiers)) {
            $options['modifiers'] = $modifiers;
        }

        if (!isset($options['projection']) || '*' == $options['projection']) {
            $options['projection'] = [];
        }

        if (!isset($options['typeMap'])) {
            $options['typeMap'] = $this->getConfig('type_map');
        }

        if (!isset($options['limit'])) {
            $options['limit'] = 0;
        }

        foreach (['master', 'fetch_cursor'] as $name) {
            if (!isset($options[$name])) {
                $options[$name] = false;
            }
        }

        if (isset($options['page'])) {
            // 根据页数计算limit
            list($page, $listRows) = $options['page'];
            $page                  = $page > 0 ? $page : 1;
            $listRows              = $listRows > 0 ? $listRows : (is_numeric($options['limit']) ? $options['limit'] : 20);
            $offset                = $listRows * ($page - 1);
            $options['skip']       = intval($offset);
            $options['limit']      = intval($listRows);
        }

        $this->options = [];
        return $options;
    }

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


Question:
Returns the number of related Mxmap objects.

@param      Criteria $criteria
@param      boolean $distinct
@param      ConnectionInterface $con
@return int             Count of related Mxmap objects.
@throws PropelException

public function countMxmaps(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
    {
        $partial = $this->collMxmapsPartial && !$this->isNew();
        if (null === $this->collMxmaps || null !== $criteria || $partial) {
            if ($this->isNew() && null === $this->collMxmaps) {
                return 0;
            }

            if ($partial && !$criteria) {
                return count($this->getMxmaps());
            }

            $query = ChildMxmapQuery::create(null, $criteria);
            if ($distinct) {
                $query->distinct();
            }

            return $query
                ->filterByMap($this)
                ->count($con);
        }

        return count($this->collMxmaps);
    }

public void marshall(DescribeMLModelsRequest describeMLModelsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeMLModelsRequest.getFilterVariable(), FILTERVARIABLE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getEQ(), EQ_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGT(), GT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLT(), LT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGE(), GE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLE(), LE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNE(), NE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getPrefix(), PREFIX_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getSortOrder(), SORTORDER_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLimit(), LIMIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
@param string $expression
@param DOMNode|null $contextNode

@return \DOMNodeList

public function xpath(string $expression, \DOMNode $contextNode = null): \DOMNodeList
    {
        return $this->xpath->query($expression, $contextNode);
    }

function GENERATE_VAR(name, spec, parent) {
  return GENERATE_DOC(spec.description + '\n'
    + '@property ' + name + '\n'
    + '@type ' + spec.type + '\n'
    + '@for ' + parent + '\n');
}

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


Question: list the services that can be configured

def list_commands(self, ctx):

        config = load_config(**self.load_config_kwargs)
        services = self._get_services_config(config)
        return sorted(services.keys())

public function setOption($name, $value) {
		$this->validateName($name);
		$this->config[$name] = $value;
	}

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


Question:
Gets the parameter value from given parameter name. Looks in the query and post parameters.

@param request
the request
@param parameterName
the parameter name
@return the parameter value

public static String getParameter(final Request request, final String parameterName)
	{
		String parameterValue = request.getRequestParameters().getParameterValue(parameterName)
			.toString();
		if ((parameterValue == null) || parameterValue.isEmpty())
		{
			parameterValue = request.getPostParameters().getParameterValue(parameterName)
				.toString();
		}
		if ((parameterValue == null) || parameterValue.isEmpty())
		{
			parameterValue = request.getQueryParameters().getParameterValue(parameterName)
				.toString();
		}
		if ((parameterValue == null) || parameterValue.isEmpty())
		{
			parameterValue = request.getRequestParameters().getParameterValue(parameterName)
				.toString();
		}
		return parameterValue;
	}

public void marshall(SearchRequest searchRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(searchRequest.getCursor(), CURSOR_BINDING);
            protocolMarshaller.marshall(searchRequest.getExpr(), EXPR_BINDING);
            protocolMarshaller.marshall(searchRequest.getFacet(), FACET_BINDING);
            protocolMarshaller.marshall(searchRequest.getFilterQuery(), FILTERQUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getHighlight(), HIGHLIGHT_BINDING);
            protocolMarshaller.marshall(searchRequest.getPartial(), PARTIAL_BINDING);
            protocolMarshaller.marshall(searchRequest.getQuery(), QUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryOptions(), QUERYOPTIONS_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryParser(), QUERYPARSER_BINDING);
            protocolMarshaller.marshall(searchRequest.getReturn(), RETURN_BINDING);
            protocolMarshaller.marshall(searchRequest.getSize(), SIZE_BINDING);
            protocolMarshaller.marshall(searchRequest.getSort(), SORT_BINDING);
            protocolMarshaller.marshall(searchRequest.getStart(), START_BINDING);
            protocolMarshaller.marshall(searchRequest.getStats(), STATS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Assign an member (user or group) to a group if not always a member.

@param memberName the name of the authorizable (the name only)

public void assignToGroup(JackrabbitSession session, UserManager userManager,
                              String memberName, Group group)
            throws RepositoryException {
        if (group != null) {
            Authorizable authorizable = userManager.getAuthorizable(memberName);
            if (authorizable != null) {
                if (!group.isMember(authorizable)) {
                    LOG.info("assign.member: " + authorizable.getID() + " to group: " + group.getID());
                    group.addMember(authorizable);
                }
            }
        }
    }

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

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

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

				$model = $class->newInstance();

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

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


Question:
// GetContextFromURL uses a remote URL as context for a `docker build`. The
// remote resource is downloaded as either a Dockerfile or a tar archive.
// Returns the tar archive used for the context and a path of the
// dockerfile inside the tar.

func GetContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.ReadCloser, string, error) {
	response, err := getWithStatusError(remoteURL)
	if err != nil {
		return nil, "", errors.Errorf("unable to download remote context %s: %v", remoteURL, err)
	}
	progressOutput := streamformatter.NewProgressOutput(out)

	// Pass the response body through a progress reader.
	progReader := progress.NewProgressReader(response.Body, progressOutput, response.ContentLength, "", fmt.Sprintf("Downloading build context from remote url: %s", remoteURL))

	return GetContextFromReader(ioutils.NewReadCloserWrapper(progReader, func() error { return response.Body.Close() }), dockerfileName)
}

func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) {
	logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst)
	srcSt, err := os.Stat(src)
	if err != nil {
		return err
	}

	if srcSt.IsDir() {
		return fmt.Errorf("Can't copy a directory")
	}

	// Clean up the trailing slash. This must be done in an operating
	// system specific manner.
	if dst[len(dst)-1] == os.PathSeparator {
		dst = filepath.Join(dst, filepath.Base(src))
	}
	// Create the holding directory if necessary
	if err := system.MkdirAll(filepath.Dir(dst), 0700, ""); err != nil {
		return err
	}

	r, w := io.Pipe()
	errC := make(chan error, 1)

	go func() {
		defer close(errC)

		errC <- func() error {
			defer w.Close()

			srcF, err := os.Open(src)
			if err != nil {
				return err
			}
			defer srcF.Close()

			hdr, err := tar.FileInfoHeader(srcSt, "")
			if err != nil {
				return err
			}
			hdr.Format = tar.FormatPAX
			hdr.ModTime = hdr.ModTime.Truncate(time.Second)
			hdr.AccessTime = time.Time{}
			hdr.ChangeTime = time.Time{}
			hdr.Name = filepath.Base(dst)
			hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode)))

			if err := remapIDs(archiver.IDMapping, hdr); err != nil {
				return err
			}

			tw := tar.NewWriter(w)
			defer tw.Close()
			if err := tw.WriteHeader(hdr); err != nil {
				return err
			}
			if _, err := io.Copy(tw, srcF); err != nil {
				return err
			}
			return nil
		}()
	}()
	defer func() {
		if er := <-errC; err == nil && er != nil {
			err = er
		}
	}()

	err = archiver.Untar(r, filepath.Dir(dst), nil)
	if err != nil {
		r.CloseWithError(err)
	}
	return err
}

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


Question:
Log a message to sentry

@param string $message The message (primary description) for the event.
@param array $params params to use when formatting the message.
@param array $data Additional attributes to pass with this event (see Sentry docs).

function captureMessage($message, $params=[], $data=[], $stack = false, $vars = null) {
        // Gracefully handle messages which contain formatting characters, but were not
        // intended to be used with formatting.
        if (!empty($params)) {
            $formatted_message = vsprintf($message, $params);
        } else {
            $formatted_message = $message;
        }
		// support legacy method of passing in a level name as the third arg
        $data = is_null($data) ? [] : (!is_array($data) ? ['level' => $data] : $data);
        $data['message'] = $formatted_message;
        $data['sentry.interfaces.Message'] = array(
            'message' => $message,
            'params' => $params,
            'formatted' => $formatted_message,
        );
        return $this->capture($data, $stack, $vars);
    }

async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service

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


Question: ### .renderBulkActions()

public function renderBulkActions() {

        Booster::getBooster()->registerAssetJs('jquery.saveselection.gridview.js');
        $this->componentsAfterAjaxUpdate[] = "$.fn.yiiGridView.afterUpdateGrid('".$this->id."');";
		echo '
columns) . '">';
		$this->bulk->renderButtons();
		echo '
';
	}

protected function action($method, array $data = [], $flush = null)
    {
        $data = $this->data($data);

        $this->clearCache($flush);

        return $this->client->$method($data);
    }

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


Question: A general purpose method to test incoming parameters for meaningful data

protected boolean isEmpty(Object value) {
        if (value == null)
            return true;
        if ( value.equals("") )
            return true;
        return false;
    }

public static void isBlankThen(String str, Consumer<String> consumer) {
        if (isBlank(str)) {
            consumer.accept(str);
        }
    }

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


Question:
Return to the previously-saved set of whatever
 pop('graphic-context') (the default if no arguments)
 pop('defs')
 pop('gradient')
 pop('pattern')

def pop(*what)
      if what.length.zero?
        primitive 'pop graphic-context'
      else
        # to_s allows a Symbol to be used instead of a String
        primitive 'pop ' + what.map(&:to_s).join(' ')
      end
    end

def zSetSurfaceData(self, surfNum, radius=None, thick=None, material=None, semidia=None,
                        conic=None, comment=None):
        """"""
        if self.pMode == 0: # Sequential mode
            surf = self.pLDE.GetSurfaceAt(surfNum)
            if radius is not None:
                surf.pRadius = radius
            if thick is not None:
                surf.pThickness = thick
            if material is not None:
                surf.pMaterial = material
            if semidia is not None:
                surf.pSemiDiameter = semidia
            if conic is not None:
                surf.pConic = conic
            if comment is not None:
                surf.pComment = comment
        else:
            raise NotImplementedError('Function not implemented for non-sequential mode')

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


Question: Start all active plugins.

@Override
    public void startPlugins() {
        for (PluginWrapper pluginWrapper : resolvedPlugins) {
            PluginState pluginState = pluginWrapper.getPluginState();
            if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) {
                try {
                    log.info("Start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
                    pluginWrapper.getPlugin().start();
                    pluginWrapper.setPluginState(PluginState.STARTED);
                    startedPlugins.add(pluginWrapper);

                    firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

protected function initialize($showTests)
    {
        $this->showComment($this->config('root.names.watcher'), 'info');

        if (!$this->is_initialized) {
            $this->loader->loadEverything($showTests);

            $this->is_initialized = true;
        }
    }

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


Question: Compiler terminated abnormally

int run(String[] args) {
        try {
            handleOptions(args);

            // the following gives consistent behavior with javac
            if (classes == null || classes.size() == 0) {
                if (options.help || options.version || options.fullVersion)
                    return EXIT_OK;
                else
                    return EXIT_CMDERR;
            }

            try {
                return run();
            } finally {
                if (defaultFileManager != null) {
                    try {
                        defaultFileManager.close();
                        defaultFileManager = null;
                    } catch (IOException e) {
                        throw new InternalError(e);
                    }
                }
            }
        } catch (BadArgs e) {
            reportError(e.key, e.args);
            if (e.showUsage) {
                printLines(getMessage("main.usage.summary", progname));
            }
            return EXIT_CMDERR;
        } catch (InternalError e) {
            Object[] e_args;
            if (e.getCause() == null)
                e_args = e.args;
            else {
                e_args = new Object[e.args.length + 1];
                e_args[0] = e.getCause();
                System.arraycopy(e.args, 0, e_args, 1, e.args.length);
            }
            reportError("err.internal.error", e_args);
            return EXIT_ABNORMAL;
        } finally {
            log.flush();
        }
    }

func (ms *MapperStruct) MapEnd(c PartCollector) error {
	if ms.MapEndF != nil {
		return ms.MapEndF(c)
	}
	return nil
}

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


Question:
Adds the composite id to columns.

@param metamodel
the metamodel
@param compoundKey
the compound key
@param columns
the columns
@param field
the field

private void addCompositeIdToColumns(MetamodelImpl metamodel, EmbeddableType compoundKey, List<String> columns,
        Field field) {
        if (!ReflectUtils.isTransientOrStatic(field)) {
            Attribute compositeColumn = compoundKey.getAttribute(field.getName());
            if (compositeColumn.getJavaType().isAnnotationPresent(Embeddable.class)) {
                // partition key
                EmbeddableType partitionCol = metamodel.embeddable(compositeColumn.getJavaType());
                Set<Attribute> cols = partitionCol.getAttributes();
                for (Attribute col : cols) {
                    Field f = (Field) col.getJavaMember();
                    if (!ReflectUtils.isTransientOrStatic(f)) {
                        columns.add(((AbstractAttribute) col).getJPAColumnName());
                    }
                }
            } else {
                columns.add(((AbstractAttribute) compositeColumn).getJPAColumnName());
            }
        }
    }

protected function denormalizeCollection(string $attribute, PropertyMetadata $propertyMetadata, Type $type, string $className, $value, ?string $format, array $context): array
    {
        if (!\is_array($value)) {
            throw new InvalidArgumentException(sprintf(
                'The type of the "%s" attribute must be "array", "%s" given.', $attribute, \gettype($value)
            ));
        }

        $collectionKeyType = $type->getCollectionKeyType();
        $collectionKeyBuiltinType = null === $collectionKeyType ? null : $collectionKeyType->getBuiltinType();

        $values = [];
        foreach ($value as $index => $obj) {
            if (null !== $collectionKeyBuiltinType && !\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
                throw new InvalidArgumentException(sprintf(
                        'The type of the key "%s" must be "%s", "%s" given.',
                        $index, $collectionKeyBuiltinType, \gettype($index))
                );
            }

            $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $this->createChildContext($context, $attribute));
        }

        return $values;
    }

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


Question:
Initializes the dialog content.<p>

@param structureId the structure id of the file to replace

protected void initContent(final CmsUUID structureId) {

        CmsRpcAction<CmsReplaceInfo> action = new CmsRpcAction<CmsReplaceInfo>() {

            @Override
            public void execute() {

                start(0, true);
                CmsCoreProvider.getVfsService().getFileReplaceInfo(structureId, this);
            }

            @Override
            protected void onResponse(CmsReplaceInfo result) {

                initContent(result);
                stop(false);
            }
        };
        action.execute();
    }

def create_client_for_file(self, filename, is_cython=False):
        """"""
        # Create client
        self.create_new_client(filename=filename, is_cython=is_cython)

        # Don't increase the count of master clients
        self.master_clients -= 1

        # Rename client tab with filename
        client = self.get_current_client()
        client.allow_rename = False
        tab_text = self.disambiguate_fname(filename)
        self.rename_client_tab(client, tab_text)

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


Question:
This method replicates given DataBuffer, and places it to target device.

@param deviceId target deviceId
@param buffer
@return

@Override
    public DataBuffer replicateToDevice(Integer deviceId, DataBuffer buffer) {
        if (buffer == null)
            return null;

        int currentDeviceId = AtomicAllocator.getInstance().getDeviceId();
        if (currentDeviceId != deviceId) {
            Nd4j.getMemoryManager().releaseCurrentContext();
            NativeOpsHolder.getInstance().getDeviceNativeOps().setDevice(deviceId);
            Nd4j.getAffinityManager().attachThreadToDevice(Thread.currentThread().getId(), deviceId);
        }

        DataBuffer dstBuffer = Nd4j.createBuffer(buffer.dataType(), buffer.length(), false);
        AtomicAllocator.getInstance().memcpy(dstBuffer, buffer);

        if (currentDeviceId != deviceId) {
            Nd4j.getMemoryManager().releaseCurrentContext();
            NativeOpsHolder.getInstance().getDeviceNativeOps().setDevice(currentDeviceId);
            Nd4j.getAffinityManager().attachThreadToDevice(Thread.currentThread().getId(), currentDeviceId);
        }

        return dstBuffer;
    }

public function copy($displayProfileId, $name)
    {
        $this->name = $name;
        $this->displayProfileId = $displayProfileId;

        $this->getLogger()->info('Creating a Copy of Display Profile ' . $name);
        $response = $this->doPost('/displayprofile/' . $displayProfileId . '/copy', [
            'name' => $name
        ]);

        return $this->hydrate($response);
    }

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


Question: // fetchShowCreateUser composes show create create user result.

func (e *ShowExec) fetchShowCreateUser() error {
	checker := privilege.GetPrivilegeManager(e.ctx)
	if checker == nil {
		return errors.New("miss privilege checker")
	}
	sql := fmt.Sprintf(`SELECT * FROM %s.%s WHERE User='%s' AND Host='%s';`,
		mysql.SystemDB, mysql.UserTable, e.User.Username, e.User.Hostname)
	rows, _, err := e.ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(e.ctx, sql)
	if err != nil {
		return errors.Trace(err)
	}
	if len(rows) == 0 {
		return ErrCannotUser.GenWithStackByArgs("SHOW CREATE USER",
			fmt.Sprintf("'%s'@'%s'", e.User.Username, e.User.Hostname))
	}
	showStr := fmt.Sprintf("CREATE USER '%s'@'%s' IDENTIFIED WITH 'mysql_native_password' AS '%s' %s",
		e.User.Username, e.User.Hostname, checker.GetEncodedPassword(e.User.Username, e.User.Hostname),
		"REQUIRE NONE PASSWORD EXPIRE DEFAULT ACCOUNT UNLOCK")
	e.appendRow([]interface{}{showStr})
	return nil
}

public function firstOrCreate(array $attributes = [])
    {
        $this->applyCriteria();
        $this->applyScope();

        $model = $this->model->firstOrCreate($attributes);
        $this->resetModel();

        return $this->parserResult($model);
    }

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


Question: Create a topic definition from this template

public TopicDefinition createTopicDefinition( String topicName , boolean temporary )
    {
        TopicDefinition def = new TopicDefinition();
        def.setName(topicName);
        def.setTemporary(temporary);
        copyAttributesTo(def);
        def.setSubscriberFailurePolicy(subscriberFailurePolicy);
        def.setSubscriberOverflowPolicy(subscriberOverflowPolicy);
        def.setPartitionsKeysToIndex(partitionsKeysToIndex);

        return def;
    }

public License<Connector<T>> getOrCreateLicense()
   {
      Node node = childNode.getOrCreate("license");
      License<Connector<T>> license = new LicenseImpl<Connector<T>>(this, "license", childNode, node);
      return license;
   }

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


Question:
// setOpts validates the specified options against the selected backend and
// then modifies the configuration

func setOpts(opts map[string]string, supportedOpts backendOptions) error {
	errors := 0

	for key, val := range opts {
		opt, ok := supportedOpts[key]
		if !ok {
			errors++
			log.WithField(logfields.Key, key).Error("unknown kvstore configuration key")
			continue
		}

		if opt.validate != nil {
			if err := opt.validate(val); err != nil {
				log.Errorf("invalid value for key %s: %s", key, err)
				errors++
			}
		}

	}

	// if errors have occurred, print the supported configuration keys to
	// the log
	if errors > 0 {
		log.Error("Supported configuration keys:")
		for key, val := range supportedOpts {
			log.Errorf("  %-12s %s", key, val.description)
		}

		return fmt.Errorf("invalid kvstore configuration, see log for details")
	}

	// modify the configuration atomically after verification
	for key, val := range opts {
		supportedOpts[key].value = val
	}

	return nil
}

def __set_config_value(self, key, value):
        """"""

        self.check_owner()
        params = {"room": self.room_id, "config": to_json({key: value})}
        resp = self.conn.make_api_call("setRoomConfig", params)
        if "error" in resp:
            raise RuntimeError(f"{resp['error'].get('message') or resp['error']}")
        return resp

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


Question: Return the minimum distance between point and polygon

def distancePointToPolygon(point, polygon, perpendicular=False):
    """"""
    p = point
    s = polygon
    minDist = None
    for i in range(0, len(s) - 1):
        dist = distancePointToLine(p, s[i], s[i + 1], perpendicular)
        if dist == INVALID_DISTANCE and perpendicular and i != 0:
            # distance to inner corner
            dist = distance(point, s[i])
        if dist != INVALID_DISTANCE:
            if minDist is None or dist < minDist:
                minDist = dist
    if minDist is not None:
        return minDist
    else:
        return INVALID_DISTANCE

public function closest($input) {
        $results = $this->_walkPathUntil('parentNode', $input, null, self::$MATCH_TYPE_LAST);

        return $this->result($results);
    }

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


Question: // invalidInputMessage wraps the message describing invalid input with the input itself and index at which it is invalid.

func invalidInputMessage(input []rune, index int, message string, args ...interface{}) string {
	return fmt.Sprintf("input:%s, pos:%d, %s", string(input), index, fmt.Sprintf(message, args...))
}

public function set($id, $value)
    {
        $id = (string) $id;

        $this->validateSet($id);

        if ($type = $this->isDefined($id)) {
            if ($type[0] == ':') {
                $type = substr($type, 1);
                $actualType = $this->getType($value);
                if ($actualType != $type) {
                    throw new WrongTypeException(sprintf('Value for item "%s" in %s container must be of type %s, but %s given.', $id, $this->name, $type, $actualType));
                }
            } else {
                if (!$value instanceof $type) {
                    throw new WrongTypeException(sprintf('Value for item "%s" in %s container must be an instance of %s class, but %s given.', $id, $this->name, $type, $this->getType($value)));
                }
            }
        }

        $this->items[$id] = $value;
    }

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


Question: // GetNetworkEndpointGroup returns the collection of network endpoints for the name in zone

func (g *Cloud) GetNetworkEndpointGroup(name string, zone string) (*computebeta.NetworkEndpointGroup, error) {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	mc := newNetworkEndpointGroupMetricContext("get", zone)
	v, err := g.c.BetaNetworkEndpointGroups().Get(ctx, meta.ZonalKey(name, zone))
	return v, mc.Observe(err)
}

func (c *Container) NetNsPath() (string, error) {
	if c.state == nil {
		return "", fmt.Errorf("container state is not populated")
	}

	if c.netns == "" {
		return fmt.Sprintf("/proc/%d/ns/net", c.state.Pid), nil
	}

	return c.netns, nil
}

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


Question:
/* (non-Javadoc)
@see org.kaazing.gateway.client.transport.http.HttpRequestDelegate#send(java.nio.ByteBuffer)

public void processSend(ByteBuffer content) {
        LOG.entering(CLASS_NAME, "processSend", content);
        if (readyState != State.OPENED && readyState != State.HEADERS_RECEIVED) {
            throw new IllegalStateException(readyState + " HttpRequest must be in an OPEN state before " + "invocation of the send() method");
        }
        try {
            if (!async && content != null && content.hasRemaining()) {
                connection.setDoOutput(true);
                connection.setDoInput(true);

                OutputStream out = connection.getOutputStream();
                out.write(content.array(), content.arrayOffset(), content.remaining());
                out.flush();
            }

            connection.connect();
            reader = new StreamReader();
            Thread t = new Thread(reader, "HttpRequestDelegate stream reader");
            t.setDaemon(true);
            t.start();
        }
        catch (Exception e) {
            LOG.log(Level.FINE, "While processing http request", e);
            // e.printStackTrace();
            listener.errorOccurred(new ErrorEvent(e));
        }
    }

public Packet putInt(int i, ByteOrder order) {
        var buffer = HEAP_BUFFER_POOL.take(Integer.BYTES);
        var array = buffer.putInt(order == ByteOrder.LITTLE_ENDIAN ? Integer.reverseBytes(i) : i).array();

        try {
            return enqueue(Arrays.copyOfRange(array, 0, Integer.BYTES));
        } finally {
            HEAP_BUFFER_POOL.give(buffer);
        }
    }

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


Question:
// ParseGPS parses a GPS/NMEA coordinate.
// e.g 15113.4322S

func ParseGPS(s string) (float64, error) {
	parts := strings.Split(s, " ")
	if len(parts) != 2 {
		return 0, fmt.Errorf("invalid format: %s", s)
	}
	dir := parts[1]
	value, err := strconv.ParseFloat(parts[0], 64)
	if err != nil {
		return 0, fmt.Errorf("parse error: %s", err.Error())
	}

	degrees := math.Floor(value / 100)
	minutes := value - (degrees * 100)
	value = degrees + minutes/60

	if dir == North || dir == East {
		return value, nil
	} else if dir == South || dir == West {
		return 0 - value, nil
	} else {
		return 0, fmt.Errorf("invalid direction [%s]", dir)
	}
}

def create_context_location(source_input,
                                document: nil,
                                pointer_segments: [])
      source = if !document
                 Openapi3Parser::Document.new(source_input).root_source
               else
                 Openapi3Parser::Source.new(
                   source_input,
                   document,
                   Openapi3Parser::Document::ReferenceRegister.new
                 )
               end

      Openapi3Parser::Context::Location.new(source, pointer_segments)
    end

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


Question: Returns the AptEventSet with the specified name

public AptEventSet getEventSet(String name)
    {
        for (AptEventSet eventSet: getEventSets())
            if (eventSet.getClassName().equals(name))
                return eventSet;

        if (_superClass != null)
            return _superClass.getEventSet(name);

        return null;
    }

def assert_datasource_protocol(event):
    """"""

    assert event.type in DATASOURCE_TYPE

    # Done packets have no dt.
    if not event.type == DATASOURCE_TYPE.DONE:
        assert isinstance(event.dt, datetime)
        assert event.dt.tzinfo == pytz.utc

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


Question:
This method removes the uncompleted correlation id and its
associated information.

@param id The correlation id
@return The node associated with the correlation id

public Node removeUncompletedCorrelationId(String id) {
        NodePlaceholder placeholder=uncompletedCorrelationIdsNodeMap.remove(id);
        if (placeholder != null) {
            return placeholder.getNode();
        }
        return null;
    }

protected function job(): void
    {
        $unfinished_auctions = CorporationContract::join('contract_details',
            'corporation_contracts.contract_id', '=',
            'contract_details.contract_id')
            ->where('corporation_id', $this->getCorporationId())
            ->where('type', 'auction')
            ->whereNotIn('status', ['finished', 'deleted'])
            ->pluck('corporation_contracts.contract_id');

        $unfinished_auctions->each(function ($contract_id) {

            while (true) {

                try {
                    $bids = $this->retrieve([
                        'corporation_id' => $this->getCorporationId(),
                        'contract_id'    => $contract_id,
                    ]);

                    if ($bids->isCachedLoad()) return;

                    collect($bids)->each(function ($bid) use ($contract_id) {

                        ContractBid::firstOrCreate([
                            'bid_id' => $bid->bid_id,
                        ], [
                            'contract_id' => $contract_id,
                            'bidder_id' => $bid->bidder_id,
                            'date_bid' => carbon($bid->date_bid),
                            'amount' => $bid->amount,
                        ]);
                    });

                    if (! $this->nextPage($bids->pages))
                        break;

                } catch (RequestFailedException $e) {
                    if (strtolower($e->getError()) == 'contract not found') {
                        ContractDetail::where('contract_id', $contract_id)
                            ->update([
                                'status' => 'deleted',
                            ]);

                        break;
                    }

                    throw $e;
                }
            }

            // reset the page back to page one for the next contract
            $this->page = 1;
        });
    }

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


Question:
Apply the filter to a database Query
@param  Query  $query
@param  array  $columns a map of field names to database column names
@return Query

public function toQuery( Query $query, array $columns = [], $alias = '' ) {

		foreach( $this->criteria as $column => $criteria ) {

			if( !$column = $this->getColumnName($columns, $column, $alias) )
				continue;

			foreach( $criteria as $operator => $value ) {
				$query->where($column, $operator, $value);
			}

		}

		foreach( $this->getOrder() as $column => $ascending ) {
			$column = $this->getColumnName($columns, $column, $alias);
			if( !$column )
				continue;
			$query->orderBy($column, $ascending);
		}

		if( $this->offset )
			$query->offset($this->offset);

		if( $this->limit )
			$query->limit($this->limit);

		return $query;

	}

public static Specification<JpaTargetFilterQuery> likeName(final String searchText) {
        return (targetFilterQueryRoot, query, cb) -> {
            final String searchTextToLower = searchText.toLowerCase();
            return cb.like(cb.lower(targetFilterQueryRoot.get(JpaTargetFilterQuery_.name)), searchTextToLower);
        };
    }

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


Question:
Sets the text body for the message.

@param  string $txt
@param  string $charset
@param  string $encoding
@return Zend_Mail Provides fluent interface

public function setBodyText($txt, $charset = null, $encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE)
    {
        if ($charset === null) {
            $charset = $this->_charset;
        }

        $mp = new Zend_Mime_Part($txt);
        $mp->encoding = $encoding;
        $mp->type = Zend_Mime::TYPE_TEXT;
        $mp->disposition = Zend_Mime::DISPOSITION_INLINE;
        $mp->charset = $charset;

        $this->_bodyText = $mp;

        return $this;
    }

protected function _initView ()
    {
        // Create default view model, to be used in all templates and layouts
        $this->appView  = new \Zend\View\Model\ViewModel();

        // Convenience access variables
        $this->_appView = $this->appView;
        $this->view     = $this->appView;
        $this->_view    = $this->appView;
    }

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


Question: Return a list of tuples specifying the column name and type

def get_table_columns(dbconn, tablename):

    cur = dbconn.cursor()
    cur.execute("PRAGMA table_info('%s');" % tablename)
    info = cur.fetchall()
    cols = [(i[1], i[2]) for i in info]
    return cols

def _get_fld2col_widths(self, **kws):
        """"""
        fld2col_widths = self._init_fld2col_widths()
        if 'fld2col_widths' not in kws:
            return fld2col_widths
        for fld, val in kws['fld2col_widths'].items():
            fld2col_widths[fld] = val
        return fld2col_widths

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


Question:
Get Options

@return array

final protected function getOptions($option = null)
    {
        if (null !== $option) {
            if (array_key_exists($option, self::$_options)) {
                return self::$_options[$option];
            } else {
                return false;
            }
        }

        return self::$_options;
    }

public function walk($callback, $output = null)
    {
        if ($output === null) {
            $output = clone $this;
            $output->exchangeArray([]);
        } elseif (is_string($output) and class_exists($output)) {
            $output = new $output();
        }

        foreach ($this as $key => $value) {
            $output[$key] = $callback($value, $key);
        }

        return $output;
    }

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