comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
Load host keys from an openssh :file:`known_hosts`-style file. Can
be called multiple times.
If *filename* is not specified, looks in the default locations i.e. :file:`~/.ssh/known_hosts` and :file:`~/ssh/known_hosts` for Windows.
|
def load_known_hosts(self, filename=None):
if filename is None:
filename = os.path.expanduser('~/.ssh/known_hosts')
try:
self._host_keys.load(filename)
except IOError:
# for windows
filename = os.path.expanduser('~/ssh/known_hosts')
try:
self._host_keys.load(filename)
except IOError:
pass
else:
self._host_keys.load(filename)
|
Generate a new key
@param string $hash
@param int $length
@param string $key
@return string
|
private function newKey($hash, $length, $key = '')
{
$generated = $this->hasReq(Hash::secure($length));
if ($hash == 'base64') {
$key = 'base64:' . base64_encode($generated);
} else {
$key = $hash . ':' . $generated;
}
return $key;
}
|
Remove a movie from an accounts watch list.
@param sessionId sessionId
@param accountId accountId
@param mediaId mediaId
@param mediaType mediaType
@return StatusCode
@throws MovieDbException exception
|
public StatusCode removeFromWatchList(String sessionId, int accountId, MediaType mediaType, Integer mediaId) throws MovieDbException {
return tmdbAccount.modifyWatchList(sessionId, accountId, mediaType, mediaId, false);
}
|
Whitelist the WORKON_HOME strings we're willing to substitute in
to strings that we provide for user's shell to evaluate.
If it smells at all bad, return True.
|
def scary_path(path):
if not path:
return True
assert isinstance(path, bytes)
return not NOT_SCARY.match(path)
|
Override the $InputWithFrame.__checkCfgConsistency in order to check the invalidText and restore the error
state if needed.
@protected
@override
|
function () {
this.$InputWithFrame._checkCfgConsistency.call(this);
var cfg = this._cfg;
if (cfg.autoselect == null) {
// the default value for autoselect comes from the environment
cfg.autoselect = ariaWidgetsEnvironmentWidgetSettings.getWidgetSettings().autoselect;
}
var value = cfg.value;
if (cfg.invalidText) {
// Check the field depending on the value and the existing error
var rep = this.checkValue({
text : cfg.invalidText,
value : value,
performCheckOnly : true
});
if (!rep.isValid) {
if (cfg.directOnBlurValidation) {
this.changeProperty("error", true);
}
// Just to set the this._helpTextSet to true in this case,
// as the invalid text will be displayed:
value = cfg.invalidText;
this._helpTextSet = false;
if (rep.report) {
rep.report.$dispose();
}
} else {
// for autocomplete, no report is raised. Asynchronous
// callback will set proper state
if (rep.report) {
this.changeProperty("error", false);
if (rep.report.text == null || rep.report.text === "") {
if (cfg.prefill && cfg.prefill + "") {
this._isPrefilled = true;
} else {
this._helpTextSet = cfg.helptext;
}
}
rep.report.$dispose();
}
}
this._setState();
} else {
// if the value is not set (namely it is null, undefined, an
// empty string or an empty array) and the
// prefill is defined
if ((ariaUtilsType.isArray(value) && ariaUtilsArray.isEmpty(value)) || (!value && value !== 0)) {
if (cfg.prefill && cfg.prefill + "") {
this._isPrefilled = true;
} else {
this._helpTextSet = cfg.helptext;
}
}
if (this._isPrefilled) {
this._setState();
}
}
}
|
Return an array of all (recursive) types known within this type
|
def sub_types
# Iterate through the Google::Protobuf::FieldDescriptor list
entries.map do |fd|
# fd.name = 'current_entity_to_update'
# fd.number = 1
# fd.label = :optional
# fd.submsg_name = "com.foo.bar.Baz"
# fd.subtype = #<Google::Protobuf::Descriptor:0x007fabb3947f08>
if fd.subtype.class == Google::Protobuf::Descriptor
# There is a subtype; recurse
[name, fd.submsg_name] + fd.subtype.sub_types
else
[name, fd.submsg_name]
end
end.flatten.compact
end
|
<p>Liefert den Selbstbezug. </p>
@return time context (usually this instance)
|
protected T getContext() {
Chronology<T> c = this.getChronology();
Class<T> type = c.getChronoType();
if (type.isInstance(this)) {
return type.cast(this);
} else {
for (ChronoElement<?> element : c.getRegisteredElements()) {
if (type == element.getType()) {
return type.cast(this.get(element));
}
}
}
throw new IllegalStateException(
"Implementation error: Cannot find entity context.");
}
|
Create empty file and return its info
@param string $dst destination directory
@param string $name file name
@return array|false
@author Dmitry (dio) Levashov
|
public function mkfile($dst, $name) {
if ($this->commandDisabled('mkfile')) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
if (!$this->nameAccepted($name)) {
return $this->setError(elFinder::ERROR_INVALID_NAME);
}
if (($dir = $this->dir($dst)) == false) {
return $this->setError(elFinder::ERROR_TRGDIR_NOT_FOUND, '#'.$dst);
}
if (!$dir['write']) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
$path = $this->decode($dst);
if ($this->stat($this->_joinPath($path, $name))) {
return $this->setError(elFinder::ERROR_EXISTS, $name);
}
$this->clearcache();
return ($path = $this->_mkfile($path, $name)) ? $this->stat($path) : false;
}
|
creates aaaa set of aaaa single {@link denominator.model.rdata.AAAAData AAAA} record for the
specified name.
@param name ex. {@code www.denominator.io.}
@param address ex. {@code 1234:ab00:ff00::6b14:abcd}
|
public static ResourceRecordSet<AAAAData> aaaa(String name, String address) {
return new AAAABuilder().name(name).add(address).build();
}
|
Display suggested values
@param integer $bas_id The collection base_id
@return string
|
public function getSuggestedValues($bas_id)
{
/** @var \databox $databox */
$databox = $this->app->findDataboxById(\phrasea::sbasFromBas($this->app, $bas_id));
$collection = \collection::getByBaseId($this->app, $bas_id);
$structFields = $suggestedValues = $basePrefs = [];
/** @var \databox_field $meta */
foreach ($databox->get_meta_structure() as $meta) {
if ($meta->is_readonly()) {
continue;
}
$structFields[$meta->get_name()] = $meta;
}
if ($sxe = simplexml_load_string($collection->get_prefs())) {
$z = $sxe->xpath('/baseprefs/sugestedValues');
if ($z && is_array($z)) {
$f = 0;
foreach ($z[0] as $ki => $vi) {
if ($vi && isset($structFields[$ki])) {
foreach ($vi->value as $oneValue) {
$suggestedValues[] = [
'key' => $ki,
'value' => $f,
'name' => (string) $oneValue
];
$f++;
}
}
}
}
$z = $sxe->xpath('/baseprefs');
if ($z && is_array($z)) {
/**
* @var string $ki
* @var \SimpleXMLElement $vi
*/
foreach ($z[0] as $ki => $vi) {
$pref = ['status' => null, 'xml' => null];
if ($ki == 'status') {
$pref['status'] = $vi;
} elseif ($ki != 'sugestedValues') {
$pref['xml'] = $vi->asXML();
}
$basePrefs[] = $pref;
}
}
}
return $this->render('admin/collection/suggested_value.html.twig', [
'collection' => $collection,
'databox' => $databox,
'suggestedValues' => $suggestedValues,
'structFields' => $structFields,
'basePrefs' => $basePrefs,
]);
}
|
Add program options.
|
def add_options(self):
super(MetafileChanger, self).add_options()
self.add_bool_option("-n", "--dry-run",
help="don't write changes to disk, just tell what would happen")
self.add_bool_option("-V", "--no-skip",
help="do not skip broken metafiles that fail the integrity check")
self.add_value_option("-o", "--output-directory", "PATH",
help="optional output directory for the modified metafile(s)")
self.add_bool_option("-p", "--make-private",
help="make torrent private (DHT/PEX disabled)")
self.add_bool_option("-P", "--make-public",
help="make torrent public (DHT/PEX enabled)")
self.add_value_option("-s", "--set", "KEY=VAL [-s ...]",
action="append", default=[],
help="set a specific key to the given value; omit the '=' to delete a key")
self.add_value_option("-r", "--regex", "KEYcREGEXcSUBSTc [-r ...]",
action="append", default=[],
help="replace pattern in a specific key by the given substitution")
self.add_bool_option("-C", "--clean",
help="remove all non-standard data from metafile outside the info dict")
self.add_bool_option("-A", "--clean-all",
help="remove all non-standard data from metafile including inside the info dict")
self.add_bool_option("-X", "--clean-xseed",
help="like --clean-all, but keep libtorrent resume information")
self.add_bool_option("-R", "--clean-rtorrent",
help="remove all rTorrent session data from metafile")
self.add_value_option("-H", "--hashed", "--fast-resume", "DATAPATH",
help="add libtorrent fast-resume information (use {} in place of the torrent's name in DATAPATH)")
# TODO: chtor --tracker
##self.add_value_option("-T", "--tracker", "DOMAIN",
## help="filter given torrents for a tracker domain")
self.add_value_option("-a", "--reannounce", "URL",
help="set a new announce URL, but only if the old announce URL matches the new one")
self.add_value_option("--reannounce-all", "URL",
help="set a new announce URL on ALL given metafiles")
self.add_bool_option("--no-ssl",
help="force announce URL to 'http'")
self.add_bool_option("--no-cross-seed",
help="when using --reannounce-all, do not add a non-standard field to the info dict ensuring unique info hashes")
self.add_value_option("--comment", "TEXT",
help="set a new comment (an empty value deletes it)")
self.add_bool_option("--bump-date",
help="set the creation date to right now")
self.add_bool_option("--no-date",
help="remove the 'creation date' field")
|
Sets the maximum progress that the animation will end at when playing or looping.
|
public void setMaxProgress(@FloatRange(from = 0f, to = 1f) final float maxProgress) {
if (composition == null) {
lazyCompositionTasks.add(new LazyCompositionTask() {
@Override
public void run(LottieComposition composition) {
setMaxProgress(maxProgress);
}
});
return;
}
setMaxFrame((int) MiscUtils.lerp(composition.getStartFrame(), composition.getEndFrame(), maxProgress));
}
|
Write unbuffered data to the client.
|
def write(self, chunk):
""""""
if self.chunked_write and chunk:
chunk_size_hex = hex(len(chunk))[2:].encode('ascii')
buf = [chunk_size_hex, CRLF, chunk, CRLF]
self.conn.wfile.write(EMPTY.join(buf))
else:
self.conn.wfile.write(chunk)
|
Create an instance of {@link Kernel}.
@param modules modules to link to the new kernel.
@return the new kernel.
|
public static final Kernel create(Module... modules) {
final Injector injector = Guice.createInjector(modules);
final Kernel k = injector.getInstance(Kernel.class);
return k;
}
|
Show the report for a single pants run.
|
def _handle_run(self, relpath, params):
""""""
args = self._default_template_args('run.html')
run_id = relpath
run_info = self._get_run_info_dict(run_id)
if run_info is None:
args['no_such_run'] = relpath
if run_id == 'latest':
args['is_latest'] = 'none'
else:
report_abspath = run_info['default_report']
report_relpath = os.path.relpath(report_abspath, self._root)
report_dir = os.path.dirname(report_relpath)
self_timings_path = os.path.join(report_dir, 'self_timings')
cumulative_timings_path = os.path.join(report_dir, 'cumulative_timings')
artifact_cache_stats_path = os.path.join(report_dir, 'artifact_cache_stats')
run_info['timestamp_text'] = \
datetime.fromtimestamp(float(run_info['timestamp'])).strftime('%H:%M:%S on %A, %B %d %Y')
timings_and_stats = '\n'.join([
self._collapsible_fmt_string.format(id='cumulative-timings-collapsible',
title='Cumulative timings', class_prefix='aggregated-timings'),
self._collapsible_fmt_string.format(id='self-timings-collapsible',
title='Self timings', class_prefix='aggregated-timings'),
self._collapsible_fmt_string.format(id='artifact-cache-stats-collapsible',
title='Artifact cache stats', class_prefix='artifact-cache-stats')
])
args.update({'run_info': run_info,
'report_path': report_relpath,
'self_timings_path': self_timings_path,
'cumulative_timings_path': cumulative_timings_path,
'artifact_cache_stats_path': artifact_cache_stats_path,
'timings_and_stats': timings_and_stats})
if run_id == 'latest':
args['is_latest'] = run_info['id']
content = self._renderer.render_name('base.html', args).encode("utf-8")
self._send_content(content, 'text/html')
|
查询是否允许授权处理,非阻塞,指定是否强制刷新
|
public boolean isPermit(boolean reload) {
if (reload) {// 判断是否需要重新reload
reload();
}
boolean result = channelStatus.isStart() && mainStemStatus.isOverTake();
if (existOpposite) {// 判断是否存在反向同步
result &= oppositeMainStemStatus.isOverTake();
}
return result;
}
|
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated
|
public void setNomPtSize(Integer newNomPtSize) {
Integer oldNomPtSize = nomPtSize;
nomPtSize = newNomPtSize;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.FND__NOM_PT_SIZE, oldNomPtSize, nomPtSize));
}
|
// Stop stops the timer and returns true if the timer has not yet fired, or false otherwise.
|
func (f *fakeTimer) Stop() bool {
f.fakeClock.lock.Lock()
defer f.fakeClock.lock.Unlock()
newWaiters := make([]fakeClockWaiter, 0, len(f.fakeClock.waiters))
for i := range f.fakeClock.waiters {
w := &f.fakeClock.waiters[i]
if w != &f.waiter {
newWaiters = append(newWaiters, *w)
}
}
f.fakeClock.waiters = newWaiters
return !f.waiter.fired
}
|
Assigns site properties.
|
def assign_site_properties(self, slab, height=0.9):
if 'surface_properties' in slab.site_properties.keys():
return slab
else:
surf_sites = self.find_surface_sites_by_height(slab, height)
surf_props = ['surface' if site in surf_sites
else 'subsurface' for site in slab.sites]
return slab.copy(
site_properties={'surface_properties': surf_props})
|
Decodes a Base64 bytes (or string) input and decompresses it using Gzip
:param data: Base64 (bytes) data to be decoded
:return: Decompressed and decoded bytes
|
def decompress(data):
if isinstance(data, bytes):
source = data
elif isinstance(data, str):
source = bytes(data, encoding='utf-8')
else:
raise RuntimeError("Compression is only supported for strings and bytes")
return gzip.decompress(base64.b64decode(source))
|
// MakeNetworkReaderFrom is a helper to transform NetworkPacketReader to io.ReaderFrom.
|
func MakeNetworkReaderFrom(rp NetworkPacketReader, p *NetworkPacket) io.ReaderFrom {
return ioutil.ReaderFromFunc(func(r io.Reader) (int64, error) {
packet, err := rp.ReadPacket(r)
if err != nil {
return 0, err
}
*p = *packet
return packet.Len, nil
})
}
|
Register event handler
@param string $type
@param \Closure|array|string $callback
@return $this
|
public function on($type, $callback)
{
if (!isset($this->callbacks[$type])) {
$this->callbacks[$type] = [];
}
$this->callbacks[$type][] = $callback;
return $this;
}
|
TODO: remove this method and make the modules bindable *
@deprecated will be removed soon
@return {Array}
|
function () {
var modules = [], conf;
for (var i = 0; i < this.$configurations.length; i++) {
conf = this.$configurations[i];
if (conf instanceof ModuleConfiguration) {
modules.push(conf.$.name);
}
}
return modules;
}
|
Get a key.
@param string $key
@param bool|null $minified
@return string|null
@throws \JosKolenberg\Jory\Exceptions\JoryException
|
public function get(string $key, bool $minified = null): ?string
{
if (is_null($minified)) {
$minified = $this->minified;
}
return $minified ? $this->getMinified($key) : $this->getFull($key);
}
|
Creates a <code>String[]</code> by calling the toString() method of each object in a list.
@deprecated Please use List.toArray(Object[])
@see List#toArray(Object[])
|
@Deprecated
public static String[] getStringArray(List<?> V) {
if(V==null) return null;
int len = V.size();
String[] SA = new String[len];
for (int c = 0; c < len; c++) {
Object O=V.get(c);
SA[c]=O==null?null:O.toString();
}
return SA;
}
|
Perform a grey erosion with masking
|
def grey_erosion(image, radius=None, mask=None, footprint=None):
''''''
if footprint is None:
if radius is None:
footprint = np.ones((3,3),bool)
radius = 1
else:
footprint = strel_disk(radius)==1
else:
radius = max(1, np.max(np.array(footprint.shape) // 2))
iradius = int(np.ceil(radius))
#
# Do a grey_erosion with masked pixels = 1 so they don't participate
#
big_image = np.ones(np.array(image.shape)+iradius*2)
big_image[iradius:-iradius,iradius:-iradius] = image
if not mask is None:
not_mask = np.logical_not(mask)
big_image[iradius:-iradius,iradius:-iradius][not_mask] = 1
processed_image = scind.grey_erosion(big_image, footprint=footprint)
final_image = processed_image[iradius:-iradius,iradius:-iradius]
if not mask is None:
final_image[not_mask] = image[not_mask]
return final_image
|
// SetBranchName sets the BranchName field's value.
|
func (s *SubDomainSetting) SetBranchName(v string) *SubDomainSetting {
s.BranchName = &v
return s
}
|
Train an learner using a dataset and return it.
@param \Rubix\ML\Learner $estimator
@param \Rubix\ML\Datasets\Dataset $dataset
@return \Rubix\ML\Learner
|
public function _train(Learner $estimator, Dataset $dataset) : Learner
{
$estimator->train($dataset);
return $estimator;
}
|
// SetOperatingSystem sets the OperatingSystem field's value.
|
func (s *PatchBaselineIdentity) SetOperatingSystem(v string) *PatchBaselineIdentity {
s.OperatingSystem = &v
return s
}
|
Builds and return a Manager instance.
@return Manager
|
public function build()
{
$annotationReader = $this->annotationReader;
if (null === $annotationReader) {
$annotationReader = new AnnotationReader();
if (null !== $this->cacheDir) {
$this->createDir($this->cacheDir . '/annotations');
$annotationReader = new FileCacheReader($annotationReader, $this->cacheDir . '/annotations', $this->debug);
}
}
$metadataDriver = $this->driverFactory->createDriver($this->metadataDirs, $annotationReader);
$metadataFactory = new MetadataFactory($metadataDriver);
$metadataFactory->setIncludeInterfaces($this->includeInterfaceMetadata);
if (null !== $this->cacheDir) {
$this->createDir($this->cacheDir . '/metadata');
$metadataFactory->setCache(new FileCache($this->cacheDir . '/metadata'));
}
$schemaRegistry = new SchemaRegistry($this->schemaDirs);
// TODO registry caching
return new Manager($metadataFactory, $schemaRegistry);
}
|
Perform the appropriate triplet combination function for the current
iteration
|
def sha1_ft(t, b, c, d)
return (b & c) | ((~b) & d) if t < 20
return b ^ c ^ d if t < 40
return (b & c) | (b & d) | (c & d) if t < 60
b ^ c ^ d
end
|
备注
@param openId
@param remark 长度小于30
|
public void remark(String openId, String remark) {
String url = WxEndpoint.get("url.user.remark");
String json = String.format("{\"openid\":\"%s\",\"remark\":\"%s\"}", openId, remark);
logger.debug("remark user: {}", json);
wxClient.post(url, json);
}
|
Creates an array containing integer line numbers starting from the 'first-line' param.
@return {Array} Returns array of integers.
|
function(code)
{
var lines = [],
firstLine = parseInt(this.getParam('first-line'))
;
eachLine(code, function(line, index)
{
lines.push(index + firstLine);
});
return lines;
}
|
// parseKeyAndInferOperator parse literals.
// in case of no operator '!, in, notin, ==, =, !=' are found
// the 'exists' operator is inferred
|
func (p *Parser) parseKeyAndInferOperator() (string, Operator, error) {
var operator Operator
tok, literal := p.consume(Values)
if tok == DoesNotExistToken {
operator = DoesNotExistOperator
tok, literal = p.consume(Values)
}
if tok != IdentifierToken {
err := fmt.Errorf("found '%s', expected: identifier", literal)
return "", "", err
}
if err := validateLabelKey(literal); err != nil {
return "", "", err
}
if t, _ := p.lookahead(Values); t == EndOfStringToken || t == CommaToken {
if operator != DoesNotExistOperator {
operator = ExistsOperator
}
}
return literal, operator, nil
}
|
Compute E_{q(z) q(x)} [log p(z) + log p(x | z) + log p(y | x, z)]
|
def expected_log_joint_probability(self):
# E_{q(z)}[log p(z)]
from pyslds.util import expected_hmm_logprob
elp = expected_hmm_logprob(
self.pi_0, self.trans_matrix,
(self.expected_states, self.expected_transcounts, self._normalizer))
# E_{q(x)}[log p(y, x | z)] is given by aBl
# To get E_{q(x)}[ aBl ] we multiply and sum
elp += np.sum(self.expected_states * self.vbem_aBl)
return elp
|
// Errorf returns an error containing an error code and a description;
// Errorf returns nil if c is OK.
//
// Deprecated: use status.Errorf instead.
|
func Errorf(c codes.Code, format string, a ...interface{}) error {
return status.Errorf(c, format, a...)
}
|
If this event does not already contain location information,
evaluate the event against the expression.
If the expression evaluates to true,
force generation of location information by
calling getLocationInfo.
@param event event
@return Filter.NEUTRAL.
|
public int decide(final LoggingEvent event) {
if (expressionRule.evaluate(event, null)) {
event.getLocationInformation();
}
return Filter.NEUTRAL;
}
|
Get possible plural forms from MO header
@access private
@return string plural form header
|
private function get_plural_forms() {
// lets assume message number 0 is header
// this is true, right?
$this->load_tables();
// cache header field for plural forms
if (!is_string($this->pluralheader)) {
if ($this->enable_cache) {
$header = $this->cache_translations[""];
}
else {
$header = $this->get_translation_string(0);
}
if (preg_match("/plural\-forms: ([^\n]*)\n/i", $header, $regs))
$expr = $regs[1];
else
$expr = "nplurals=2; plural=n == 1 ? 0 : 1;";
$this->pluralheader = $expr;
}
return $this->pluralheader;
}
|
(see Riot::AssertionMacro#evaluate)
@param [Class] expected_class the expected Exception class
@param [String, nil] expected_message an optional exception message or message partial
|
def evaluate(actual_exception, expected_class, expected_message=nil)
actual_message = actual_exception && actual_exception.message
if actual_exception.nil?
fail new_message.expected_to_raise(expected_class).but.raised_nothing
elsif expected_class != actual_exception.class
fail new_message.expected_to_raise(expected_class).not(actual_exception.class)
elsif expected_message && !(actual_message.to_s =~ %r[#{expected_message}])
fail expected_message(expected_message).for_message.not(actual_message)
else
message = new_message.raises(expected_class)
pass(expected_message ? message.with_message(expected_message) : message)
end
end
|
get_authorized_tokens
Returns authorized tokens after they go through the auth_url phase.
|
def get_authorized_tokens(self):
resp, content = self.client.request(self.access_token_url, "GET")
return dict(urlparse.parse_qsl(content))
|
////////////////////////////////////////////////////////////
|
public function generateNewsVisitHitTop($VisitorsID, $limit = 10, $parse = true)
{
$arrNewsStatCount = false;
//News Tables exists?
if (true === $this->getNewstableexists())
{
$objNewsStatCount = \Database::getInstance()
->prepare("SELECT
visitors_page_id,
visitors_page_lang,
SUM(visitors_page_visit) AS visitors_page_visits,
SUM(visitors_page_hit) AS visitors_page_hits
FROM
tl_visitors_pages
WHERE
vid = ?
AND visitors_page_type = ?
GROUP BY
visitors_page_id,
visitors_page_lang
ORDER BY
visitors_page_visits DESC,
visitors_page_hits DESC,
visitors_page_id,
visitors_page_lang
")
->limit($limit)
->execute($VisitorsID, self::PAGE_TYPE_NEWS);
while ($objNewsStatCount->next())
{
$alias = false;
$aliases = $this->getNewsAliases($objNewsStatCount->visitors_page_id);
if (false !== $aliases['PageAlias'])
{
$alias = $aliases['PageAlias'] .'/'. $aliases['NewsAlias'];
}
if (false !== $alias)
{
$arrNewsStatCount[] = array
(
'title' => $aliases['NewsArchivTitle'],
'alias' => $alias,
'lang' => $objNewsStatCount->visitors_page_lang,
'visits' => $objNewsStatCount->visitors_page_visits,
'hits' => $objNewsStatCount->visitors_page_hits
);
}
}
if ($parse === true)
{
/* @var $TemplatePartial Template */
$TemplatePartial = new \BackendTemplate('mod_visitors_be_stat_partial_newsvisithittop');
$TemplatePartial->NewsVisitHitTop = $arrNewsStatCount;
return $TemplatePartial->parse();
}
return $arrNewsStatCount;
}
return false;
}
|
////////////////////////////////////////////////////////////////////////// helper methods for handling label and axis formatting
|
function(properties, data) {
var axisType = data.xAxisType,
axisProperties = this.parseUtils.getXAxisProperties(properties),
orientation = (this.axesAreInverted) ? 'vertical' : 'horizontal',
colorScheme = this.getAxisColorScheme();
// add some extra info to the axisProperties as needed
axisProperties.chartType = properties.chart;
axisProperties.axisLength = $(this.renderTo).width();
if(axisProperties['axisTitle.text']){
axisProperties['axisTitle.text'] = Splunk.JSCharting.ParsingUtils.escapeHtml(axisProperties['axisTitle.text']);
}
switch(axisType) {
case 'category':
this.xAxis = new Splunk.JSCharting.CategoryAxis(axisProperties, data, orientation, colorScheme);
break;
case 'time':
this.xAxis = new Splunk.JSCharting.TimeAxis(axisProperties, data, orientation, colorScheme, this.exportMode);
break;
default:
// assumes a numeric axis
this.xAxis = new Splunk.JSCharting.NumericAxis(axisProperties, data, orientation, colorScheme);
break;
}
this.hcConfig.xAxis = this.xAxis.getConfig();
if(this.exportMode && (axisType === 'time')) {
var xAxisMargin,
spanSeries = data._spanSeries,
span = (spanSeries && spanSeries.length > 0) ? parseInt(spanSeries[0], 10) : 1,
secsPerDay = 60 * 60 * 24,
secsPerYear = secsPerDay * 365;
if(span >= secsPerYear) {
xAxisMargin = 15;
}
else if(span >= secsPerDay) {
xAxisMargin = 25;
}
else {
xAxisMargin = 35;
}
this.hcConfig.xAxis.title.margin = xAxisMargin;
}
if(typeof this.hcConfig.xAxis.title.text === 'undefined') {
this.hcConfig.xAxis.title.text = this.processedData.xAxisKey;
}
}
|
initialize a Logger for tracking hits to the server
|
def init_access_log
return if access_log_dest.nil?
log = ::Logging.logger['access_log']
pattern = ::Logging.layouts.pattern(:pattern => ACCESS_LOG_PATTERN)
log.add_appenders(
::Logging.appenders.rolling_file(access_log_dest,
:level => :debug,
:age => 'daily',
:layout => pattern)
)
log
end
|
@param string $schema
@param string $typeName
@param array $criteria
@return array
|
public function findBy(string $schema, string $typeName, array $criteria = []) : array
{
if (!$this->typeExists($schema, $typeName)) {
return [];
}
foreach ($this->storage[$schema][$typeName] as $id => $data) {
if ($this->matchesCriteria($criteria, $data)) {
return $data;
}
}
return [];
}
|
confidence weighted accuracy assuming the scores are probabilities and using .5 as treshold
|
public int[] cwaArray() {
int[] arr = new int[numSamples()];
for (int recall = 1; recall <= numSamples(); recall++) {
arr[recall - 1] = logPrecision(recall);
}
return arr;
}
|
today all
Returns:
[type] -- [description]
|
def get_today_all(output='pd'):
data = []
today = str(datetime.date.today())
codes = QA_fetch_get_stock_list('stock').code.tolist()
bestip = select_best_ip()['stock']
for code in codes:
try:
l = QA_fetch_get_stock_day(
code, today, today, '00', ip=bestip)
except:
bestip = select_best_ip()['stock']
l = QA_fetch_get_stock_day(
code, today, today, '00', ip=bestip)
if l is not None:
data.append(l)
res = pd.concat(data)
if output in ['pd']:
return res
elif output in ['QAD']:
return QA_DataStruct_Stock_day(res.set_index(['date', 'code'], drop=False))
|
Return args parser
@return program parser
|
private static OptionParser getParser() {
OptionParser parser = new OptionParser();
parser.accepts("help", "print help information");
parser.accepts("url", "[REQUIRED] bootstrap URL")
.withRequiredArg()
.describedAs("bootstrap-url")
.ofType(String.class);
parser.accepts("in-dir",
"[REQUIRED] Directory in which to find the input key files (named \"{storeName}.kvs\", generated by KeyFetcherCLI.")
.withRequiredArg()
.describedAs("inputDirectory")
.ofType(String.class);
parser.accepts("out-dir",
"[REQUIRED] Directory in which to output the key files (named \"{storeName}.kvs\".")
.withRequiredArg()
.describedAs("outputDirectory")
.ofType(String.class);
parser.accepts("store-names",
"Store names to sample. Comma delimited list or singleton. [Default: ALL]")
.withRequiredArg()
.describedAs("storeNames")
.withValuesSeparatedBy(',')
.ofType(String.class);
parser.accepts("parallelism",
"Number of key-versions to sample in parallel. [Default: "
+ DEFAULT_KEY_PARALLELISM + " ]")
.withRequiredArg()
.describedAs("storeParallelism")
.ofType(Integer.class);
parser.accepts("progress-period-ops",
"Number of operations between progress info is displayed. [Default: "
+ DEFAULT_PROGRESS_PERIOD_OPS + " ]")
.withRequiredArg()
.describedAs("progressPeriodOps")
.ofType(Integer.class);
parser.accepts("output-batch-size",
"Number of keys fetched and written out in sorted order at once. [Default: "
+ DEFAULT_OUTPUT_BATCH_SIZE + " ]")
.withRequiredArg()
.describedAs("outputBatchSize")
.ofType(Integer.class);
parser.accepts("details",
"print details of each key-version: partition ID, node ID, & hostname");
return parser;
}
|
Generates deployment for given application.
@param type Module type to generate
@param basename Base name of module to generate
@param doFiltering should do basic filtering
@return EnterpriseArchive containing given module and all dependencies
|
public static EnterpriseArchive getModuleDeployment(ModuleType type, String basename, boolean doFiltering) {
String name = basename + "." + type.getExtension();
String testJarName = basename + "-tests.jar";
// LOG.debug("Creating Arquillian deployment for [" + name + "]");
try {
EarDescriptorBuilder descriptorBuilder = new EarDescriptorBuilder(basename);
MavenResolverSystem maven = Maven.resolver();
//ConfigurableMavenResolverSystem maven = Maven.configureResolver().workOffline().withMavenCentralRepo(false);
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, basename + "-full.ear");
PomEquippedResolveStage resolveStage = maven.loadPomFromFile("pom.xml");
// przejrzenie dependency oznaczonych jako provided w celu znalezienia EJB'ków
MavenResolvedArtifact[] provided = resolveStage.importRuntimeDependencies().importDependencies(ScopeType.PROVIDED).resolve().using(new AcceptScopesStrategy(ScopeType.PROVIDED)).asResolvedArtifact();
for (MavenResolvedArtifact mra : provided) {
// System.out.println("Checking provided: " + mra.getCoordinate().toCanonicalForm());
if (isArtifactEjb(mra.getCoordinate())) {
ear.addAsModule(mra.as(JavaArchive.class));
// dodajemy jako moduł
descriptorBuilder.addEjb(mra.asFile().getName());
// przeglądamy dependency EJB'ka w celu pobrania także zależności z EJB'ka
for (MavenArtifactInfo mai : mra.getDependencies()) {
// LOG.debug("Resolved: " + mai.getCoordinate().getGroupId() + ":" + mai.getCoordinate().getArtifactId());
// pomijamy wzajemne zależności do innych EJB'ków
if (!isArtifactEjb(mai.getCoordinate())) {
for (MavenResolvedArtifact reqMra : provided) {
if (reqMra.getCoordinate().toCanonicalForm().equals(mai.getCoordinate().toCanonicalForm())) {
// dodanie zależności do lib'ów
ear.addAsLibrary(reqMra.asFile());
break;
}
}
}
}
}
}
MavenResolvedArtifact[] deps = resolveStage.importRuntimeAndTestDependencies().resolve().withTransitivity().asResolvedArtifact();
for (MavenResolvedArtifact mra : deps) {
MavenCoordinate mc = mra.getCoordinate();
PackagingType packaging = mc.getPackaging();
if (doFiltering && isFiltered(mc)) {
continue;
}
LOG.log(Level.FINEST, "Adding: {0}", mc.toCanonicalForm());
if (isArtifactEjb(mc)) {
// dependency w postaci ejb'ków
ear.addAsModule(mra.as(JavaArchive.class));
descriptorBuilder.addEjb(mra.asFile().getName());
} else if (packaging.equals(PackagingType.WAR)) {
// dependency w postaci war'ów
ear.addAsModule(mra.as(WebArchive.class));
descriptorBuilder.addWeb(mra.asFile().getName());
} else {
// resztę dodajemy jako lib
ear.addAsLibrary(mra.asFile());
}
}
// utworzenie głównego archiwum
// Archive<?> module = ShrinkWrap.create(MavenImporter.class, name)
// .loadPomFromFile("pom.xml")
// .as(type.getType());
Archive<?> module = ShrinkWrap.create(ExplodedImporter.class, name)
.importDirectory(type.getExplodedDir(basename))
.as(type.getType());
JavaArchive testJar = ShrinkWrap.create(ExplodedImporter.class, testJarName)
.importDirectory("target/test-classes")
.as(JavaArchive.class);
module = module.merge(testJar, type.getMergePoint());
// mergeReplace(ear, module, testJar);
module.add(new StringAsset(RUN_AT_ARQUILLIAN_CONTENT), RUN_AT_ARQUILLIAN_PATH);
LOG.log(Level.FINE, module.toString(true));
addMainModule(ear, type, module, descriptorBuilder);
// Workaround for arquillian bug
if (!descriptorBuilder.containsWar()) {
String testModuleName = ModuleType.WAR.generateModuleName() + ".war";
ear.addAsModule(ShrinkWrap.create(WebArchive.class, testModuleName));
descriptorBuilder.addWeb(testModuleName);
}
ear.setApplicationXML(new StringAsset(descriptorBuilder.render()));
ear.addManifest();
LOG.log(Level.INFO, "Created deployment [{0}]", ear.getName());
// System.out.println(ear.toString(true));
// System.out.println(descriptorBuilder.render());
return ear;
} catch (IllegalArgumentException ex) {
throw new IllegalStateException("Error in creating deployment [" + ex + "]", ex);
} catch (InvalidConfigurationFileException ex) {
throw new IllegalStateException("Error in creating deployment [" + ex + "]", ex);
} catch (ArchiveImportException ex) {
throw new IllegalStateException("Error in creating deployment [" + ex + "]", ex);
}
}
|
Rewrite the ``<c:tx>``, ``<c:xVal>`` and ``<c:yVal>`` child elements
of *ser* based on the values in *series_data*.
|
def _rewrite_ser_data(self, ser, series_data, date_1904):
ser._remove_tx()
ser._remove_xVal()
ser._remove_yVal()
xml_writer = _XySeriesXmlWriter(series_data)
ser._insert_tx(xml_writer.tx)
ser._insert_xVal(xml_writer.xVal)
ser._insert_yVal(xml_writer.yVal)
|
// Migrate the "fs" backend.
// Migration should happen when formatFSV1.FS.Version changes. This version
// can change when there is a change to the struct formatFSV1.FS or if there
// is any change in the backend file system tree structure.
|
func formatFSMigrate(ctx context.Context, wlk *lock.LockedFile, fsPath string) error {
// Add any migration code here in case we bump format.FS.Version
version, err := formatFSGetVersion(wlk)
if err != nil {
return err
}
switch version {
case formatFSVersionV1:
if err = formatFSMigrateV1ToV2(ctx, wlk, fsPath); err != nil {
return err
}
fallthrough
case formatFSVersionV2:
// We are at the latest version.
}
// Make sure that the version is what we expect after the migration.
version, err = formatFSGetVersion(wlk)
if err != nil {
return err
}
if version != formatFSVersionV2 {
return uiErrUnexpectedBackendVersion(fmt.Errorf(`%s file: expected FS version: %s, found FS version: %s`, formatConfigFile, formatFSVersionV2, version))
}
return nil
}
|
// InitOnboarding will invoke the onboarding / setup wizard
|
func (s *Action) InitOnboarding(ctx context.Context, c *cli.Context) error {
remote := c.String("remote")
team := c.String("alias")
create := c.Bool("create")
name := c.String("name")
email := c.String("email")
ctx = backend.WithCryptoBackendString(ctx, c.String("crypto"))
// default to git
if rcs := c.String("rcs"); rcs != "" {
ctx = backend.WithRCSBackendString(ctx, c.String("rcs"))
} else {
out.Debug(ctx, "Using default RCS backend (GitCLI)")
ctx = backend.WithRCSBackend(ctx, backend.GitCLI)
}
ctx = out.AddPrefix(ctx, "[init] ")
out.Debug(ctx, "Starting Onboarding Wizard - remote: %s - team: %s - create: %t - name: %s - email: %s", remote, team, create, name, email)
crypto := s.getCryptoFor(ctx, name)
out.Debug(ctx, "Crypto Backend initialized as: %s", crypto.Name())
// check for existing GPG keypairs (private/secret keys). We need at least
// one useable key pair. If none exists try to create one
if !s.initHasUseablePrivateKeys(ctx, crypto, team) {
out.Yellow(ctx, "No useable crypto keys. Generating new key pair")
ctx := out.AddPrefix(ctx, "[crypto] ")
out.Print(ctx, "Key generation may take up to a few minutes")
if err := s.initCreatePrivateKey(ctx, crypto, team, name, email); err != nil {
return errors.Wrapf(err, "failed to create new private key")
}
}
out.Debug(ctx, "Has useable private keys")
// if a git remote and a team name are given attempt unattended team setup
if remote != "" && team != "" {
if create {
return s.initCreateTeam(ctx, c, team, remote)
}
return s.initJoinTeam(ctx, c, team, remote)
}
// no flags given, run interactively
choices := []string{
"Local store",
"Create a Team",
"Join an existing Team",
}
act, sel := cui.GetSelection(ctx, "Select action", "<↑/↓> to change the selection, <→> to select, <ESC> to quit", choices)
switch act {
case "default":
fallthrough
case "show":
switch sel {
case 0:
return s.initLocal(ctx, c)
case 1:
return s.initCreateTeam(ctx, c, "", "")
case 2:
return s.initJoinTeam(ctx, c, "", "")
}
default:
return fmt.Errorf("user aborted")
}
return nil
}
|
// BreakerTimeout is the period of the open state, after which the state of CircuitBreaker becomes half-open.
// If Timeout is 0, the timeout value of CircuitBreaker is set to 60 seconds.
|
func BreakerTimeout(timeout time.Duration) Option {
return func(r *Rabbus) error {
r.config.breaker.timeout = timeout
return nil
}
}
|
Bind data to the view.
@param \Illuminate\Contracts\View\View $view
@return void
|
public function compose(View $view)
{
$displayMetrics = $this->config->get('setting.display_graphs');
$metrics = $this->getVisibleMetrics($displayMetrics);
$view->withDisplayMetrics($displayMetrics)
->withMetrics($metrics);
}
|
{@inheritDoc}
@see java.nio.file.Path#toUri()
|
@Override
public URI toUri() {
final URI root = ShrinkWrapFileSystems.getRootUri(this.fileSystem.getArchive());
// Compose a new URI location, stripping out the extra "/" root
final String location = root.toString() + this.toString().substring(1);
final URI uri = URI.create(location);
return uri;
}
|
get the attribute name and value as a string
@param {Element} node The element that has the attribute
@param {Attribute} at The attribute
@return {String}
|
function getAttributeNameValue(node, at) {
const name = at.name;
let atnv;
if (name.indexOf('href') !== -1 || name.indexOf('src') !== -1) {
let friendly = axe.utils.getFriendlyUriEnd(node.getAttribute(name));
if (friendly) {
let value = encodeURI(friendly);
if (value) {
atnv = escapeSelector(at.name) + '$="' + escapeSelector(value) + '"';
} else {
return;
}
} else {
atnv =
escapeSelector(at.name) +
'="' +
escapeSelector(node.getAttribute(name)) +
'"';
}
} else {
atnv = escapeSelector(name) + '="' + escapeSelector(at.value) + '"';
}
return atnv;
}
|
Makes a string URL-compatible
@param string $string String to transform
@return string
|
private function vulgarize($string)
{
return trim(
preg_replace(
'/(-+)/',
'-',
preg_replace(
'/([^a-z0-9-]*)/',
'',
preg_replace(
'/((\s|\.|\'|\/)+)/',
'-',
html_entity_decode(
preg_replace(
'/&(a|o)elig;/',
'$1e',
preg_replace(
'/&([a-z])(uml|acute|grave|circ|tilde|ring|cedil|slash);/',
'$1',
strtolower(
htmlentities(
$string,
ENT_COMPAT,
'utf-8'
)
)
)
),
ENT_COMPAT,
'utf-8'
)
)
)
),
'-'
);
}
|
Load image as a resource
@param string $path Image filepath to load
@return resource
|
public static function _Load ($path)
{
// Check file exists
if (!parent::_Exists ($path))
{
return FALSE;
}
// Set image resource
$image = FALSE;
// Switch image type and load
switch (self::_getMIME ($path))
{
// gif
case IMAGETYPE_GIF:
$image = imagecreatefromgif ($path);
break;
// png
case IMAGETYPE_PNG:
$resImg = imagecreatefrompng ($path);
break;
// jpeg / default
default:
$image = imagecreatefromjpeg ($path);
break;
}
// Return image resource
return $image;
}
|
Converts angle value to radians.
When value is "deg" suffixed, it means value is in degrees.
@return float|null angle in radians or null
|
public static function convertAngleValue($value)
{
if($value !== null && strpos($value, 'deg') !== false)
{
$value = (float) $value;
$value = deg2rad($value);
}
return $value !== null ? ((float) $value) : null;
}
|
Execute the search and return the response.
|
def execute(self):
r = self._s.execute()
r._faceted_search = self
return r
|
Load view template with arguments
@param string $slug
@param string $name
@param array $args
|
public static function view($slug, $name = '', array $args = []){
$class_name = get_called_class();
/** @var Controller $instance */
$instance = $class_name::get_instance();
$instance->lazy_scripts();
$instance->load_template($slug, $name, $args);
}
|
Invokes {@link QuickDiagnose#matches(org.hamcrest.Matcher, java.lang.Object, org.hamcrest.Description, java.lang.String)}
for {@code m},
enclosed in parentheses if necessary.
@param self
@param matcher
@param item
@param mismatch
@param message
@return
|
public static boolean matches(PrecedencedSelfDescribing self, Matcher<?> matcher, Object item, Description mismatch, String message) {
if (message == null) {
return matches(self, matcher, item, mismatch);
}
boolean paren = useParen(self, matcher);
if (paren) message = message.replace("$1", "($1)");
return QuickDiagnose.matches(matcher, item, mismatch, message);
}
|
Checks if the specified {@code arg} is positive, and throws {@code IllegalArgumentException} if it is not.
@param arg
@param argNameOrErrorMsg
@throws IllegalArgumentException if the specified {@code arg} is negative.
|
public static int checkArgPositive(final int arg, final String argNameOrErrorMsg) {
if (arg <= 0) {
if (argNameOrErrorMsg.indexOf(' ') == N.INDEX_NOT_FOUND) {
throw new IllegalArgumentException("'" + argNameOrErrorMsg + "' can not be zero or negative: " + arg);
} else {
throw new IllegalArgumentException(argNameOrErrorMsg);
}
}
return arg;
}
|
Returns the url of the forum whose topics will be marked read.
|
def get_forum_url(self):
return reverse('forum:forum', kwargs={'slug': self.forum.slug, 'pk': self.forum.pk})
|
Runs migration against a data set.
|
def run_migration(data, version_start, version_end):
""""""
items = []
if version_start == 1 and version_end == 2:
for item in data['accounts']:
items.append(v2.upgrade(item))
if version_start == 2 and version_end == 1:
for item in data:
items.append(v2.downgrade(item))
items = {'accounts': items}
return items
|
Creates the text field based date picker with the calendar widget without a model object.
|
def unobtrusive_date_text_picker_tag(name, date = Date.current, options = {}, html_options = {})
date ||= Date.current
options = merge_defaults_for_text_picker(options)
DateTimePickerSelector.new(date, options, html_options).text_date_picker(name)
end
|
// ChaincodeInfo implements function in interface ledger.DeployedChaincodeInfoProvider
|
func (p *DeployedCCInfoProvider) ChaincodeInfo(chaincodeName string, qe ledger.SimpleQueryExecutor) (*ledger.DeployedChaincodeInfo, error) {
chaincodeDataBytes, err := qe.GetState(lsccNamespace, chaincodeName)
if err != nil || chaincodeDataBytes == nil {
return nil, err
}
chaincodeData := &ccprovider.ChaincodeData{}
if err := proto.Unmarshal(chaincodeDataBytes, chaincodeData); err != nil {
return nil, errors.Wrap(err, "error unmarshalling chaincode state data")
}
collConfigPkg, err := fetchCollConfigPkg(chaincodeName, qe)
if err != nil {
return nil, err
}
return &ledger.DeployedChaincodeInfo{
Name: chaincodeName,
Hash: chaincodeData.Id,
Version: chaincodeData.Version,
CollectionConfigPkg: collConfigPkg,
}, nil
}
|
@param ItemDto[] $data Map[string, ItemDto]
@return $this
|
public function setData($data)
{
foreach ($data as $key => $dtoData) {
$this->data[$key] = new ItemDto($dtoData);
}
return $this;
}
|
/* (non-Javadoc)
@see com.ibm.ws.sib.processor.impl.interfaces.UpstreamControl#sendAckMessage(com.ibm.ws.sib.trm.topology.Cellule, long, int, com.ibm.websphere.sib.Reliability, com.ibm.ws.sib.utils.SIBUuid12)
|
public void sendAckMessage(
SIBUuid8 meUuid,
SIBUuid12 destUuid,
SIBUuid8 busUuid,
long ackPrefix,
int priority,
Reliability reliability,
SIBUuid12 streamID,
boolean consolidate)
throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "sendAckMessage",
new Object[] { meUuid,
new Long(ackPrefix),
new Integer(priority),
reliability,
streamID });
ControlAck newAckMsg =
createControlAckMessage(
priority,
reliability,
streamID);
newAckMsg.setAckPrefix(ackPrefix);
try
{
_parentInputHandler.handleControlMessage(null, newAckMsg);
}
catch (SIException e)
{
// FFDC
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.PubSubOutputHandler.sendAckMessage",
"1:1731:1.164.1.5",
this);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
{
SibTr.exception(tc, e);
SibTr.exit(tc, "sendAckMessage", e);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "sendAckMessage");
}
|
Use the Nexpose::Connection to establish a correct HTTPS object.
|
def https(nsc, timeout = nil)
http = Net::HTTP.new(nsc.host, nsc.port)
http.read_timeout = (timeout || nsc.timeout)
http.open_timeout = nsc.open_timeout
http.use_ssl = true
if nsc.trust_store.nil?
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
else
http.cert_store = nsc.trust_store
end
http
end
|
// extractOperationOptionFromMethodDescriptor extracts the message of type
// swagger_options.Operation from a given proto method's descriptor.
|
func extractOperationOptionFromMethodDescriptor(meth *pbdescriptor.MethodDescriptorProto) (*swagger_options.Operation, error) {
if meth.Options == nil {
return nil, nil
}
if !proto.HasExtension(meth.Options, swagger_options.E_Openapiv2Operation) {
return nil, nil
}
ext, err := proto.GetExtension(meth.Options, swagger_options.E_Openapiv2Operation)
if err != nil {
return nil, err
}
opts, ok := ext.(*swagger_options.Operation)
if !ok {
return nil, fmt.Errorf("extension is %T; want an Operation", ext)
}
return opts, nil
}
|
Stores custom URL alias data for $path to the backup table.
@param int $locationId
@param string $path
@param string $languageCode
@param bool $alwaysAvailable
@param bool $forwarding
|
protected function storeCustomAliasPath(
$locationId,
$path,
$languageCode,
$alwaysAvailable,
$forwarding
) {
$queryBuilder = $this->connection->createQueryBuilder();
$queryBuilder->insert(static::CUSTOM_ALIAS_BACKUP_TABLE);
$queryBuilder->values(
[
'id' => '?',
'location_id' => '?',
'path' => '?',
'language_code' => '?',
'always_available' => '?',
'forwarding' => '?',
]
);
$queryBuilder->setParameter(0, 0);
$queryBuilder->setParameter(1, $locationId);
$queryBuilder->setParameter(2, $path);
$queryBuilder->setParameter(3, $languageCode);
$queryBuilder->setParameter(4, (int)$alwaysAvailable);
$queryBuilder->setParameter(5, (int)$forwarding);
$queryBuilder->execute();
}
|
Construct `Config` object and return a list.
:parse filename: A string containing the path to YAML file.
:return: list
|
def config(filename):
Config = collections.namedtuple('Config', [
'git',
'lock_file',
'version',
'name',
'src',
'dst',
'files',
'post_commands',
])
return [Config(**d) for d in _get_config_generator(filename)]
|
called when a label was clicked.
@param name
name of the lael
@param clickType
the type of click
|
private void processLabelClicked(final String name, final ClickType clickType) {
if (logger.isTraceEnabled()) {
logger.trace("JS reports label {} clicked {}", name, clickType);
}
synchronized (mapCoordinateElements) {
if (mapCoordinateElements.containsKey(name)) {
final MapCoordinateElement mapCoordinateElement = mapCoordinateElements.get(name).get();
if (mapCoordinateElement instanceof MapLabel) {
EventType<MapLabelEvent> eventType = null;
switch (clickType) {
case LEFT:
eventType = MapLabelEvent.MAPLABEL_CLICKED;
break;
case DOUBLE:
eventType = MapLabelEvent.MAPLABEL_DOUBLECLICKED;
break;
case RIGHT:
eventType = MapLabelEvent.MAPLABEL_RIGHTCLICKED;
break;
case MOUSEDOWN:
eventType = MapLabelEvent.MAPLABEL_MOUSEDOWN;
break;
case MOUSEUP:
eventType = MapLabelEvent.MAPLABEL_MOUSEUP;
break;
case ENTERED:
eventType = MapLabelEvent.MAPLABEL_ENTERED;
break;
case EXITED:
eventType = MapLabelEvent.MAPLABEL_EXITED;
break;
}
fireEvent(new MapLabelEvent(eventType, (MapLabel) mapCoordinateElement));
}
}
}
}
|
// NodeID returns the CN for the certificate encapsulated in this TransportCredentials
|
func (c *MutableTLSCreds) NodeID() string {
c.Lock()
defer c.Unlock()
return c.subject.CommonName
}
|
Returns an array of files
@return array
|
protected function getListFile()
{
$id = $this->getParam(0);
if (!isset($id)) {
return $this->file->getList(array('limit' => $this->getLimit()));
}
if ($this->getParam('type')) {
return $this->file->getList(array('file_type' => $id, 'limit' => $this->getLimit()));
}
if ($this->getParam('mime')) {
return $this->file->getList(array('mime_type' => $id, 'limit' => $this->getLimit()));
}
if ($this->getParam('entity')) {
return $this->file->getList(array('entity' => $id, 'limit' => $this->getLimit()));
}
if (!is_numeric($id)) {
$this->errorAndExit($this->text('Invalid argument'));
}
$result = $this->file->get($id);
if (empty($result)) {
$this->errorAndExit($this->text('Unexpected result'));
}
return array($result);
}
|
// CountBitsUintReference count 1's in x
|
func CountBitsUintReference(x uint) int {
c := 0
for x != 0 {
x &= x - 1
c++
}
return c
}
|
// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise.
|
func (p *ProjectCard) GetUpdatedAt() Timestamp {
if p == nil || p.UpdatedAt == nil {
return Timestamp{}
}
return *p.UpdatedAt
}
|
Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.
Args:
string (str): The string to convert.
Return
(float)
|
def energy_string_to_float( string ):
energy_re = re.compile( "(-?\d+\.\d+)" )
return float( energy_re.match( string ).group(0) )
|
Double Precision Shift Left.
|
public final void shld(Mem dst, Register src1, Immediate src2)
{
emitX86(INST_SHLD, dst, src1, src2);
}
|
Parses an individual tag line
@param string $line
@throws \InvalidArgumentException
@return \gossi\docblock\tags\AbstractTag
|
protected function parseTag($line) {
$matches = [];
if (!preg_match('/^@(' . self::REGEX_TAGNAME . ')(?:\s*([^\s].*)|$)?/us', $line, $matches)) {
throw new \InvalidArgumentException('Invalid tag line detected: ' . $line);
}
$tagName = $matches[1];
$content = isset($matches[2]) ? $matches[2] : '';
return TagFactory::create($tagName, $content);
}
|
// SetUsers sets the Users field's value.
|
func (s *SendUsersMessageRequest) SetUsers(v map[string]*EndpointSendConfiguration) *SendUsersMessageRequest {
s.Users = v
return s
}
|
// ListPodSandbox returns a list of PodSandboxes.
|
func (r *RemoteRuntimeService) ListPodSandbox(filter *runtimeapi.PodSandboxFilter) ([]*runtimeapi.PodSandbox, error) {
ctx, cancel := getContextWithTimeout(r.timeout)
defer cancel()
resp, err := r.runtimeClient.ListPodSandbox(ctx, &runtimeapi.ListPodSandboxRequest{
Filter: filter,
})
if err != nil {
klog.Errorf("ListPodSandbox with filter %+v from runtime service failed: %v", filter, err)
return nil, err
}
return resp.Items, nil
}
|
Remove event listener from event loop.
@param mixed $fd
@param int $flag
@return bool
|
public function del($fd, $flag)
{
switch ($flag) {
case EventInterface::EV_READ:
return $this->removeReadStream($fd);
case EventInterface::EV_WRITE:
return $this->removeWriteStream($fd);
case EventInterface::EV_SIGNAL:
return $this->removeSignal($fd);
case EventInterface::EV_TIMER:
case EventInterface::EV_TIMER_ONCE;
if (isset($this->_timerIdMap[$fd])){
$timer_obj = $this->_timerIdMap[$fd];
unset($this->_timerIdMap[$fd]);
$this->cancelTimer($timer_obj);
return true;
}
}
return false;
}
|
// NewStatsClient initializes a new stats client
|
func NewStatsClient(cr statscollector.Collector) (StatsClient, error) {
sc := &statsClient{
collector: cr,
rpchdl: rpcwrapper.NewRPCWrapper(),
secret: os.Getenv(constants.EnvStatsSecret),
statsChannel: os.Getenv(constants.EnvStatsChannel),
statsInterval: defaultStatsIntervalMiliseconds * time.Millisecond,
userRetention: defaultUserRetention * time.Minute,
stop: make(chan bool),
}
if sc.statsChannel == "" {
return nil, errors.New("no path to stats socket provided")
}
if sc.secret == "" {
return nil, errors.New("no secret provided for stats channel")
}
return sc, nil
}
|
// SetAgentType sets the AgentType field's value.
|
func (s *AgentInfo) SetAgentType(v string) *AgentInfo {
s.AgentType = &v
return s
}
|
Given a set of quad faces, return them as triangle faces.
Parameters
-----------
quads: (n, 4) int
Vertex indices of quad faces
Returns
-----------
faces : (m, 3) int
Vertex indices of triangular faces
|
def triangulate_quads(quads):
if len(quads) == 0:
return quads
quads = np.asanyarray(quads)
faces = np.vstack((quads[:, [0, 1, 2]],
quads[:, [2, 3, 0]]))
return faces
|
忽略指定的 path
@param {Array} ignores 忽略规则列表
@param {string} pathName 需要判断的 path
@return {boolean} 判断的结果
|
function ignoreMatch(ignores, pathName) {
let result = false;
ignores.forEach(ignore => {
if (minimatch(pathName, ignore)) {
result = true;
}
});
return result;
}
|
Get disabled algorithm constraints from the specified security property.
|
private static void loadDisabledAlgorithmsMap(
final String propertyName) {
String property = AccessController.doPrivileged(
new PrivilegedAction<String>() {
public String run() {
return Security.getProperty(propertyName);
}
});
String[] algorithmsInProperty = null;
if (property != null && !property.isEmpty()) {
// remove double quote marks from beginning/end of the property
if (property.charAt(0) == '"' &&
property.charAt(property.length() - 1) == '"') {
property = property.substring(1, property.length() - 1);
}
algorithmsInProperty = property.split(",");
for (int i = 0; i < algorithmsInProperty.length; i++) {
algorithmsInProperty[i] = algorithmsInProperty[i].trim();
}
}
// map the disabled algorithms
if (algorithmsInProperty == null) {
algorithmsInProperty = new String[0];
}
disabledAlgorithmsMap.put(propertyName, algorithmsInProperty);
// map the key constraints
KeySizeConstraints keySizeConstraints =
new KeySizeConstraints(algorithmsInProperty);
keySizeConstraintsMap.put(propertyName, keySizeConstraints);
}
|
// WeekdayWide returns the locales wide weekday given the 'weekday' provided
|
func (lv *lv) WeekdayWide(weekday time.Weekday) string {
return lv.daysWide[weekday]
}
|
Renders the container for the HTML template.
@param string $layout Page layout passed from template.
@param string $title Page title passed from template.
@return string
|
public function renderContainer($layout = null, $title = null)
{
return sprintf(
"<div class=\"%s\">\n%s</div>\n",
$this->getContainerClass(),
$this->renderChildren($layout, $title)
);
}
|
remove blank(or only includes space and tab) item in array
@param array
@returns {*}
|
function trimEndBlankLines(array) {
if (!array || array.length < 1) {
return array;
}
let temp;
while (array.length > 0) {
temp = array[array.length - 1];
if (temp === '' || Str.trim(temp, ' \t') === '') {
array.pop();
} else {
break;
}
}
return array;
}
|
// GenerateJobID returns a random job identifier, prefixed with the given host ID.
|
func GenerateJobID(hostID, uuid string) string {
if uuid == "" {
uuid = random.UUID()
}
return hostID + "-" + uuid
}
|
// Remove removes a container
|
func (c *ContainerServer) Remove(ctx context.Context, container string, force bool) (string, error) {
ctr, err := c.LookupContainer(container)
if err != nil {
return "", err
}
ctrID := ctr.ID()
cStatus := ctr.State()
switch cStatus.Status {
case oci.ContainerStatePaused:
return "", errors.Errorf("cannot remove paused container %s", ctrID)
case oci.ContainerStateCreated, oci.ContainerStateRunning:
if force {
_, err = c.ContainerStop(ctx, container, 10)
if err != nil {
return "", errors.Wrapf(err, "unable to stop container %s", ctrID)
}
} else {
return "", errors.Errorf("cannot remove running container %s", ctrID)
}
}
if err := c.runtime.DeleteContainer(ctr); err != nil {
return "", errors.Wrapf(err, "failed to delete container %s", ctrID)
}
if err := os.Remove(filepath.Join(c.Config().RuntimeConfig.ContainerExitsDir, ctrID)); err != nil && !os.IsNotExist(err) {
return "", errors.Wrapf(err, "failed to remove container exit file %s", ctrID)
}
c.RemoveContainer(ctr)
if err := c.storageRuntimeServer.DeleteContainer(ctrID); err != nil {
return "", errors.Wrapf(err, "failed to delete storage for container %s", ctrID)
}
c.ReleaseContainerName(ctr.Name())
if err := c.ctrIDIndex.Delete(ctrID); err != nil {
return "", err
}
return ctrID, nil
}
|
Draw r-hat for each plotter.
|
def plot_rhat(self, ax, xt_labelsize, titlesize, markersize):
""""""
for plotter in self.plotters.values():
for y, r_hat, color in plotter.r_hat():
if r_hat is not None:
ax.plot(r_hat, y, "o", color=color, markersize=markersize, markeredgecolor="k")
ax.set_xlim(left=0.9, right=2.1)
ax.set_xticks([1, 2])
ax.tick_params(labelsize=xt_labelsize)
ax.set_title("r_hat", fontsize=titlesize, wrap=True)
return ax
|
// Refresh implementation of terraform.ResourceProvider interface.
|
func (p *Provider) Refresh(
info *terraform.InstanceInfo,
s *terraform.InstanceState) (*terraform.InstanceState, error) {
r, ok := p.ResourcesMap[info.Type]
if !ok {
return nil, fmt.Errorf("unknown resource type: %s", info.Type)
}
return r.Refresh(s, p.meta)
}
|
追加子节点
@param ele
@returns {*}
|
function (ele) {
var node = this[0];
//结点类型判断
if (node.nodeType === 1 || node.nodeType === 11 || node.nodeType === 9) {
if(ele instanceof vQ){
ele.each(function(inx,ele){
node.appendChild(ele);
});
} else if(ele.nodeType){
node.appendChild(ele);
}
// string array
}
return this;
}
|
Assign the dialect.
@param string|object $dialect (string or object with __toString)
@return self
|
public function setDialect($dialect)
{
if (!Type::isStringLike($dialect)) {
throw new InvalidArgumentException('Dialect hast to be stringlike, not ' . Type::of($dialect));
}
$this->dialect = $dialect;
return $this;
}
|
Returns new Pooled {@link DataSource} implementation
@param poolProperties pool properties
@return new Pooled {@link DataSource} implementation
@throws SQLException
|
public static DataSource createDataSource(Properties poolProperties) throws SQLException {
assertNotNull(poolProperties);
try {
return BasicDataSourceFactory.createDataSource(poolProperties);
} catch (Exception e) {
throw new SQLException(e.getMessage());
}
}
|
Export a JWKS as a JSON document.
:param private: Whether it should be the private keys or the public
:param issuer: The entity ID.
:return: A JSON representation of a JWKS
|
def export_jwks_as_json(self, private=False, issuer=""):
return json.dumps(self.export_jwks(private, issuer))
|
Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
GRIDSET record.
|
private function _writePrintGridlines()
{
$record = 0x002b; // Record identifier
$length = 0x0002; // Bytes to follow
$fPrintGrid = $this->_phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag
$header = pack("vv", $record, $length);
$data = pack("v", $fPrintGrid);
$this->_append($header . $data);
}
|
Subsets and Splits
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.