comment stringlengths 16 255 | code stringlengths 52 3.87M |
|---|---|
Returns the next $fact value or FALSE if there are no more facts.
{@inheritDoc}
@see Iterator::next() | public function next()
{
if ( is_null( $this->facts ) )
{
return false;
}
$this->yieldedFact = null;
$success = $this->facts->next();
return $success;
} |
Compare the structures of two databases.
Analysis's and compares the column definitions of each table
in both databases's. Identifies differences in column names,
data types and keys. | def compare_schemas(self, db_x, db_y, show=True):
# TODO: Improve method
self._printer("\tComparing database schema's {0} and {1}".format(db_x, db_y))
# Run compare_dbs_getter to get row counts
x = self._schema_getter(db_x)
y = self._schema_getter(db_y)
x_count ... |
Display a listing of the resource.
@param $type
@param Request $request
@return Response | public function index($type, Request $request)
{
try {
$resultColumns = [];
$query = $request->get('q');
$column = $request->get('c');
$model = app()->make(config('mentions.' . $type));
$records = $model->where($column, 'LIKE', "%$query%")
... |
// NewRocR100ForStreamWithSrcLen creates a Rate of Change Ratio 100 Scale Indicator (RocR100) for offline usage with a source data stream | func NewRocR100ForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *RocR100, err error) {
ind, err := NewRocR100WithSrcLen(sourceLength, timePeriod, selectData)
priceStream.AddTickSubscription(ind)
return ind, err
} |
/* ------------------------------------------------------------ | public void reset()
{
try{
out=IO.getNullWriter();
super.flush();
out=new OutputStreamWriter(os,encoding);
written=false;
}
catch(UnsupportedEncodingException e)
{
log.fatal(e); System.exit(1);
}
} |
When an error status the payload is holding an AsyncException that
is converted to a serializable dict. | def _payload_to_dict(self):
if self.status != self.ERROR or not self.payload:
return self.payload
import traceback
return {
"error": self.payload.error,
"args": self.payload.args,
"traceback": traceback.format_exception(*self.payload.tra... |
// IsEmptyConfig returns true if the provided error indicates the provided configuration
// is empty. | func IsEmptyConfig(err error) bool {
switch t := err.(type) {
case errConfigurationInvalid:
return len(t) == 1 && t[0] == ErrEmptyConfig
}
return err == ErrEmptyConfig
} |
Generate file name.
@return the string | public static String generatePreviousPreviousFileName() {
StringBuffer name = new StringBuffer();
name.append("Audit_Log-").append(AuditUtil.dateToString(new Date(), "yyyy-MM-dd"))
.append(CoreConstants.AUDIT_EXTENTION);
return name.toString();
} |
// SetDeploymentStatusMessages sets the DeploymentStatusMessages field's value. | func (s *DeploymentInfo) SetDeploymentStatusMessages(v []*string) *DeploymentInfo {
s.DeploymentStatusMessages = v
return s
} |
Load dependencies on demand.
@see \SimpleComplex\Config\EnvSectionedConfig
@return void | protected function loadDependencies() /*: void*/
{
if (!$this->validate) {
$this->validate = Validate::getInstance();
if (!$this->config) {
// Use enviroment variable wrapper config class if exists;
// fall back on empty sectioned map.
... |
Encode an arbitrary value | private void encodeObject(StringBuffer result, Object value) {
if (value != null) {
if (value instanceof byte[]) {
result.append("[]");
HexString.binToHex((byte[])value, 0, ((byte[])value).length, result);
} else
URLEncode(result, value.toString());
} |
Create a new UnboundNode representing a given class. | def _createunbound(kls, **info):
""""""
if issubclass(kls, Bitfield):
nodetype = UnboundBitfieldNode
elif hasattr(kls, '_fields_'):
nodetype = UnboundStructureNode
elif issubclass(kls, ctypes.Array):
nodetype = UnboundArrayNode
else:
nodetype = UnboundSimpleNode ... |
/*
Get singleton instance
@return Some\Class Object singleton instance | public static function getInstance ()
{
// If this class is used for multiple singletons, we need to keep
// track of multiple singleton objects, one for each class name
static $instances = array();
// Get class name to use. Use late static binding here,
// if method is over... |
Compile an expression and return the corresponding executable
@param string $expression
@return \FormulaInterpreter\Executable | function compile($expression) {
$options = $this->parser->parse($expression);
$command = $this->commandFactory->create($options);
return new Executable($command, $this->variables);
} |
Outputs the current progress string. | public function display(): void
{
if (null === $this->format) {
$this->format = self::DEFAULT_FORMAT;
}
$this->render($this->buildLine());
} |
Add field rules from either a Jpf.ValidationField or a Jpf.ValidationLocaleRules annotation. | private void addFieldRules( AnnotationInstance rulesContainerAnnotation, RuleInfo ruleInfo,
boolean applyToAllLocales )
{
//
// First parse the locale from the wrapper annotation. This will apply to all rules inside.
//
Locale locale = null;
... |
Execute unpublishing documents | private function manageDeleteDocument(&$params, &$dmsLoader, &$manageCategory, &$arrMessages, &$blnShowStart, $documentId)
{
$params->loadRootCategory = true; // get complete path to root, for checking inherited access rights
$params->loadAccessRights = true;
$params->loadDocuments = false;
$category ... |
Gets the value for the given key in the {@link Properties}; if this key is not found, a
RuntimeException is thrown.
@param key the key to get the value for
@param options options for getting configuration value
@return the value for the given key | public static String get(PropertyKey key, ConfigurationValueOptions options) {
return sConf.get(key, options);
} |
Generate vendor directory
@param string $sVendor | protected function _generateVendorDir($sVendor)
{
$sVendorDir = $this->_sModuleDir . $sVendor . DIRECTORY_SEPARATOR;
if (!file_exists($sVendorDir)) {
mkdir($sVendorDir);
// Generate vendor metadata file
file_put_contents($sVendorDir . 'vendormetadata.php', '<?php... |
Read a 32-bit little-endian integer from the internal buffer. | public int readRawLittleEndian32() throws IOException
{
final byte[] buffer = this.buffer;
int offset = this.offset;
final byte b1 = buffer[offset++];
final byte b2 = buffer[offset++];
final byte b3 = buffer[offset++];
final byte b4 = buffer[offset++];
... |
{@inheritdoc}
@param FlowQuery $flowQuery
@param array $arguments
@return void
@throws FizzleException
@throws \Neos\Eel\Exception | public function evaluate(FlowQuery $flowQuery, array $arguments)
{
$subject = $arguments[0];
if (!isset($subject) || empty($subject)) {
$flowQuery->setContext([]);
return;
}
$filteredContext = [];
$context = $flowQuery->getContext();
if (is_st... |
ensureExists
@param string $dir
@return void | private function ensureExists($dir)
{
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
return $this->validatePath($dir);
} |
// Error returns the JSONified version of this error which will
// trigger the appropriate integration mapping. | func (apigError *Error) Error() string {
bytes, bytesErr := json.Marshal(apigError)
if bytesErr != nil {
bytes = []byte(http.StatusText(http.StatusInternalServerError))
}
return string(bytes)
} |
Clean up, return key/value pairs
@param array $matched
@return array
@access protected | protected function clearPairs(/*# array */ $matched)/*# : array */
{
$pairs = [];
foreach ($matched as $m) {
// source another env file
if (isset($m[5])) {
$file = trim($m[5]);
$pairs[$file] = $this->source_marker;
// value found
... |
Connects to all the event listeners
@method startListening
@chainable | function () {
this.events.on('report:run:browser', this.runBrowser.bind(this));
this.events.on('report:assertion', this.assertion.bind(this));
this.events.on('report:test:started', this.testStarted.bind(this));
this.events.on('report:test:finished', this.testFinished.bind(this));
this.events.on('rep... |
12.12 Labelled Statement | private ParseTree parseLabelledStatement() {
SourcePosition start = getTreeStartLocation();
IdentifierToken name = eatId();
eat(TokenType.COLON);
return new LabelledStatementTree(getTreeLocation(start), name, parseStatement());
} |
Browse Episodes of an remote application (with the keychain)
@Route("/remote/{keychain}", name="oktolab_media_remote_episodes")
@Method("GET")
@Template() | public function listRemoteEpisodes(Keychain $keychain)
{
$episodes_url = $this->get('bprs_applink')->getApiUrlsForKey(
$keychain,
'oktolab_media_api_list_episodes'
);
if ($episodes_url) {
$client = new Client();
$response = $client->request(
... |
Checks if a symbol is a special.
@param NumberPatternSymbol $symbol
@param array $is
An array of self::SYMBOL_* constants, one of which the symbol should
match.
@return boolean | function symbolIsSpecial(NumberPatternSymbol $symbol, array $is) {
return !$symbol->escaped && in_array($symbol->symbol, $is, TRUE);
} |
Invoke method, every class will have its own
returns true/false on completion, setting both
errormsg and output as necessary | function invoke() {
parent::invoke();
$result = true;
// Set own core attributes
$this->does_generate = ACTION_NONE;
// These are always here
global $CFG, $XMLDB;
// Do the job, setting result as needed
// Get the dir containing the file
$dirp... |
// Beep beeps the PC speaker (https://en.wikipedia.org/wiki/PC_speaker). | func Beep(freq float64, duration int) error {
if freq == 0 {
freq = DefaultFreq
} else if freq > 32767 {
freq = 32767
} else if freq < 37 {
freq = DefaultFreq
}
if duration == 0 {
duration = DefaultDuration
}
kernel32, _ := syscall.LoadLibrary("kernel32.dll")
beep32, _ := syscall.GetProcAddress(kernel... |
Returns the direct properties of this resource in a map.<p>
This is without "search", so it will not include inherited properties from the parent folders.<p>
@return the direct properties of this resource in a map | public Map<String, String> getProperty() {
if (m_properties == null) {
try {
List<CmsProperty> properties = m_cms.readPropertyObjects(this, false);
m_properties = CmsProperty.toMap(properties);
} catch (CmsException e) {
if (LOG.isDebugEna... |
Write mesage to tansport. msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method. | def write(self, msg):
ser = msg.SerializeToString()
header = struct.pack(">HL", mapping.get_type(msg), len(ser))
self._write(b"##" + header + ser, msg) |
@param CreditCard $card
@return CreditCard | public function tokenizeCard(CreditCard $card)
{
$tokenizeCardRequest = new TokenizeCardRequest($this->merchant, $this->environment);
return $tokenizeCardRequest->execute($card);
} |
Drop several tables at once
@param array $tables
@param boolean $fkChecks Whether to enabled Foreign Key checks
@return boolean | final public function dropTables(array $tables, $fkChecks = false)
{
// Whether FK checks are enabled
if ($fkChecks == false) {
$this->db->raw('SET FOREIGN_KEY_CHECKS=0')
->execute();
}
foreach ($tables as $table) {
if (!$this->dropTable(... |
Executes a detach operation on the given entity.
@param object $entity
@param array $visited
@param boolean $noCascade if true, don't cascade detach operation.
@return void | private function doDetach($entity, array &$visited, $noCascade = false)
{
$oid = spl_object_hash($entity);
if (isset($visited[$oid])) {
return; // Prevent infinite recursion
}
$visited[$oid] = $entity; // mark visited
switch ($this->getEntityState($entity, self... |
@param array $attributes
@param Assertion $assertion
@return array | private function resolveAttributesFromAssertion(array $attributes, Assertion $assertion)
{
$attributeStatements = $assertion->getAllAttributeStatements();
return array_reduce($attributeStatements, [$this, 'resolveAttributesFromAttributeStatement'], $attributes);
} |
To date.
@param value the value
@return the date | public static Date toDate(final Object value) {
if (value instanceof Date) {
return (Date) value;
}
if (value == null || value.equals("null")) {
return null;
}
if (value instanceof String) {
throw new IllegalStateException("fix me");
}
return null;
} |
Calculate the centre x position | function (d, chart, series) {
var returnCx = 0;
if (series.x.measure !== null && series.x.measure !== undefined) {
returnCx = series.x._scale(d.cx);
} else if (series.x._hasCategories() && series.x.categoryFields.length >= 2) {
returnCx = series.x._sca... |
HTTP Method Patch
@param string $uri optional uri to use
@param string $payload data to send in body of request
@param string $mime MIME to use for Content-Type
@return Request | public static function patch($uri, $payload = null, $mime = null)
{
return self::init(Http::PATCH)->uri($uri)->body($payload, $mime);
} |
@param Ability $ability
@param array $options
@return array | public function serialize(Ability $ability, array $options = [])
{
$serialized = [
'id' => $ability->getUuid(),
'name' => $ability->getName(),
'minResourceCount' => $ability->getMinResourceCount(),
'minEvaluatedResourceCount' => $ability->getMinEvaluatedResour... |
// NoAutoCondition disable generate SQL condition from beans | func (session *Session) NoAutoCondition(no ...bool) *Session {
session.Statement.NoAutoCondition(no...)
return session
} |
Make data filter definition consistent.
Create a tuple where first element is the row filter and the second element
is the column filter | def _homogenize_data_filter(dfilter):
if isinstance(dfilter, tuple) and (len(dfilter) == 1):
dfilter = (dfilter[0], None)
if (dfilter is None) or (dfilter == (None, None)) or (dfilter == (None,)):
dfilter = (None, None)
elif isinstance(dfilter, dict):
dfilter = (dfilter, None)
... |
Modifies a list of contacts.
Provide comma separated list of contact ids and desired paused state
Returns status message | def modifyContacts(self, contactids, paused):
response = self.request("PUT", "notification_contacts", {'contactids': contactids,
'paused': paused})
return response.json()['message'] |
Returns the @GROUPID.
If derived_from is set, returns that group_id. | def group_id(self):
if self.derived_from is not None:
return self.derived_from.group_id()
if self.file_uuid is None:
return None
return utils.GROUP_ID_PREFIX + self.file_uuid |
Create a TypedArray instance.
@param {object} config
@returns {TypedArray}
@augments Typed
@constructor | function TypedArray (config) {
const array = this;
// validate min items
if (config.hasOwnProperty('minItems') && (!util.isInteger(config.minItems) || config.minItems < 0)) {
throw Error('Invalid configuration value for property: minItems. Must be an integer that is greater than or equal to zero. R... |
/*
(non-Javadoc)
@see javax.servlet.sip.SipServletMessage#getLocalAddr() | public String getLocalAddr() {
final SIPTransaction sipTransaction = (SIPTransaction)getTransaction();
if(sipTransaction != null) {
return sipTransaction.getHost();
} else {
final String transport = JainSipUtils.findTransport(message);
final MobicentsExtendedListeningPoint listeningPoint = sipFactoryImpl... |
Export a literal as an XPath expression
@param mixed $value Literal, e.g. "foo"
@return string XPath expression, e.g. "'foo'" | public static function export($value)
{
if (!is_scalar($value))
{
throw new InvalidArgumentException(__METHOD__ . '() cannot export non-scalar values');
}
if (is_int($value))
{
return (string) $value;
}
if (is_float($value))
{
// Avoid locale issues by using sprintf()
return preg_replace('(... |
Set person address
@param array|Address $value Parameter value
@return Person provides a fluent interface. | public function setAddress($value)
{
if (is_array($value)) {
$value = new Address($value);
}
return $this->setParameter('address', $value);
} |
Return connection base type device
@param array $params
@param string $type
@return object | public function getConnection(array $params, $type) {
if ($type == 'S') {
$host = (!empty($params['num_ip'])) ? $params['num_ip'] : '127.0.0.1';
$community = (!empty($params['des_snmp_community'])) ? $params['des_snmp_community'] : 'public';
$version = (!empty($params['des_sn... |
Marks passed node as active
@param string $nodeId node id | public function markNodeActive($nodeId)
{
$xPath = new DOMXPath($this->getDomXml());
$nodeList = $xPath->query("//*[@cl='{$nodeId}' or @list='{$nodeId}']");
if ($nodeList->length) {
foreach ($nodeList as $node) {
// special case for external resources
... |
Remove keys from the public or secret keyrings.
:param keys: Single key ID or list of mutiple IDs
:param secret: Delete secret keys
:rtype: DeleteResult | def delete_keys(self, keys, secret=False):
'''
'''
return self.execute(
DeleteResult(),
['--batch', '--yes', '--delete-secret-key' if secret else '--delete-key'] + list(make_list(keys))
) |
unique method
@method unique | public function unique() : Collection
{
$acc = [];
foreach ($this->list as $item) {
if (!in_array($item, $acc)) {
$acc[] = $item;
}
}
return self::from(...$acc);
} |
ubuntu 16.04 systemctl service config
:param service_name:
:param start_cmd:
:param stop_cmd:
:return: | def systemctl_autostart(self, service_name, start_cmd, stop_cmd):
# get config content
service_content = bigdata_conf.systemctl_config.format(
service_name=service_name,
start_cmd=start_cmd,
stop_cmd=stop_cmd
)
# write config into file
... |
Set the ``xlink:href`` of this file. | def url(self, url):
if url is None:
return
el_FLocat = self._el.find('mets:FLocat', NS)
if el_FLocat is None:
el_FLocat = ET.SubElement(self._el, TAG_METS_FLOCAT)
el_FLocat.set("{%s}href" % NS["xlink"], url) |
@param mixed $use_customer_key
@return Realm | public function setUseCustomerKey( $use_customer_key )
{
$this->use_customer_key = ($use_customer_key == 1 || $use_customer_key == 'Y' || $use_customer_key === TRUE) ? TRUE : FALSE;
return $this;
} |
Create an instance of {@link JAXBElement }{@code <}{@link MsupType }{@code >}} | @XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "msup")
public JAXBElement<MsupType> createMsup(MsupType value) {
return new JAXBElement<MsupType>(_Msup_QNAME, MsupType.class, null, value);
} |
Compute SHA-1 hash value for a given input stream.
@param in Input stream
@return SHA-1 hash value (array of 20 bytes). | static byte[] sha1(InputStream in) {
try {
MessageDigest md = MessageDigest.getInstance(SHA1_DIGEST);
byte[] buffer = new byte[4096];
int bytes;
while ( (bytes = in.read(buffer)) > 0) {
md.update(buffer, 0, bytes);
}
return md.digest();
}
catch(NoSuchAlgorithmExc... |
// SplitFullName splits a name and returns the firstname, lastname | func SplitFullName(fullName string) (string, string) {
nameComponents := strings.Split(fullName, " ")
firstName := nameComponents[0]
lastName := ""
if len(nameComponents) > 1 {
lastName = strings.Join(nameComponents[1:], " ")
}
return firstName, lastName
} |
Sets the WHERE param to the query.
@param int|array $where WHERE param.
@param QueryBuilder $query Query to build.
@param string $primaryKey Table primary key.
@return QueryBuilder Query object. | private static function _setWhere($where, QueryBuilder $query, string $primaryKey = "id") : QueryBuilder
{
if(!is_array($where)) {
return $query->where([
$primaryKey => $where
]);
}
$columns = $where;
unset($columns["ORDER BY"]);
unse... |
Create an enum config
:param enum_type:
:param help_string:
:param default:
:return: | def create_enum(enum_type, help_string=NO_HELP, default=NO_DEFAULT):
# type: (Type[Enum], str, Union[Any, NO_DEFAULT_TYPE]) -> Type[Enum]
# noinspection PyTypeChecker
return ParamEnum(
help_string=help_string,
default=default,
enum_type=enum_type,
... |
e
@param {String} label the label of the async task
@required @param {Any} gen the object to yield
@return {Function} trunked function | function e(label, gen) {
if (!gen) {
gen = label;
label = '';
}
if (!enabled) {
return gen;
}
var hackErr = new Error('hack');
hackErr.label = label;
return function *() {
try {
return yield gen;
} catch(err) {
throw buildError(err, hackErr);
}
};
} |
Add faxes.
@param \Sulu\Bundle\ContactBundle\Entity\Fax $faxes
@return FaxType | public function addFaxe(\Sulu\Bundle\ContactBundle\Entity\Fax $faxes)
{
$this->faxes[] = $faxes;
return $this;
} |
Lists the views this connection has.
@return View[] | public function listViews()
{
$database = $this->_conn->getDatabase();
$sql = $this->_platform->getListViewsSQL($database);
$views = $this->_conn->fetchAll($sql);
return $this->_getPortableViewsList($views);
} |
Block a user.
Returns a `relationship dict`_ containing the updated relationship to the user. | def account_block(self, id):
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/block'.format(str(id))
return self.__api_request('POST', url) |
// MysqlAddr returns hostname:mysql port. | func (ti *TabletInfo) MysqlAddr() string {
return netutil.JoinHostPort(topoproto.MysqlHostname(ti.Tablet), topoproto.MysqlPort(ti.Tablet))
} |
// Custom marshaller to add the resourceType property, as required by the specification | func (resource *AppointmentResponse) MarshalJSON() ([]byte, error) {
resource.ResourceType = "AppointmentResponse"
// Dereferencing the pointer to avoid infinite recursion.
// Passing in plain old x (a pointer to AppointmentResponse), would cause this same
// MarshallJSON function to be called again
return json.Ma... |
Check the user has configured API version correctly. | def check_stripe_api_version(app_configs=None, **kwargs):
""""""
from . import settings as djstripe_settings
messages = []
default_version = djstripe_settings.DEFAULT_STRIPE_API_VERSION
version = djstripe_settings.get_stripe_api_version()
if not validate_stripe_api_version(version):
msg = "Invalid Stripe API ... |
Resumes all the worker threads. | def resume(self):
for child in chain(self.consumers.values(), self.workers):
child.resume() |
boolean response if a message contains correct information to serialize
:param msg: <proto object>
:param raise_err: <bool>
:return: <bool> | def successfuly_encodes(msg, raise_err=False):
result = True
try:
msg.SerializeToString()
except EncodeError as encode_error:
if raise_err:
raise encode_error
result = False
return result |
Convert co-ordinate values to floats. | def floatize(self):
""""""
self.x = float(self.x)
self.y = float(self.y) |
Get the route to the error page
@param ServerRequestInterface $request
@param ResponseInterface $response
@return Router\Route | protected function getErrorRoute(ServerRequestInterface $request, ResponseInterface $response)
{
if (
interface_exists('Jasny\HttpMessage\GlobalEnvironmentInterface') &&
$request instanceof GlobalEnvironmentInterface
) {
$request = $request->withoutGlobalEnvironme... |
Returns a copy of this LocalTime with the nano-of-second value altered.
@param int $nano The new nano-of-second.
@return LocalTime
@throws DateTimeException If the nano-of-second if not valid. | public function withNano(int $nano) : LocalTime
{
if ($nano === $this->nano) {
return $this;
}
Field\NanoOfSecond::check($nano);
return new LocalTime($this->hour, $this->minute, $this->second, $nano);
} |
Internal method to validate the local part of the email address
@return boolean | private function _validateLocalPart()
{
// First try to match the local part on the common dot-atom format
$result = false;
// Dot-atom characters are: 1*atext *("." 1*atext)
// atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*",
// "+", "-", "/", "=", "?", ... |
Returns all RDF types (classes) of a given resource.
@return array | public function getClasses(): array {
$this->loadMetadata();
$ret = array();
foreach ($this->metadata->allResources('http://www.w3.org/1999/02/22-rdf-syntax-ns#type') as $i) {
$ret[] = $i->getUri();
}
return $ret;
} |
Set closed date from this issue
@param [Hash] event
@param [Hash] issue | def set_date_from_event(event, issue)
if event["commit_id"].nil?
issue["actual_date"] = issue["closed_at"]
else
begin
commit = @fetcher.fetch_commit(event["commit_id"])
issue["actual_date"] = commit["commit"]["author"]["date"]
# issue['actual_date'] = commit['a... |
// SetUserName sets the UserName field's value. | func (s *DescribeUserStackAssociationsInput) SetUserName(v string) *DescribeUserStackAssociationsInput {
s.UserName = &v
return s
} |
/* insert line breaks into first-pass tokenized data | function breakLines(tokens, maxWidth) {
if (!maxWidth) {
maxWidth = Infinity;
}
let i = 0;
let lineLength = 0;
let lastTokenWithSpace = -1;
while (i < tokens.length) { /* take all text tokens, remove space, apply linebreaks */
let token = tokens[i];
if (token.type == TYPE... |
Gets the member attribute.
@return Member|null The member attribute. | public function getMemberAttribute()
{
$guild = $this->discord->guilds->get('id', $this->guild_id);
return $guild->members->get('id', $this->user_id);
} |
Given supplied arguments, find a contained
subcommand
@param array $args
@return \WP_CLI\Dispatcher\Subcommand|false | public function find_subcommand( &$args ) {
$name = array_shift( $args );
$subcommands = $this->get_subcommands();
if ( ! isset( $subcommands[ $name ] ) ) {
$aliases = self::get_aliases( $subcommands );
if ( isset( $aliases[ $name ] ) ) {
$name = $aliases[ $name ];
}
}
if ( ! isset( $subcomma... |
Handles rolling back to a selected version on save.
@param int $version | public function savePreviousVersion($version)
{
if (!is_numeric($version)) {
return;
}
try {
$this->setVersionNumber($version);
$this->owner->write();
} catch (Exception $e) {
throw new ValidationException(new ValidationResult(
... |
Initializes the options for the object.
Called from {@link __construct()} as a first step of object instantiation.
@param object An optional AnConfig object with configuration options. | protected function _initialize(AnConfig $config)
{
$config->append(array(
'name' => 'google',
'version' => '3',
'url' => 'https://maps.googleapis.com/maps/api/geocode/json?',
'key' => get_config_value('locations.api_key', null)
));
parent::_in... |
Adds the given component as a child of this component. The tag is used to identify the child in a velocity
template.
@param component the component to add.
@param tag the tag used to identify the component.
@deprecated Use {@link WTemplate} instead. | @Deprecated
void add(final WComponent component, final String tag) {
add(component);
component.setTag(tag);
} |
read a file and inject a string of swagger (str, str) -> null | function useMain (mdFile, swagger) {
const mainOpts = {
position: argv.position,
title: argv.title
}
opts.yaml ? mainOpts.yaml = true : mainOpts.json = true
fs.readFile(mdFile, { encoding: 'utf8' }, function (err, md) {
assert.ifError(err)
const compiled = remark()
.use(main(swagger, main... |
{@inheritdoc}
@see Knp\Menu.MenuItem::addChild()
Our menu items created by menu factory and $child always MenuItemInterface.
Factory sets current uri and other variable parts of menu item options
We don't need to set it here | public function addChild($child, array $options = array())
{
$child->setParent($this);
$this->children[$child->getName()] = $child;
return $child;
} |
Get a default db value, if any is available
@return ConnectionInterface|null A default db value or Null if no default value is available | public function getDefaultDb(): ?ConnectionInterface
{
// By default, the DB Facade does not return the
// any actual database connection, but rather an
// instance of \Illuminate\Database\DatabaseManager.
// Therefore, we make sure only to obtain its
// "connection", to make... |
Loads source HTML into memory, either from $source string or a file.
@param string $source HTML content
@param bool $from_file Indicates $source is a file to pull content from | public function set_html($source, $from_file = false)
{
if ($from_file && file_exists($source)) {
$this->html = file_get_contents($source);
} else {
$this->html = $source;
}
$this->_converted = false;
} |
文字列のダイアクリティカルマークや囲みを外します。
@param string $input
@return string | protected static function deleteMarks(string $input): string
{
return preg_replace(
'/\\p{M}+/u',
'',
\Normalizer::normalize($input, \Normalizer::FORM_KD)
);
} |
Update components. | def command_update(prog_name, prof_mgr, prof_name, prog_args):
# Retrieve arguments
parser = argparse.ArgumentParser(
prog=prog_name
)
parser.add_argument(
"components",
metavar="comps",
nargs=argparse.REMAINDER,
help="system components"
)
args = parser.parse_args(prog_args)
# Profile load
prof... |
@param string $input
@param int $length
@param string $string
@param int $type
@return string | public static function pad(string $input, int $length, string $string = ' ', int $type = STR_PAD_RIGHT): string
{
$diff = strlen($input) - mb_strlen($input, 'utf-8');
return str_pad($input, $length + $diff, $string, $type);
} |
The system creates a new draft version as a copy from the current version.
@param mixed $contentId
@throws ForbiddenException if the current version is already a draft
@return \eZ\Publish\Core\REST\Server\Values\CreatedVersion | public function createDraftFromCurrentVersion($contentId)
{
$contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);
$contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId);
$versionInfo = $this->repository->getConten... |
Set name
@throws \InvalidArgumentException if the name is empty
@param string $name Capability name
@return \RolesCapabilities\Capability | public function setName(string $name): \RolesCapabilities\Capability
{
if (empty($name)) {
throw new InvalidArgumentException("Name cannot be empty");
}
$this->name = $name;
return $this;
} |
// Receives a multi-part message. | func (s *Socket) Recv() (parts [][]byte, err error) {
parts = make([][]byte, 0)
for more := true; more; {
var part []byte
if part, more, err = s.RecvPart(); err != nil {
return
}
parts = append(parts, part)
}
return
} |
Prints alerts and updates the prompt any time the prompt is showing | def _alerter_thread_func(self) -> None:
self._alert_count = 0
self._next_alert_time = 0
while not self._stop_thread:
# Always acquire terminal_lock before printing alerts or updating the prompt
# To keep the app responsive, do not block on this call
... |
// Warningf forwards to Logger.Warning | func (l logf) Warningf(s string, args ...interface{}) {
l.log.Warning(s, args...)
} |
Build an instance of TodayInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.today.TodayInstance
:rtype: twilio.rest.api.v2010.account.usage.record.today.TodayInstance | def get_instance(self, payload):
return TodayInstance(self._version, payload, account_sid=self._solution['account_sid'], ) |
// SetAuthenticationToken sets the AuthenticationToken field's value. | func (s *CreateUserInput) SetAuthenticationToken(v string) *CreateUserInput {
s.AuthenticationToken = &v
return s
} |
// Everything but the last element of the full type name, CamelCased.
// The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... . | func (e *EnumDescriptor) prefix() string {
typeName := e.alias()
if e.parent == nil {
// If the enum is not part of a message, the prefix is just the type name.
return CamelCase(typeName[len(typeName)-1]) + "_"
}
return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_"
} |
expects pages/:name/template.hbs | function (id) {
var o = this.options;
return path.resolve(o.root, o.viewsDir, id, "template" + o.extension);
} |
General power-of-2 base conversion. | def convertbits(data, frombits, tobits, pad=True):
""""""
acc = 0
bits = 0
ret = []
maxv = (1 << tobits) - 1
max_acc = (1 << (frombits + tobits - 1)) - 1
for value in data:
if value < 0 or (value >> frombits):
return None
acc = ((acc << frombits) | value) & max_ac... |
Adds new tag words.
@param string[] $allWords All words extracted from post
@throws Exception | protected function addNewWords($allWords)
{
try {
$newWords = $allWords;
$query = (new Query())->from(Vocabulary::tableName())->where(['word' => $allWords]);
foreach ($query->each() as $vocabularyFound) {
if (($key = array_search($vocabularyFound['wo... |
Subsets and Splits
SQL Console for sentence-transformers/codesearchnet
Identifies examples where both requests.get() and beautifulsoup libraries are used together in code comments, revealing common web scraping patterns in the training data.
Golang Code and Comments
Retrieves all entries containing the term 'golang' in either the comment or code, providing a basic filter for data related to the Go programming language.