query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Adds a tablespace to the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.tablespace_create tablespacename '/path/datadir'
.. versionadded:: 2015.8.0 | def tablespace_create(name, location, options=None, owner=None, user=None,
host=None, port=None, maintenance_db=None, password=None,
runas=None):
'''
Adds a tablespace to the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.tablespace_create tablespacename '/path/datadir'
.. versionadded:: 2015.8.0
'''
owner_query = ''
options_query = ''
if owner:
owner_query = 'OWNER "{0}"'.format(owner)
# should come out looking like: 'OWNER postgres'
if options:
optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)]
options_query = 'WITH ( {0} )'.format(', '.join(optionstext))
# should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )'
query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name,
owner_query,
location,
options_query)
# Execute the command
ret = _psql_prepare_and_run(['-c', query],
user=user, host=host, port=port,
maintenance_db=maintenance_db,
password=password, runas=runas)
return ret['retcode'] == 0 | csn |
Removes all locks from user account
@throws Exception | public function unlock()
{
$user = UserHelper::getUser($this->getUserResource());
if ($this->getUserLocksService()->unlockUser($user)) {
$this->returnJson(['success' => true, 'message' => __('User %s successfully unlocked', UserHelper::getUserLogin(UserHelper::getUser($user)))]);
} else {
$this->returnJson(['success' => false, 'message' => __('User %s can not be unlocked', UserHelper::getUserLogin(UserHelper::getUser($user)))]);
}
} | csn |
def maybe_expire(self, request_timeout_ms, retry_backoff_ms, linger_ms, is_full):
"""Expire batches if metadata is not available
A batch whose metadata is not available should be expired if one
of the following is true:
* the batch is not in retry AND request timeout has elapsed after
it is ready (full or linger.ms has reached).
* the batch is in retry AND request timeout has elapsed after the
backoff period ended.
"""
now = time.time()
since_append = now - self.last_append
since_ready = now - (self.created + linger_ms / 1000.0)
since_backoff = now - (self.last_attempt + retry_backoff_ms / 1000.0)
timeout = request_timeout_ms / 1000.0
error = None
if not self.in_retry() and is_full and timeout < since_append:
| error = "%d seconds have passed since last append" % (since_append,)
elif not self.in_retry() and timeout < since_ready:
error = "%d seconds have passed since batch creation plus linger time" % (since_ready,)
elif self.in_retry() and timeout < since_backoff:
error = "%d seconds have passed since last attempt plus backoff time" % (since_backoff,)
if error:
self.records.close()
self.done(-1, None, Errors.KafkaTimeoutError(
"Batch for %s containing %s record(s) expired: %s" % (
self.topic_partition, self.records.next_offset(), error)))
return True
return False | csn_ccr |
public static final Token restore(java.io.DataInputStream dataInputStream,
ObjectManagerState objectManagerState)
throws ObjectManagerException
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(cclass
, "restore"
, new Object[] { dataInputStream, objectManagerState });
int objectStoreIdentifier;
long storedObjectIdentifier;
try {
byte version = dataInputStream.readByte();
if (Tracing.isAnyTracingEnabled() && trace.isDebugEnabled())
trace.debug(cclass,
"restore",
new Object[] { new Byte(version) });
objectStoreIdentifier = dataInputStream.readInt();
storedObjectIdentifier = dataInputStream.readLong();
} catch (java.io.IOException exception) {
// No FFDC Code Needed.
ObjectManager.ffdc.processException(cclass, "restore", exception, "1:400:1.14");
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(cclass,
"restore",
"via | PermanentIOException");
throw new PermanentIOException(cclass,
exception);
} // catch (java.io.IOException exception).
Token tokenToReturn = new Token(objectManagerState.getObjectStore(objectStoreIdentifier),
storedObjectIdentifier);
// Swap for the definitive Token.
// TODO should have a smarter version of like() which takes a storedObjectIdentifier,
// instead of requiring a new Token().
tokenToReturn = tokenToReturn.current();
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(cclass
, "restore"
, "returns token=" + tokenToReturn + "(Token)"
);
return tokenToReturn;
} | csn_ccr |
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = | kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
) | csn_ccr |
Transform objects into an array of key value pairs. | function (obj) {
// sanity check
if (!obj || typeof obj !== 'object') {
return []
}
var results = []
Object.keys(obj).forEach(function (name) {
// nested values in query string
if (typeof obj[name] === 'object') {
obj[name].forEach(function (value) {
results.push({
name: name,
value: value
})
})
return
}
results.push({
name: name,
value: obj[name]
})
})
return results
} | csn |
function Hbs () {
if (!(this instanceof Hbs)) {
return new Hbs();
}
this.handlebars | = require('handlebars').create();
this.Utils = this.handlebars.Utils;
this.SafeString = this.handlebars.SafeString;
} | csn_ccr |
func (t *Table) SetAlign(align tableAlignment, column int) {
if column < 0 {
return
}
for i := range t.elements {
row, ok := t.elements[i].(*Row)
if !ok {
continue
| }
if column >= len(row.cells) {
continue
}
row.cells[column-1].alignment = &align
}
} | csn_ccr |
def extract_table_names(query):
""" Extract table names from an SQL query. """
# a good old fashioned regex. turns out this worked better than actually parsing the | code
tables_blocks = re.findall(r'(?:FROM|JOIN)\s+(\w+(?:\s*,\s*\w+)*)', query, re.IGNORECASE)
tables = [tbl
for block in tables_blocks
for tbl in re.findall(r'\w+', block)]
return set(tables) | csn_ccr |
Get the available TAN mechanisms.
Note: Only checks for HITANS versions listed in IMPLEMENTED_HKTAN_VERSIONS.
:return: Dictionary of security_function: TwoStepParameters objects. | def get_tan_mechanisms(self):
"""
Get the available TAN mechanisms.
Note: Only checks for HITANS versions listed in IMPLEMENTED_HKTAN_VERSIONS.
:return: Dictionary of security_function: TwoStepParameters objects.
"""
retval = OrderedDict()
for version in sorted(IMPLEMENTED_HKTAN_VERSIONS.keys()):
for seg in self.bpd.find_segments('HITANS', version):
for parameter in seg.parameter.twostep_parameters:
if parameter.security_function in self.allowed_security_functions:
retval[parameter.security_function] = parameter
return retval | csn |
public function validActivationKey($attribute, $params)
{
if ($this->hasErrors()) {
return false;
}
if (($identity = $this->getIdentity()) === null) {
return false;
}
$errorCode = $identity->verifyActivationKey($this->activationKey);
switch ($errorCode) {
default:
case $identity::ERROR_AKEY_INVALID:
$this->addError('activationKey', Yii::t('usr', 'Activation key is invalid.'));
return false;
| case $identity::ERROR_AKEY_TOO_OLD:
$this->addError('activationKey', Yii::t('usr', 'Activation key is too old.'));
return false;
case $identity::ERROR_AKEY_NONE:
return true;
}
return true;
} | csn_ccr |
Create a structing element composed of the origin and another pixel
x, y - x and y offsets of the other pixel
returns a structuring element | def strel_pair(x, y):
"""Create a structing element composed of the origin and another pixel
x, y - x and y offsets of the other pixel
returns a structuring element
"""
x_center = int(np.abs(x))
y_center = int(np.abs(y))
result = np.zeros((y_center * 2 + 1, x_center * 2 + 1), bool)
result[y_center, x_center] = True
result[y_center + int(y), x_center + int(x)] = True
return result | csn |
Add client side JAX-WS handlers.
@param handlers JAX-WS handlers.
@return ClientBuilder instance. | public ClientBuilder<T> handlers(Handler... handlers) {
this.handlers = ImmutableList.<Handler>builder().add(handlers).build();
return this;
} | csn |
public static function fromURL ($url, $stripHost) {
$data = parse_url ($url);
$parameters = array ();
if (!empty ($data['query']))
parse_str ($data['query'], $parameters);
$request = new self ();
if ($stripHost) {
$request->setUrl ($data['path']);
}
else {
$request->setUrl (
$data['scheme'] . '://' .
| $data['host'] . (isset ($data['port']) ? ':' . $data['port'] : '') .
$data['path']
);
}
$request->setParameters ($parameters);
return $request;
} | csn_ccr |
public Revision getNearest(final int revisionCounter)
{
if (first != null) {
ChronoStorageBlock previous = null, current = first;
while (current != null
&& current.getRevisionCounter() <= revisionCounter) {
| previous = current;
current = current.getCounterNext();
}
return previous.getRev();
}
return null;
} | csn_ccr |
Solve the current model asynchronously.
Args:
callback: Callback to be executed when the solver is done. | def solveAsync(self, callback):
"""
Solve the current model asynchronously.
Args:
callback: Callback to be executed when the solver is done.
"""
def async_call():
self._lock.acquire()
try:
self._impl.solve()
except Exception:
self._lock.release()
raise
else:
self._lock.release()
callback.run()
Thread(target=async_call).start() | csn |
def decode(self,data):
"""Decode the MAC address from a byte array.
This will take the first 6 bytes from data and transform them into a MAC address
string representation. This will be assigned to the attribute "val". It then returns
| the data stream minus the bytes consumed
:param data: The data stream containing the value to decode at its head
:type data: bytes
:returns: The datastream minus the bytes consumed
:rtype: bytes
"""
self.val=':'.join("%02x" % x for x in reversed(data[:6]))
return data[6:] | csn_ccr |
python serialize datetime json | def _time_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, datetime.time):
value = value.isoformat()
return value | cosqa |
Connect to a SwarmServer and do its dirty work.
:param ip: ip address of server
:param port: port to connect to on server
:param authkey: authorization key
:param max_items: maximum number of items to process from server.
Useful for say running clients on a cluster. | def run_client(ip, port, authkey, max_items=None, timeout=2):
"""Connect to a SwarmServer and do its dirty work.
:param ip: ip address of server
:param port: port to connect to on server
:param authkey: authorization key
:param max_items: maximum number of items to process from server.
Useful for say running clients on a cluster.
"""
manager = make_client(ip, port, authkey)
job_q = manager.get_job_q()
job_q_closed = manager.q_closed()
result_q = manager.get_result_q()
function = manager.get_function()._getvalue()
processed = 0
while True:
try:
job = job_q.get_nowait()
result = function(job)
result_q.put(result)
except Queue.Empty:
if job_q_closed._getvalue().value:
break
else:
processed += 1
if max_items is not None and processed == max_items:
break
sleep(timeout) | csn |
Create an output buffer for each task.
@return null if there aren't enough buffers left in the pool. | private List<BBContainer> getOutputBuffers(Collection<SnapshotTableTask> tableTasks, boolean noSchedule)
{
final int desired = tableTasks.size();
while (true) {
int available = m_availableSnapshotBuffers.get();
//Limit the number of buffers used concurrently
if (desired > available) {
return null;
}
if (m_availableSnapshotBuffers.compareAndSet(available, available - desired)) break;
}
List<BBContainer> outputBuffers = new ArrayList<BBContainer>(tableTasks.size());
for (int ii = 0; ii < tableTasks.size(); ii++) {
final BBContainer origin = DBBPool.allocateDirectAndPool(m_snapshotBufferLength);
outputBuffers.add(createNewBuffer(origin, noSchedule));
}
return outputBuffers;
} | csn |
Creates the cache DB table.
@param CDbConnection $db the database connection
@param string $tableName the name of the table to be created | protected function createCacheTable($db,$tableName)
{
$driver=$db->getDriverName();
if($driver==='mysql')
$blob='LONGBLOB';
elseif($driver==='pgsql')
$blob='BYTEA';
else
$blob='BLOB';
$sql=<<<EOD
CREATE TABLE $tableName
(
id CHAR(128) PRIMARY KEY,
expire INTEGER,
value $blob
)
EOD;
$db->createCommand($sql)->execute();
} | csn |
public function getCheckedOutDocs(
$repositoryId,
$folderId,
$filter = null,
$orderBy = null,
$includeAllowableActions = false,
IncludeRelationships $includeRelationships = null,
$renditionFilter = Constants::RENDITION_NONE,
$maxItems = null,
$skipCount = 0,
ExtensionDataInterface $extension = null
) {
$url = $this->getObjectUrl($repositoryId, $folderId, Constants::SELECTOR_CHECKEDOUT);
$url->getQuery()->modify(
[
Constants::PARAM_ALLOWABLE_ACTIONS => $includeAllowableActions ? 'true' : 'false',
Constants::PARAM_RENDITION_FILTER => $renditionFilter,
Constants::PARAM_SKIP_COUNT => (string) $skipCount,
Constants::PARAM_SUCCINCT => $this->getSuccinct() ? 'true' : 'false',
Constants::PARAM_DATETIME_FORMAT => (string) $this->getDateTimeFormat()
]
);
if (!empty($filter)) {
$url->getQuery()->modify([Constants::PARAM_FILTER => (string) $filter]);
}
if (!empty($orderBy)) {
| $url->getQuery()->modify([Constants::PARAM_ORDER_BY => $orderBy]);
}
if ($maxItems > 0) {
$url->getQuery()->modify([Constants::PARAM_MAX_ITEMS => (string) $maxItems]);
}
if ($includeRelationships !== null) {
$url->getQuery()->modify([Constants::PARAM_RELATIONSHIPS => (string) $includeRelationships]);
}
$responseData = (array) $this->readJson($url);
// TODO Implement Cache
return $this->getJsonConverter()->convertObjectList($responseData);
} | csn_ccr |
private String getKeyAsString(Object id, EntityMetadata metadata, MetamodelImpl metaModel)
{
if (metaModel.isEmbeddable(((AbstractAttribute) metadata.getIdAttribute()).getBindableJavaType()))
{
| return KunderaCoreUtils.prepareCompositeKey(metadata, id);
}
return id.toString();
} | csn_ccr |
Remove a widget from the window. | def remove(self, widget):
"""Remove a widget from the window."""
for i, (wid, _) in enumerate(self._widgets):
if widget is wid:
del self._widgets[i]
return True
raise ValueError('Widget not in list') | csn |
Converts an rpc call into an API call governed by the settings.
In typical usage, ``func`` will be a callable used to make an rpc request.
This will mostly likely be a bound method from a request stub used to make
an rpc call.
The result is created by applying a series of function decorators defined
in this module to ``func``. ``settings`` is used to determine which
function decorators to apply.
The result is another callable which for most values of ``settings`` has
has the same signature as the original. Only when ``settings`` configures
bundling does the signature change.
Args:
func (Callable[Sequence[object], object]): is used to make a bare rpc
call.
settings (_CallSettings): provides the settings for this call
Returns:
Callable[Sequence[object], object]: a bound method on a request stub used
to make an rpc call
Raises:
ValueError: if ``settings`` has incompatible values, e.g, if bundling
and page_streaming are both configured | def create_api_call(func, settings):
"""Converts an rpc call into an API call governed by the settings.
In typical usage, ``func`` will be a callable used to make an rpc request.
This will mostly likely be a bound method from a request stub used to make
an rpc call.
The result is created by applying a series of function decorators defined
in this module to ``func``. ``settings`` is used to determine which
function decorators to apply.
The result is another callable which for most values of ``settings`` has
has the same signature as the original. Only when ``settings`` configures
bundling does the signature change.
Args:
func (Callable[Sequence[object], object]): is used to make a bare rpc
call.
settings (_CallSettings): provides the settings for this call
Returns:
Callable[Sequence[object], object]: a bound method on a request stub used
to make an rpc call
Raises:
ValueError: if ``settings`` has incompatible values, e.g, if bundling
and page_streaming are both configured
"""
def base_caller(api_call, _, *args):
"""Simply call api_call and ignore settings."""
return api_call(*args)
def inner(request, options=None):
"""Invoke with the actual settings."""
this_options = _merge_options_metadata(options, settings)
this_settings = settings.merge(this_options)
if this_settings.retry and this_settings.retry.retry_codes:
api_call = gax.retry.retryable(
func, this_settings.retry, **this_settings.kwargs)
else:
api_call = gax.retry.add_timeout_arg(
func, this_settings.timeout, **this_settings.kwargs)
api_call = _catch_errors(api_call, gax.config.API_ERRORS)
return api_caller(api_call, this_settings, request)
if settings.page_descriptor:
if settings.bundler and settings.bundle_descriptor:
raise ValueError('The API call has incompatible settings: '
'bundling and page streaming')
api_caller = _page_streamable(settings.page_descriptor)
elif settings.bundler and settings.bundle_descriptor:
api_caller = _bundleable(settings.bundle_descriptor)
else:
api_caller = base_caller
return inner | csn |
Finish the current legend.
@param LegendInterface $legend Return the final legend.
@return PaletteBuilder
@throws DcGeneralRuntimeException When no legend is stored in the builder. | public function finishLegend(&$legend = null)
{
if (!$this->legend) {
throw new DcGeneralRuntimeException('Legend is missing, please create a legend first');
}
if ($this->property) {
$this->finishProperty();
}
$event = new FinishLegendEvent($this->legend, $this);
$this->dispatchEvent($event);
$legend = $event->getLegend();
if ($this->palette) {
$this->palette->addLegend($legend);
}
$this->legend = null;
return $this;
} | csn |
public function send()
{
$ch = curl_init();
$url = $this->_url;
$d = '';
$this->_params['format'] = 'xml';
$this->_params['key'] = self::$apiKey;
// The language to retrieve results in (see http://en.wikipedia.org/wiki/ISO_639-1 for the language codes (first
// two characters) and http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes for the country codes (last two characters))
$this->_params['language'] = 'en_us';
foreach ($this->_params as $key => $value) {
$d .= $key . '=' . $value . '&';
}
$d = rtrim($d, '&');
$url .= '?' . $d;
| curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Ignore SSL warnings and questions
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$r = curl_exec($ch);
curl_close($ch);
libxml_use_internal_errors(true);
try {
$r = new SimpleXMLElement($r);
} catch (Exception $e) {
return null;
}
return $r;
} | csn_ccr |
Converts date and time strings into a timestamp.
Recent versions of Office Scan write a log field with a Unix timestamp.
Older versions may not write this field; their logs only provide a date and
a time expressed in the local time zone. This functions handles the latter
case.
Args:
date (str): date as an 8-character string in the YYYYMMDD format.
time (str): time as a 3 or 4-character string in the [H]HMM format or a
6-character string in the HHMMSS format.
Returns:
dfdatetime_time_elements.TimestampElements: the parsed timestamp.
Raises:
ValueError: if the date and time values cannot be parsed. | def _ConvertToTimestamp(self, date, time):
"""Converts date and time strings into a timestamp.
Recent versions of Office Scan write a log field with a Unix timestamp.
Older versions may not write this field; their logs only provide a date and
a time expressed in the local time zone. This functions handles the latter
case.
Args:
date (str): date as an 8-character string in the YYYYMMDD format.
time (str): time as a 3 or 4-character string in the [H]HMM format or a
6-character string in the HHMMSS format.
Returns:
dfdatetime_time_elements.TimestampElements: the parsed timestamp.
Raises:
ValueError: if the date and time values cannot be parsed.
"""
# Check that the strings have the correct length.
if len(date) != 8:
raise ValueError(
'Unsupported length of date string: {0!s}'.format(repr(date)))
if len(time) < 3 or len(time) > 4:
raise ValueError(
'Unsupported length of time string: {0!s}'.format(repr(time)))
# Extract the date.
try:
year = int(date[:4], 10)
month = int(date[4:6], 10)
day = int(date[6:8], 10)
except (TypeError, ValueError):
raise ValueError('Unable to parse date string: {0!s}'.format(repr(date)))
# Extract the time. Note that a single-digit hour value has no leading zero.
try:
hour = int(time[:-2], 10)
minutes = int(time[-2:], 10)
except (TypeError, ValueError):
raise ValueError('Unable to parse time string: {0!s}'.format(repr(date)))
time_elements_tuple = (year, month, day, hour, minutes, 0)
date_time = dfdatetime_time_elements.TimeElements(
time_elements_tuple=time_elements_tuple)
date_time.is_local_time = True
# TODO: add functionality to dfdatetime to control precision.
date_time._precision = dfdatetime_definitions.PRECISION_1_MINUTE # pylint: disable=protected-access
return date_time | csn |
def add_type_struct_or_union(self, name, interp, node):
"""Store the node with the name. When it is instantiated,
the node itself will be handled.
:name: name of the typedefd struct/union
:node: the union/struct node
| :interp: the 010 interpreter
"""
self.add_type_class(name, StructUnionDef(name, interp, node)) | csn_ccr |
func (m *Model) IsControllerModel() bool | {
return m.st.controllerModelTag.Id() == m.doc.UUID
} | csn_ccr |
public function getLog()
{
$log = [];
foreach ($this->traces as $request => $traces) {
$log[] = sprintf('%s: %s', | $request, implode(', ', $traces));
}
return implode('; ', $log);
} | csn_ccr |
Load a PLY file from an open file object.
Parameters
---------
file_obj : an open file- like object
Source data, ASCII or binary PLY
resolver : trimesh.visual.resolvers.Resolver
Object which can resolve assets
fix_texture : bool
If True, will re- index vertices and faces
so vertices with different UV coordinates
are disconnected.
Returns
---------
mesh_kwargs : dict
Data which can be passed to
Trimesh constructor, eg: a = Trimesh(**mesh_kwargs) | def load_ply(file_obj,
resolver=None,
fix_texture=True,
*args,
**kwargs):
"""
Load a PLY file from an open file object.
Parameters
---------
file_obj : an open file- like object
Source data, ASCII or binary PLY
resolver : trimesh.visual.resolvers.Resolver
Object which can resolve assets
fix_texture : bool
If True, will re- index vertices and faces
so vertices with different UV coordinates
are disconnected.
Returns
---------
mesh_kwargs : dict
Data which can be passed to
Trimesh constructor, eg: a = Trimesh(**mesh_kwargs)
"""
# OrderedDict which is populated from the header
elements, is_ascii, image_name = parse_header(file_obj)
# functions will fill in elements from file_obj
if is_ascii:
ply_ascii(elements, file_obj)
else:
ply_binary(elements, file_obj)
# try to load the referenced image
image = None
if image_name is not None:
try:
data = resolver.get(image_name)
image = PIL.Image.open(util.wrap_as_stream(data))
except BaseException:
log.warning('unable to load image!',
exc_info=True)
kwargs = elements_to_kwargs(elements,
fix_texture=fix_texture,
image=image)
return kwargs | csn |
public function validation($instance = true)
{
if ($instance instanceof Validation)
{
$this->validation = $instance;
return $instance;
}
if (empty($this->validation) and $instance === true)
| {
$this->validation = \Validation::forge($this);
}
return $this->validation;
} | csn_ccr |
Executes the specified prepared statement.
@param name The prepared statement name.
@throws DatabaseEngineException If something goes wrong while executing.
@throws ConnectionResetException If the connection is down and reestablishment occurs. If this happens, the user must reset the parameters and re-execute
the query. | @Override
public synchronized void executePS(final String name) throws DatabaseEngineException, ConnectionResetException {
final PreparedStatementCapsule ps = stmts.get(name);
if (ps == null) {
throw new DatabaseEngineRuntimeException(String.format("PreparedStatement named '%s' does not exist", name));
}
try {
ps.ps.execute();
} catch (final SQLException e) {
logger.error("Error executing prepared statement", e);
if (checkConnection(conn) || !properties.isReconnectOnLost()) {
throw new DatabaseEngineException(String.format("Something went wrong executing the prepared statement '%s'", name), e);
}
// At this point maybe it is an error with the connection, so we try to re-establish it.
try {
getConnection();
} catch (final Exception e2) {
throw new DatabaseEngineException("Connection is down", e2);
}
throw new ConnectionResetException("Connection was lost, you must reset the prepared statement parameters and re-execute the statement");
}
} | csn |
Merge the state of the given entity into the current persistence context.
@param entity
@return the managed instance that the state was merged to
@throws IllegalArgumentException
if instance is not an entity or is a removed entity
@throws TransactionRequiredException
if invoked on a container-managed entity manager of type
PersistenceContextType.TRANSACTION and there is no
transaction
@see javax.persistence.EntityManager#merge(java.lang.Object) | @Override
public final <E> E merge(E e)
{
checkClosed();
checkTransactionNeeded();
try
{
return getPersistenceDelegator().merge(e);
}
catch (Exception ex)
{
// on Rollback
doRollback();
throw new KunderaException(ex);
}
} | csn |
func NewConfig() *Config {
return &Config{
Collation: defaultCollation,
Loc: | time.UTC,
MaxAllowedPacket: defaultMaxAllowedPacket,
AllowNativePasswords: true,
}
} | csn_ccr |
func (t *Template) GetAllAWSCloudFrontCloudFrontOriginAccessIdentityResources() map[string]*resources.AWSCloudFrontCloudFrontOriginAccessIdentity {
results := map[string]*resources.AWSCloudFrontCloudFrontOriginAccessIdentity{}
for name, untyped := range t.Resources {
| switch resource := untyped.(type) {
case *resources.AWSCloudFrontCloudFrontOriginAccessIdentity:
results[name] = resource
}
}
return results
} | csn_ccr |
Find all link tags in a string representing a HTML document and
return a list of their attributes.
@todo This is quite ineffective and may fail with the default
pcre.backtrack_limit of 100000 in PHP 5.2, if $html is big.
It should rather use stripos (in PHP5) or strpos()+strtoupper()
in PHP4 to manage this.
@param string $html The text to parse
@return array $list An array of arrays of attributes, one for each
link tag | function parseLinkAttrs($html)
{
$stripped = preg_replace($this->_removed_re,
"",
$html);
$html_begin = $this->htmlBegin($stripped);
$html_end = $this->htmlEnd($stripped);
if ($html_begin === false) {
return array();
}
if ($html_end === false) {
$html_end = strlen($stripped);
}
$stripped = substr($stripped, $html_begin,
$html_end - $html_begin);
// Workaround to prevent PREG_BACKTRACK_LIMIT_ERROR:
$old_btlimit = ini_set( 'pcre.backtrack_limit', -1 );
// Try to find the <HEAD> tag.
$head_re = $this->headFind();
$head_match = array();
if (!$this->match($head_re, $stripped, $head_match)) {
ini_set( 'pcre.backtrack_limit', $old_btlimit );
return array();
}
$link_data = array();
$link_matches = array();
if (!preg_match_all($this->_link_find, $head_match[0],
$link_matches)) {
ini_set( 'pcre.backtrack_limit', $old_btlimit );
return array();
}
foreach ($link_matches[0] as $link) {
$attr_matches = array();
preg_match_all($this->_attr_find, $link, $attr_matches);
$link_attrs = array();
foreach ($attr_matches[0] as $index => $full_match) {
$name = $attr_matches[1][$index];
$value = $this->replaceEntities(
$this->removeQuotes($attr_matches[2][$index]));
$link_attrs[strtolower($name)] = $value;
}
$link_data[] = $link_attrs;
}
ini_set( 'pcre.backtrack_limit', $old_btlimit );
return $link_data;
} | csn |
def _serie_format(self, serie, value):
"""Format an independent value for the serie"""
kwargs = {'chart': self, 'serie': serie, | 'index': None}
formatter = (serie.formatter or self.formatter or self._value_format)
kwargs = filter_kwargs(formatter, kwargs)
return formatter(value, **kwargs) | csn_ccr |
Set the grid values for y.
Create information for the grid of y values.
Args:
num_y (int): Number of points on axis.
y_low/y_high (float): Lowest/highest value for the axis.
yscale (str): Scale of the axis. Choices are 'log' or 'lin'.
yval_name (str): Name representing the axis. See GenerateContainer documentation
for options for the name. | def set_y_grid_info(self, y_low, y_high, num_y, yscale, yval_name):
"""Set the grid values for y.
Create information for the grid of y values.
Args:
num_y (int): Number of points on axis.
y_low/y_high (float): Lowest/highest value for the axis.
yscale (str): Scale of the axis. Choices are 'log' or 'lin'.
yval_name (str): Name representing the axis. See GenerateContainer documentation
for options for the name.
"""
self._set_grid_info('y', y_low, y_high, num_y, yscale, yval_name)
return | csn |
func Create(device Device, id string, size int64) *NBD {
if shuttingDown {
logrus.Warnf("Cannot create NBD device during shutdown")
return nil
}
if size >= 0 {
| globalMutex.Lock()
defer globalMutex.Unlock()
dev := &NBD{device: device,
devicePath: "",
size: size,
deviceFile: nil,
socket: 0,
mutex: &sync.Mutex{},
}
nbdDevices[id] = dev
return dev
}
return nil
} | csn_ccr |
Decodes a VLQ-sequence to a block of numbers
@param int[] $digits
@return int[]
@throws \axy\codecs\base64vlq\errors\InvalidVLQSequence | public function decode(array $digits)
{
$result = [];
$current = 0;
$cBit = $this->cBit;
$bits = $this->bits;
$shift = 0;
foreach ($digits as $digit) {
$current += (($digit % $cBit) << $shift);
if ($digit < $cBit) {
$result[] = $current;
$current = 0;
$shift = 0;
} else {
$shift += $bits;
}
}
if ($current > 0) {
throw new InvalidVLQSequence($digits);
}
if ($this->signed) {
$result = Signed::decodeBlock($result);
}
return $result;
} | csn |
// Check checks that this issuer public key is valid, i.e.
// that all components are present and a ZK proofs verifies | func (IPk *IssuerPublicKey) Check() error {
// Unmarshall the public key
NumAttrs := len(IPk.GetAttributeNames())
HSk := EcpFromProto(IPk.GetHSk())
HRand := EcpFromProto(IPk.GetHRand())
HAttrs := make([]*FP256BN.ECP, len(IPk.GetHAttrs()))
for i := 0; i < len(IPk.GetHAttrs()); i++ {
HAttrs[i] = EcpFromProto(IPk.GetHAttrs()[i])
}
BarG1 := EcpFromProto(IPk.GetBarG1())
BarG2 := EcpFromProto(IPk.GetBarG2())
W := Ecp2FromProto(IPk.GetW())
ProofC := FP256BN.FromBytes(IPk.GetProofC())
ProofS := FP256BN.FromBytes(IPk.GetProofS())
// Check that the public key is well-formed
if NumAttrs < 0 ||
HSk == nil ||
HRand == nil ||
BarG1 == nil ||
BarG1.Is_infinity() ||
BarG2 == nil ||
HAttrs == nil ||
len(IPk.HAttrs) < NumAttrs {
return errors.Errorf("some part of the public key is undefined")
}
for i := 0; i < NumAttrs; i++ {
if IPk.HAttrs[i] == nil {
return errors.Errorf("some part of the public key is undefined")
}
}
// Verify Proof
// Recompute challenge
proofData := make([]byte, 18*FieldBytes+3)
index := 0
// Recompute t-values using s-values
t1 := GenG2.Mul(ProofS)
t1.Add(W.Mul(FP256BN.Modneg(ProofC, GroupOrder))) // t1 = g_2^s \cdot W^{-C}
t2 := BarG1.Mul(ProofS)
t2.Add(BarG2.Mul(FP256BN.Modneg(ProofC, GroupOrder))) // t2 = {\bar g_1}^s \cdot {\bar g_2}^C
index = appendBytesG2(proofData, index, t1)
index = appendBytesG1(proofData, index, t2)
index = appendBytesG2(proofData, index, GenG2)
index = appendBytesG1(proofData, index, BarG1)
index = appendBytesG2(proofData, index, W)
index = appendBytesG1(proofData, index, BarG2)
// Verify that the challenge is the same
if *ProofC != *HashModOrder(proofData) {
return errors.Errorf("zero knowledge proof in public key invalid")
}
return IPk.SetHash()
} | csn |
def get_cube(cube, init=False, pkgs=None, cube_paths=None, config=None,
backends=None, **kwargs):
'''
Dynamically locate and load a metrique cube
:param cube: name of the cube class to import from given module
:param init: flag to request initialized instance or uninitialized class
:param config: config dict to pass on initialization (implies init=True)
:param pkgs: list of package names to search for the cubes in
:param cube_path: additional paths to search for modules in (sys.path)
:param kwargs: additional kwargs to pass to cube during initialization
'''
pkgs = pkgs or ['cubes']
pkgs = [pkgs] if isinstance(pkgs, basestring) else pkgs
# search in the given path too, if provided
cube_paths = cube_paths or []
cube_paths_is_basestring = isinstance(cube_paths, basestring)
cube_paths = [cube_paths] if cube_paths_is_basestring else cube_paths
cube_paths = [os.path.expanduser(path) for path in cube_paths]
# append paths which | don't already exist in sys.path to sys.path
[sys.path.append(path) for path in cube_paths if path not in sys.path]
pkgs = pkgs + DEFAULT_PKGS
err = False
for pkg in pkgs:
try:
_cube = _load_cube_pkg(pkg, cube)
except ImportError as err:
_cube = None
if _cube:
break
else:
logger.error(err)
raise RuntimeError('"%s" not found! %s; %s \n%s)' % (
cube, pkgs, cube_paths, sys.path))
if init:
_cube = _cube(config=config, **kwargs)
return _cube | csn_ccr |
def create_log2fc_bigwigs(matrix, outdir, args):
# type: (pd.DataFrame, str, Namespace) -> None
"""Create bigwigs from matrix."""
call("mkdir -p {}".format(outdir), shell=True)
genome_size_dict = args.chromosome_sizes
outpaths = []
for bed_file in matrix[args.treatment]:
outpath = join(outdir, splitext(basename(bed_file))[0] + "_log2fc.bw")
outpaths.append(outpath)
| data = create_log2fc_data(matrix, args)
Parallel(n_jobs=args.number_cores)(delayed(_create_bigwig)(bed_column, outpath, genome_size_dict) for outpath, bed_column in zip(outpaths, data)) | csn_ccr |
public static String sort( String s )
{
char[] chars = s.toCharArray();
| Arrays.sort( chars );
return new String( chars );
} | csn_ccr |
Return our provider, creating it if needed. | @Override
public CacheManagerPeerProvider createCachePeerProvider (
CacheManager cacheManager, Properties properties)
{
if (_instance == null) {
_instance = new Provider(cacheManager);
}
return _instance;
} | csn |
func (s *SyncState) RemoveResourceIfEmpty(addr addrs.AbsResource) bool {
s.lock.Lock()
defer s.lock.Unlock()
ms := s.state.Module(addr.Module)
if ms == nil {
return true // nothing to do
}
rs := ms.Resource(addr.Resource)
if rs == nil {
return true // nothing to do
}
if len(rs.Instances) != 0 {
// We don't check here for the possibility of instances that exist
// but don't have | any objects because it's the responsibility of the
// instance-mutation methods to prune those away automatically.
return false
}
ms.RemoveResource(addr.Resource)
s.maybePruneModule(addr.Module)
return true
} | csn_ccr |
private function replaceStyle($match)
{
if (!$this->isDecorated()) {
return $match[2];
}
if ($this->hasStyle($match[1])) {
| $style = $this->getStyle($match[1]);
} else {
return $match[0];
}
return $style->apply($match[2]);
} | csn_ccr |
Dynamically generate our mock configuration | def generate_mock_config(self, release):
"""Dynamically generate our mock configuration"""
mock_tmpl = pkg_resources.resource_string(__name__, 'templates/mock.mako')
mock_dir = release['mock_dir'] = os.path.join(release['tmp_dir'], 'mock')
mock_cfg = os.path.join(release['mock_dir'], release['mock'] + '.cfg')
os.mkdir(mock_dir)
for cfg in ('site-defaults.cfg', 'logging.ini'):
os.symlink('/etc/mock/%s' % cfg, os.path.join(mock_dir, cfg))
with file(mock_cfg, 'w') as cfg:
mock_out = Template(mock_tmpl).render(**release)
self.log.debug('Writing %s:\n%s', mock_cfg, mock_out)
cfg.write(mock_out) | csn |
Retrieves a job matching the given `id`
Args:
id (str): Job `id` to match.
Returns:
Job: Job matching the given `id`
Raises:
ValueError: No resource matches given `id` or multiple resources matching given `id` | def get_job(self, id):
"""Retrieves a job matching the given `id`
Args:
id (str): Job `id` to match.
Returns:
Job: Job matching the given `id`
Raises:
ValueError: No resource matches given `id` or multiple resources matching given `id`
"""
return self._get_element_by_id(self.jobs, 'jobs', Job, str(id)) | csn |
Executes the update and returns the affected row count
Moved to its own method to reduce possibility for variable name confusion | protected int doUpdate(JdbcTemplate jdbcTemplate, TaskRequest req, TaskResponse res) {
//Setup the update parameters and setter
final List<Phrase> parametersInUse = update_parameters != null ? update_parameters : parameters;
final PreparedStatementSetter preparedStatementSetter = new PhraseParameterPreparedStatementSetter(parametersInUse, req, res);
//Get the update sql and execute the update.
final String fUpdateSql = (String) update_sql.evaluate(req, res);
return jdbcTemplate.update(fUpdateSql, preparedStatementSetter);
} | csn |
public function make(Table $table, $action, array $ids = [], array $options = [])
{
$count = count($ids);
$options = $this->_getOptions($options, $count);
$redirectUrl = $options['redirect'];
$messages = new JSON($options['messages']);
$event = EventManager::trigger($this->_getEventName($action), $this->_controller, ['ids' => $ids]);
$ids = (array) $event->getData('ids');
$count = count($ids);
if (!$action) {
$this->Flash->error($messages->get('no_action'));
return $this->_controller->redirect($redirectUrl);
}
if ($count <= 0) {
| $this->Flash->error($messages->get('no_choose'));
return $this->_controller->redirect($redirectUrl);
}
$this->_loadBehavior($table);
if ($table->process($action, $ids)) {
return $this->_process($action, $messages, $redirectUrl, $ids);
}
$this->Flash->error(__d('core', 'An error has occurred. Please try again.'));
return $this->_controller->redirect($redirectUrl);
} | csn_ccr |
def diskwarp_multi_fn(src_fn_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, outdir=None, dst_ndv=None):
"""Helper function for diskwarp of multiple input filenames
"""
| #Should implement proper error handling here
if not iolib.fn_list_check(src_fn_list):
sys.exit('Missing input file(s)')
src_ds_list = [gdal.Open(fn, gdal.GA_ReadOnly) for fn in src_fn_list]
return diskwarp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, outdir=outdir, dst_ndv=dst_ndv) | csn_ccr |
function (excludeDisabled, caseSensitive, multiValue, sanitizeKeys) {
var obj = {}, // create transformation data accumulator
// gather all the switches of the list
key = this._postman_listIndexKey,
sanitiseKeys = this._postman_sanitizeKeys || sanitizeKeys,
sensitive = !this._postman_listIndexCaseInsensitive || caseSensitive,
multivalue = this._postman_listAllowsMultipleValues || multiValue;
// iterate on each member to create the transformation object
this.each(function (member) {
// Bail out for the current member if ANY of the conditions below is true:
// 1. The member is falsy.
// 2. The member does not have the specified property list index key.
// 3. The member is disabled and disabled properties have to be ignored.
// 4. The member has a falsy key, and sanitize is true.
if (!member || !member.hasOwnProperty(key) || (excludeDisabled && member.disabled) ||
(sanitiseKeys && !member[key])) {
return;
}
// based on | case sensitivity settings, we get the property name of the item
var prop = sensitive ? member[key] : String(member[key]).toLowerCase();
// now, if transformation object already has a member with same property name, we either overwrite it or
// append to an array of values based on multi-value support
if (multivalue && obj.hasOwnProperty(prop)) {
(!Array.isArray(obj[prop])) && (obj[prop] = [obj[prop]]);
obj[prop].push(member.valueOf());
}
else {
obj[prop] = member.valueOf();
}
});
return obj;
} | csn_ccr |
protected function _updateControllers($root, $controllers, $plugin = null, $prefix = null)
{
$pluginPath = $this->_pluginAlias($plugin);
// look at each controller
$controllersNames = [];
foreach ($controllers as $controller) {
$tmp = explode('/', $controller);
$controllerName = str_replace('Controller.php', '', array_pop($tmp));
if ($controllerName == 'App') {
continue;
}
$controllersNames[] = $controllerName;
$path = [
$this->rootNode,
$pluginPath,
$prefix,
$controllerName
];
| $path = implode('/', Hash::filter($path));
if(!in_array($path, $this->ignorePaths)) {
$controllerNode = $this->_checkNode($path, $controllerName, $root->id);
$this->_checkMethods($controller, $controllerName, $controllerNode, $pluginPath, $prefix);
}
}
return $controllersNames;
} | csn_ccr |
// SetSettingName sets the SettingName field's value. | func (s *OptionGroupOptionSetting) SetSettingName(v string) *OptionGroupOptionSetting {
s.SettingName = &v
return s
} | csn |
func (cache *Cache) Del(key []byte) (affected bool) {
hashVal := hashFunc(key)
segID := hashVal | & segmentAndOpVal
cache.locks[segID].Lock()
affected = cache.segments[segID].del(key, hashVal)
cache.locks[segID].Unlock()
return
} | csn_ccr |
function( wcDir, options, callback ) {
if ( typeof options === "function" ) {
callback = options;
options = null;
}
options = options || {};
if ( !Array.isArray( wcDir ) ) {
wcDir = [wcDir];
}
var args = [ '-n' ];
if ( options.lastChangeRevision ) {
args.push( '-c' );
}
execSvnVersion( wcDir.concat( args ), options, function( err, data ) {
var result;
if ( !err ) {
var match = data.match( /(\d+):?(\d*)(\w*)/ );
if ( match ) {
result = {};
result.low = parseInt( match[1] );
if ( match[2].length > 0 ) {
result.high = parseInt( match[2] );
} else {
result.high = result.low;
| }
result.flags = match[3];
if ( result.flags.length > 0 ) {
result.modified = result.flags.indexOf( 'M' ) >= 0;
result.partial = result.flags.indexOf( 'P' ) >= 0;
result.switched = result.flags.indexOf( 'S' ) >= 0;
}
} else {
err = data;
}
}
callback( err, result );
} );
} | csn_ccr |
def _communicate(self):
"""Callback for communicate."""
if (not self._communicate_first and
self._process.state() | == QProcess.NotRunning):
self.communicate()
elif self._fired:
self._timer.stop() | csn_ccr |
public function getIngestManifestAssetList()
{
$propertyList = $this->_getEntityList('IngestManifestAssets');
$result = [];
foreach ($propertyList as $properties) {
$result[] = | IngestManifestAsset::createFromOptions($properties);
}
return $result;
} | csn_ccr |
python check existance of config | def _is_already_configured(configuration_details):
"""Returns `True` when alias already in shell config."""
path = Path(configuration_details.path).expanduser()
with path.open('r') as shell_config:
return configuration_details.content in shell_config.read() | cosqa |
// Tokenizer is the name of the tokenizer to use for the analysis. | func (s *IndicesAnalyzeService) Tokenizer(tokenizer string) *IndicesAnalyzeService {
s.request.Tokenizer = tokenizer
return s
} | csn |
Levko loves array a_1, a_2, ... , a_{n}, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:
Increase all elements from l_{i} to r_{i} by d_{i}. In other words, perform assignments a_{j} = a_{j} + d_{i} for all j that meet the inequation l_{i} ≤ j ≤ r_{i}. Find the maximum of elements from l_{i} to r_{i}. That is, calculate the value $m_{i} = \operatorname{max}_{j = l_{i}}^{r_{i}} a_{j}$.
Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 10^9 in their absolute value, so he asks you to find such an array.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 5000) — the size of the array and the number of operations in Levko's records, correspondingly.
Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer t_{i} (1 ≤ t_{i} ≤ 2) that describes the operation type. If t_{i} = 1, then it is followed by three integers l_{i}, r_{i} and d_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n, - 10^4 ≤ d_{i} ≤ 10^4) — the description of the operation of the first type. If t_{i} = 2, then it is followed by three integers l_{i}, r_{i} and m_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n, - 5·10^7 ≤ m_{i} ≤ 5·10^7) — the description of the operation of the second type.
The operations are given in the order Levko performed them on his array.
-----Output-----
In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.
If the solution exists, then on the second line print n integers a_1, a_2, ... , a_{n} (|a_{i}| ≤ 10^9) — the recovered array.
-----Examples-----
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 8
Output
YES
4 7 4 7
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 13
Output
NO | n, m = map(int, input().split())
a = [10**9 for _ in range(n)]
extra = [0 for _ in range(n)]
query = list()
for _ in range(m):
t, l, r, x = map(int, input().split())
l -= 1
r -= 1
query.append((t, l, r, x))
if t == 1:
for j in range(l, r + 1):
extra[j] += x
else:
for j in range(l, r + 1):
a[j] = min(a[j], x - extra[j])
extra = a.copy()
for t, l, r, x in query:
if t == 1:
for j in range(l, r + 1):
a[j] += x
else:
val = -10**9
for j in range(l, r + 1):
val = max(val, a[j])
if not val == x:
print('NO')
return
print('YES')
for x in extra:
print(x, end=' ')
| apps |
def generate_http_manifest(self):
"""Return http manifest.
The http manifest is the resource that defines a dataset as HTTP
enabled (published).
"""
base_path = os.path.dirname(self.translate_path(self.path))
self.dataset = dtoolcore.DataSet.from_uri(base_path)
admin_metadata_fpath = os.path.join(base_path, ".dtool", "dtool") |
with open(admin_metadata_fpath) as fh:
admin_metadata = json.load(fh)
http_manifest = {
"admin_metadata": admin_metadata,
"manifest_url": self.generate_url(".dtool/manifest.json"),
"readme_url": self.generate_url("README.yml"),
"overlays": self.generate_overlay_urls(),
"item_urls": self.generate_item_urls()
}
return bytes(json.dumps(http_manifest), "utf-8") | csn_ccr |
public void concatenate(JavaMethod tail)
{
CodeAttribute codeAttr = getCode();
CodeAttribute tailCodeAttr = tail.getCode();
byte []code = codeAttr.getCode();
byte []tailCode = tailCodeAttr.getCode();
int codeLength = code.length;
if ((code[codeLength - 1] & 0xff) == CodeVisitor.RETURN)
codeLength = codeLength - 1;
byte []newCode = new byte[codeLength + tailCode.length];
System.arraycopy(code, 0, newCode, 0, codeLength);
System.arraycopy(tailCode, 0, newCode, codeLength, tailCode.length);
codeAttr.setCode(newCode);
if (codeAttr.getMaxStack() < tailCodeAttr.getMaxStack())
codeAttr.setMaxStack(tailCodeAttr.getMaxStack());
if (codeAttr.getMaxLocals() < tailCodeAttr.getMaxLocals())
| codeAttr.setMaxLocals(tailCodeAttr.getMaxLocals());
ArrayList<CodeAttribute.ExceptionItem> exns = tailCodeAttr.getExceptions();
for (int i = 0; i < exns.size(); i++) {
CodeAttribute.ExceptionItem exn = exns.get(i);
CodeAttribute.ExceptionItem newExn = new CodeAttribute.ExceptionItem();
newExn.setType(exn.getType());
newExn.setStart(exn.getStart() + codeLength);
newExn.setEnd(exn.getEnd() + codeLength);
newExn.setHandler(exn.getHandler() + codeLength);
}
} | csn_ccr |
function getCategories (posts) {
var categories = posts.reduce(function (categories, post) {
if (!post.category) return categories;
| return categories.concat(post.category);
}, []);
return _.unique(categories).sort();
} | csn_ccr |
func LineCount(screenWidth, w int) int {
r := w / screenWidth |
if w%screenWidth != 0 {
r++
}
return r
} | csn_ccr |
protected void readUUID(StreamReader stream, Map<String, Object> map) throws IOException
{
int unknown0Size = | stream.getMajorVersion() > 5 ? 8 : 16;
map.put("UNKNOWN0", stream.readBytes(unknown0Size));
map.put("UUID", stream.readUUID());
} | csn_ccr |
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
"""Parse the system profiler output. We get it in the form of a plist."""
_ = stderr, time_taken, args, knowledge_base # Unused
self.CheckReturn(cmd, return_val)
plist = biplist.readPlist(io.BytesIO(stdout))
if len(plist) > 1:
raise parser.ParseError("SPHardwareDataType plist has too many items.")
hardware_list = plist[0]["_items"][0]
serial_number = hardware_list.get("serial_number", None)
| system_product_name = hardware_list.get("machine_model", None)
bios_version = hardware_list.get("boot_rom_version", None)
yield rdf_client.HardwareInfo(
serial_number=serial_number,
bios_version=bios_version,
system_product_name=system_product_name) | csn_ccr |
def url_for(endpoint_or_url_or_config_key: str,
_anchor: Optional[str] = None,
_cls: Optional[Union[object, type]] = None,
_external: Optional[bool] = False,
_external_host: Optional[str] = None,
_method: Optional[str] = None,
_scheme: Optional[str] = None,
**values,
) -> Union[str, None]:
"""
An improved version of flask's url_for function
:param endpoint_or_url_or_config_key: what to lookup. it can be an endpoint
name, an app config key, or an already-formed url. if _cls is specified,
it also accepts a method name.
:param values: the variable arguments of the URL rule
:param _anchor: if provided this is added as anchor to the URL.
:param _cls: if specified, can also pass a method name as the first argument
:param _external: if set to ``True``, an absolute URL is generated. Server
address can be changed via ``SERVER_NAME`` configuration variable which
defaults to `localhost`.
:param _external_host: if specified, the host of an external server
to generate urls for (eg https://example.com or localhost:8888)
:param _method: if provided this explicitly specifies an HTTP method.
:param _scheme: a string specifying the desired URL scheme. The `_external`
parameter must be set to ``True`` or a :exc:`ValueError` is raised. The
default behavior uses the same scheme as the current request, or
``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no
request context is available. As of Werkzeug 0.10, this also can be set
to an empty string to build protocol-relative URLs.
"""
what = endpoint_or_url_or_config_key
# if what is a config key
if what and | what.isupper():
what = current_app.config.get(what)
if isinstance(what, LocalProxy):
what = what._get_current_object()
# if we already have a url (or an invalid value, eg None)
if not what or '/' in what:
return what
flask_url_for_kwargs = dict(_anchor=_anchor, _external=_external,
_external_host=_external_host, _method=_method,
_scheme=_scheme, **values)
# check if it's a class method name, and try that endpoint
if _cls and '.' not in what:
controller_routes = getattr(_cls, CONTROLLER_ROUTES_ATTR)
method_routes = controller_routes.get(what)
try:
return _url_for(method_routes[0].endpoint, **flask_url_for_kwargs)
except (
BuildError, # url not found
IndexError, # method_routes[0] is out-of-range
TypeError, # method_routes is None
):
pass
# what must be an endpoint
return _url_for(what, **flask_url_for_kwargs) | csn_ccr |
List all the resource pools for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_resourcepools my-vmware-config | def list_resourcepools(kwargs=None, call=None):
'''
List all the resource pools for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_resourcepools my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_resourcepools function must be called with '
'-f or --function.'
)
return {'Resource Pools': salt.utils.vmware.list_resourcepools(_get_si())} | csn |
Decorator that copies a method's docstring from another class.
Args:
source_class (type): The class that has the documented method.
Returns:
Callable: A decorator that will copy the docstring of the same
named method in the source class to the decorated method. | def copy_docstring(source_class):
"""Decorator that copies a method's docstring from another class.
Args:
source_class (type): The class that has the documented method.
Returns:
Callable: A decorator that will copy the docstring of the same
named method in the source class to the decorated method.
"""
def decorator(method):
"""Decorator implementation.
Args:
method (Callable): The method to copy the docstring to.
Returns:
Callable: the same method passed in with an updated docstring.
Raises:
ValueError: if the method already has a docstring.
"""
if method.__doc__:
raise ValueError('Method already has a docstring.')
source_method = getattr(source_class, method.__name__)
method.__doc__ = source_method.__doc__
return method
return decorator | csn |
protected function _createToken($identity)
{
$plain = $this->_createPlainToken($identity);
$hash = $this->getPasswordHasher()->hash($plain);
| $usernameField = $this->getConfig('fields.username');
return json_encode([$identity[$usernameField], $hash]);
} | csn_ccr |
@Bean
public PropertiesFactoryBean casCommonMessages() {
val properties = new PropertiesFactoryBean();
val resourceLoader = new DefaultResourceLoader();
val commonNames = casProperties.getMessageBundle().getCommonNames();
val resourceList = commonNames
.stream()
.map(resourceLoader::getResource)
| .collect(Collectors.toList());
resourceList.add(resourceLoader.getResource("classpath:/cas_common_messages.properties"));
properties.setLocations(resourceList.toArray(Resource[]::new));
properties.setSingleton(true);
properties.setIgnoreResourceNotFound(true);
return properties;
} | csn_ccr |
def backout_last(self, updated_singles, num_coincs):
"""Remove the recently added singles and coincs
Parameters
----------
updated_singles: dict of numpy.ndarrays
Array of indices that have been just updated in the internal
buffers of single detector triggers.
num_coincs: int
| The number of coincs that were just added to the internal buffer
of coincident triggers
"""
for ifo in updated_singles:
self.singles[ifo].discard_last(updated_singles[ifo])
self.coincs.remove(num_coincs) | csn_ccr |
public function word($data, $default = '', $options = [])
{
//First word in a sanitized string
$sentence = $this->string($data, $default, | $options, false);
//@TODO validate string before breaking into words;
//Requires php5.3!!
return (string)strstr($sentence, ' ', true);
} | csn_ccr |
public Collection<Metric> metricNames(long applicationId, String name)
{
QueryParameterList queryParams = new QueryParameterList();
| if(name != null && name.length() > 0)
queryParams.add("name", name);
return HTTP.GET(String.format("/v2/mobile_applications/%d/metrics.json", applicationId), null, queryParams, METRICS).get();
} | csn_ccr |
func (t *Template) GetAllAWSGuardDutyMemberResources() map[string]*resources.AWSGuardDutyMember {
results := map[string]*resources.AWSGuardDutyMember{}
for name, untyped := range t.Resources {
| switch resource := untyped.(type) {
case *resources.AWSGuardDutyMember:
results[name] = resource
}
}
return results
} | csn_ccr |
def validate_one_format(jupytext_format):
"""Validate extension and options for the given format"""
if not isinstance(jupytext_format, dict):
raise JupytextFormatError('Jupytext format should be a dictionary')
for key in jupytext_format:
if key not in _VALID_FORMAT_INFO + _VALID_FORMAT_OPTIONS:
raise JupytextFormatError("Unknown format option '{}' - should be one of '{}'".format(
key, "', '".join(_VALID_FORMAT_OPTIONS)))
value = jupytext_format[key]
if key in _BINARY_FORMAT_OPTIONS:
if not isinstance(value, bool):
raise JupytextFormatError("Format option '{}' should be a bool, not '{}'".format(key, str(value)))
if | 'extension' not in jupytext_format:
raise JupytextFormatError('Missing format extension')
ext = jupytext_format['extension']
if ext not in NOTEBOOK_EXTENSIONS + ['.auto']:
raise JupytextFormatError("Extension '{}' is not a notebook extension. Please use one of '{}'.".format(
ext, "', '".join(NOTEBOOK_EXTENSIONS + ['.auto'])))
return jupytext_format | csn_ccr |
public function getLinkForPage($pageNumber, $label, $htmlOptions = array()) {
| return Html::get()->link($this->getURLForPage($pageNumber), $label, $htmlOptions);
} | csn_ccr |
func NewErrorLexer(msg string, l *buffer.Lexer) *Error {
r := buffer.NewReader(l.Bytes())
offset | := l.Offset()
return NewError(msg, r, offset)
} | csn_ccr |
List all available instance configurations.
Example:
```
$configurations = $spanner->instanceConfigurations();
```
@codingStandardsIgnoreStart
@see https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.ListInstanceConfigsRequest ListInstanceConfigsRequest
@codingStandardsIgnoreEnd
@param array $options [optional] {
Configuration Options.
@type int $pageSize Maximum number of results to return per
request.
@type int $resultLimit Limit the number of results returned in total.
**Defaults to** `0` (return all results).
@type string $pageToken A previously-returned page token used to
resume the loading of results from a specific point.
}
@return ItemIterator<InstanceConfiguration> | public function instanceConfigurations(array $options = [])
{
$resultLimit = $this->pluck('resultLimit', $options, false) ?: 0;
return new ItemIterator(
new PageIterator(
function (array $config) {
return $this->instanceConfiguration($config['name'], $config);
},
[$this->connection, 'listInstanceConfigs'],
['projectId' => InstanceAdminClient::projectName($this->projectId)] + $options,
[
'itemsKey' => 'instanceConfigs',
'resultLimit' => $resultLimit
]
)
);
} | csn |
func (s *authKeyV1) Put() interface{} {
var handler AuthPutHandler = func(params martini.Params, log *log.Logger, r render.Render, tokens oauth2.Tokens) {
var (
err error
apikey string
)
log.Println("executing the put handler")
username := params[UserParam]
userInfo := GetUserInfo(tokens)
details, _ := json.Marshal(userInfo)
NewUserMatch().
UserInfo(userInfo).
UserName(username).
OnSuccess(func() {
log.Println("getting userInfo: ", userInfo)
if err = s.keyGen.Delete(username); err != nil {
log.Println("keyGen.Delete error: ", err)
} |
if err = s.keyGen.Create(username, string(details[:])); err != nil {
log.Println("keyGen.Create error: ", err)
}
if apikey, err = s.keyGen.Get(username); err != nil {
log.Println("keyGen.Get error: ", err)
}
}).
OnFailure(func() {
err = ErrInvalidCallerEmail
log.Println("invalid user token error: ", err)
}).Run()
genericResponseFormatter(r, apikey, userInfo, err)
}
return handler
} | csn_ccr |
On Setting display.
@param AnEvent $event The event parameter | public function onSettingDisplay(AnEvent $event)
{
$actor = $event->actor;
$tabs = $event->tabs;
$this->_setSettingTabs($actor, $tabs);
} | csn |
Returns a logger
@param string $logger Logger's name
@return LoggerInterface | public function getLog(string $logger = 'default'): LoggerInterface
{
if (!isset($this->loggers[$logger])) {
if ($logger === 'default') {
if (!isset($this->implicit['logger'])) {
throw new \RuntimeException('The default logger was not set');
}
$this->loggers[$logger] = $this->implicit['logger'];
} else {
$this->loggers[$logger] = $this->getCollector()->getLogger($logger);
}
}
return $this->loggers[$logger];
} | csn |
def matches(self, txt: str) -> bool:
"""Determine whether txt matches pattern
:param txt: text to check
:return: True if match
"""
# rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape')
if r'\\u' in self.pattern_re.pattern:
| txt = txt.encode('utf-8').decode('unicode-escape')
match = self.pattern_re.match(txt)
return match is not None and match.end() == len(txt) | csn_ccr |
Loads the given class, definition or interface.
@param string $class The name of the class | public function loadClass($class)
{
if ((true === $this->apc && ($file = $this->findFileInApc($class))) or
($file = $this->findFile($class))
) {
require_once $file;
}
} | csn |
protected static String jacksonObjectToString(Object object) {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
| logger.error("Failed to serialize JSON data: " + e.toString());
return null;
}
} | csn_ccr |
def _join_keys_v1(left, right):
"""
Join two keys into a format separable by using _split_keys_v1.
"""
if left.endswith(':') or '::' in left:
raise ValueError("Can't join a left string | ending in ':' or containing '::'")
return u"{}::{}".format(_encode_v1(left), _encode_v1(right)) | csn_ccr |
func Convert_v1_QuobyteVolumeSource_To_core_QuobyteVolumeSource(in *v1.QuobyteVolumeSource, out | *core.QuobyteVolumeSource, s conversion.Scope) error {
return autoConvert_v1_QuobyteVolumeSource_To_core_QuobyteVolumeSource(in, out, s)
} | csn_ccr |
Sets the alert_statuses of this IntegrationStatus.
A Map from the ids of the alerts contained in this integration to their install status. The install status can take on one of three values, `VISIBLE`, `HIDDEN`, and `NOT_LOADED` # noqa: E501
:param alert_statuses: The alert_statuses of this IntegrationStatus. # noqa: E501
:type: dict(str, str) | def alert_statuses(self, alert_statuses):
"""Sets the alert_statuses of this IntegrationStatus.
A Map from the ids of the alerts contained in this integration to their install status. The install status can take on one of three values, `VISIBLE`, `HIDDEN`, and `NOT_LOADED` # noqa: E501
:param alert_statuses: The alert_statuses of this IntegrationStatus. # noqa: E501
:type: dict(str, str)
"""
if alert_statuses is None:
raise ValueError("Invalid value for `alert_statuses`, must not be `None`") # noqa: E501
allowed_values = ["VISIBLE", "HIDDEN", "NOT_LOADED"] # noqa: E501
if not set(alert_statuses.keys()).issubset(set(allowed_values)):
raise ValueError(
"Invalid keys in `alert_statuses` [{0}], must be a subset of [{1}]" # noqa: E501
.format(", ".join(map(str, set(alert_statuses.keys()) - set(allowed_values))), # noqa: E501
", ".join(map(str, allowed_values)))
)
self._alert_statuses = alert_statuses | csn |
Use this API to fetch spilloverpolicy_binding resource of given name . | public static spilloverpolicy_binding get(nitro_service service, String name) throws Exception{
spilloverpolicy_binding obj = new spilloverpolicy_binding();
obj.set_name(name);
spilloverpolicy_binding response = (spilloverpolicy_binding) obj.get_resource(service);
return response;
} | csn |
public static function label($name, $value = null, array $options = [])
{
self::exclure($options, ['value', 'for']);
self::$labels[] = $name;
$value = e(self::formatLabel($name, $value));
| $options = Html::attributes($options);
return '<label for="'.$name.'"'.$options.'>'.$value.'</label>';
} | csn_ccr |
Calculate the next fallback locale for the given locale.
Note: always keep this in sync with the fallback mechanism in Java, ABAP (MIME & BSP)
resource handler (Java: Peter M., MIME: Sebastian A., BSP: Silke A.)
@param {string} sLocale Locale string in Java format (underscores) or null
@returns {string|null} Next fallback Locale or null if there is no more fallback
@private | function nextFallbackLocale(sLocale) {
// there is no fallback for the 'raw' locale or for null/undefined
if ( !sLocale ) {
return null;
}
// special (legacy) handling for zh_HK: try zh_TW (for Traditional Chinese) first before falling back to 'zh'
if ( sLocale === "zh_HK" ) {
return "zh_TW";
}
// if there are multiple segments (separated by underscores), remove the last one
var p = sLocale.lastIndexOf('_');
if ( p >= 0 ) {
return sLocale.slice(0,p);
}
// invariant: only a single segment, must be a language
// for any language but 'en', fallback to 'en' first before falling back to the 'raw' language (empty string)
return sLocale !== 'en' ? 'en' : '';
} | csn |
private function doCallBackSingleProp($propertyName, callable $callback)
{
$result = $callback($this->mutations[$propertyName]);
if (is_bool($result)) {
if ($result) {
if (is_null($this->mutations[$propertyName])) {
// Delete
$result = 204;
} else {
// Update
$result = 200;
}
} else {
// Fail
$result = 403;
} |
}
if (!is_int($result)) {
throw new UnexpectedValueException('A callback sent to handle() did not return an int or a bool');
}
$this->result[$propertyName] = $result;
if ($result >= 400) {
$this->failed = true;
}
} | csn_ccr |
def next_game_date(dt,wday)
dt += 1 until wday == dt.wday && | !self.exclude_dates.include?(dt)
dt
end | csn_ccr |
Top level policy delete routine. | def fw_policy_delete(self, data, fw_name=None):
"""Top level policy delete routine. """
LOG.debug("FW Policy Debug")
self._fw_policy_delete(fw_name, data) | csn |
def process_file(path)
code = File.read(path)
sexp_node = RubyParser.new.parse(code)
file = Mago::RubyFile.new(path)
sexp_processor = Mago::SexpProcessor.new(file, @ignore)
sexp_processor.process(sexp_node)
| @report.files << file
@on_file.call(file) if @on_file
rescue Errno::ENOENT => err
handle_error(err.message)
rescue Racc::ParseError, Encoding::CompatibilityError => err
msg = "#{path} has invalid ruby code. " << err.message
handle_error(msg)
end | csn_ccr |
// DataURI parses the given data URI and returns the mediatype, data and ok. | func DataURI(dataURI []byte) ([]byte, []byte, error) {
if len(dataURI) > 5 && bytes.Equal(dataURI[:5], []byte("data:")) {
dataURI = dataURI[5:]
inBase64 := false
var mediatype []byte
i := 0
for j := 0; j < len(dataURI); j++ {
c := dataURI[j]
if c == '=' || c == ';' || c == ',' {
if c != '=' && bytes.Equal(TrimWhitespace(dataURI[i:j]), []byte("base64")) {
if len(mediatype) > 0 {
mediatype = mediatype[:len(mediatype)-1]
}
inBase64 = true
i = j
} else if c != ',' {
mediatype = append(append(mediatype, TrimWhitespace(dataURI[i:j])...), c)
i = j + 1
} else {
mediatype = append(mediatype, TrimWhitespace(dataURI[i:j])...)
}
if c == ',' {
if len(mediatype) == 0 || mediatype[0] == ';' {
mediatype = []byte("text/plain")
}
data := dataURI[j+1:]
if inBase64 {
decoded := make([]byte, base64.StdEncoding.DecodedLen(len(data)))
n, err := base64.StdEncoding.Decode(decoded, data)
if err != nil {
return nil, nil, err
}
data = decoded[:n]
} else if unescaped, err := url.QueryUnescape(string(data)); err == nil {
data = []byte(unescaped)
}
return mediatype, data, nil
}
}
}
}
return nil, nil, ErrBadDataURI
} | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.