comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
Validate if method exists in object.
@param object $objectInstance An object that requires method existing
validation
@param string $method Method name
@param string $name The parameter name
@return bool | public static function methodExists($objectInstance, $method, $name)
{
self::isString($method, 'method');
self::notNull($objectInstance, 'objectInstance');
self::isObject($objectInstance, 'objectInstance');
if (method_exists($objectInstance, $method)) {
return true;
} else {
throw new \InvalidArgumentException(
sprintf(
Resources::ERROR_METHOD_NOT_FOUND,
$method,
$name
)
);
}
} |
Filters the table according to given search string.<p>
@param search string to be looked for. | public void filterTable(String search) {
m_container.removeAllContainerFilters();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(search)) {
m_container.addContainerFilter(
new Or(
new SimpleStringFilter(PROP_USER, search, true, false),
new SimpleStringFilter(PROP_RESOURCES, search, true, false),
new SimpleStringFilter(PROP_PROJECT, search, true, false)));
}
} |
Use this method to apply an iterable of filters to
a stream. If lexer is given it's forwarded to the
filter, otherwise the filter receives `None`. | def apply_filters(stream, filters, lexer=None):
def _apply(filter_, stream):
for token in filter_.filter(lexer, stream):
yield token
for filter_ in filters:
stream = _apply(filter_, stream)
return stream |
If only one (or none) of the seed node children is not a leaf node
it is not possible to prune that edge and make a topology-changing
regraft. | def _check_single_outgroup(self):
root_child_nodes = self.tree._tree.seed_node.child_nodes()
not_leaves = np.logical_not([n.is_leaf() for n in root_child_nodes])
if not_leaves[not_leaves].size <= 1:
return [root_child_nodes[np.where(not_leaves)[0]].edge]
return [] |
// Convert_v1_ControllerConfig_To_config_ControllerConfig is an autogenerated conversion function. | func Convert_v1_ControllerConfig_To_config_ControllerConfig(in *v1.ControllerConfig, out *config.ControllerConfig, s conversion.Scope) error {
return autoConvert_v1_ControllerConfig_To_config_ControllerConfig(in, out, s)
} |
internal method, called by repaint to print text_center in the center | def print_center(htext, r = 0, c = 0)
win = @window
len = win.getmaxx
len = Ncurses.COLS-0 if len == 0 || len > Ncurses.COLS
#
win.printstring r, ((len-htext.length)/2).floor, htext, @color_pair, @attr
end |
Indirect the implementation of L{IWebViewer} to L{_AnonymousWebViewer}. | def indirect(self, interface):
if interface == IWebViewer:
return _AnonymousWebViewer(self.store)
return super(AnonymousSite, self).indirect(interface) |
Checks if a parameter exists. If it exists, it is left untouched. If it doesn't, it is created. Only works for parameters which key
is unique. Must be called from within an open transaction. | static void initSingleParam(String key, String initValue, DbConn cnx)
{
try
{
cnx.runSelectSingle("globalprm_select_by_key", 2, String.class, key);
return;
}
catch (NoResultException e)
{
GlobalParameter.create(cnx, key, initValue);
}
catch (NonUniqueResultException e)
{
// It exists! Nothing to do...
}
} |
refreshButtons - enables or disables buttons based on availability | function refreshButtons(editor) {
// Webkit requires focus before queryCommandEnabled will return anything but false
if (!iOS && $.browser.webkit && !editor.focused) {
editor.$frame[0].contentWindow.focus();
window.focus();
editor.focused = true;
}
// Get the object used for checking queryCommandEnabled
var queryObj = editor.doc;
if (ie) queryObj = getRange(editor);
// Loop through each button
var inSourceMode = sourceMode(editor);
$.each(editor.$toolbar.find("." + BUTTON_CLASS), function(idx, elem) {
var $elem = $(elem),
button = $.cleditor.buttons[$.data(elem, BUTTON_NAME)],
command = button.command,
enabled = true;
// Determine the state
if (editor.disabled)
enabled = false;
else if (button.getEnabled) {
var data = {
editor: editor,
button: elem,
buttonName: button.name,
popup: popups[button.popupName],
popupName: button.popupName,
command: button.command,
useCSS: editor.options.useCSS
};
enabled = button.getEnabled(data);
if (enabled === undefined)
enabled = true;
}
else if (((inSourceMode || iOS) && button.name != "source") ||
(ie && (command == "undo" || command == "redo")))
enabled = false;
else if (command && command != "print") {
if (ie && command == "hilitecolor")
command = "backcolor";
// IE does not support inserthtml, so it's always enabled
if (!ie || command != "inserthtml") {
try {enabled = queryObj.queryCommandEnabled(command);}
catch (err) {enabled = false;}
}
}
// Enable or disable the button
if (enabled) {
$elem.removeClass(DISABLED_CLASS);
$elem.removeAttr(DISABLED);
}
else {
$elem.addClass(DISABLED_CLASS);
$elem.attr(DISABLED, DISABLED);
}
});
} |
**
Выполните обратный вызов для каждого атрибута.
@param callable $callable
@return \Steein\Common\Collections\Collection | public function each(callable $callable)
{
foreach ($this->attributes as $key => $value)
{
if($callable($value, $key) === false)
break;
}
return $this;
} |
Create request token
@param array $data
@return RequestToken | public function createRequestToken(array $data = [])
{
$token = new RequestToken();
if (array_key_exists('expires_at', $data)) {
$token->setExpiresAt(new \DateTime($data['expires_at']));
}
if (array_key_exists('request_token', $data)) {
$token->setToken($data['request_token']);
}
if (array_key_exists('success', $data)) {
$token->setSuccess($data['success']);
}
return $token;
} |
Sends some data down the connection. | async def send(self, data: Union[bytes, str], final: bool = True):
MsgType = TextMessage if isinstance(data, str) else BytesMessage
data = MsgType(data=data, message_finished=final)
data = self._connection.send(event=data)
await self._sock.send_all(data) |
Outputs a single comment
@param $comment \asinfotrack\yii2\comments\models\Comment the comment model | protected function outputComment($comment)
{
if ($this->commentOptions instanceof \Closure) {
$options = call_user_func($this->commentOptions, $comment);
} else {
$options = $this->commentOptions;
}
$options = ArrayHelper::merge($options, ['data-comment-id'=>$comment->id]);
if ($this->useBootstrapClasses) Html::addCssClass($options, 'media');
//render comment
echo Html::beginTag('div', $options);
//body
$wrapperOptions = ['class'=>'comment-wrapper'];
if ($this->useBootstrapClasses) Html::addCssClass($wrapperOptions, 'media-body');
echo Html::beginTag('div', $wrapperOptions);
//title
if (!empty($comment->title)) {
$titleOptions = ['class'=>'comment-title'];
if ($this->useBootstrapClasses) Html::addCssClass($titleOptions, 'media-heading');
$title = $this->encodeCommentTitle ? Html::encode($comment->title) : $comment->title;
echo Html::tag($this->commentTitleTag, $title, $titleOptions);
}
//content
$content = $this->encodeCommentContents ? Html::encode($comment->content) : $comment->content;
echo Html::tag('div', $content, ['class'=>'comment-content']);
//meta
echo Html::beginTag('dl', ['class'=>'comment-meta']);
echo Html::tag('dt', Yii::t('app', 'Created'));
echo Html::tag('dd', Yii::$app->formatter->asDatetime($comment->created));
if (!empty($comment->updated) && $comment->updated != $comment->created) {
echo Html::tag('dt', Yii::t('app', 'Updated'));
echo Html::tag('dd', Yii::$app->formatter->asDatetime($comment->updated));
}
if (!empty($comment->user_id)) {
$author = $this->authorCallback === null ? $comment->created_by : call_user_func($this->authorCallback, $comment->created_by);
echo Html::tag('dt', Yii::t('app', 'Author'));
echo Html::tag('dd', $author);
}
echo Html::endTag('dl');
echo Html::endTag('div');
echo Html::endTag('div');
} |
Runs the given args in subprocess.Popen, and then calls the function
on_exit when the subprocess completes.
on_exit is a callable object, and args is a lists/tuple of args
that would give to subprocess.Popen. | def start_playing(self, on_exit, args):
# log.debug("%s,%s,%s" % (args['song_id'], args['song_name'], args['mp3_url']))
if "cache" in args.keys() and os.path.isfile(args["cache"]):
thread = threading.Thread(
target=self.run_mpg123, args=(on_exit, args["cache"])
)
else:
new_url = NetEase().songs_url([args["song_id"]])[0]["url"] #使用新地址
if not new_url: #如果没有获得新地址
new_url = args["mp3_url"] #使用老地址传给mpg123
thread = threading.Thread(
target=self.run_mpg123,
args=(on_exit, new_url, args["expires"], args["get_time"]),
)
cache_thread = threading.Thread(
target=self.download_song,
args=(
args["song_id"],
args["song_name"],
args["artist"],
args["mp3_url"],
),
)
cache_thread.start()
thread.start()
lyric_download_thread = threading.Thread(target=self.download_lyric)
lyric_download_thread.start()
tlyric_download_thread = threading.Thread(
target=self.download_lyric, args=(True,)
)
tlyric_download_thread.start()
# returns immediately after the thread starts
return thread |
---------------------------------------------------------- COLLECTIONS-------------------------------------------------------------------- | function getCollection(docdbClient, nodeContext) {
nodeContext.log(`Getting collection:\n${collectionName}\n`);
var colldef = {id : collectionName};
return new Promise((resolve, reject) => {
docdbClient.readCollection(collectionUrl, (err, result) => {
if (err) {
if (err.code == HttpStatusCodes.NOTFOUND) {
docdbClient.createCollection(databaseUrl, colldef, { offerThroughput: 400 }, (err, created) => {
if (err) reject(err)
else resolve(created);
});
} else {
reject(err);
}
} else {
resolve(result);
}
});
});
} |
Returns the environment name. | public static String getId(ClassLoader loader)
{
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof DynamicClassLoader) {
String name = ((DynamicClassLoader) loader).getId();
if (name != null)
return name;
else
return "";
}
}
return Thread.currentThread().getContextClassLoader().toString();
} |
Generate log friendly serialized identity for one or more ids
Limit to 1000 bytes
=== Parameters
ids(Array|String):: Serialized identity or array of serialized identities
=== Return
(String):: Log friendly serialized identity | def ids_to_s(ids)
if ids.is_a?(Array)
s = ids.each { |i| id_to_s(i) }.join(', ')
s.size > 1000 ? "[#{s[0, 1000]}...]" : "[#{s}]"
else
id_to_s(ids)
end
end |
Adds a query.
:param value: the query | def uri_query(self, value):
del self.uri_query
queries = value.split("&")
for q in queries:
option = Option()
option.number = defines.OptionRegistry.URI_QUERY.number
option.value = str(q)
self.add_option(option) |
// Walk traverses nodes
// Walk is invoked recursively until v.EnterNode returns true | func (n *ClassConstFetch) Walk(v walker.Visitor) {
if v.EnterNode(n) == false {
return
}
if n.Class != nil {
v.EnterChildNode("Class", n)
n.Class.Walk(v)
v.LeaveChildNode("Class", n)
}
if n.ConstantName != nil {
v.EnterChildNode("ConstantName", n)
n.ConstantName.Walk(v)
v.LeaveChildNode("ConstantName", n)
}
v.LeaveNode(n)
} |
@param string $name
@param string $language
@return bool | public function hasValue($name, $language = null)
{
if (!$language) {
$language = $this->defaultLanguage;
}
return isset($this->values[$language][$name]);
} |
Note: LocalStorage converts the value to string We are using empty string as a marker for null/undefined values. | function save(storage, name, value) {
try {
var key = propsPrefix + name;
if (value == null) value = '';
storage[key] = value;
} catch (err) {
console.log('Cannot access local/session storage:', err);
}
} |
Expires old cache entries. | def Expire(self):
""""""
while len(self._age) > self._limit:
node = self._age.PopLeft()
self._hash.pop(node.key, None)
self.KillObject(node.data) |
Access the invites
@return \Twilio\Rest\Chat\V1\Service\Channel\InviteList | protected function getInvites() {
if (!$this->_invites) {
$this->_invites = new InviteList(
$this->version,
$this->solution['serviceSid'],
$this->solution['sid']
);
}
return $this->_invites;
} |
After an it() spec we need to tear down the test case.
@param Spec $spec | public function afterSpec(Spec $spec)
{
$time = 0;
if ($spec->isFailed()) {
self::$result->addFailure(
self::$test,
new PHPUnit_Framework_AssertionFailedError(
$spec->exception
),
$time
);
} elseif ($spec->isIncomplete()) {
self::$result->addFailure(
self::$test,
new PHPUnit_Framework_IncompleteTestError(
$spec->exception
),
$time
);
}
self::$testCase->tearDown();
self::$result->endTest(self::$test, $time);
} |
Simplify where_in methods
@param mixed $key
@param mixed $val
@param string $in - The (not) in fragment
@param string $conj - The where in conjunction
@return self | protected function _whereIn($key, $val=[], string $in='IN', string $conj='AND'): self
{
$key = $this->driver->quoteIdent($key);
$params = array_fill(0, count($val), '?');
$this->state->appendWhereValues($val);
$conjunction = empty($this->state->getQueryMap()) ? ' WHERE ' : " {$conj} ";
$str = $key . " {$in} (".implode(',', $params).') ';
$this->state->appendMap($conjunction, $str, 'where_in');
return $this;
} |
Create the parameters available for evaluation. | private void loadSeqEvalParameters() {
this.seqevalParser.addArgument("--metric").required(false)
.choices("accuracy", "fmeasure").setDefault("fmeasure").help(
"Choose evaluation metric for Sequence Labeler; it defaults to fmeasure.\n");
this.seqevalParser.addArgument("-l", "--language").required(true)
.choices("de", "en", "es", "eu", "gl", "it", "nl").help("Choose language.\n");
this.seqevalParser.addArgument("-m", "--model").required(false)
.setDefault(Flags.DEFAULT_EVALUATE_MODEL)
.help("Pass the model to evaluate as a parameter.\n");
this.seqevalParser.addArgument("-t", "--testset").required(true)
.help("The test or reference corpus.\n");
this.seqevalParser.addArgument("--clearFeatures").required(false)
.choices("yes", "no", "docstart").setDefault(Flags.DEFAULT_FEATURE_FLAG)
.help("Reset the adaptive features; defaults to 'no'.\n");
this.seqevalParser.addArgument("-f", "--corpusFormat").required(false)
.choices("conll02", "conll03", "lemmatizer", "tabulated")
.setDefault(Flags.DEFAULT_EVAL_FORMAT).help(
"Choose format of reference corpus; it defaults to conll02 format.\n");
this.seqevalParser.addArgument("--evalReport").required(false)
.choices("brief", "detailed", "error").help(
"Choose level of detail of evaluation report; it defaults to detailed evaluation.\n");
this.seqevalParser.addArgument("--types").required(false)
.setDefault(Flags.DEFAULT_SEQUENCE_TYPES).help(
"Choose which Sequence types used for evaluation; the argument must be a comma separated"
+ " string; e.g., 'person,organization'.\n");
this.seqevalParser.addArgument("-u", "--unknownAccuracy").required(false)
.setDefault(Flags.DEFAULT_FEATURE_FLAG).help(
"Pass the model training set to evaluate unknown and known word accuracy.\n");
} |
Gerrit server-based time stamp when the event was created by Gerrit Server.
ONLY USE FOR UNIT TESTS!
@param eventCreatedOn the eventCreatedOn to set | public void setEventCreatedOn(String eventCreatedOn) {
Long milliseconds = TimeUnit.SECONDS.toMillis(Long.parseLong(eventCreatedOn));
this.eventCreatedOn = new Date(milliseconds);
} |
Read the context no-op flag from XML. | private boolean readContextNoOp(XMLEventReader reader)
throws XMLStreamException, JournalException {
readStartTag(reader, QNAME_TAG_NOOP);
String value = readCharactersUntilEndTag(reader, QNAME_TAG_NOOP);
return Boolean.valueOf(value).booleanValue();
} |
saves a new submission in the repo (done async) | def save(self, submission, result, grade, problems, tests, custom, archive): # pylint: disable=unused-argument
# Save submission to repo
self._logger.info("Save submission " + str(submission["_id"]) + " to git repo")
# Verify that the directory for the course exists
if not os.path.exists(os.path.join(self.repopath, submission["courseid"])):
os.mkdir(os.path.join(self.repopath, submission["courseid"]))
# Idem with the task
if not os.path.exists(os.path.join(self.repopath, submission["courseid"], submission["taskid"])):
os.mkdir(os.path.join(self.repopath, submission["courseid"], submission["taskid"]))
# Idem with the username, but empty it
dirname = os.path.join(self.repopath, submission["courseid"], submission["taskid"], str.join("-", submission["username"]))
if os.path.exists(dirname):
shutil.rmtree(dirname)
os.mkdir(dirname)
# Now we can put the input, the output and the zip
open(os.path.join(dirname, 'submitted_on'), "w+").write(str(submission["submitted_on"]))
open(os.path.join(dirname, 'input.yaml'), "w+").write(inginious.common.custom_yaml.dump(submission["input"]))
result_obj = {
"result": result[0],
"text": result[1],
"problems": problems
}
open(os.path.join(dirname, 'result.yaml'), "w+").write(inginious.common.custom_yaml.dump(result_obj))
if archive is not None:
os.mkdir(os.path.join(dirname, 'output'))
tar = tarfile.open(mode='r:gz', fileobj=io.BytesIO(archive))
tar.extractall(os.path.join(dirname, 'output'))
tar.close()
self.git.add('--all', '.')
title = " - ".join([str(submission["courseid"]) + "/" + str(submission["taskid"]),
str(submission["_id"]),
str.join("-", submission["username"]),
("success" if result[0] == "success" else "failed")])
self.git.commit('-m', title) |
设置ç
@param field
@param value
@return | public boolean set(String field, Object value) {
boolean result = false;
if(value == null)return false;
//返回值(1:新字段被设置,0:已经存在值被更新)
try {
if (isCluster(groupName)) {
result = getBinaryJedisClusterCommands(groupName)
.hset(keyBytes, SafeEncoder.encode(field), valueSerialize(value)) >= 0;
} else {
result = getBinaryJedisCommands(groupName).hset(keyBytes, SafeEncoder.encode(field), valueSerialize(value)) >= 0;
}
//设置超时时间
if(result)setExpireIfNot(expireTime);
return result;
} finally {
getJedisProvider(groupName).release();
}
} |
Default search options.
@param \Cake\Datasource\RepositoryInterface $table Table instance
@return mixed[] | public static function getDefaults(RepositoryInterface $table): array
{
$result['display_columns'] = static::getListingFields($table);
$result['sort_by_field'] = current($result['display_columns']);
$result['sort_by_order'] = static::DEFAULT_SORT_BY_ORDER;
$result['aggregator'] = static::DEFAULT_AGGREGATOR;
return $result;
} |
Deserializes given InputStream to an Object using Kryo instance in pool.
@param stream input stream
@param <T> deserialized Object type
@param bufferSize size of the buffer in front of the stream
@return deserialized Object | public <T> T deserialize(final InputStream stream, final int bufferSize) {
ByteBufferInput in = new ByteBufferInput(stream, bufferSize);
Kryo kryo = borrow();
try {
@SuppressWarnings("unchecked")
T obj = (T) kryo.readClassAndObject(in);
return obj;
} finally {
release(kryo);
}
} |
Issue a log message at the given log level using {@link java.text.MessageFormat}-style formatting.
@param level the level
@param t the throwable
@param format the message format string
@param params the parameters | public void logv(Level level, Throwable t, String format, Object... params) {
doLog(level, FQCN, format, params, t);
} |
// LogRequestObject fills in the request object into an audit event. The passed runtime.Object
// will be converted to the given gv. | func LogRequestObject(ae *auditinternal.Event, obj runtime.Object, gvr schema.GroupVersionResource, subresource string, s runtime.NegotiatedSerializer) {
if ae == nil || ae.Level.Less(auditinternal.LevelMetadata) {
return
}
// complete ObjectRef
if ae.ObjectRef == nil {
ae.ObjectRef = &auditinternal.ObjectReference{}
}
// meta.Accessor is more general than ObjectMetaAccessor, but if it fails, we can just skip setting these bits
if meta, err := meta.Accessor(obj); err == nil {
if len(ae.ObjectRef.Namespace) == 0 {
ae.ObjectRef.Namespace = meta.GetNamespace()
}
if len(ae.ObjectRef.Name) == 0 {
ae.ObjectRef.Name = meta.GetName()
}
if len(ae.ObjectRef.UID) == 0 {
ae.ObjectRef.UID = meta.GetUID()
}
if len(ae.ObjectRef.ResourceVersion) == 0 {
ae.ObjectRef.ResourceVersion = meta.GetResourceVersion()
}
}
if len(ae.ObjectRef.APIVersion) == 0 {
ae.ObjectRef.APIGroup = gvr.Group
ae.ObjectRef.APIVersion = gvr.Version
}
if len(ae.ObjectRef.Resource) == 0 {
ae.ObjectRef.Resource = gvr.Resource
}
if len(ae.ObjectRef.Subresource) == 0 {
ae.ObjectRef.Subresource = subresource
}
if ae.Level.Less(auditinternal.LevelRequest) {
return
}
// TODO(audit): hook into the serializer to avoid double conversion
var err error
ae.RequestObject, err = encodeObject(obj, gvr.GroupVersion(), s)
if err != nil {
// TODO(audit): add error slice to audit event struct
klog.Warningf("Auditing failed of %v request: %v", reflect.TypeOf(obj).Name(), err)
return
}
} |
Internal
Internal: Check if this heuristic matches the candidate filenames or
languages. | def matches?(filename, candidates)
filename = filename.downcase
candidates = candidates.compact.map(&:name)
@exts_and_langs.any? { |ext| filename.end_with?(ext) }
end |
gets rtf code of font
@return string rtf code | public function getContent()
{
$content = '';
if ($this->_size > 0) {
$content .= '\fs' . ($this->_size * 2) . ' ';
}
if ($this->_fontFamily && $this->_fontTable) {
$fontIndex = $this->_fontTable->getFontIndex($this->_fontFamily);
if ($fontIndex !== false) {
$content .= '\f' . $fontIndex . ' ';
}
}
if ($this->_color && $this->_colorTable) {
$colorIndex = $this->_colorTable->getColorIndex($this->_color);
if ($colorIndex !== false) {
$content .= '\cf' . $colorIndex . ' ';
}
}
if ($this->_backgroundColor && $this->_colorTable) {
$colorIndex = $this->_colorTable->getColorIndex($this->_backgroundColor);
if ($colorIndex !== false) {
$content .= '\chcbpat' . $colorIndex . ' ';
}
}
if ($this->_isBold) {
$content .= '\b ';
}
if ($this->_isItalic) {
$content .= '\i ';
}
if ($this->_isUnderlined) {
$content .= '\ul ';
}
if ($this->_animation) {
$content .= '\animtext' . $this->_animation;
}
if ($this->_isStriked) {
$content .= '\strike ' . $this->_animation;
}
elseif ($this->_isDoubleStriked) {
$content .= '\striked1 ' . $this->_animation;
}
return $content;
} |
Collect terms by prefixes for list of hit positions.
@param field
the field
@param docId
the doc id
@param prefixes
the prefixes
@param positionsHits
the positions hits
@throws IOException
Signals that an I/O exception has occurred. | public void collectTermsByPrefixesForListOfHitPositions(String field,
int docId, ArrayList<String> prefixes,
ArrayList<IntervalTreeNodeData<String>> positionsHits)
throws IOException {
IndexDoc doc = getDoc(field, docId);
IndexInput inIndexObjectPosition = indexInputList
.get("indexObjectPosition");
IndexInput inTerm = indexInputList.get("term");
// create tree interval hits
IntervalRBTree<String> positionTree = new IntervalRBTree<String>(
positionsHits);
// find prefixIds
Map<String, Integer> prefixIds = getPrefixesIds(field, prefixes);
// search matching tokens
if (prefixIds != null) {
CodecSearchTree.searchMtasTreeWithIntervalTree(prefixIds.values(),
positionTree, inIndexObjectPosition, doc.fpIndexObjectPosition,
doc.smallestObjectFilepointer);
// reverse list
Map<Integer, String> idPrefixes = new HashMap<>();
for (Entry<String, Integer> entry : prefixIds.entrySet()) {
idPrefixes.put(entry.getValue(), entry.getKey());
}
// term administration
Map<Long, String> refTerms = new HashMap<>();
for (IntervalTreeNodeData<String> positionHit : positionsHits) {
for (MtasTreeHit<String> hit : positionHit.list) {
if (hit.idData == null) {
hit.idData = idPrefixes.get(hit.additionalId);
if (!refTerms.containsKey(hit.additionalRef)) {
refTerms.put(hit.additionalRef,
MtasCodecPostingsFormat.getTerm(inTerm, hit.additionalRef));
}
hit.refData = refTerms.get(hit.additionalRef);
}
}
}
}
} |
Prompts user to input a date in the past. | def pastdate(self, prompt, default=None):
""""""
prompt = prompt if prompt is not None else "Enter a past date"
if default is not None:
prompt += " [" + default.strftime('%d %m %Y') + "]"
prompt += ': '
return self.input(curry(filter_pastdate, default=default), prompt) |
Wraps the supplied contents in a scroll panel with the specified maximum height. | public static ScrollPanel newScrollPanelY (Widget contents, int maxHeight)
{
ScrollPanel panel = new ScrollPanel(contents);
DOM.setStyleAttribute(panel.getElement(), "maxHeight", maxHeight + "px");
return panel;
} |
Create the import job.
@param projects the projects to import.
@return the import job. | protected WorkspaceJob createImportJob(Collection<MavenProjectInfo> projects) {
final WorkspaceJob job = new ImportMavenSarlProjectsJob(projects, this.workingSets, this.importConfiguration);
job.setRule(MavenPlugin.getProjectConfigurationManager().getRule());
return job;
} |
Find which resources are missing on the local disk for the requested CMU motion capture motions. | def cmu_urls_files(subj_motions, messages = True):
'''
'''
dr = data_resources['cmu_mocap_full']
cmu_url = dr['urls'][0]
subjects_num = subj_motions[0]
motions_num = subj_motions[1]
resource = {'urls' : [], 'files' : []}
# Convert numbers to strings
subjects = []
motions = [list() for _ in range(len(subjects_num))]
for i in range(len(subjects_num)):
curSubj = str(int(subjects_num[i]))
if int(subjects_num[i]) < 10:
curSubj = '0' + curSubj
subjects.append(curSubj)
for j in range(len(motions_num[i])):
curMot = str(int(motions_num[i][j]))
if int(motions_num[i][j]) < 10:
curMot = '0' + curMot
motions[i].append(curMot)
all_skels = []
assert len(subjects) == len(motions)
all_motions = []
for i in range(len(subjects)):
skel_dir = os.path.join(data_path, 'cmu_mocap')
cur_skel_file = os.path.join(skel_dir, subjects[i] + '.asf')
url_required = False
file_download = []
if not os.path.exists(cur_skel_file):
# Current skel file doesn't exist.
if not os.path.isdir(skel_dir):
os.makedirs(skel_dir)
# Add skel file to list.
url_required = True
file_download.append(subjects[i] + '.asf')
for j in range(len(motions[i])):
file_name = subjects[i] + '_' + motions[i][j] + '.amc'
cur_motion_file = os.path.join(skel_dir, file_name)
if not os.path.exists(cur_motion_file):
url_required = True
file_download.append(subjects[i] + '_' + motions[i][j] + '.amc')
if url_required:
resource['urls'].append(cmu_url + '/' + subjects[i] + '/')
resource['files'].append(file_download)
return resource |
Compute the number of antenna for the
given number of baselines. Can specify whether
auto-correlations should be taken into
account | def nr_of_antenna(nbl, auto_correlations=False):
t = 1 if auto_correlations is False else -1
return int(t + math.sqrt(1 + 8*nbl)) // 2 |
Get available and assigned routes
@return array | public function getRoutes()
{
$manager = Configs::authManager();
///[yii2-brainbase v0.3.0 (admin:rbac):fix Added multi app (frontend/backend)]@see https://github.com/mdmsoft/yii2-admin/pull/309/
// Get advanced configuration
$advanced = Configs::instance()->advanced;
if ($advanced) {
// Use advanced route scheme.
// Set advanced route prefix.
$this->_routePrefix = self::PREFIX_ADVANCED;
// Create empty routes array.
$routes = [];
// Step through each configured application
foreach ($advanced as $id => $configPaths) {
///[2.6.7 (CHG# advanced, \yongtiger\application\Application::remoteAppConfigs)]
Application::remoteAppCall($id, function ($app) use (&$routes, $id) {
// Prepend the app id to all routes.
foreach ($this->getAppRoutes($app) as $route) {
// Force correct id string.
$id = $this->routePrefix . ltrim(trim($id), $this->routePrefix);
$routes[$id . $route] = $id . $route;
}
}, function ($config) {
unset($config['bootstrap']); ///[yii2-brainbase v0.3.0 (admin:rbac):fix Yii debug disappear in route]
return $config;
});
}
} else {
// Use basic route scheme.
// Set basic route prefix
$this->_routePrefix = self::PREFIX_BASIC;
// Get basic app routes.
$routes = $this->getAppRoutes();
}
///[http://www.brainbook.cc]
$exists = [];
foreach (array_keys($manager->getPermissions()) as $name) {
// if ($name[0] !== '/') {
if ($name[0] !== $this->routePrefix) { ///[yii2-brainbase v0.3.0 (admin:rbac):fix Added multi app (frontend/backend)]@see https://github.com/mdmsoft/yii2-admin/pull/309/
continue;
}
$exists[] = $name;
unset($routes[$name]);
}
return [
'available' => array_keys($routes),
'assigned' => $exists,
];
} |
反射调用对象方法, 无视private/protected修饰符.
根据参数类型参数进行匹配, 支持方法参数定义是接口,父类,原子类型等情况
性能较低,仅用于单次调用. | public static <T> T invokeMethod(final Object obj, final String methodName, final Object[] args,
final Class<?>[] parameterTypes) {
Method method = getMethod(obj.getClass(), methodName, parameterTypes);
if (method == null) {
throw new IllegalArgumentException("Could not find method [" + methodName + "] with parameter types:"
+ ObjectUtil.toPrettyString(parameterTypes) + " on class [" + obj.getClass() + ']');
}
return invokeMethod(obj, method, args);
} |
Adds an YAxis to the chart. You can use {@link #setyAxis(Axis)} if you want
to define a single axis only.
@param yAxis the YAxis to add.
@return the {@link Options} object for chaining. | public Options addyAxis(final Axis yAxis) {
if (this.getyAxis() == null) {
this.setyAxis(new ArrayList<Axis>());
}
this.getyAxis().add(yAxis);
return this;
} |
一次性计算多种分词结果的三元模型分值
@param sentences 多种分词结果
@return 分词结果及其对应的分值 | public static Map<List<Word>, Float> trigram(List<Word>... sentences){
Map<List<Word>, Float> map = new HashMap<>();
//计算多种分词结果的分值
for(List<Word> sentence : sentences){
if(map.get(sentence) != null){
//相同的分词结果只计算一次分值
continue;
}
float score=0;
//计算其中一种分词结果的分值
if(sentence.size() > 2){
for(int i=0; i<sentence.size()-2; i++){
String first = sentence.get(i).getText();
String second = sentence.get(i+1).getText();
String third = sentence.get(i+2).getText();
float trigramScore = getScore(first, second, third);
if(trigramScore > 0){
score += trigramScore;
}
}
}
map.put(sentence, score);
}
return map;
} |
Set the Company currently valid for this context.
@param _company Company to set
@throws CacheReloadException on error | public void setCompany(final Company _company)
throws CacheReloadException
{
if (_company == null) {
this.companyId = null;
} else {
this.companyId = _company.getId();
}
} |
Deletes thumbnail from S3 storage or locally
@param string $path | protected function deleteThumbnail($path)
{
if(file_exists($path)) {
if(is_dir($path)) {
if($this->config['s3']['localThumbsPath']) {
$this->unlinkRecursive($path);
} else {
$key = $this->getDynamicPath($path, false);
$this->s3->batchDelete($key);
}
} else {
unlink($path);
}
}
} |
Get the value of a config item for a particular user.
@param string $key key to fetch
@param int $userid id of user (defaults to current)
@return string the corresponding value | public final function get_user_config($key, $userid=0) {
global $DB;
if (empty($userid)) {
$userid = $this->user->id;
}
if ($key != 'visible') { // handled by the parent class
if (!in_array($key, $this->get_allowed_user_config())) {
$a = (object)array('property' => $key, 'class' => get_class($this));
throw new portfolio_export_exception($this->get('exporter'), 'invaliduserproperty', 'portfolio', null, $a);
}
}
if (!array_key_exists($userid, $this->userconfig)) {
$this->userconfig[$userid] = (object)array_fill_keys(array_merge(array('visible'), $this->get_allowed_user_config()), null);
foreach ($DB->get_records('portfolio_instance_user', array('instance' => $this->id, 'userid' => $userid)) as $config) {
$this->userconfig[$userid]->{$config->name} = $config->value;
}
}
if ($this->userconfig[$userid]->visible === null) {
$this->set_user_config(array('visible' => 1), $userid);
}
return $this->userconfig[$userid]->{$key};
} |
Start this service.
Override this to do all the startup.
@return true if successful. | public Object startupService(BundleContext bundleContext)
{
Map<String,Object> props = this.getServiceProperties();
Environment env = (Environment)this.getService(Env.class);
props = Utility.putAllIfNew(props, env.getProperties()); // Use the same params as environment
// Note the order that I do this... this is because MainApplication may need access to the remoteapp during initialization
App app = env.getMessageApplication(true, props);
Task task = new AutoTask(app, null, props);
return this.createMessageService(task, null, props);
} |
Register all checkers of TwistedChecker to C{PyLinter}.
@return: a list of allowed messages | def registerCheckers(self):
# We patch the default pylint format checker.
patch_pylint_format.patch()
# register checkers
allowedMessages = list(self.allowedMessagesFromPylint)
for strChecker in self.checkers:
modname, classname = strChecker.split(".")
strModule = "twistedchecker.checkers.%s" % modname
checker = getattr(__import__(strModule,
fromlist=["twistedchecker.checkers"]),
classname)
instanceChecker = checker(self.linter)
allowedMessages += list(instanceChecker.msgs.keys())
self.linter.register_checker(instanceChecker)
self.restrictCheckers(allowedMessages)
return set(allowedMessages) |
// ListIPv4 lists the IPv4 information of a virtual machine | func (c *Client) ListIPv4(id string) (list []IPv4, err error) {
var ipMap map[string][]IPv4
if err := c.get(`server/list_ipv4?SUBID=`+id+`&public_network=yes`, &ipMap); err != nil {
return nil, err
}
for _, iplist := range ipMap {
for _, ip := range iplist {
list = append(list, ip)
}
}
sort.Sort(ipv4s(list))
return list, nil
} |
Adds a float
@param f Float
@throws IllegalStateException see {@link #checkBuilt()} | public synchronized PacketBuilder withFloat(final float f)
{
checkBuilt();
try
{
dataOutputStream.writeFloat(f);
}
catch (final IOException e)
{
logger.error("Unable to add float: {} : {}", e.getClass(), e.getMessage());
}
return this;
} |
Returns a JSON array containing the FormZ configuration.
@return string | protected function getFormzConfiguration()
{
$rootConfigurationArray = $this->getFormObject()
->getConfiguration()
->getRootConfiguration()
->toArray();
$cleanFormzConfigurationArray = [
'view' => $rootConfigurationArray['view']
];
return ArrayService::get()->arrayToJavaScriptJson($cleanFormzConfigurationArray);
} |
Find a username by email address
@param string $email Email address to look up
@return mixed False if not found, string if found | public static function find_by_email($email)
{
if (empty($email))
{
return false;
}
$db = \App::get('db');
$db->setQuery("SELECT username FROM `#__xprofiles` WHERE `email`=" . $db->quote($email));
$result = $db->loadColumn();
if (empty($result))
{
return false;
}
return $result;
} |
make limit and ttl required | def decorate(self, func, limit, ttl, *anoop, **kwnoop):
""""""
return super(ratelimit, self).decorate(func, limit, ttl, *anoop, **kwnoop) |
函数具体逻辑
@param scope 上下文
@return 计算好的节点 | @Override
public XValue call(Scope scope) {
NodeTest textFun = Scanner.findNodeTestByName("allText");
XValue textVal = textFun.call(scope);
String whole = StringUtils.join(textVal.asList(),"");
Matcher matcher = numExt.matcher(whole);
if (matcher.find()){
String numStr = matcher.group();
BigDecimal num = new BigDecimal(numStr);
return XValue.create(num.doubleValue());
}else {
return XValue.create(null);
}
} |
Find an existing {@link PerformanceMonitorBean}
@param name the value for the {@link PerformanceMonitorBean}
@return the found {@link PerformanceMonitorBean}, or null if it is not
found. | public PerformanceMonitorBean findPerformanceMonitorBean(String name) {
PerformanceMonitor performanceMonitor = findPerformanceMonitor(name);
if (performanceMonitor instanceof PerformanceMonitorBean) {
return (PerformanceMonitorBean)performanceMonitor;
}
return null;
} |
Add the given targets to the given rule
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.put_targets myrule [{'Id': 'target1', 'Arn': 'arn:***'}] | def put_targets(Rule, Targets,
region=None, key=None, keyid=None, profile=None):
'''
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(Targets, six.string_types):
Targets = salt.utils.json.loads(Targets)
failures = conn.put_targets(Rule=Rule, Targets=Targets)
if failures and failures.get('FailedEntryCount', 0) > 0:
return {'failures': failures.get('FailedEntries')}
else:
return {'failures': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':
return {'error': "Rule {0} not found".format(Rule)}
return {'error': __utils__['boto3.get_error'](e)} |
// Set implements DB.Set, as documented in the leveldb/db package. | func (m *MemDB) Set(key, value []byte, o *db.WriteOptions) error {
m.mutex.Lock()
defer m.mutex.Unlock()
// Find the node, and its predecessors at all heights.
var prev [maxHeight]int
n, exactMatch := m.findNode(key, &prev)
if exactMatch {
m.nodeData[n+fVal] = m.save(value)
return nil
}
// Choose the new node's height, branching with 25% probability.
h := 1
for h < maxHeight && rand.Intn(4) == 0 {
h++
}
// Raise the skiplist's height to the node's height, if necessary.
if m.height < h {
for i := m.height; i < h; i++ {
prev[i] = headNode
}
m.height = h
}
// Insert the new node.
var x [fNxt + maxHeight]int
n1 := len(m.nodeData)
x[fKey] = m.save(key)
x[fVal] = m.save(value)
for i := 0; i < h; i++ {
j := prev[i] + fNxt + i
x[fNxt+i] = m.nodeData[j]
m.nodeData[j] = n1
}
m.nodeData = append(m.nodeData, x[:fNxt+h]...)
return nil
} |
taobao.fenxiao.discounts.get 获取折扣信息
查询折扣信息 | def get(self, session, discount_id=None, ext_fields=None):
''''''
request = TOPRequest('taobao.fenxiao.discounts.get')
if discount_id!=None: request['discount_id'] = discount_id
if ext_fields!=None: request['ext_fields'] = ext_fields
self.create(self.execute(request, session))
return self.discounts |
Returns the name of the field by number.
@param int $num
The number of the field.
@return string|null
Returns the name of the field by number.
@see field_by_num()
@see field_info_by_num()
@author Oleg Schildt | public function field_name($num)
{
$info = $this->field_info_by_num($num);
if (!$info) {
return null;
}
return \SmartFactory\checkempty($info["name"]);
} |
Parse input arguments of script.
:param args: list of parameters
:type: argparse.Namespace
:param cfg: configuration storage
:type: Config | def parse_args(args, cfg):
prog = pathlib.Path(sys.argv[0]).parts[-1].replace('.py', '')
prog_version = "%%(prog)s %s" % versionner.__version__
# pylint: disable=invalid-name
p = argparse.ArgumentParser(prog=prog, description='Helps manipulating version of the project')
p.add_argument('--file', '-f', dest='version_file', type=str,
default=cfg.version_file,
help="path to file where version is saved")
p.add_argument('--version', '-v', action="version", version=prog_version)
p.add_argument('--date-format', type=str,
default=cfg.date_format,
help="Date format used in project files")
p.add_argument('--verbose', action="store_true",
help="Be more verbose if it's possible")
sub = p.add_subparsers(dest='command')
p_init = sub.add_parser('init', aliases=commands.get_aliases_for('init'),
help="Create new version file")
p_init.add_argument('value', nargs='?', type=str,
default=cfg.default_init_version,
help="Initial version")
p_init.add_argument('--vcs-engine', type=str,
default=cfg.vcs_engine,
help="Select VCS engine (only git is supported currently)", )
p_init.add_argument('--vcs-commit-message', '-m', type=str,
default=cfg.vcs_commit_message,
help="Commit message used when committing changes")
p_init.add_argument('--commit', '-c', action='store_true',
help="Commit changes done by `up` command (only if there is no changes in repo before)")
p_up = sub.add_parser('up', aliases=commands.get_aliases_for('up'),
help="Increase version")
p_up.add_argument('--vcs-engine', type=str,
default=cfg.vcs_engine,
help="Select VCS engine (only git is supported currently)", )
p_up.add_argument('--vcs-commit-message', '-m', type=str,
default=cfg.vcs_commit_message,
help="Commit message used when committing changes")
p_up.add_argument('--commit', '-c', action='store_true',
help="Commit changes done by `up` command (only if there is no changes in repo before)")
p_up.add_argument('value', nargs='?', type=int,
default=cfg.default_increase_value,
help="Increase version by this value (default: %d)" % cfg.default_increase_value)
p_up_gr = p_up.add_mutually_exclusive_group()
p_up_gr.add_argument('--major', '-j', action="store_true",
help="increase major part of version" + (" (project default)" if cfg.up_part == 'major' else ""))
p_up_gr.add_argument('--minor', '-n', action="store_true",
help="increase minor part of version" + (" (project default)" if cfg.up_part == 'minor' else ""))
p_up_gr.add_argument('--patch', '-p', action="store_true",
help="increase patch part of version" + (" (project default)" if cfg.up_part == 'patch' else ""))
p_set = sub.add_parser('set', aliases=commands.get_aliases_for('set'),
help="Set version to specified one")
p_set.add_argument('--major', '-j', type=int,
help="set major part of version to MAJOR")
p_set.add_argument('--minor', '-n', type=int,
help="set minor part of version to MINOR")
p_set.add_argument('--patch', '-p', type=int,
help="set patch part of version to PATCH")
p_set.add_argument('--prerelease', '-r', type=str,
help="set prerelease part of version to PRERELEASE")
p_set.add_argument('--build', '-b', type=str,
help="set build part of version to BUILD")
p_set.add_argument('--vcs-engine', type=str,
default=cfg.vcs_engine,
help="Select VCS engine (only git is supported currently)", )
p_set.add_argument('--vcs-commit-message', '-m', type=str,
default=cfg.vcs_commit_message,
help="Commit message used when committing changes")
p_set.add_argument('--commit', '-c', action='store_true',
help="Commit changes done by `set` command (only if there is no changes in repo before)")
p_set.add_argument('value', nargs='?', type=str,
help="set version to this value")
p_tag = sub.add_parser('tag', aliases=commands.get_aliases_for('tag'),
help="Create VCS tag with current version")
p_tag.add_argument('--vcs-tag-param', dest='vcs_tag_params', type=str, action="append",
help="Additional params for VCS for \"tag\" command")
sub.add_parser('read', aliases=commands.get_aliases_for('read'),
help="Read current version")
args = p.parse_args(args)
cfg.command = args.command
cfg.version_file = pathlib.Path(args.version_file).absolute()
cfg.date_format = args.date_format
cfg.verbose = args.verbose
version_file_requirement = 'doesn\'t matter'
if cfg.command == 'init':
version_file_requirement = 'none'
cfg.commit = args.commit
cfg.vcs_engine = args.vcs_engine
cfg.vcs_commit_message = args.vcs_commit_message
cfg.value = args.value
elif cfg.command == 'up':
version_file_requirement = 'required'
cfg.commit = args.commit
cfg.vcs_engine = args.vcs_engine
cfg.vcs_commit_message = args.vcs_commit_message
cfg.value = args.value
if args.major:
cfg.up_part = 'major'
elif args.minor:
cfg.up_part = 'minor'
elif args.patch:
cfg.up_part = 'patch'
elif cfg.command == 'set':
version_file_requirement = 'required'
cfg.commit = args.commit
cfg.vcs_engine = args.vcs_engine
cfg.vcs_commit_message = args.vcs_commit_message
if args.value:
cfg.value = args.value
else:
cfg.value = (
args.major, args.minor, args.patch,
args.prerelease, args.build
)
if all(value is None for value in cfg.value):
p.error("Version is not specified")
elif cfg.command == 'tag':
version_file_requirement = 'required'
cfg.vcs_tag_params = args.vcs_tag_params or []
elif cfg.command is None:
cfg.command = 'read'
version_file_requirement = 'required'
if version_file_requirement == 'required':
if not cfg.version_file.exists():
p.error("Version file \"%s\" doesn't exists" % cfg.version_file)
elif version_file_requirement == 'none':
if cfg.version_file.exists():
p.error("Version file \"%s\" already exists" % cfg.version_file) |
// XXX_OneofFuncs is for the internal use of the proto package. | func (*ConfigSource) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _ConfigSource_OneofMarshaler, _ConfigSource_OneofUnmarshaler, _ConfigSource_OneofSizer, []interface{}{
(*ConfigSource_Path)(nil),
(*ConfigSource_ApiConfigSource)(nil),
(*ConfigSource_Ads)(nil),
}
} |
Set logging levels for given loggers. | def set_loglevel(loggers, level):
""""""
if not loggers:
return
if 'all' in loggers:
loggers = lognames.keys()
for key in loggers:
logging.getLogger(lognames[key]).setLevel(level) |
// Wrap wraps the specified ModelCommand, returning a ModelCommand
// that proxies to each of the ModelCommand methods.
// Any provided options are applied to the wrapped command
// before it is returned. | func Wrap(c ModelCommand, options ...WrapOption) ModelCommand {
wrapper := &modelCommandWrapper{
ModelCommand: c,
skipModelFlags: false,
useDefaultModel: true,
}
for _, option := range options {
option(wrapper)
}
// Define a new type so that we can embed the ModelCommand
// interface one level deeper than cmd.Command, so that
// we'll get the Command methods from WrapBase
// and all the ModelCommand methods not in cmd.Command
// from modelCommandWrapper.
type embed struct {
*modelCommandWrapper
}
return struct {
embed
cmd.Command
}{
Command: WrapBase(wrapper),
embed: embed{wrapper},
}
} |
md5 加密
@link http://www.w3school.com.cn/php/func_string_md5.asp
@param $sTmp
@param bool $bDefault false 32位, true 15位
@param null $sRtn
@param string $sDesc
@return int | public static function MD5( $sTmp, $bDefault = true )
{
$sRtn = null;
if( CLib::SafeStringVal( $sTmp ) )
{
$sRtn = self::MD5( $sTmp, $bDefault );
}
return $sRtn;
} |
//
// UnmarshalJSON is defined for proper JSON decoding of a ExceptionDef
// | func (self *ExceptionDef) UnmarshalJSON(b []byte) error {
var m rawExceptionDef
err := json.Unmarshal(b, &m)
if err == nil {
o := ExceptionDef(m)
*self = o
err = self.Validate()
}
return err
} |
// Dt14ForTime returns a Dt14 value given a time.Time struct. | func Dt14ForTime(t time.Time) int64 {
u := t.UTC()
s := u.Format(DT14)
iDt14, err := strconv.ParseInt(s, 10, 64)
if err != nil {
panic(err)
}
return int64(iDt14)
} |
EndAdvertisement on a running channel.
@param Channel|string $channel Channel data or channel Id
@param mixed $cueId
@return Operation | public function sendEndAdvertisementChannelOperation($channel, $cueId)
{
$channelId = Utilities::getEntityId(
$channel,
'WindowsAzure\MediaServices\Models\Channel'
);
$headers = [
Resources::CONTENT_TYPE => Resources::JSON_CONTENT_TYPE,
];
$body = json_encode([
'cueId' => $cueId,
]);
return $this->_sendOperation(
$body,
"Channels('{$channelId}')/EndAdvertisement",
Resources::HTTP_POST,
Resources::STATUS_ACCEPTED,
$headers);
} |
@param string $format
@return Org_Heigl\DateFormatter\Formatter\FormatterInterface | public static function getFormatter($format)
{
foreach (self::getList() as $class => $path) {
if (! in_array(strtolower($format), array_map('strtolower', $class::getFormatString()))) {
continue;
}
return new $class();
}
throw new UnknownFormatException('There is no formater for this format');
} |
// Delete marks this job as complete by deleting it form the database.
//
// You must also later call Done() to return this job's database connection to
// the pool. | func (j *Job) Delete() error {
j.mu.Lock()
defer j.mu.Unlock()
if j.deleted {
return nil
}
_, err := j.conn.Exec("que_destroy_job", j.Queue, j.Priority, j.RunAt, j.ID)
if err != nil {
return err
}
j.deleted = true
return nil
} |
Renders the correct title of the current page. The correct title is either the title provided by the SEO
extension, or the title of the content, if the SEO extension does not provide one.
@deprecated use the twig include function to render the seo | public function renderSeoTags(
\Twig_Environment $twig,
array $seoExtension,
array $content,
array $urls,
$shadowBaseLocale
) {
$template = 'SuluWebsiteBundle:Extension:seo.html.twig';
@trigger_error(sprintf(
'This twig extension is deprecated and should not be used anymore, include the "%s".',
$template
));
$defaultLocale = null;
$portal = $this->requestAnalyzer->getPortal();
if ($portal) {
$defaultLocale = $portal->getXDefaultLocalization()->getLocale();
}
return $twig->render(
$template,
[
'seo' => $seoExtension,
'content' => $content,
'urls' => $urls,
'defaultLocale' => $defaultLocale,
'shadowBaseLocale' => $shadowBaseLocale,
]
);
} |
Marshall the given parameter object. | public void marshall(JobExecutionsRolloutConfig jobExecutionsRolloutConfig, ProtocolMarshaller protocolMarshaller) {
if (jobExecutionsRolloutConfig == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(jobExecutionsRolloutConfig.getMaximumPerMinute(), MAXIMUMPERMINUTE_BINDING);
protocolMarshaller.marshall(jobExecutionsRolloutConfig.getExponentialRate(), EXPONENTIALRATE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
// NewWithOptions returns a stdlib logger that implements the Gournal Appender
// interface. | func NewWithOptions(out io.Writer, prefix string, flags int) gournal.Appender {
return &appender{log.New(out, prefix, flags)}
} |
decorator(caller) converts a caller function into a decorator | def decorator(caller, _func=None):
""""""
if _func is not None: # return a decorated function
# this is obsolete behavior; you should use decorate instead
return decorate(_func, caller)
# else return a decorator function
defaultargs, defaults = '', ()
if inspect.isclass(caller):
name = caller.__name__.lower()
doc = 'decorator(%s) converts functions/generators into ' \
'factories of %s objects' % (caller.__name__, caller.__name__)
elif inspect.isfunction(caller):
if caller.__name__ == '<lambda>':
name = '_lambda_'
else:
name = caller.__name__
doc = caller.__doc__
nargs = caller.__code__.co_argcount
ndefs = len(caller.__defaults__ or ())
defaultargs = ', '.join(caller.__code__.co_varnames[nargs-ndefs:nargs])
if defaultargs:
defaultargs += ','
defaults = caller.__defaults__
else: # assume caller is an object with a __call__ method
name = caller.__class__.__name__.lower()
doc = caller.__call__.__doc__
evaldict = dict(_call=caller, _decorate_=decorate)
dec = FunctionMaker.create(
'%s(func, %s)' % (name, defaultargs),
'if func is None: return lambda func: _decorate_(func, _call, (%s))\n'
'return _decorate_(func, _call, (%s))' % (defaultargs, defaultargs),
evaldict, doc=doc, module=caller.__module__, __wrapped__=caller)
if defaults:
dec.__defaults__ = (None,) + defaults
return dec |
Get the total number of entities
@return int | final public function count()
{
if(!isset($this->_count))
{
$context = $this->getContext();
$context->count = null;
if ($this->invokeCommand('before.count', $context) !== false)
{
$context->count = $this->_actionCount($context);
$this->invokeCommand('after.count', $context);
}
$this->_count = KObjectConfig::unbox($context->count);
}
return $this->_count;
} |
Returns the fully qualified name for the called function.
@param Frame $frame
@return string | protected function getCaller(Frame $frame)
{
$class = $frame->getClass();
$fn = $frame->getFunction();
$caller = '';
if ($class) {
$caller .= $class;
}
if ($class && $fn) {
$caller .= '::';
}
if ($fn) {
$caller .= $fn . '(' . $this->getArgumentsAsString($frame->getArgs()) . ')';
}
return $caller;
} |
Should be used only for local resolution
in remote, use the Symfony firewall. | public function getVersion()
{
//Try to find the password inside symfony configuration
if ($this->isSymfony() && $this->symfonyContainer->hasParameter('pb_version')) {
$this->symfonyContainer->getParameter('pb_version');
}
//Using static PureBilling as fallback
if (class_exists('\PureBilling')) {
return\PureBilling::getVersion();
}
} |
Set profile open graph
@param object $profileObj
@return $this | public function setProfileOG($profileObj)
{
Meta::set("profile:first_name", $profileObj->firstName, "property");
Meta::set("profile:last_name", $profileObj->lastName, "property");
if(isset($profileObj->gender)) {
Meta::set("profile:gender", $profileObj->gender, "property");
}
return $this;
} |
Adds a poly line plot to this canvas.
@param data a n x 2 or n x 3 matrix that describes coordinates of points.
@param style the stroke style of line.
@param color the color of line. | public LinePlot line(double[][] data, Line.Style style, Color color) {
return line(null, data, style, color);
} |
Check if entity is in a valid state for operations.
@param object $entity
@return bool | protected function isValidEntityState($entity)
{
$entityState = $this->uow->getEntityState($entity, UnitOfWork::STATE_NEW);
if ($entityState === UnitOfWork::STATE_NEW) {
return false;
}
// If Entity is scheduled for inclusion, it is not in this collection.
// We can assure that because it would have return true before on array check
if ($entityState === UnitOfWork::STATE_MANAGED && $this->uow->isScheduledForInsert($entity)) {
return false;
}
return true;
} |
// SetAutoAssignElasticIps sets the AutoAssignElasticIps field's value. | func (s *Layer) SetAutoAssignElasticIps(v bool) *Layer {
s.AutoAssignElasticIps = &v
return s
} |
Return ``self(x)``. | def _call(self, x):
""""""
sum_constr = abs(x.ufuncs.sum() / self.diameter - 1) <= self.sum_rtol
nonneq_constr = x.ufuncs.greater_equal(0).asarray().all()
if sum_constr and nonneq_constr:
return 0
else:
return np.inf |
Internally log errors. | private JSONNavi<?> failure(String err, Object jPathPostfix) {
failure = true;
StringBuilder sb = new StringBuilder();
sb.append("Error: ");
sb.append(err);
sb.append(" at ");
sb.append(getJPath());
if (jPathPostfix != null)
if (jPathPostfix instanceof Integer)
sb.append('[').append(jPathPostfix).append(']');
else
sb.append('/').append(jPathPostfix);
this.failureMessage = sb.toString();
return this;
} |
Attempt to load the beans defined by a BeanBuilder DSL closure in "resources.groovy".
@param config
@param context | private static void doLoadSpringGroovyResources(RuntimeSpringConfiguration config, GrailsApplication application,
GenericApplicationContext context) {
loadExternalSpringConfig(config, application);
if (context != null) {
springGroovyResourcesBeanBuilder.registerBeans(context);
}
} |
First View Blocker, Set Banner Categorie-ID and timestamp
@param integer $banner_categorie | protected function setFirstViewBlockerId($banner_categorie=0)
{
if ($banner_categorie==0) { return; }// keine Banner Kategorie, nichts zu tun
$this->statusFirstViewBlocker = true;
$this->setSession('FirstViewBlocker'.$this->module_id, array( $banner_categorie => time() ));
return ;
} |
{@inheritDoc}
@return | @Override
public ListenableFuture<Table> createTableAsync(CreateTableRequest request) {
return createUnaryListener(request, createTableRpc, request.getParent()).getAsyncResult();
} |
// Close will finish any flush that is currently in progress and close file handles. | func (l *WAL) Close() error {
l.mu.Lock()
defer l.mu.Unlock()
l.once.Do(func() {
// Close, but don't set to nil so future goroutines can still be signaled
l.traceLogger.Info("Closing WAL file", zap.String("path", l.path))
close(l.closing)
if l.currentSegmentWriter != nil {
l.sync()
l.currentSegmentWriter.close()
l.currentSegmentWriter = nil
}
})
return nil
} |
Logger that logs exclusively to stderr so that logging doesn't pollute the
scraper result which is written to stdout. | function Logger(level) {
if (_.isString(level) && _.has(LogLevel, level)) {
this.level = LogLevel[level];
} else if (_.isNumber(level) && level >= 0 && level <= 4) {
this.level = level;
} else {
this.level = LogLevel.info;
}
} |
// Error is the implementation of error.Error interface | func (e ErrPortAlreadyAllocated) Error() string {
return fmt.Sprintf("Bind for %s:%d failed: port is already allocated", e.ip, e.port)
} |
Defines builtin default mappers that required for agent proper work
@return array of builtin mappers configurations | public MapperConfig[] getDefault() {
MapperConfig executionStatsMapper = new MapperConfig();
executionStatsMapper.setMapperClass("net.anotheria.extensions.php.mappers.impl.ExecutionStatsMapper");
executionStatsMapper.setMapperId("ExecutionStatsMapper");
MapperConfig serviceStatsMapper = new MapperConfig();
serviceStatsMapper.setMapperClass("net.anotheria.extensions.php.mappers.impl.ServiceStatsMapper");
serviceStatsMapper.setMapperId("ServiceStatsMapper");
MapperConfig counterStatsMapper = new MapperConfig();
counterStatsMapper.setMapperClass("net.anotheria.extensions.php.mappers.impl.CounterStatsMapper");
counterStatsMapper.setMapperId("CounterStatsMapper");
return new MapperConfig[]{
executionStatsMapper, serviceStatsMapper, counterStatsMapper
};
} |
Args:
flush(bool): Flush stream after clearing progress bar (Default:True)
Clear progress bar | def clear(self, flush=True):
if self.enabled:
self.manager.write(flush=flush, position=self.position) |
Returns a list of all the keys for this settings instance.
:return [<str>, ..] | def allKeys(self):
if self._customFormat:
return self._customFormat.allKeys()
else:
return super(XSettings, self).allKeys() |
Creates a new Network View for the Network specified by the `networkId` parameter.
:param networkId: SUID of the Network
:param verbose: print more
:returns: 201: Network View SUID | def createNetworkView(self, networkId, verbose=None):
PARAMS=set_param(['networkId'],[networkId])
response=api(url=self.___url+'networks/'+str(networkId)+'/views', PARAMS=PARAMS, method="POST", verbose=verbose)
return response |
Check the body expression matches matches the body. | function checkJSONExpression(expression, json) {
if (! (expression && json)) {
return false;
}
// array expressions never match non-arrays or arrays of a different length.
if (_.isArray(expression) && !(_.isArray(json) && expression.length === json.length)) {
return false;
}
return _.all(expression, function(v, k) {
// check "$" properties
if (k === "$not") return (! checkJSONExpression(v, json));
if (k === "$unordered") {
return v.length === json.length && arrayContains(json, v);
}
if (k === "$contains") {
return arrayContains(json, v);
}
if (k === "$length" ) return(v === json.length);
if (k === "$gt") return (json > v);
if (k === "$gte") return (json >= v);
if (k === "$lt") return (json < v);
if (k === "$lte") return (json <= v);
// check $not-exists
if (! _.has(json, k)) return (v === "$not-exists");
// check rest of "$" values.
if (v === "$exists") return _.has(json, k);
if (v === "$string") return _.isString(json[k]);
if (_.isRegExp(v)) return v.test(json[k]);
if (_.isObject(v)) return checkJSONExpression(v, json[k]);
if (v === "$date") {
try {
new Date(json[k]);
return true;
} catch (e) {
return false;
}
}
if (v === "$int") {
//http://stackoverflow.com/questions/3885817/how-to-check-if-a-number-is-float-or-integer
return (typeof json[k] === 'number' && json[k] % 1 === 0);
}
// check a strict equals
return (v === json[k]);
});
} |
Codes service.
@module api/CodesApi
@version 0.0.139
Constructs a new CodesApi.
@alias module:api/CodesApi
@class
@param {module:ApiClient} apiClient Optional API client implementation to use,
default to {@link module:ApiClient#instance} if unspecified. | function(apiClient) {
this.apiClient = apiClient || ApiClient.instance;
/**
* Finds a code
* Finds a code
* @param {String} codeId Id of the code
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Code}
*/
this.findCode = function(codeId) {
var postBody = null;
// verify the required parameter 'codeId' is set
if (codeId == undefined || codeId == null) {
throw "Missing the required parameter 'codeId' when calling findCode";
}
var pathParams = {
'codeId': codeId
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = ['basicAuth'];
var contentTypes = ['application/json;charset=utf-8'];
var accepts = ['application/json;charset=utf-8'];
var returnType = Code;
return this.apiClient.callApi(
'/codes/{codeId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
/**
* Lists codes
* Lists codes
* @param {Object} opts Optional parameters
* @param {Array.<String>} opts.types Filter results by types
* @param {String} opts.search Search codes by free-text query
* @param {String} opts.sortBy define order (NATURAL or SCORE). Default is SCORE
* @param {String} opts.sortDir ASC or DESC. Default is ASC
* @param {Integer} opts.firstResult First result
* @param {Integer} opts.maxResults Max results
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Code>}
*/
this.listCodes = function(opts) {
opts = opts || {};
var postBody = null;
var pathParams = {
};
var queryParams = {
'types': this.apiClient.buildCollectionParam(opts['types'], 'csv'),
'search': opts['search'],
'sortBy': opts['sortBy'],
'sortDir': opts['sortDir'],
'firstResult': opts['firstResult'],
'maxResults': opts['maxResults']
};
var headerParams = {
};
var formParams = {
};
var authNames = ['basicAuth'];
var contentTypes = ['application/json;charset=utf-8'];
var accepts = ['application/json;charset=utf-8'];
var returnType = [Code];
return this.apiClient.callApi(
'/codes', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
} |
Initialize Data
Lets you clear current zip data. Useful if you need to create
multiple zips with different data.
@return FW_Zip | public function clear_data()
{
$this->zipdata = '';
$this->directory = '';
$this->entries = 0;
$this->file_num = 0;
$this->offset = 0;
return $this;
} |
If you do not want certain openstreetmap objects to appear in the search result, give a list of the place_id's
you want to skip.
@param placeId
the place id to exclude | public void addExcludedlaceId(final String placeId) {
if (null == this.countryCodes) {
this.excludePlaceIds = new ArrayList<String>();
}
this.excludePlaceIds.add(placeId);
} |
Combines a warning with a call to errors.position().
Simple convenience function.
Arguments:
string (str): The string being parsed.
pos (int): The index of the character that caused trouble. | def warn(what, string, pos):
pos = position(string, pos)
warnings.warn("{0} at position {1}!".format(what, pos), Warning) |