comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
Get an entry from the Special sensor log.
:param index: Index for the sensor log entry to be obtained.
:return: Response containing the sensor log entry, or None if not found.
|
async def async_get_sensor_log(self, index: int) -> Optional[SensorLogResponse]:
response = await self._protocol.async_execute(
GetSensorLogCommand(index))
if isinstance(response, SensorLogResponse):
return response
return None
|
Get decision value for a consent campaign
REST: GET /me/consent/{campaignName}/decision
@param campaignName [required] Consent campaign name
|
public OvhConsent consent_campaignName_decision_GET(String campaignName) throws IOException {
String qPath = "/me/consent/{campaignName}/decision";
StringBuilder sb = path(qPath, campaignName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhConsent.class);
}
|
// IPv6 generates random IPv6 address
|
func (internet Internet) IPv6(v reflect.Value) (interface{}, error) {
return internet.ipv6(), nil
}
|
https://github.com/defunctzombie/node-uuid/blob/master/uuid.js
|
function unparse(buf, offset) {
var i = offset || 0;
return buf[i++].toString(16) + buf[i++].toString(16) +
buf[i++].toString(16) + buf[i++].toString(16) + '-' +
buf[i++].toString(16) + buf[i++].toString(16) + '-' +
buf[i++].toString(16) + buf[i++].toString(16) + '-' +
buf[i++].toString(16) + buf[i++].toString(16) + '-' +
buf[i++].toString(16) + buf[i++].toString(16) +
buf[i++].toString(16) + buf[i++].toString(16) +
buf[i++].toString(16) + buf[i++].toString(16);
}
|
Defines the object mappers registered in the orm.
@param OrmDefinition $orm
@return void
|
protected function define(OrmDefinition $orm)
{
$orm->valueObjects([
Directory::class => DirectoryMapper::class,
File::class => FileMapper::class,
Image::class => ImageMapper::class,
]);
}
|
Decide if the recently fetched data are still fresh enough
@param int $now current timestamp
@return bool true if no need to re-fetch, false otherwise
|
protected function cron_has_fresh_fetch($now) {
$recent = $this->get_last_timefetched();
if (empty($recent)) {
return false;
}
if ($now < $recent) {
$this->cron_mtrace('The most recent fetch is reported to be in the future, this is weird!');
return true;
}
if ($now - $recent > 24 * HOURSECS) {
return false;
}
return true;
}
|
Normalize numerical columns.
Args:
X (numpy.array) : numerical columns to normalize
Returns:
X (numpy.array): normalized numerical columns
|
def fit_transform(self, X, y=None):
self.ecdfs = [None] * X.shape[1]
for col in range(X.shape[1]):
self.ecdfs[col] = ECDF(X[:, col])
X[:, col] = self._transform_col(X[:, col], col)
return X
|
Redirect to the {@link cancelUrl} or simply close the popup window.
|
public function cancel($url = null)
{
$this->component->redirect(isset($url) ? $url : $this->cancelUrl, !$this->component->popup);
}
|
// NumServers takes out an internal "read lock" and returns the number of
// servers. numServers includes both healthy and unhealthy servers.
|
func (m *Manager) NumServers() int {
l := m.getServerList()
return len(l.servers)
}
|
// Retrieve a POST request field as a string.
// Returns `MissingFieldError` if requested field is missing.
|
func GetStringField(r *http.Request, fieldName string) (string, error) {
if _, ok := r.Form[fieldName]; !ok {
return "", MissingFieldError{fieldName}
}
return r.FormValue(fieldName), nil
}
|
Returns height of the (sub)tree, without considering
empty leaf-nodes
>>> create(dimensions=2).height()
0
>>> create([ (1, 2) ]).height()
1
>>> create([ (1, 2), (2, 3) ]).height()
2
|
def height(self):
min_height = int(bool(self))
return max([min_height] + [c.height()+1 for c, p in self.children])
|
Turns a dictionary into a bencoded str with alphabetized keys
e.g., {'spam': 'eggs', 'cow': 'moo'} --> d3:cow3:moo4:spam4:eggse
|
def bencode(canonical):
'''
'''
in_dict = dict(canonical)
def encode_str(in_str):
out_str = str(len(in_str)) + ':' + in_str
return out_str
def encode_int(in_int):
out_str = str('i' + str(in_int) + 'e')
return out_str
def encode_list(in_list):
out_str = 'l'
for item in in_list:
out_str += encode_item(item)
else:
out_str += 'e'
return out_str
def encode_dict(in_dict):
out_str = 'd'
keys = sorted(in_dict.keys())
for key in keys:
val = in_dict[key]
out_str = out_str + encode_item(key) + encode_item(val)
else:
out_str += 'e'
return out_str
def encode_item(x):
if isinstance(x, str):
return encode_str(x)
elif isinstance(x, int):
return encode_int(x)
elif isinstance(x, list):
return encode_list(x)
elif isinstance(x, dict):
return encode_dict(x)
return encode_item(in_dict)
|
// createFile is a helper function to call [Nt]CreateFile to get a handle to
// the file or directory.
|
func createFile(name string, isDir bool) (syscall.Handle, error) {
namep := syscall.StringToUTF16(name)
da := uint32(desiredAccessReadControl | desiredAccessWriteDac)
sm := uint32(shareModeRead | shareModeWrite)
fa := uint32(syscall.FILE_ATTRIBUTE_NORMAL)
if isDir {
fa = uint32(fa | syscall.FILE_FLAG_BACKUP_SEMANTICS)
}
fd, err := syscall.CreateFile(&namep[0], da, sm, nil, syscall.OPEN_EXISTING, fa, 0)
if err != nil {
return 0, errors.Wrapf(err, "%s syscall.CreateFile %s", gvmga, name)
}
return fd, nil
}
|
Execute the console command.
@return void
|
public function fire()
{
if ($this->downForMaintenance()) return;
$queue = $this->option('queue');
$delay = $this->option('delay');
// The memory limit is the amount of memory we will allow the script to occupy
// before killing it and letting a process manager restart it for us, which
// is to protect us against any memory leaks that will be in the scripts.
$memory = $this->option('memory');
$connection = $this->argument('connection');
$this->worker->pop($connection, $queue, $delay, $memory, $this->option('sleep'), $this->option('tries'));
}
|
Lists all the debuggees that the user has access to.
@param \Google\Cloud\Debugger\V2\ListDebuggeesRequest $argument input argument
@param array $metadata metadata
@param array $options call options
|
public function ListDebuggees(\Google\Cloud\Debugger\V2\ListDebuggeesRequest $argument,
$metadata = [], $options = []) {
return $this->_simpleRequest('/google.devtools.clouddebugger.v2.Debugger2/ListDebuggees',
$argument,
['\Google\Cloud\Debugger\V2\ListDebuggeesResponse', 'decode'],
$metadata, $options);
}
|
保存数据
@param array $option 参数
|
public function save($fileName = null)
{
file_put_contents(empty($fileName) ? $this->fileName : $fileName, json_encode($this->data), LOCK_EX);
}
|
Set indicator name.
@param string|null $indicator Symbolic name of indicator to use or null for no indicator
@return $this
|
public function setIndicator( $indicator = null ) {
if ( $this->indicatorName !== null ) {
$this->indicator->removeClasses( [ 'oo-ui-indicator-' . $this->indicatorName ] );
}
if ( $indicator !== null ) {
$this->indicator->addClasses( [ 'oo-ui-indicator-' . $indicator ] );
}
$this->indicatorName = $indicator;
$this->toggleClasses( [ 'oo-ui-indicatorElement' ], (bool)$this->indicatorName );
$this->indicator->toggleClasses( [ 'oo-ui-indicatorElement-noIndicator' ],
!$this->indicatorName );
return $this;
}
|
// UnmarshalJSON sets the object from the provided JSON representation
|
func (l *CodeBuildProjectEnvironmentList) UnmarshalJSON(buf []byte) error {
// Cloudformation allows a single object when a list of objects is expected
item := CodeBuildProjectEnvironment{}
if err := json.Unmarshal(buf, &item); err == nil {
*l = CodeBuildProjectEnvironmentList{item}
return nil
}
list := []CodeBuildProjectEnvironment{}
err := json.Unmarshal(buf, &list)
if err == nil {
*l = CodeBuildProjectEnvironmentList(list)
return nil
}
return err
}
|
Get campaign ids, membership id and full name from SESSION.
@param int $campaignId
Campaign node ID.
@return array MemberCampaign data from SESSION.
|
public static function getMemberCampaignData($campaignId) {
$request = \Drupal::request();
$session = $request->getSession();
$openyCampaignSession = $session->get('openy_campaign', [
'campaign_ids' => [],
'member_ids' => [],
'membership_ids' => [],
'full_names' => [],
]);
$membershipIDs = $openyCampaignSession['membership_ids'];
$fullNames = $openyCampaignSession['full_names'];
$memberIDs = $openyCampaignSession['member_ids'];
return [
'campaign_id' => $campaignId,
'membership_id' => !empty($membershipIDs[$campaignId]) ? $membershipIDs[$campaignId] : '',
'full_name' => !empty($fullNames[$campaignId]) ? $fullNames[$campaignId] : '',
'member_id' => !empty($memberIDs[$campaignId]) ? $memberIDs[$campaignId] : '',
];
}
|
Return the parent scope.
:return: FoldScope or None
|
def parent(self):
if TextBlockHelper.get_fold_lvl(self._trigger) > 0 and \
self._trigger.blockNumber():
block = self._trigger.previous()
ref_lvl = self.trigger_level - 1
while (block.blockNumber() and
(not TextBlockHelper.is_fold_trigger(block) or
TextBlockHelper.get_fold_lvl(block) > ref_lvl)):
block = block.previous()
try:
return FoldScope(block)
except ValueError:
return None
return None
|
Creates a request from a method function call.
|
def make_request(self, method, *args, **kwargs):
""""""
if args and not use_signature:
raise NotImplementedError("Only keyword arguments allowed in Python2")
new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items()}
if use_signature:
new_args = tuple(unwrap(value) for value in args)
bound_args = method.signature.bind(
unwrap(self), *new_args, **new_kwargs).arguments
# if we encounter any Enum arguments, replace them with their value
def translate_enum(arg):
return arg.value if isinstance(arg, Enum) else arg
for k in bound_args:
if isinstance(bound_args[k], str):
continue
if isinstance(bound_args[k], dict):
continue
try:
x = [translate_enum(arg) for arg in bound_args[k]]
bound_args[k] = x
except TypeError:
bound_args[k] = translate_enum(bound_args[k])
# replace `self` with the correct keyword
new_kwargs = {(kw if kw != 'self' else method.field_name): v
for kw, v in bound_args.items()}
# args = tuple(x.value if isinstance(x, Enum) else x for x in args)
else:
new_kwargs[self.field_name] = unwrap(self)
return method.request_type(**new_kwargs)
|
Generates cryptographically strong pseudo-random data.
@param {Numbers} length How many bytes of data you want.
@return {Buffer} The random data as a Buffer.
|
function(length) {
var array, byte, _i, _len, _results;
array = new Uint8Array(length);
window.crypto.getRandomValues(array);
_results = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
byte = array[_i];
_results.push(byte);
}
return _results;
}
|
Survey source synchronization check function
@param string $sourceSurveyId
@param int $surveyId
@param int $userId
@return mixed message string or array of messages
|
public function checkSurvey($sourceSurveyId, $surveyId, $userId)
{
$changed = 0;
$created = false;
$deleted = false;
$deletedFile = false;
$survey = $this->tracker->getSurvey($surveyId);
// Get OpenRosa data
if ($sourceSurveyId) {
// Surveys in OpenRose
$db = $this->getSourceDatabase();
$select = $db->select();
$select->from('gems__openrosaforms')
->where('gof_id = ?', $sourceSurveyId);
$openRosaSurvey = $db->fetchRow($select);
} else {
$openRosaSurvey = false;
}
if ($openRosaSurvey) {
// Exists
$values['gsu_survey_name'] = sprintf(
'%s [%s]',
$openRosaSurvey['gof_form_title'],
$openRosaSurvey['gof_form_version']
);
$values['gsu_status'] = 'OK';
$values['gsu_surveyor_active'] = $openRosaSurvey['gof_form_active'];
if (!$surveyId) {
// New
$values['gsu_active'] = 0;
$values['gsu_id_source'] = $this->getId();
$values['gsu_surveyor_id'] = $sourceSurveyId;
$created = true;
}
if (!$this->sourceFileExists($openRosaSurvey['gof_form_xml'])) {
// No longer exists
$values['gsu_surveyor_active'] = 0;
$values['gsu_status'] = 'Survey form XML was removed from directory.';
$deletedFile = true;
}
} else {
// No longer exists
$values['gsu_surveyor_active'] = 0;
$values['gsu_status'] = 'Survey was removed from source.';
$deleted = true;
}
$changed = $survey->saveSurvey($values, $userId);
if (! $changed) {
return;
}
if ($deleted) {
$message = $this->_('The \'%s\' survey is no longer active. The survey was removed from OpenRosa!');
} elseif ($deletedFile) {
$message = $this->_('The \'%s\' survey is no longer active. The survey XML file was removed from its directory!');
} elseif ($created) {
$message = $this->_('Imported the \'%s\' survey.');
} else {
$message = $this->_('Updated the \'%s\' survey.');
}
return sprintf($message, $survey->getName());;
}
|
Finds and initializes the phpDocumentor installation
|
private function initializePhpDocumentor()
{
$phpDocumentorPath = '';
if (!empty($this->pharLocation)) {
include_once 'phar://' . $this->pharLocation . '/vendor/autoload.php';
if (!class_exists('phpDocumentor\\Bootstrap')) {
throw new BuildException(
$this->pharLocation . ' does not look like a phpDocumentor 2 .phar'
);
}
} elseif (class_exists('Composer\\Autoload\\ClassLoader', false)) {
if (!class_exists('phpDocumentor\\Bootstrap')) {
throw new BuildException('You need to install phpDocumentor 2 or add your include path to your composer installation.');
}
} else {
$phpDocumentorPath = $this->findPhpDocumentorPath();
if (empty($phpDocumentorPath)) {
throw new BuildException("Please make sure phpDocumentor 2 is installed and on the include_path.");
}
set_include_path($phpDocumentorPath . PATH_SEPARATOR . get_include_path());
include_once $phpDocumentorPath . '/phpDocumentor/Bootstrap.php';
}
$this->app = \phpDocumentor\Bootstrap::createInstance()->initialize();
$this->phpDocumentorPath = $phpDocumentorPath;
}
|
Returns the maximum bounds of the ripple relative to the ripple center.
|
public void getBounds(Rect bounds) {
final int outerX = (int) mTargetX;
final int outerY = (int) mTargetY;
final int r = (int) mTargetRadius + 1;
bounds.set(outerX - r, outerY - r, outerX + r, outerY + r);
}
|
// SetQueryLoggingConfigs sets the QueryLoggingConfigs field's value.
|
func (s *ListQueryLoggingConfigsOutput) SetQueryLoggingConfigs(v []*QueryLoggingConfig) *ListQueryLoggingConfigsOutput {
s.QueryLoggingConfigs = v
return s
}
|
Reverse-finds all files and directories with a given name/subpath
@param string $name
@param boolean $reload
@param string $type
|
public function findAllReversed($name, $reload = false, $type = 'all')
{
return $this->findAll($name, $reload, true, $type);
}
|
Performs encoding of url matrix parameters from dictionary to
a string.
See http://www.w3.org/DesignIssues/MatrixURIs.html for specs.
|
def encode_matrix_parameters(parameters):
result = []
for param in iter(sorted(parameters)):
if isinstance(parameters[param], (list, tuple)):
value = (';%s=' % (param)).join(parameters[param])
else:
value = parameters[param]
result.append("%s=%s" % (param, value))
return ';'.join(result)
|
// PeekNextTokenType returns only the token type
// of the next character and it does not move forward the cursor.
// It's being used by parser to recognise empty functions, i.e `even()`
// as valid functions with zero input arguments.
|
func (l *Lexer) PeekNextTokenType() token.Type {
if len(l.input)-1 > l.pos {
ch := l.input[l.pos]
return resolveTokenType(ch)
}
return resolveTokenType(0) // EOF
}
|
Construct a unique selector for the `el` element within this view. `prevSelector` is being collected through the recursive call. No value for `prevSelector` is expected when using this method.
|
function(el, prevSelector) {
var selector;
if (el === this.el) {
if (typeof prevSelector === 'string') selector = '> ' + prevSelector;
return selector;
}
if (el) {
var nthChild = V(el).index() + 1;
selector = el.tagName + ':nth-child(' + nthChild + ')';
if (prevSelector) {
selector += ' > ' + prevSelector;
}
selector = this.getSelector(el.parentNode, selector);
}
return selector;
}
|
Builds SQL for selecting articles by price
@param double $dPriceFrom Starting price
@param double $dPriceTo Max price
@return string
|
protected function _getPriceSelect($dPriceFrom, $dPriceTo)
{
$oBaseObject = $this->getBaseObject();
$sArticleTable = $oBaseObject->getViewName();
$sSelectFields = $oBaseObject->getSelectFields();
$sSelect = "select {$sSelectFields} from {$sArticleTable} where oxvarminprice >= 0 ";
$sSelect .= $dPriceTo ? "and oxvarminprice <= " . (double) $dPriceTo . " " : " ";
$sSelect .= $dPriceFrom ? "and oxvarminprice >= " . (double) $dPriceFrom . " " : " ";
$sSelect .= " and " . $oBaseObject->getSqlActiveSnippet() . " and {$sArticleTable}.oxissearch = 1";
if (!$this->_sCustomSorting) {
$sSelect .= " order by {$sArticleTable}.oxvarminprice asc , {$sArticleTable}.oxid";
} else {
$sSelect .= " order by {$this->_sCustomSorting}, {$sArticleTable}.oxid ";
}
return $sSelect;
}
|
Read a grp file at the path specified by in_path.
Args:
in_path (string): path to GRP file
Returns:
grp (list)
|
def read(in_path):
assert os.path.exists(in_path), "The following GRP file can't be found. in_path: {}".format(in_path)
with open(in_path, "r") as f:
lines = f.readlines()
# need the second conditional to ignore comment lines
grp = [line.strip() for line in lines if line and not re.match("^#", line)]
return grp
|
// CmdStart start cmdFile.
|
func (c *Cmd) CmdStart() error {
var err error
// CmdLine check
if c.CmdLine != "" && c.Cmd == nil {
parseCmd, err := shellwords.Parse(c.CmdLine)
if err != nil {
return err
}
c.Cmd = exec.Command(parseCmd[0], parseCmd[1:]...)
}
if c.CmdLine == "" {
c.CmdLine = strings.Join(c.Cmd.Args, " ")
}
var stdoutPipe, stderrPipe io.ReadCloser
if !c.stdoutPipe {
stdoutPipe, err = c.Cmd.StdoutPipe()
if err != nil {
return err
}
}
if !c.stderrPipe {
stderrPipe, err = c.Cmd.StderrPipe()
if err != nil {
return err
}
}
// Start command.
err = c.Cmd.Start()
if err != nil {
c.ExitError = err
c.GetExitCode()
return err
}
scanWrite := func(c *Cmd, r io.ReadCloser, w io.Writer, enc *encoding.Decoder, print bool) {
if r == nil {
return
}
c.Wg.Add(1)
go func() {
defer c.Wg.Done()
if enc == nil {
ScanWrite(bufio.NewScanner(r), w, print)
} else {
ScanWrite(bufio.NewScanner(transform.NewReader(r, enc)), w, print)
}
}()
}
scanWrite(c, stdoutPipe, &c.Stdout, c.StdoutEnc, c.StdoutPrint)
scanWrite(c, stderrPipe, &c.Stderr, c.StderrEnc, c.StderrPrint)
return nil
}
|
Return configuration value by key
@param string $configKey The identifier to read configuration
of application.
@return array Configuration value
|
protected function _getConfigValueArray($configKey = null) {
$result = [];
if (empty($configKey)) {
return $result;
}
$configPath = 'CakeInstaller.' . $configKey;
if (!Configure::check($configPath)) {
return $result;
}
$configValue = (array)Configure::read($configPath);
if (!empty($configValue)) {
$result = $configValue;
}
return $result;
}
|
Imports the media library to the cloud.
@when after_wp_load
@param $args
@param $assoc_args
|
public function import($args, $assoc_args) {
$this->debugMode = (\WP_CLI::get_config('debug') == 'mediacloud');
// Force the logger to initialize
Logger::instance();
/** @var StorageTool $storageTool */
$storageTool = ToolsManager::instance()->tools['storage'];
if (!$storageTool || !$storageTool->enabled()) {
Command::Error('Storage tool is not enabled in Media Cloud or the settings are incorrect.');
return;
}
$postArgs = [
'post_type' => 'attachment',
'post_status' => 'inherit',
'nopaging' => true,
'fields' => 'ids',
];
if(!StorageSettings::uploadDocuments()) {
$args['post_mime_type'] = 'image';
}
$query = new \WP_Query($postArgs);
if($query->post_count > 0) {
BatchManager::instance()->reset('storage');
BatchManager::instance()->setStatus('storage', true);
BatchManager::instance()->setTotalCount('storage', $query->post_count);
BatchManager::instance()->setCurrent('storage', 1);
BatchManager::instance()->setShouldCancel('storage', false);
Command::Info("Total posts found: %Y{$query->post_count}.", true);
$pd = new DefaultProgressDelegate();
for($i = 1; $i <= $query->post_count; $i++) {
$postId = $query->posts[$i - 1];
$upload_file = get_attached_file($postId);
$fileName = basename($upload_file);
BatchManager::instance()->setCurrentFile('storage', $fileName);
BatchManager::instance()->setCurrent('storage', $i);
Command::Info("%w[%C{$i}%w of %C{$query->post_count}%w] %NImporting %Y$fileName%N %w(Post ID %N$postId%w)%N ... ", $this->debugMode);
$storageTool->processImport($i - 1, $postId, $pd);
if (!$this->debugMode) {
Command::Info("%YDone%N.", true);
}
}
BatchManager::instance()->reset('storage');
}
}
|
Executes an SQL query on the storage engine. Should be used for SELECT
only.
@access public
@author Jerome Bogaerts, <jerome@taotesting.com>
@param string statement
@param array params
@return PDOStatement
|
public function query($statement, $params = array())
{
$returnValue = null;
// $trace=debug_backtrace();
// $caller=array_shift($trace);
// $caller=array_shift($trace);
// common_Logger::d('trace : '. $caller['function'] .$caller['class'] );
// common_Logger::d($statement . implode('|', $params));
$sth = $this->persistence->query($statement,$params);
if (!empty($sth)){
$returnValue = $sth;
}
$this->incrementNrOfQueries();
return $returnValue;
}
|
Exports the {@link MutationState} into a universal format, which can be used either to serialize it into
a N1QL query or to send it over the network to a different application/SDK.
@return the exported {@link JsonObject}.
|
public JsonObject export() {
JsonObject result = JsonObject.create();
for (MutationToken token : tokens) {
JsonObject bucket = result.getObject(token.bucket());
if (bucket == null) {
bucket = JsonObject.create();
result.put(token.bucket(), bucket);
}
bucket.put(
String.valueOf(token.vbucketID()),
JsonArray.from(token.sequenceNumber(), String.valueOf(token.vbucketUUID()))
);
}
return result;
}
|
Reads a private key from keystore
@param alias
@param password
@return
@throws UnrecoverableKeyException
@throws KeyStoreException
@throws NoSuchAlgorithmException
|
public Key getPrivateKey(String alias, String password) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {
return this.keystore.getKey(alias, password.toCharArray());
}
|
(Lazy)load list of all supported symbols (sorted)
Look into `_data()` for all currency symbols, then sort by length and
unicode-ord (A-Z is not as relevant as ֏).
Returns:
List[unicode]: Sorted list of possible currency symbols.
|
def _symbols():
global _SYMBOLS
if _SYMBOLS is None:
tmp = [(s, 'symbol') for s in _data()['symbol'].keys()]
tmp += [(s, 'alpha3') for s in _data()['alpha3'].keys()]
tmp += [(s.name, 'name') for s in _data()['alpha3'].values()]
_SYMBOLS = sorted(
tmp,
key=lambda s: (len(s[0]), ord(s[0][0])),
reverse=True)
return _SYMBOLS
|
// SetInitiator sets the Initiator field's value.
|
func (s *ListPartsOutput) SetInitiator(v *Initiator) *ListPartsOutput {
s.Initiator = v
return s
}
|
/*
(non-Javadoc)
@see org.fcrepo.server.access.FedoraAPIA#resumeFindObjects(String
sessionToken )*
|
@Override
public org.fcrepo.server.types.gen.FieldSearchResult resumeFindObjects(String sessionToken) {
MessageContext ctx = context.getMessageContext();
Context context = ReadOnlyContext.getSoapContext(ctx);
assertInitialized();
try {
org.fcrepo.server.search.FieldSearchResult result =
m_access.resumeFindObjects(context, sessionToken);
return TypeUtility
.convertFieldSearchResultToGenFieldSearchResult(result);
} catch (Throwable th) {
LOG.error("Error resuming finding objects", th);
throw CXFUtility.getFault(th);
}
}
|
Attempts to label this invoice with a status. Note that an invoice can be more than one of the choices.
We just set a priority on which status appears.
|
def status(self):
if self.paid:
return self.STATUS_PAID
if self.forgiven:
return self.STATUS_FORGIVEN
if self.closed:
return self.STATUS_CLOSED
return self.STATUS_OPEN
|
直接读取对象成员值,无视 private/protected 修饰符,不经过 getter 函数。
@param target
目标对象
@param name
成员名
@param <T>
期待的成员值类型
@return 成员值
|
public static <T> T getFieldValue(final Object target, final String name) {
Field field = FieldUtils.getDeclaredField(target.getClass(), name, true);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" + name + "] on target [" + target + ']');
}
T result = null;
try {
result = (T) field.get(target);
} catch (IllegalAccessException e) {
throw new ImpossibleException(e);
}
return result;
}
|
/*
(non-Javadoc)
@see
javax.persistence.criteria.CriteriaBuilder#or(javax.persistence.criteria
.Expression, javax.persistence.criteria.Expression)
|
@Override
public Predicate or(Expression<Boolean> arg0, Expression<Boolean> arg1)
{
// TODO Auto-generated method stub
if (arg0 != null && arg1 != null)
{
if (arg0.getClass().isAssignableFrom(ComparisonPredicate.class) && arg1.getClass().isAssignableFrom(ComparisonPredicate.class))
{
return new DisjunctionPredicate((Predicate)arg0, (Predicate)arg1);
}
}
return null;
}
|
Check if table exists
@param string $table
@return bool
|
public function hasTable($table)
{
$parts = explode('.', $table);
if (count($parts) == 1) {
$db = $this->db->getDbname();
$table = $parts[0];
} else {
list($db, $table) = $parts;
}
$tableExistsSql = $this->checkTableSqls[$this->db->getDriver()];
return (bool) $this->db->fetchColumn($tableExistsSql, array($db, $table));
}
|
parse route file and put data in an array
@access protected
@param $src string
@param $controller string
@param $annotation array
@since 3.0
@package Gcs\Framework\Core\Config
|
protected function _parseAnnotationRoute($src, $controller, $annotation) {
foreach ($annotation['methods'] as $action => $annotationMethods) {
$data = [];
foreach ($annotationMethods as $annotationMethod) {
if ($annotationMethod['annotation'] == 'Routing') {
/** @var \Gcs\Framework\Core\Annotation\Annotations\Router\Routing $annotation */
$annotation = $annotationMethod['instance'];
$data['name'] = $annotation->name;
$data['url'] = $annotation->url;
$data['vars'] = $annotation->vars;
$data['method'] = $annotation->method;
$data['access'] = $annotation->access;
$data['cache'] = $annotation->cache;
$data['logged'] = $annotation->logged;
$data['action'] = lcfirst(basename($controller, '.php')) . '.' . lcfirst(str_replace('action', '', $action));
}
$this->config['route'][$src][$data['name']] = $data;
}
}
}
|
------------------------------------------------------------------------
|
public JobClient getJobClient(JobGraph jobGraph) throws Exception {
Configuration configuration = jobGraph.getJobConfiguration();
configuration.setString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, "localhost");
configuration.setInteger(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY, jobManagerRpcPort);
return new JobClient(jobGraph, configuration);
}
|
// contains returns true and the offset if the label is in the range (and aligned), and false
// and nil otherwise.
|
func (r *Allocator) contains(label *mcs.Label) (bool, uint64) {
return r.r.Offset(label)
}
|
Return the record for the ip_address in the MaxMind DB
Arguments:
ip_address -- an IP address in the standard string notation
|
def get(self, ip_address):
address = ipaddress.ip_address(ip_address)
if address.version == 6 and self._metadata.ip_version == 4:
raise ValueError('Error looking up {0}. You attempted to look up '
'an IPv6 address in an IPv4-only database.'.format(
ip_address))
pointer = self._find_address_in_tree(address)
return self._resolve_data_pointer(pointer) if pointer else None
|
setup observations from PEST-style SMP file pairs
|
def setup_smp(self):
if self.obssim_smp_pairs is None:
return
if len(self.obssim_smp_pairs) == 2:
if isinstance(self.obssim_smp_pairs[0],str):
self.obssim_smp_pairs = [self.obssim_smp_pairs]
for obs_smp,sim_smp in self.obssim_smp_pairs:
self.log("processing {0} and {1} smp files".format(obs_smp,sim_smp))
if not os.path.exists(obs_smp):
self.logger.lraise("couldn't find obs smp: {0}".format(obs_smp))
if not os.path.exists(sim_smp):
self.logger.lraise("couldn't find sim smp: {0}".format(sim_smp))
new_obs_smp = os.path.join(self.m.model_ws,
os.path.split(obs_smp)[-1])
shutil.copy2(obs_smp,new_obs_smp)
new_sim_smp = os.path.join(self.m.model_ws,
os.path.split(sim_smp)[-1])
shutil.copy2(sim_smp,new_sim_smp)
pyemu.smp_utils.smp_to_ins(new_sim_smp)
|
Check that commands are either lower case or upper case, but not both
|
def CheckUpperLowerCase(filename, linenumber, clean_lines, errors):
line = clean_lines.lines[linenumber]
if ContainsCommand(line):
command = GetCommand(line)
if IsCommandMixedCase(command):
return errors(
filename,
linenumber,
'readability/wonkycase',
'Do not use mixed case commands')
if clean_lines.have_seen_uppercase is None:
clean_lines.have_seen_uppercase = IsCommandUpperCase(command)
else:
is_upper = IsCommandUpperCase(command)
if is_upper != clean_lines.have_seen_uppercase:
return errors(
filename,
linenumber,
'readability/mixedcase',
'Do not mix upper and lower case commands')
|
Perform batch import into database.
|
private void batchImport() {
m_jdbcTemplate.batchUpdate(createInsertQuery(),
new BatchPreparedStatementSetter() {
public void setValues(
PreparedStatement ps, int i)
throws SQLException {
int j = 1;
for (String property : m_propertyNames) {
Map params = (Map) m_batch.get(
i);
ps.setObject(j++, params.get(
property));
}
}
public int getBatchSize() {
return m_batch.size();
}
});
}
|
<p>
The Amazon Resource Names (ARN) of one or more principals. Permissions are revoked for principals in this list.
</p>
@return The Amazon Resource Names (ARN) of one or more principals. Permissions are revoked for principals in this
list.
|
public java.util.List<String> getRemoveAllowedPrincipals() {
if (removeAllowedPrincipals == null) {
removeAllowedPrincipals = new com.amazonaws.internal.SdkInternalList<String>();
}
return removeAllowedPrincipals;
}
|
// Index sets the indices on which to perform the delete operation.
|
func (s *DeleteByQueryService) Index(index ...string) *DeleteByQueryService {
s.index = append(s.index, index...)
return s
}
|
取消刷新
@param appid appid
@param types ticket 类型 [jsapi,wx_card]
|
public static void destroyed(String appid,String... types){
for(String type : types){
String key = appid + KEY_JOIN + type;
if(futureMap.containsKey(key)){
futureMap.get(key).cancel(true);
logger.info("destroyed appid:{} type:{}",appid,type);
}
}
}
|
Returns the processed response to PUBSUB NUMSUB.
@param array $channels List of channels
@return array
|
protected static function processNumsub(array $channels)
{
$processed = array();
$count = count($channels);
for ($i = 0; $i < $count; ++$i) {
$processed[$channels[$i]] = $channels[++$i];
}
return $processed;
}
|
Check Qt binding requirements
|
def check_qt():
""""""
qt_infos = dict(pyqt5=("PyQt5", "5.6"))
try:
import qtpy
package_name, required_ver = qt_infos[qtpy.API]
actual_ver = qtpy.PYQT_VERSION
if LooseVersion(actual_ver) < LooseVersion(required_ver):
show_warning("Please check Spyder installation requirements:\n"
"%s %s+ is required (found v%s)."
% (package_name, required_ver, actual_ver))
except ImportError:
show_warning("Failed to import qtpy.\n"
"Please check Spyder installation requirements:\n\n"
"qtpy 1.2.0+ and\n"
"%s %s+\n\n"
"are required to run Spyder."
% (qt_infos['pyqt5']))
|
Add a new metrics to the registry
@param metricsName - the name
@param theMetricsObj - the metrics
@throws IllegalArgumentException if a name is already registered
|
public void add(final String metricsName, final MetricsBase theMetricsObj) {
if (metricsList.putIfAbsent(metricsName, theMetricsObj) != null) {
throw new IllegalArgumentException("Duplicate metricsName:" + metricsName);
}
}
|
returns a list of countries and there codes
@return array
|
public static function countriesList()
{
$path = dirname(realpath(__FILE__)).DIRECTORY_SEPARATOR.'data/countries.json';
$countries = self::readJson($path, true);
$listCountries = [];
foreach ($countries['Names'] as $code => $value) {
$listCountries[$code] = $value;
}
return $listCountries;
}
|
// Free frees the RWops structure allocated by AllocRW().
// (https://wiki.libsdl.org/SDL_FreeRW)
|
func (rwops *RWops) Free() error {
if rwops == nil {
return ErrInvalidParameters
}
C.SDL_FreeRW(rwops.cptr())
return nil
}
|
Get totp status for the supplied identifier
@param string $identifier
@return Totp
@throws Exception
|
public function getTotp($identifier)
{
$totp = $this->factory->createEmptyTotp();
$totp->populate($identifier);
return $totp;
}
|
Returns the physical volume mda count.
|
def mda_count(self):
self.open()
mda = lvm_pv_get_mda_count(self.handle)
self.close()
return mda
|
// LitByte renders a byte literal.
|
func (g *Group) LitByte(v byte) *Statement {
s := LitByte(v)
g.items = append(g.items, s)
return s
}
|
@param string $path
@param array $params
@param string $method
@param null $body
@param array $headers
@return \Psr\Http\Message\ResponseInterface
|
public function request(string $path, array $params = null, string $method = null, $body = null, array $headers = null):ResponseInterface{
parse_str(parse_url($this->apiURL.$path, PHP_URL_QUERY), $query);
$query['v'] = $this::API_VERSIONDATE;
$query['m'] = 'foursquare';
return parent::request(explode('?', $path)[0], array_merge($params ?? [], $query), $method, $body, $headers);
}
|
Custom read() function
@access private
|
function read($session_id)
{
// get the lock name, associated with the current session
$this->session_lock = $this->_mysql_real_escape_string('session_' . $session_id);
// try to obtain a lock with the given name and timeout
$result = $this->_mysql_query('SELECT GET_LOCK("' . $this->session_lock . '", ' . $this->_mysql_real_escape_string($this->lock_timeout) . ')');
// if there was an error
// stop execution
if (!is_object($result) || strtolower(get_class($result)) != 'mysqli_result' || @mysqli_num_rows($result) != 1 || !($row = mysqli_fetch_array($result)) || $row[0] != 1) die('Session Worker: Could not obtain session lock!');
// reads session data associated with a session id, but only if
// - the session ID exists;
// - the session has not expired;
// - if lock_to_user_agent is TRUE and the HTTP_USER_AGENT is the same as the one who had previously been associated with this particular session;
// - if lock_to_ip is TRUE and the host is the same as the one who had previously been associated with this particular session;
$hash = '';
// if we need to identify sessions by also checking the user agent
if ($this->lock_to_user_agent && isset($_SERVER['HTTP_USER_AGENT']))
$hash .= $_SERVER['HTTP_USER_AGENT'];
// if we need to identify sessions by also checking the host
if ($this->lock_to_ip && isset($_SERVER['REMOTE_ADDR']))
$hash .= $_SERVER['REMOTE_ADDR'];
// append this to the end
$hash .= $this->security_code;
$result = $this->_mysql_query('
SELECT
session_data
FROM
' . $this->table_name . '
WHERE
session_id = "' . $this->_mysql_real_escape_string($session_id) . '" AND
session_expire > "' . time() . '" AND
hash = "' . $this->_mysql_real_escape_string(md5($hash)) . '"
LIMIT 1
') or die($this->_mysql_error());
// if anything was found
if (is_object($result) && strtolower(get_class($result)) == 'mysqli_result' && @mysqli_num_rows($result) > 0) {
// return found data
$fields = @mysqli_fetch_assoc($result);
// don't bother with the unserialization - PHP handles this automatically
return $fields['session_data'];
}
$this->regenerate_id();
// on error return an empty string - this HAS to be an empty string
return '';
}
|
// SetStyle sets the style (e.g.: BASE, BOOTSTRAP) of the field, correctly populating the Widget field.
|
func (f *Field) SetStyle(style string) FieldInterface {
f.tmplStyle = style
f.Widget = widgets.BaseWidget(style, f.fieldType, f.tmpl)
return f
}
|
Set key pattern
@param null|string $keyPattern
@throws Exception\InvalidArgumentException
@return AdapterOptions
|
public function setKeyPattern($keyPattern)
{
$keyPattern = (string)$keyPattern;
if ($this->keyPattern !== $keyPattern) {
// validate pattern
if ($keyPattern !== '') {
ErrorHandler::start(E_WARNING);
$result = preg_match($keyPattern, '');
$error = ErrorHandler::stop();
if ($result === false) {
throw new Exception\InvalidArgumentException(
sprintf(
'Invalid pattern "%s"%s',
$keyPattern,
($error ? ': ' . $error->getMessage() : '')
),
0,
$error
);
}
}
$this->keyPattern = $keyPattern;
}
return $this;
}
|
// see interface
|
func (s *schedule) GetOption(timestamp uint32, length uint32) (id string, score uint) {
id = random.String(32)
score = s.getConflicts(timestamp, length)
item := &scheduledItem{
id: id,
deadlineAt: s.realtime(timestamp).Add(-1 * Deadline),
timestamp: timestamp,
length: length,
score: score,
}
s.Lock()
defer s.Unlock()
s.items[id] = item
return id, score
}
|
Simple class helper
@param {Function} Constructor Constructor function
@param {Object} members Members dictionary
@param {Function} [Base] Base class
@return {Function} New class constructor
@private
|
function _class (Constructor, members, Base) {
var ResultConstructor;
if (Base) {
ResultConstructor = function () {
Base.apply(this, arguments);
Constructor.apply(this, arguments);
};
ResultConstructor.prototype = new Base();
} else {
ResultConstructor = function () {
Constructor.apply(this, arguments);
};
}
if (members) {
Object.keys(members).forEach(function (memberName) {
ResultConstructor.prototype[memberName] = members[memberName];
});
}
return ResultConstructor;
}
|
gets a horiztonal line
|
def get_hline():
return Window(
width=LayoutDimension.exact(1),
height=LayoutDimension.exact(1),
content=FillControl('-', token=Token.Line))
|
Returns the value at the specified position.
@param row
index of the row
@param col
index of the column
@return string representation of the specified field
|
@Override
public Object getValueAt(final int row, final int col)
{
switch (col) {
case 0:
return archives.get(row).getType();
case 1:
return archives.get(row).getStartPosition();
case 2:
return archives.get(row).getPath();
}
return "---";
}
|
************************ utility methods ***************************
|
private static Parser<Expression> compare(
Parser<Expression> operand, String name, Op op) {
return Parsers.sequence(
operand, term(name).retn(op), operand,
BinaryExpression::new);
}
|
A memorization decorator for class properties.
It implements the above `classproperty` decorator, with
the difference that the function result is computed and attached
to class as direct attribute. (Lazy loading and caching.)
|
def cached_classproperty(fun):
@functools.wraps(fun)
def get(cls):
try:
return cls.__cache[fun]
except AttributeError:
cls.__cache = {}
except KeyError: # pragma: no cover
pass
ret = cls.__cache[fun] = fun(cls)
return ret
return classproperty(get)
|
Parses command-line and directs to sub-commands.
@param args Command-line input
@throws Exception
|
public static void executeCommand(String[] args) throws Exception {
String subCmd = (args.length > 0) ? args[0] : "";
args = AdminToolUtils.copyArrayCutFirst(args);
if(subCmd.equals("list")) {
SubCommandScheduledList.executeCommand(args);
} else if(subCmd.equals("stop")) {
SubCommandScheduledStop.executeCommand(args);
} else if(subCmd.equals("enable")) {
SubCommandScheduledEnable.executeCommand(args);
} else {
printHelp(System.out);
}
}
|
Interrupt the thread and then log and re-throw an InterruptedException
as an IOException.
@param msg The message to log and include when re-throwing
@param e The actual exception instances
@throws IOException
|
public static void interruptedException(String msg, InterruptedException e)
throws IOException {
Thread.currentThread().interrupt();
LOG.error(msg, e);
throw new IOException(msg, e);
}
|
Creates an exception for a server name that was not found.
@param string $serverName The server name.
@param Exception|null $cause The exception that caused this
exception.
@return static The created exception.
|
public static function serverNotFound($serverName, Exception $cause = null)
{
return new static(sprintf(
'The asset server "%s" does not exist.',
$serverName
), self::SERVER_NOT_FOUND, $cause);
}
|
Includes the file corresponding with the class name to be autoloaded
@param string $class Class name as defined by PHP autoloading
@return void
|
protected function includeClass($class)
{
$this->updateLog("info", "Setting up {$class} class for inclusion.");
$class_bits = explode("\\", $class);
$package = "";
$package_stack = array();
foreach ($class_bits as $bit) {
$package = $package . $bit . "\\";
$package_registered = $this->packageRegistered($package);
if ($package_registered) {
$package_stack[] = $package;
}
}
$this->loadPackageStack($class, $package_stack);
}
|
Creates Guava's {@link FutureCallback} from provided Actions
|
public static <A> FutureCallback<A> futureCallback(final Action<A> success, final Action<Throwable> failure) {
return new FutureCallback<A>() {
@Override public void onSuccess(A result) {
checkNotNull(success).apply(result);
}
@Override public void onFailure(Throwable t) {
checkNotNull(failure).apply(t);
}
};
}
|
// walletLock handles a walletlock request by locking the all account
// wallets, returning an error if any wallet is not encrypted (for example,
// a watching-only wallet).
|
func walletLock(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
w.Lock()
return nil, nil
}
|
/* (non-Javadoc)
@see com.ibm.ws.webcontainer.webapp.IWebAppDispatcherContext#getPathTranslated()
|
public String getPathTranslated()
{
String pathInfo = getPathInfo();
if (pathInfo == null)
{
return null;
}
else
{
return getWebApp().getRealPath(pathInfo);
}
}
|
Decide whether a file/directory is too small to raid.
|
public static boolean shouldRaid(Configuration conf, FileSystem srcFs,
FileStatus stat, Codec codec, List<FileStatus> lfs) throws IOException {
Path p = stat.getPath();
long blockNum = 0L;
if (stat.isDir() != codec.isDirRaid) {
return false;
}
if (tooNewForRaid(stat)) {
return false;
}
blockNum = codec.isDirRaid ?
DirectoryStripeReader.getBlockNum(lfs) : numBlocks(stat);
// if the file/directory has fewer than 2 blocks, then nothing to do
if (blockNum <= RaidState.TOO_SMALL_NOT_RAID_NUM_BLOCKS) {
return false;
}
return !raidedByOtherHighPriCodec(conf, stat, codec);
}
|
Segment the rest of the text taking into account some exceptions for
periods as sentence breakers. It decides when a period marks an end of
sentence.
@param lines
the segmented sentences so far
@return all the segmented sentences
|
public String[] segmenterExceptions(final String[] lines) {
final List<String> sentences = new ArrayList<>();
for (final String line : lines) {
final String segmentedLine = segmenterNonBreaker(line);
final String[] lineSentences = segmentedLine.split("\n");
for (final String lineSentence : lineSentences) {
sentences.add(lineSentence);
}
}
return sentences.toArray(new String[sentences.size()]);
}
|
calculate square sum.
@param pvalue value to calculate square sum for
@return square sum
|
private static int squareSum(final int pvalue) {
int result = 0;
for (final char valueDigit : String.valueOf(pvalue).toCharArray()) {
result += Character.digit(valueDigit, 10);
}
return result;
}
|
Sector matrix in X
:param theta: bend angle, in [rad]
:param rho: bend radius, in [m]
:return: 2x2 numpy array
|
def funTransSectX(theta, rho):
return np.matrix([[np.cos(theta), rho * np.sin(theta)], [-np.sin(theta) / rho, np.cos(theta)]], dtype=np.double)
|
Initializes the widget.
If you override this method, make sure you call the parent implementation first.
|
public function init()
{
parent::init();
//checks for the element id
if (!isset($this->options['id']))
{
$this->options['id'] = $this->getId();
}
echo Html::beginTag('div', ['id' => $this->options['id']]); //opens the container
}
|
/* (non-Javadoc)
@see org.deckfour.xes.util.XRegistry#areEqual(java.lang.Object, java.lang.Object)
|
@Override
protected boolean areEqual(XSerializer a, XSerializer b) {
return a.getClass().equals(b.getClass());
}
|
https://url.spec.whatwg.org/#url-miscellaneous
|
function getDefaultPortFromScheme( scheme ) {
var port = null;
if ( scheme === 'ftp') {
port = 21;
}
else if ( scheme === 'gopher' ) {
port = 70;
}
else if ( scheme === 'http' || scheme === 'ws' ) {
port = 80;
}
else if ( scheme === 'https' || scheme === 'wss' ) {
port = 443;
}
return port;
}
|
Returns the timestamp for first day of the year for the given date.
@param timestamp
@return timestamp
|
public static function firstDayOfYear($ts = null)
{
// default to now
if ($ts === null) $ts = sfDateTimeToolkit::now();
return sfTime::subtractMonth(sfTime::firstDayOfMonth($ts), date('m', $ts) - 1);
}
|
Get configured server.
@return Server
|
public function getServer()
{
if (!$this->server) {
$server = new Server(
$this->getSource(),
$this->getCache(),
$this->getApi()
);
$server->setSourcePathPrefix($this->sourcePathPrefix);
$server->setCachePathPrefix($this->cachePathPrefix);
$server->setGroupCacheInFolders($this->groupCacheInFolders);
$server->setDefaults($this->defaults);
$server->setPresets($this->presets);
$server->setBaseUrl($this->baseUrl);
$server->setResponseFactory($this->responseFactory);
$this->server = $server;
}
return $this->server;
}
|
// SetClientCAList sets the list of CAs sent to the client when requesting a
// client certificate for Ctx. See
// https://www.openssl.org/docs/ssl/SSL_CTX_set_client_CA_list.html
|
func (c *Ctx) SetClientCAList(caList *StackOfX509Name) {
C.SSL_CTX_set_client_CA_list(c.ctx, caList.stack)
caList.shared = true
}
|
初始化各种连接池
@throws \Server\CoreBase\SwooleException
|
protected function initAsynPools()
{
if ($this->config->get('redis.enable', true)) {
get_instance()->addAsynPool('redisPool', new RedisAsynPool($this->config, $this->config->get('redis.active')));
}
if ($this->config->get('mysql.enable', true)) {
get_instance()->addAsynPool('mysqlPool', new MysqlAsynPool($this->config, $this->config->get('mysql.active')));
}
}
|
Build ``query_string`` object from ``q``.
:param q: q of type String
:param default_field: default_field
:return: dictionary object.
|
def _build_query_string(q, default_field=None, default_operator='AND'):
def _is_phrase_search(query_string):
clean_query = query_string.strip()
return clean_query and clean_query.startswith('"') and clean_query.endswith('"')
def _get_phrase(query_string):
return query_string.strip().strip('"')
if _is_phrase_search(q):
query = {'match_phrase': {'_all': _get_phrase(q)}}
else:
query = {'query_string': {'query': q, 'default_operator': default_operator}}
query['query_string'].update({'lenient': False} if default_field else {'default_field': default_field})
return query
|
Renders the control as a HTML string.
@method renderHtml
@return {String} HTML representing the control.
|
function () {
var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix;
var value = self.state.get('value') || '';
var icon, text, openBtnHtml = '', extraAttrs = '', statusHtml = '';
if ("spellcheck" in settings) {
extraAttrs += ' spellcheck="' + settings.spellcheck + '"';
}
if (settings.maxLength) {
extraAttrs += ' maxlength="' + settings.maxLength + '"';
}
if (settings.size) {
extraAttrs += ' size="' + settings.size + '"';
}
if (settings.subtype) {
extraAttrs += ' type="' + settings.subtype + '"';
}
statusHtml = '<i id="' + id + '-status" class="mce-status mce-ico" style="display: none"></i>';
if (self.disabled()) {
extraAttrs += ' disabled="disabled"';
}
icon = settings.icon;
if (icon && icon != 'caret') {
icon = prefix + 'ico ' + prefix + 'i-' + settings.icon;
}
text = self.state.get('text');
if (icon || text) {
openBtnHtml = (
'<div id="' + id + '-open" class="' + prefix + 'btn ' + prefix + 'open" tabIndex="-1" role="button">' +
'<button id="' + id + '-action" type="button" hidefocus="1" tabindex="-1">' +
(icon != 'caret' ? '<i class="' + icon + '"></i>' : '<i class="' + prefix + 'caret"></i>') +
(text ? (icon ? ' ' : '') + text : '') +
'</button>' +
'</div>'
);
self.classes.add('has-open');
}
return (
'<div id="' + id + '" class="' + self.classes + '">' +
'<input id="' + id + '-inp" class="' + prefix + 'textbox" value="' +
self.encode(value, false) + '" hidefocus="1"' + extraAttrs + ' placeholder="' +
self.encode(settings.placeholder) + '" />' +
statusHtml +
openBtnHtml +
'</div>'
);
}
|
// SetInstanceIds sets the InstanceIds field's value.
|
func (s *DescribeAutoScalingInstancesInput) SetInstanceIds(v []*string) *DescribeAutoScalingInstancesInput {
s.InstanceIds = v
return s
}
|
This function is called when the application has provided a response
and needs it to be sent to the client.
|
def confirmation(self, apdu):
""""""
if _debug: ServerSSM._debug("confirmation %r", apdu)
# check to see we are in the correct state
if self.state != AWAIT_RESPONSE:
if _debug: ServerSSM._debug(" - warning: not expecting a response")
# abort response
if (apdu.apduType == AbortPDU.pduType):
if _debug: ServerSSM._debug(" - abort")
self.set_state(ABORTED)
# send the response to the device
self.response(apdu)
return
# simple response
if (apdu.apduType == SimpleAckPDU.pduType) or (apdu.apduType == ErrorPDU.pduType) or (apdu.apduType == RejectPDU.pduType):
if _debug: ServerSSM._debug(" - simple ack, error, or reject")
# transaction completed
self.set_state(COMPLETED)
# send the response to the device
self.response(apdu)
return
# complex ack
if (apdu.apduType == ComplexAckPDU.pduType):
if _debug: ServerSSM._debug(" - complex ack")
# save the response and set the segmentation context
self.set_segmentation_context(apdu)
# the segment size is the minimum of the size of the largest packet
# that can be delivered to the client and the largest it can accept
if (not self.device_info) or (self.device_info.maxNpduLength is None):
self.segmentSize = self.maxApduLengthAccepted
else:
self.segmentSize = min(self.device_info.maxNpduLength, self.maxApduLengthAccepted)
if _debug: ServerSSM._debug(" - segment size: %r", self.segmentSize)
# compute the segment count
if not apdu.pduData:
# always at least one segment
self.segmentCount = 1
else:
# split into chunks, maybe need one more
self.segmentCount, more = divmod(len(apdu.pduData), self.segmentSize)
if more:
self.segmentCount += 1
if _debug: ServerSSM._debug(" - segment count: %r", self.segmentCount)
# make sure we support segmented transmit if we need to
if self.segmentCount > 1:
if _debug: ServerSSM._debug(" - segmentation required, %d segments", self.segmentCount)
# make sure we support segmented transmit
if self.segmentationSupported not in ('segmentedTransmit', 'segmentedBoth'):
if _debug: ServerSSM._debug(" - server can't send segmented responses")
abort = self.abort(AbortReason.segmentationNotSupported)
self.response(abort)
return
# make sure client supports segmented receive
if not self.segmented_response_accepted:
if _debug: ServerSSM._debug(" - client can't receive segmented responses")
abort = self.abort(AbortReason.segmentationNotSupported)
self.response(abort)
return
# make sure we dont exceed the number of segments in our response
# that the client said it was willing to accept in the request
if (self.maxSegmentsAccepted is not None) and (self.segmentCount > self.maxSegmentsAccepted):
if _debug: ServerSSM._debug(" - client can't receive enough segments")
abort = self.abort(AbortReason.apduTooLong)
self.response(abort)
return
# initialize the state
self.segmentRetryCount = 0
self.initialSequenceNumber = 0
self.actualWindowSize = None
# send out the first segment (or the whole thing)
if self.segmentCount == 1:
self.response(apdu)
self.set_state(COMPLETED)
else:
self.response(self.get_segment(0))
self.set_state(SEGMENTED_RESPONSE, self.segmentTimeout)
else:
raise RuntimeError("invalid APDU (4)")
|
Change the current(default) theme
Parameters
----------
new : theme
New default theme
Returns
-------
out : theme
Previous theme
|
def theme_set(new):
if (not isinstance(new, theme) and
not issubclass(new, theme)):
raise PlotnineError("Expecting object to be a theme")
out = get_option('current_theme')
set_option('current_theme', new)
return out
|
Format values for the API
@param mixed $value
@param bool $exclude [optional] If true, value will be excluded from datastore indexes.
@param int $meaning [optional] The Meaning value. Maintained only for backwards compatibility.
@return array
|
public function valueObject($value, $exclude = false, $meaning = null)
{
switch (gettype($value)) {
case 'boolean':
$propertyValue = [
'booleanValue' => $value
];
break;
case 'integer':
$propertyValue = [
'integerValue' => $value
];
break;
case 'double':
$propertyValue = [
'doubleValue' => $value
];
break;
case 'string':
$propertyValue = [
'stringValue' => $value
];
break;
case 'array':
if (!empty($value) && $this->isAssoc($value)) {
$propertyValue = $this->convertArrayToEntityValue($value);
} else {
$propertyValue = $this->convertArrayToArrayValue($value);
}
break;
case 'object':
$propertyValue = $this->objectProperty($value);
break;
case 'resource':
$content = stream_get_contents($value);
$propertyValue = [
'blobValue' => ($this->encode)
? base64_encode($content)
: $content
];
break;
case 'NULL':
$propertyValue = [
'nullValue' => null
];
break;
//@codeCoverageIgnoreStart
case 'unknown type':
throw new \InvalidArgumentException(sprintf(
'Unknown type for `%s',
$content
));
break;
default:
throw new \InvalidArgumentException(sprintf(
'Invalid type for `%s',
$content
));
break;
//@codeCoverageIgnoreEnd
}
if ($exclude) {
$propertyValue['excludeFromIndexes'] = true;
}
if ($meaning) {
$propertyValue['meaning'] = $meaning;
}
return $propertyValue;
}
|
Inserts the specified objects at the specified index in the array.
@param items The objects to insert into the array.
@param index The index at which the object must be inserted.
|
public void addAll(int index, T... items) {
List<T> collection = Arrays.asList(items);
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.addAll(index, collection);
} else {
mObjects.addAll(index, collection);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}
|
@param \Interpro\Extractor\Contracts\Db\CMapper
@return void
|
public function registerCMapper(CMapper $mapper)
{
$family = $mapper->getFamily();
if(array_key_exists($family, $this->mappersC))
{
throw new ExtractorException('Маппер простых(С) типов пакета '.$family.' уже зарегестрирована в медиаторе!');
}
$this->mappersC[$family] = $mapper;
}
|
Reads the data from the input stream and writes to the
output stream.
@param inputStream
The inputStream to read from
@param outputStream
The output stream to write to
@throws IOException
Any IO exception
|
public static void readAndWriteStreams(InputStream inputStream,OutputStream outputStream) throws IOException
{
byte[] buffer=new byte[5000];
int read=-1;
try
{
do
{
//read next buffer
read=inputStream.read(buffer);
if(read!=-1)
{
//write to in memory stream
outputStream.write(buffer,0,read);
}
}while(read!=-1);
}
finally
{
//close streams
IOHelper.closeResource(inputStream);
IOHelper.closeResource(outputStream);
}
}
|
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.