query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Tags the response with the data for block provided by the event. | public function onKernelResponse(FilterResponseEvent $event): void
{
if (!$event->isMasterRequest()) {
return;
}
$blockView = $event->getRequest()->attributes->get('ngbmView');
if (!$blockView instanceof BlockViewInterface) {
return;
}
$this->tagger->tagBlock($event->getResponse(), $blockView->getBlock());
} | csn |
Run structural variation detection.
The stage indicates which level of structural variant calling to run.
- initial, callers that can be used in subsequent structural variation steps (cnvkit -> lumpy)
- standard, regular batch calling
- ensemble, post-calling, combine other callers or prioritize results | def run(samples, run_parallel, stage):
"""Run structural variation detection.
The stage indicates which level of structural variant calling to run.
- initial, callers that can be used in subsequent structural variation steps (cnvkit -> lumpy)
- standard, regular batch calling
- ensemble, post-calling, combine other callers or prioritize results
"""
to_process, extras, background = _batch_split_by_sv(samples, stage)
processed = run_parallel("detect_sv", ([xs, background, stage]
for xs in to_process.values()))
finalized = (run_parallel("finalize_sv", [([xs[0] for xs in processed], processed[0][0]["config"])])
if len(processed) > 0 else [])
return extras + finalized | csn |
Initialize audit4j when starting spring application context.
{@inheritDoc}
@see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() | @Override
public void afterPropertiesSet() throws Exception {
Configuration configuration = Configuration.INSTANCE;
configuration.setLayout(layout);
configuration.setHandlers(handlers);
configuration.setFilters(filters);
configuration.setCommands(commands);
configuration.setJmx(jmx);
configuration.setProperties(properties);
if (metaData == null) {
if (actorSessionAttributeName == null) {
configuration.setMetaData(new SpringSecurityWebAuditMetaData());
} else {
configuration.setMetaData(new WebSessionAuditMetaData());
}
} else {
configuration.setMetaData(metaData);
}
if (annotationTransformer != null) {
configuration.setAnnotationTransformer(annotationTransformer);
}
AuditManager.startWithConfiguration(configuration);
} | csn |
protected void setTypeConversions(List<Pair<String, String>> typeConversions, boolean notifyController) {
this.conversions.clear();
if (typeConversions != null) {
for (final Pair<String, String> entry : typeConversions) {
| this.conversions.add(new ConversionMapping(entry.getKey(), entry.getValue()));
}
}
this.list.setInput(this.conversions);
refreshListUI();
if (notifyController) {
preferenceValueChanged();
}
} | csn_ccr |
private void checkAllTables() throws SQLException {
logger.entering(CLASSNAME, "checkAllTables");
createIfNotExists(CHECKPOINTDATA_TABLE, CREATE_TAB_CHECKPOINTDATA);
executeStatement(CREATE_CHECKPOINTDATA_INDEX);
createIfNotExists(JOBINSTANCEDATA_TABLE, CREATE_TAB_JOBINSTANCEDATA);
|
createIfNotExists(EXECUTIONINSTANCEDATA_TABLE,
CREATE_TAB_EXECUTIONINSTANCEDATA);
createIfNotExists(STEPEXECUTIONINSTANCEDATA_TABLE,
CREATE_TAB_STEPEXECUTIONINSTANCEDATA);
createIfNotExists(JOBSTATUS_TABLE, CREATE_TAB_JOBSTATUS);
createIfNotExists(STEPSTATUS_TABLE, CREATE_TAB_STEPSTATUS);
logger.exiting(CLASSNAME, "checkAllTables");
} | csn_ccr |
Set allowed pagination limits
@param array $limits
@return $this | public function setLimits(array $limits = [])
{
if (empty($limits)) {
throw new ListingException("You must provide at least one limit option");
}
$this->limits = array_values($limits);
return $this;
} | csn |
public ConsoleLog getConsoleOutputText(int bufferOffset, boolean crumbFlag) throws IOException {
List<NameValuePair> formData = new ArrayList<>();
formData.add(new BasicNameValuePair("start", Integer.toString(bufferOffset)));
String path = getUrl() + "logText/progressiveText";
HttpResponse httpResponse = client.post_form_with_result(path, formData, crumbFlag);
Header moreDataHeader = httpResponse.getFirstHeader(MORE_DATA_HEADER);
Header textSizeHeader = httpResponse.getFirstHeader(TEXT_SIZE_HEADER);
String response = EntityUtils.toString(httpResponse.getEntity());
boolean hasMoreData = false;
if (moreDataHeader != null) {
hasMoreData = Boolean.TRUE.toString().equals(moreDataHeader.getValue());
}
Integer currentBufferSize = bufferOffset; |
if (textSizeHeader != null) {
try {
currentBufferSize = Integer.parseInt(textSizeHeader.getValue());
} catch (NumberFormatException e) {
LOGGER.warn("Cannot parse buffer size for job {0} build {1}. Using current offset!", this.getDisplayName(), this.getNumber());
}
}
return new ConsoleLog(response, hasMoreData, currentBufferSize);
} | csn_ccr |
Produces an html blob of attribution statements for the array
of attachment ids it's given.
@since 5.5.0
@param array $attributions
@return string | function attributionsContent( $attributions ) {
$media_attributions = '';
$html = '';
$licensing = new Licensing();
$supported = $licensing->getSupportedTypes();
if ( $attributions ) {
// generate appropriate markup for each field
foreach ( $attributions as $attribution ) {
// unset empty arrays
$attribution = array_filter( $attribution, 'strlen' );
// only process if non-empty
if ( count( $attribution ) > 0 ) {
$author_byline = isset( $attribution['author'] ) ? __( ' by ', 'pressbooks' ) : '';
$adapted_byline = isset( $attribution['adapted'] ) ? __( ' adapted by ', 'pressbooks' ) : '';
$license_prefix = isset( $attribution['license'] ) ? ' © ' : '';
$author = isset( $attribution['author'] ) ? $attribution['author'] : '';
$title = isset( $attribution['title'] ) ? $attribution['title'] : '';
$adapted_author = isset( $attribution['adapted'] ) ? $attribution['adapted'] : '';
$media_attributions .= sprintf(
'<li %1$s>%2$s %3$s %4$s %5$s</li>',
// about attribute
( isset( $attribution['title_url'] ) ) ?
sprintf(
'about="%s"',
$attribution['title_url']
) : '',
// title attribution
( isset( $attribution['title_url'] ) ) ?
sprintf(
'<a rel="cc:attributionURL" href="%1$s" property="dc:title">%2$s</a>',
$attribution['title_url'],
$title
) : $title,
// author attribution
sprintf(
'%1$s %2$s',
$author_byline,
( isset( $attribution['author_url'] ) ) ?
sprintf(
'<a rel="dc:creator" href="%1$s" property="cc:attributionName">%2$s</a>',
$attribution['author_url'],
$author
) : $author
),
// adapted attribution
sprintf(
'%1$s %2$s',
$adapted_byline,
( isset( $attribution['adapted_url'] ) ) ?
sprintf(
'<a rel="dc:source" href="%1$s">%2$s</a>',
$attribution['adapted_url'],
$adapted_author
) : $adapted_author
),
// license attribution
sprintf(
'%1$s %2$s',
$license_prefix,
( isset( $attribution['license'] ) ) ?
sprintf(
'<a rel="license" href="%1$s">%2$s</a>',
$licensing->getUrlForLicense( $attribution['license'] ),
$supported[ $attribution['license'] ]['desc']
) : ''
)
);
}
}
if ( ! empty( $media_attributions ) ) {
$html = sprintf(
'<div class="media-atttributions" prefix:cc="http://creativecommons.org/ns#" prefix:dc="http://purl.org/dc/terms/"><h3>' . __( 'Media Attributions', 'pressbooks' ) . '</h3><ul>%s</ul></div>',
$media_attributions
);
}
}
return $html;
} | csn |
async def send_request(self):
"""Coroutine to send request headers with metadata to the server.
New HTTP/2 stream will be created during this coroutine call.
.. note:: This coroutine will be called implicitly during first
:py:meth:`send_message` coroutine call, if not called before
explicitly.
"""
if self._send_request_done:
raise ProtocolError('Request is already sent')
with self._wrapper:
protocol = await self._channel.__connect__()
stream = protocol.processor.connection\
.create_stream(wrapper=self._wrapper)
headers = [
(':method', 'POST'),
(':scheme', self._channel._scheme),
(':path', self._method_name),
(':authority', self._channel._authority),
]
if self._deadline is not None:
timeout = self._deadline.time_remaining()
headers.append(('grpc-timeout', encode_timeout(timeout)))
content_type = (GRPC_CONTENT_TYPE
| + '+' + self._codec.__content_subtype__)
headers.extend((
('te', 'trailers'),
('content-type', content_type),
('user-agent', USER_AGENT),
))
metadata, = await self._dispatch.send_request(
self._metadata,
method_name=self._method_name,
deadline=self._deadline,
content_type=content_type,
)
headers.extend(encode_metadata(metadata))
release_stream = await stream.send_request(
headers, _processor=protocol.processor,
)
self._stream = stream
self._release_stream = release_stream
self._send_request_done = True | csn_ccr |
public static void present(final Map<?, ?> map, final Object key, final String name)
{
if (null == map.get(key))
{
| throw new IllegalStateException(name + " not found in map for key: " + key);
}
} | csn_ccr |
Get parameters relevant for lateration from full all_points, edm and W. | def get_lateration_parameters(all_points, indices, index, edm, W=None):
""" Get parameters relevant for lateration from full all_points, edm and W.
"""
if W is None:
W = np.ones(edm.shape)
# delete points that are not considered anchors
anchors = np.delete(all_points, indices, axis=0)
r2 = np.delete(edm[index, :], indices)
w = np.delete(W[index, :], indices)
# set w to zero where measurements are invalid
if np.isnan(r2).any():
nan_measurements = np.where(np.isnan(r2))[0]
r2[nan_measurements] = 0.0
w[nan_measurements] = 0.0
if np.isnan(w).any():
nan_measurements = np.where(np.isnan(w))[0]
r2[nan_measurements] = 0.0
w[nan_measurements] = 0.0
# delete anchors where weight is zero to avoid ill-conditioning
missing_anchors = np.where(w == 0.0)[0]
w = np.asarray(np.delete(w, missing_anchors))
r2 = np.asarray(np.delete(r2, missing_anchors))
w.resize(edm.shape[0] - len(indices) - len(missing_anchors), 1)
r2.resize(edm.shape[0] - len(indices) - len(missing_anchors), 1)
anchors = np.delete(anchors, missing_anchors, axis=0)
assert w.shape[0] == anchors.shape[0]
assert np.isnan(w).any() == False
assert np.isnan(r2).any() == False
return anchors, w, r2 | csn |
func (d *ClientDigestsFile) Equal(a *ClientDigestsFile) bool {
if len(d.entries) != len(a.entries) {
return false
}
for i, l := range d.entries {
if r := a.entries[i]; l.plat | != r.plat || !proto.Equal(l.ref, r.ref) {
return false
}
}
return true
} | csn_ccr |
public static long indexFromString(String str)
{
// The length of the decimal string representation of
// Integer.MAX_VALUE, 2147483647
final int MAX_VALUE_LENGTH = 10;
int len = str.length();
if (len > 0) {
int i = 0;
boolean negate = false;
int c = str.charAt(0);
if (c == '-') {
if (len > 1) {
c = str.charAt(1);
if (c == '0') return -1L; // "-0" is not an index
i = 1;
negate = true;
}
}
c -= '0';
if (0 <= c && c <= 9
&& len <= (negate ? MAX_VALUE_LENGTH + 1 : MAX_VALUE_LENGTH))
{
// Use negative numbers to accumulate index to handle
// Integer.MIN_VALUE that is greater by 1 in absolute value
// then Integer.MAX_VALUE
int index = -c;
int oldIndex = 0;
i++;
if (index != 0) {
// Note that 00, 01, 000 etc. are not indexes
while (i != len && 0 <= (c = str.charAt(i) - '0') && c <= 9)
{
oldIndex = index;
index = 10 * index - c;
| i++;
}
}
// Make sure all characters were consumed and that it couldn't
// have overflowed.
if (i == len &&
(oldIndex > (Integer.MIN_VALUE / 10) ||
(oldIndex == (Integer.MIN_VALUE / 10) &&
c <= (negate ? -(Integer.MIN_VALUE % 10)
: (Integer.MAX_VALUE % 10)))))
{
return 0xFFFFFFFFL & (negate ? index : -index);
}
}
}
return -1L;
} | csn_ccr |
Convenience method for getting an iterator over the entries.
@return an iterator over the entries | public Iterator<Entry<String, Object>> entryIterator() {
final Iterator<String> iter = keyIterator();
return new Iterator<Entry<String, Object>>() {
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public Entry<String, Object> next() {
String key = iter.next();
Object value = get(key);
return new MyMapEntry(BeanMap.this, key, value);
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove() not supported for BeanMap");
}
};
} | csn |
Get list of all genre.
@return array | private function getAllInfo()
{
$data = [];
foreach ($this->_parser->find('.genre-list a') as $each_genre) {
$genre = [];
$link = $each_genre->href;
$link = explode('/', $link);
$id = $link[3];
$genre['id'] = $id;
$name = str_replace('_', ' ', $link[4]);
$genre['name'] = $name;
$genre['count'] = $this->getGenreCount($each_genre);
$data[] = $genre;
}
return $data;
} | csn |
func (c CursorPosition) String() string {
return | "\x1b[" + strconv.Itoa(c.X) + ";" + strconv.Itoa(c.Y) + "H"
} | csn_ccr |
// OnKeyEvent handles terminal events. | func (l *List) OnKeyEvent(ev KeyEvent) {
if !l.IsFocused() {
return
}
switch ev.Key {
case KeyUp:
l.moveUp()
case KeyDown:
l.moveDown()
case KeyEnter:
if l.onItemActivated != nil {
l.onItemActivated(l)
}
}
switch ev.Rune {
case 'k':
l.moveUp()
case 'j':
l.moveDown()
}
} | csn |
protected function parseSqliteOptions(array $config)
{
if (isset($config['memory']) && $config['memory']) {
// If in-memory, no need to parse paths
unset($config['path']);
return $config;
}
// Prevent SQLite driver from trying to use in-memory connection
unset($config['memory']);
// Get path from config or use database path
$path = isset($config['path']) ? $config['path'] : $this->app['path_resolver']->resolve('database');
if (Path::isRelative($path)) {
$path = $this->app['path_resolver']->resolve($path);
}
// If path has filename with extension, use that
if (Path::hasExtension($path)) {
| $config['path'] = $path;
return $config;
}
// Use database name for filename
$filename = basename($config['dbname']);
if (!Path::hasExtension($filename)) {
$filename .= '.db';
}
// Join filename with database path
$config['path'] = Path::join($path, $filename);
return $config;
} | csn_ccr |
def list_arc (archive, compression, cmd, verbosity, interactive):
"""List a ARC archive."""
cmdlist = [cmd]
if verbosity > 1:
| cmdlist.append('v')
else:
cmdlist.append('l')
cmdlist.append(archive)
return cmdlist | csn_ccr |
public function start($identifier = null)
{
$this->loadProfile($identifier); |
$this->currentProfile->start();
return $this;
} | csn_ccr |
func (c *Callbacks) OnCDOTAUserMsg_ShowGenericPopup(fn func(*dota.CDOTAUserMsg_ShowGenericPopup) | error) {
c.onCDOTAUserMsg_ShowGenericPopup = append(c.onCDOTAUserMsg_ShowGenericPopup, fn)
} | csn_ccr |
import tensorflow as tf
from d2l import tensorflow as d2l
batch_size, num_steps = 32, 35
train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)
num_hiddens = 256
rnn_cell = tf.keras.layers.SimpleRNNCell(num_hiddens, kernel_initializer='glorot_uniform')
rnn_layer = tf.keras.layers.RNN(rnn_cell, time_major=True, return_sequences=True, return_state=True)
state = rnn_cell.get_initial_state(batch_size=batch_size, dtype=tf.float32)
state.shape
X = tf.random.uniform((num_steps, batch_size, len(vocab)))
Y, state_new = rnn_layer(X, state)
Y.shape, len(state_new), state_new[0].shape
class RNNModel(tf.keras.layers.Layer):
def __init__(self, rnn_layer, vocab_size, **kwargs):
super(RNNModel, self).__init__(**kwargs)
self.rnn = rnn_layer
self.vocab_size = vocab_size
self.dense = tf.keras.layers.Dense(vocab_size)
def call(self, inputs, state):
X = tf.one_hot(tf.transpose(inputs), self.vocab_size)
Y, *state = self.rnn(X, state)
output = self.dense(tf.reshape(Y, (-1, Y.shape[-1])))
return output, state
def begin_state(self, *args, **kwargs):
return self.rnn.cell.get_initial_state(*args, **kwargs)
device_name = d2l.try_gpu()._device_name
strategy = tf.distribute.OneDeviceStrategy(device_name)
with strategy.scope():
net = RNNModel(rnn_layer, vocab_size=len(vocab))
d2l.predict_ch8('time traveller', 10, net, vocab)
num_epochs, lr = 500, 1
d2l.train_ch8(net, train_iter, vocab, lr, num_epochs, strategy) | from mxnet import np, npx
from mxnet.gluon import nn, rnn
from d2l import mxnet as d2l
npx.set_np()
batch_size, num_steps = 32, 35
train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)
num_hiddens = 256
rnn_layer = rnn.RNN(num_hiddens)
rnn_layer.initialize()
state = rnn_layer.begin_state(batch_size=batch_size)
len(state), state[0].shape
X = np.random.uniform(size=(num_steps, batch_size, len(vocab)))
Y, state_new = rnn_layer(X, state)
Y.shape, len(state_new), state_new[0].shape
class RNNModel(nn.Block):
def __init__(self, rnn_layer, vocab_size, **kwargs):
super(RNNModel, self).__init__(**kwargs)
self.rnn = rnn_layer
self.vocab_size = vocab_size
self.dense = nn.Dense(vocab_size)
def forward(self, inputs, state):
X = npx.one_hot(inputs.T, self.vocab_size)
Y, state = self.rnn(X, state)
output = self.dense(Y.reshape(-1, Y.shape[-1]))
return output, state
def begin_state(self, *args, **kwargs):
return self.rnn.begin_state(*args, **kwargs)
device = d2l.try_gpu()
net = RNNModel(rnn_layer, len(vocab))
net.initialize(force_reinit=True, ctx=device)
d2l.predict_ch8('time traveller', 10, net, vocab, device)
num_epochs, lr = 500, 1
d2l.train_ch8(net, train_iter, vocab, lr, num_epochs, device) | codetrans_dl |
public function addTorg12Documents(\AgentSIB\Diadoc\Api\Proto\Events\BasicDocumentAttachment $value)
{
if ($this->Torg12Documents === null) {
$this->Torg12Documents | = new \Protobuf\MessageCollection();
}
$this->Torg12Documents->add($value);
} | csn_ccr |
// parseLeftDelim scans the left delimiter, which is known to be present. | func (p *Parser) parseLeftDelim(cur *ListNode) error {
p.pos += len(leftDelim)
p.consumeText()
newNode := newList()
cur.append(newNode)
cur = newNode
return p.parseInsideAction(cur)
} | csn |
public function filter(callable $func) : self
{
$list = $this->list;
$acc = [];
foreach ($list as $index => $val) {
if ($func($val)) {
| $acc[] = $val;
}
}
return new static(\SplFixedArray::fromArray($acc));
} | csn_ccr |
Prepare new WAP message. | function sendBinary ( $to, $from, $body, $udh ) {
//Binary messages must be hex encoded
$body = bin2hex ( $body );
$udh = bin2hex ( $udh );
// Make sure $from is valid
$from = $this->validateOriginator($from);
// Send away!
$post = array(
'from' => $from,
'to' => $to,
'type' => 'binary',
'body' => $body,
'udh' => $udh
);
return $this->sendRequest ( $post );
} | csn |
Is called before each view file is rendered. This includes elements, views, parent views and layouts.
@param Event $event
@param string $viewFile
@return void
@throws \JBZoo\Utils\Exception | public function beforeRenderFile(Event $event, $viewFile)
{
$pluginEvent = Plugin::getData('Core', 'View.beforeRenderFile');
if (is_callable($pluginEvent->find(0)) && Plugin::hasManifestEvent('View.beforeRenderFile')) {
call_user_func_array($pluginEvent->find(0), [$this->_View, $event, $viewFile]);
}
} | csn |
protected void addBooleanValue(Document doc, String fieldName, Object internalValue)
{
| doc.add(createFieldWithoutNorms(fieldName, internalValue.toString(), PropertyType.BOOLEAN));
} | csn_ccr |
public function semantic(Semantic $semantic=NULL) {
if ($semantic!==NULL) {
$this->_semantic=$semantic;
$semantic->setJs($this);
$ui=$this->ui();
| if (isset($ui)) {
$this->conflict();
}
}
return $this->_semantic;
} | csn_ccr |
Parse the given palettes.
@param array(string => string) $palettes The array of palettes, e.g.
<code>array('default' => '{title_legend},title')</code>.
@param array(string => string) $subPaletteProperties Mapped array from subpalette [optional].
@param array $selectorFieldNames List of names of the properties to be used as selector
[optional].
@param PaletteCollectionInterface $collection The palette collection to populate [optional].
@return PaletteCollectionInterface | public function parsePalettes(
array $palettes,
array $subPaletteProperties = [],
array $selectorFieldNames = [],
PaletteCollectionInterface $collection = null
) {
if (!$collection) {
$collection = new PaletteCollection();
}
if (isset($palettes['__selector__'])) {
$selectorFieldNames = \array_merge($selectorFieldNames, $palettes['__selector__']);
$selectorFieldNames = \array_unique($selectorFieldNames);
unset($palettes['__selector__']);
}
foreach ($palettes as $selector => $fields) {
// Fields list must be a string.
if (!\is_string($fields)) {
continue;
}
if ($collection->hasPaletteByName($selector)) {
$palette = $collection->getPaletteByName($selector);
$this->parsePalette(
$selector,
$fields,
$subPaletteProperties,
$selectorFieldNames,
$palette
);
continue;
}
$palette = $this->parsePalette(
$selector,
$fields,
$subPaletteProperties,
$selectorFieldNames
);
$collection->addPalette($palette);
}
return $collection;
} | csn |
getelementsbytagname python get all child | def getChildElementsByTagName(self, tagName):
""" Return child elements of type tagName if found, else [] """
result = []
for child in self.childNodes:
if isinstance(child, Element):
if child.tagName == tagName:
result.append(child)
return result | cosqa |
You must create a method that can convert a string from any format into CamelCase. This must support symbols too.
*Don't presume the separators too much or you could be surprised.*
### Tests
```python
camelize("example name") # => ExampleName
camelize("your-NaMe-here") # => YourNameHere
camelize("testing ABC") # => TestingAbc
``` | import re
def camelize(s):
return "".join([w.capitalize() for w in re.split("\W|_", s)]) | apps |
public function & add($filter)
{
$filters = func_get_args();
foreach ($filters as $filter) {
if (!($filter instanceof \Erebot\Interfaces\Event\Match)) {
throw new \Erebot\InvalidValueException('Not a valid matcher');
} |
if (!in_array($filter, $this->submatchers, true)) {
$this->submatchers[] = $filter;
}
}
return $this;
} | csn_ccr |
Get this report's output as an HTML string.
@return The html for this control. | public String getHtmlControl()
{
StringWriter sw = new StringWriter();
PrintWriter rw = new PrintWriter(sw);
this.getScreenField().printData(rw, HtmlConstants.HTML_DISPLAY); // DO print screen
String string = sw.toString();
return string;
} | csn |
Identify the subset of desired `features` that are valid for the Kmeans
model. A warning is emitted for each feature that is excluded.
Parameters
----------
features : list[str]
Desired feature names.
column_type_map : dict[str, type]
Dictionary mapping each column name to the type of values in the
column.
valid_types : list[type]
Exclude features whose type is not in this list.
label : str
Name of the row label column.
Returns
-------
valid_features : list[str]
Names of features to include in the model. | def _validate_features(features, column_type_map, valid_types, label):
"""
Identify the subset of desired `features` that are valid for the Kmeans
model. A warning is emitted for each feature that is excluded.
Parameters
----------
features : list[str]
Desired feature names.
column_type_map : dict[str, type]
Dictionary mapping each column name to the type of values in the
column.
valid_types : list[type]
Exclude features whose type is not in this list.
label : str
Name of the row label column.
Returns
-------
valid_features : list[str]
Names of features to include in the model.
"""
if not isinstance(features, list):
raise TypeError("Input 'features' must be a list, if specified.")
if len(features) == 0:
raise ValueError("If specified, input 'features' must contain " +
"at least one column name.")
## Remove duplicates
num_original_features = len(features)
features = set(features)
if len(features) < num_original_features:
_logging.warning("Duplicates have been removed from the list of features")
## Remove the row label
if label in features:
features.remove(label)
_logging.warning("The row label has been removed from the list of features.")
## Check the type of each feature against the list of valid types
valid_features = []
for ftr in features:
if not isinstance(ftr, str):
_logging.warning("Feature '{}' excluded. ".format(ftr) +
"Features must be specified as strings " +
"corresponding to column names in the input dataset.")
elif ftr not in column_type_map.keys():
_logging.warning("Feature '{}' excluded because ".format(ftr) +
"it is not in the input dataset.")
elif column_type_map[ftr] not in valid_types:
_logging.warning("Feature '{}' excluded because of its type. ".format(ftr) +
"Kmeans features must be int, float, dict, or array.array type.")
else:
valid_features.append(ftr)
if len(valid_features) == 0:
raise _ToolkitError("All specified features have been excluded. " +
"Please specify valid features.")
return valid_features | csn |
public static function getArrayItemByPointSeparatedKey(array & $aData, $sKey)
{
if (strpos($sKey, '.') !== false) {
preg_match('/([a-zA-Z0-9_\-]+)\.([a-zA-Z0-9_\-\.]+)/', $sKey, $aKey);
if (!isset($aData[$aKey[1]])) {
throw new Exception('Undefined index: '.$aKey[1]);
}
if (!is_array($aData[$aKey[1]])) {
throw new Exception("The element indexed {$aKey[1]} isn't an array.");
}
| return self::getArrayItemByPointSeparatedKey(
$aData[$aKey[1]],
$aKey[2]
);
} elseif (isset($aData[$sKey])) {
return $aData[$sKey];
} else {
throw new Exception('Undefined index: '.$sKey);
}
} | csn_ccr |
function preProcessBindings(bindingString) {
var results = [];
var bindingHandlers = this.bindingHandlers;
var preprocessed;
// Check for a Provider.preprocessNode property
if (typeof this.preprocessNode === 'function') {
preprocessed = this.preprocessNode(bindingString, this);
if (preprocessed) { bindingString = preprocessed; }
}
for (var i = 0, j = this.bindingPreProcessors.length; i < j; ++i) {
preprocessed = this.bindingPreProcessors[i](bindingString, this);
| if (preprocessed) { bindingString = preprocessed; }
}
function addBinding(name, value) {
results.push("'" + name + "':" + value);
}
function processBinding(key, value) {
// Get the "on" binding from "on.click"
var handler = bindingHandlers.get(key.split('.')[0]);
if (handler && typeof handler.preprocess === 'function') {
value = handler.preprocess(value, key, processBinding);
}
addBinding(key, value);
}
arrayForEach(parseObjectLiteral(bindingString), function(keyValueItem) {
processBinding(
keyValueItem.key || keyValueItem.unknown,
keyValueItem.value
);
});
return results.join(',');
} | csn_ccr |
public function onRestore(RestoreEvent $event)
{
$plugin = $this->pluginRegistry->getPlugin($event->getOption('plugin'));
$optionsResolver = new OptionsResolver();
$plugin->configureOptionsResolver($optionsResolver);
$parameter = $optionsResolver->resolve($event->getOption('parameter'));
try {
$plugin->restore($event->getSource(), $event->getDestination(), $event->getDatabase(), $parameter);
| $event->setStatus(BackupStatus::STATE_SUCCESS);
} catch (\Exception $exception) {
$event->setStatus(BackupStatus::STATE_FAILED);
$event->setException($exception);
}
} | csn_ccr |
func ResolveAddr(addr string) (string, error) {
tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
return "", fmt.Errorf("Could not resolve address: %s", err.Error())
}
if tcpAddr.IP == nil {
ipstr, err := ExternalIP()
if err != nil {
return "", err
}
| tcpAddr.IP = net.ParseIP(ipstr)
}
if tcpAddr.Port == 0 {
tcpAddr.Port = DefaultPort
}
return tcpAddr.String(), nil
} | csn_ccr |
static KeyRange keyRangeStartRow(byte[] startRowKey) {
KeyRange keyRange = new KeyRange();
keyRange.setStart_key(startRowKey);
|
keyRange.setEnd_key(EMPTY_BYTE_BUFFER);
keyRange.setCount(MAX_ROWS_BATCH_SIZE);
return keyRange;
} | csn_ccr |
Returns true if the module has already been loaded.
@param string|array $module
@return bool True if the module has already been loaded | protected function js_module_loaded($module) {
if (is_string($module)) {
$modulename = $module;
} else {
$modulename = $module['name'];
}
return array_key_exists($modulename, $this->YUI_config->modules) ||
array_key_exists($modulename, $this->extramodules);
} | csn |
def get_env():
''' Get the correct Jinja2 Environment, also for frozen scripts.
'''
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
# PyInstaller uses _MEIPASS and only works with jinja2.FileSystemLoader |
templates_path = join(sys._MEIPASS, 'bokeh', 'core', '_templates')
else:
# Non-frozen Python and cx_Freeze can use __file__ directly
templates_path = join(dirname(__file__), '_templates')
return Environment(loader=FileSystemLoader(templates_path)) | csn_ccr |
Generates the lines for the converted input file using the specified
value dictionary. | def write(self, valuedict):
"""Generates the lines for the converted input file using the specified
value dictionary."""
result = []
if self.identifier in valuedict:
values = valuedict[self.identifier]
else:
return result
if self.comment != "":
result.append(self.comment)
if self.repeat is not None and type(values) == type([]):
if self.repeat.isdigit():
for i in range(int(self.repeat)):
result.extend(self._write_iterate(values[i]))
else:
#We are repeating for as many values as we have in the value
#entry for the group in the dictionary.
for value in values:
result.extend(self._write_iterate(value))
elif type(values) == type({}):
#This group doesn't get repeated, so the values variable must
#be a dictionary, just run it once.
result = self._write_iterate(values)
return result | csn |
public GitlabSSHKey createSSHKey(Integer targetUserId, String title, String key) throws IOException {
Query query = new Query()
.append("title", title)
| .append("key", key);
String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + GitlabSSHKey.KEYS_URL + query.toString();
return dispatch().to(tailUrl, GitlabSSHKey.class);
} | csn_ccr |
func (d differ) do() [][2]string {
// Early out if they have different numbers of ugens or constants.
if l1, l2 := len(d[0].Ugens), len(d[1].Ugens); l1 != l2 {
return [][2]string{
{
fmt.Sprintf("%d ugens", l1), |
fmt.Sprintf("%d ugens", l2),
},
}
}
if l1, l2 := len(d[0].Constants), len(d[1].Constants); l1 != l2 {
return [][2]string{
{
fmt.Sprintf("%d constants", l1),
fmt.Sprintf("%d constants", l2),
},
}
}
return d.crawl([][2]string{}, d[0].Root(), d[1].Root())
} | csn_ccr |
protected function _actionReorder($context)
{
$photo_ids = (array) AnConfig::unbox($context->data->photo_id); |
$this->getItem()->reorder($photo_ids);
return $this->getItem();
} | csn_ccr |
Allow executing logic on completion of a Publisher.
@param publisher The publisher
@param future The runnable
@param <T> The generic type
@return The mapped publisher | public static <T> Publisher<T> onComplete(Publisher<T> publisher, Supplier<CompletableFuture<Void>> future) {
return actual -> publisher.subscribe(new CompletionAwareSubscriber<T>() {
@Override
protected void doOnSubscribe(Subscription subscription) {
actual.onSubscribe(subscription);
}
@Override
protected void doOnNext(T message) {
try {
actual.onNext(message);
} catch (Throwable e) {
onError(e);
}
}
@Override
protected void doOnError(Throwable t) {
actual.onError(t);
}
@Override
protected void doOnComplete() {
future.get().whenComplete((aVoid, throwable) -> {
if (throwable != null) {
actual.onError(throwable);
} else {
actual.onComplete();
}
});
}
});
} | csn |
def fit(self, col):
"""Prepare the transformer to convert data.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
None
"""
| dates = self.safe_datetime_cast(col)
self.default_val = dates.groupby(dates).count().index[0].timestamp() * 1e9 | csn_ccr |
def from_list(cls, l):
"""Generate an GeneSet object from a list of strings.
Note: See also :meth:`to_list`.
Parameters
----------
l: list or tuple of str
A list of strings representing gene set ID, name, genes,
source, collection, and description. The genes must be
comma-separated. See also :meth:`to_list`.
Returns
-------
`genometools.basic.GeneSet`
The gene set.
| """
id_ = l[0]
name = l[3]
genes = l[4].split(',')
src = l[1] or None
coll = l[2] or None
desc = l[5] or None
return cls(id_, name, genes, src, coll, desc) | csn_ccr |
// close closes a handle handle previously returned in the response
// to SSH_FXP_OPEN or SSH_FXP_OPENDIR. The handle becomes invalid
// immediately after this request has been sent. | func (c *Client) close(handle string) error {
id := c.nextID()
typ, data, err := c.sendPacket(sshFxpClosePacket{
ID: id,
Handle: handle,
})
if err != nil {
return err
}
switch typ {
case ssh_FXP_STATUS:
return normaliseError(unmarshalStatus(id, data))
default:
return unimplementedPacketErr(typ)
}
} | csn |
func (c *Client) List(prefix string) (*KVMeta, KVPairs, error) {
| return c.getRecurse(prefix, true, 0)
} | csn_ccr |
Block while waiting for the given dialog to return
If the dialog is already closed, this returns immediately, without doing
much at all. If the dialog is not yet opened, it will be opened and this
method will wait for the dialog to be handled (i.e. either completed or
closed). Clicking "ok" will result in a boolean true value, clicking
"cancel" or hitten escape key will or running into a timeout will result
in a boolean false. For all other input fields, their respective (parsed)
value will be returned.
For this to work, this method will temporarily start the event loop and
stop it afterwards. Thus, it is *NOT* a good idea to mix this if anything
else is listening on the event loop. The recommended way in this case is
to avoid using this blocking method call and go for a fully async
`self::then()` instead.
@param AbstractDialog $dialog
@return boolean|string dialog return value
@uses Launcher::waitFor() | public function waitFor(AbstractDialog $dialog)
{
$done = false;
$ret = null;
$loop = $this->loop;
$process = $this->launch($dialog);
$process->then(function ($result) use (&$ret, &$done, $loop) {
$ret = $result;
$done = true;
$loop->stop();
}, function () use (&$ret, &$done, $loop) {
$ret = false;
$done = true;
$loop->stop();
});
if (!$done) {
$loop->run();
}
return $ret;
} | csn |
Sets the optional BitCoin options.
@param array $options | protected function setOptions(array $options)
{
if (isset($options['label'])) {
$this->label = $options['label'];
}
if (isset($options['message'])) {
$this->message = $options['message'];
}
if (isset($options['returnAddress'])) {
$this->returnAddress = $options['returnAddress'];
}
} | csn |
def init(envVarName, enableColorOutput=False):
"""
Initialize the logging system and parse the environment variable
of the given name.
Needs to be called before starting the actual application.
"""
global _initialized
if _initialized:
return
global _ENV_VAR_NAME
_ENV_VAR_NAME = envVarName
if enableColorOutput:
_preformatLevels(envVarName + | "_NO_COLOR")
else:
_preformatLevels(None)
if envVarName in os.environ:
# install a log handler that uses the value of the environment var
setDebug(os.environ[envVarName])
addLimitedLogHandler(stderrHandler)
_initialized = True | csn_ccr |
return rows with one field not null in python | def selectnotnone(table, field, complement=False):
"""Select rows where the given field is not `None`."""
return select(table, field, lambda v: v is not None,
complement=complement) | cosqa |
public function pathname()
{
$uri = $this->uri();
// Strip the | query string from the URI
$uri = strstr($uri, '?', true) ?: $uri;
return $uri;
} | csn_ccr |
private function name($extra)
{
$file = $extra[0];
$file = str_replace('.', '/', $file);
//
switch ($extra[1]) {
| case 'smarty': $extention = '.tpl.php'; break;
case 'atom': $extention = '.atom'; break;
default: $extention = '.php'; break;
}
return $file.$extention;
} | csn_ccr |
Add goal to counter
@see http://api.yandex.ru/metrika/doc/beta/management/goals/addgoal.xml
@param int $counterId
@param Models\Goal $goal
@return Models\Goal | public function addGoal($counterId, Models\Goal $goal)
{
$resource = 'counter/' . $counterId . '/goals';
$response = $this->sendPostRequest($resource, ["goal" => $goal->toArray()]);
$goalResponse = new Models\AddGoalResponse($response);
return $goalResponse->getGoal();
} | csn |
func NewWithTagsSentryHook(DSN string, tags map[string]string, levels []logrus.Level) (*SentryHook, error) {
client, err := raven.NewWithTags(DSN, tags)
| if err != nil {
return nil, err
}
return NewWithClientSentryHook(client, levels)
} | csn_ccr |
Enable System Setting Cache ~
When enabled, system settings will be cached to reduce load times. MODX recommends leaving this on.
@param bool $value
@return $this | public function setCoreCacheSystemSettings($value)
{
$this->setFieldName('cache_system_settings');
$this->loadObject(true);
$this->setFieldValue($value);
return $this;
} | csn |
protected static String generateFastaFromPeptide(List<Monomer> monomers) {
StringBuilder fasta = new StringBuilder();
for (Monomer monomer : | monomers) {
fasta.append(monomer.getNaturalAnalog());
}
return fasta.toString();
} | csn_ccr |
Return country list
@return oxcountrylist | public function getCountryList()
{
if ($this->_oCountryList === null) {
// passing country list
$this->_oCountryList = oxNew(\OxidEsales\Eshop\Application\Model\CountryList::class);
$this->_oCountryList->loadActiveCountries();
}
return $this->_oCountryList;
} | csn |
func Merge(w io.Writer, opts *BuilderOpts, itrs []Iterator, f MergeFunc) error {
builder, err := New(w, opts)
if err != nil {
return err
}
itr, err := NewMergeIterator(itrs, f)
for err == nil {
k, v := itr.Current()
err = builder.Insert(k, v)
if err != nil {
return err
}
err = itr.Next()
}
|
if err != nil && err != ErrIteratorDone {
return err
}
err = itr.Close()
if err != nil {
return err
}
err = builder.Close()
if err != nil {
return err
}
return nil
} | csn_ccr |
@Override
public PdfFormField makeField() throws IOException, DocumentException, VectorPrintException {
switch (getFieldtype()) {
case TEXT:
return ((TextField) bf).getTextField();
case COMBO:
return ((TextField) bf).getComboField();
case LIST:
return ((TextField) bf).getListField();
case BUTTON:
return ((PushbuttonField) bf).getField();
case CHECKBOX:
return ((RadioCheckField) bf).getCheckField();
case RADIO: |
return ((RadioCheckField) bf).getRadioField();
}
throw new VectorPrintException(String.format("cannot create pdfformfield from %s and %s", (bf != null) ? bf.getClass() : null, String.valueOf(getFieldtype())));
} | csn_ccr |
Automatically generate the attribute we want.
@param string|callable $kind The kind of attribute.
@param object $model The model instance.
@param \League\FactoryMuffin\FactoryMuffin $factoryMuffin The factory muffin instance.
@return mixed | public function generate($kind, $model, FactoryMuffin $factoryMuffin)
{
$generator = $this->make($kind, $model, $factoryMuffin);
if ($generator) {
return $generator->generate();
}
return $kind;
} | csn |
public void forAllColumns(String template, Properties attributes) throws XDocletException
{
for (Iterator it = _curTableDef.getColumns(); it.hasNext(); )
{
| _curColumnDef = (ColumnDef)it.next();
generate(template);
}
_curColumnDef = null;
} | csn_ccr |
// checkControllerInheritedConfig returns an error if the shared local cloud config is definitely invalid. | func checkControllerInheritedConfig(attrs attrValues) error {
disallowedCloudConfigAttrs := append(disallowedModelConfigAttrs[:], config.AgentVersionKey)
for _, attr := range disallowedCloudConfigAttrs {
if _, ok := attrs[attr]; ok {
return errors.Errorf("local cloud config cannot contain " + attr)
}
}
for attrName := range attrs {
if controller.ControllerOnlyAttribute(attrName) {
return errors.Errorf("local cloud config cannot contain controller attribute %q", attrName)
}
}
return nil
} | csn |
public function data()
{
return [
'property' => $this->property(),
'table' => $this->table(),
'value' => $this->value(),
'func' => $this->func(),
'operator' => $this->operator(),
'conjunction' => $this->conjunction(),
| 'filters' => $this->filters(),
'condition' => $this->condition(),
'active' => $this->active(),
'name' => $this->name(),
];
} | csn_ccr |
def postgis_type(self):
"""
Get the type of the geometry in PostGIS format, including additional
dimensions and SRID if they exist.
"""
dimz = "Z" if self.dimz else ""
dimm = "M" if self.dimm else ""
if self.srid:
| return "geometry({}{}{},{})".format(self.type, dimz, dimm, self.srid)
else:
return "geometry({}{}{})".format(self.type, dimz, dimm) | csn_ccr |
Use this API to count clusternodegroup_crvserver_binding resources configued on NetScaler. | public static long count(nitro_service service, clusternodegroup_crvserver_binding obj) throws Exception{
options option = new options();
option.set_count(true);
option.set_args(nitro_util.object_to_string_withoutquotes(obj));
clusternodegroup_crvserver_binding response[] = (clusternodegroup_crvserver_binding[]) obj.get_resources(service,option);
if (response != null) {
return response[0].__count;
}
return 0;
} | csn |
func Migrate(from From, root string) error {
sys, found := registered[from]
if !found {
return ErrNoSuchSystem{
NotExist: string(from),
Has: SystemList(),
}
}
sys, err | := sys.Check(root)
if err != nil {
return err
}
if sys == nil {
return errors.New("Root not found.")
}
return sys.Migrate(root)
} | csn_ccr |
// BoolArrayOr returns given slice if receiver is nil or invalid. | func (ba *BoolArray) BoolArrayOr(or []bool) []bool {
switch {
case ba == nil:
return or
case !ba.Valid:
return or
default:
return ba.BoolArray
}
} | csn |
Add a handler that is called whenever the client stops communicating with the back-end.
@param handler
The actual handler (closure).
@return The registration for the handler. Using this object the handler can be removed again. | @Export
public JsHandlerRegistration addDispatchStoppedHandler(final DispatchStoppedHandler handler) {
HandlerRegistration registration = GwtCommandDispatcher.getInstance().addDispatchStoppedHandler(
new org.geomajas.gwt.client.command.event.DispatchStoppedHandler() {
public void onDispatchStopped(DispatchStoppedEvent event) {
handler.onDispatchStopped(new org.geomajas.plugin.jsapi.client.event.DispatchStoppedEvent());
}
});
return new JsHandlerRegistration(new HandlerRegistration[] { registration });
} | csn |
function (evt) {
var evh = this.evtHandlers, et = evt.type;
if (evh) {
for (var i = 0, sz = evh.length; sz > i; i++) {
if (evh[i].evtType === et) {
| evh[i].executeCb(evt, this.eh, this.parent.vscope);
break;
}
}
}
} | csn_ccr |
private void handleRequestAndRespond(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
RDFUnitConfiguration configuration = null;
try {
configuration = getConfiguration(httpServletRequest);
} catch (ParameterException e) {
String message = e.getMessage();
if (message != null) {
printMessage(httpServletResponse, message);
}
printHelpMessage(httpServletResponse);
httpServletResponse.getWriter().close();
return;
}
assert configuration != null;
final TestSource dataset = configuration.getTestSource();
final TestSuite testSuite | = getTestSuite(configuration, dataset);
assert testSuite != null;
TestExecution results = null;
try {
results = validate(configuration, dataset, testSuite);
} catch (TestCaseExecutionException e) {
// TODO catch error
}
assert results != null;
try {
writeResults(configuration, results, httpServletResponse);
} catch (RdfWriterException e) {
printMessage(httpServletResponse, e.getMessage());
}
} | csn_ccr |
def _check_env_var(envvar: str) -> bool:
"""Check Environment Variable to verify that it is set and not empty.
:param envvar: Environment Variable to Check.
:returns: True if Environment Variable is set and not empty.
:raises: KeyError if Environment Variable is not set or is empty.
.. versionadded:: 0.0.12
"""
if os.getenv(envvar) is None:
| raise KeyError(
"Required ENVVAR: {0} is not set".format(envvar))
if not os.getenv(envvar): # test if env var is empty
raise KeyError(
"Required ENVVAR: {0} is empty".format(envvar))
return True | csn_ccr |
def unique_slug(queryset, slug_field, slug):
"""
Ensures a slug is unique for the given queryset, appending
an integer to its end until the slug is unique.
"""
i = 0
while True:
| if i > 0:
if i > 1:
slug = slug.rsplit("-", 1)[0]
slug = "%s-%s" % (slug, i)
try:
queryset.get(**{slug_field: slug})
except ObjectDoesNotExist:
break
i += 1
return slug | csn_ccr |
python set to rangeindex | def empty(self, start=None, stop=None):
"""Empty the range from start to stop.
Like delete, but no Error is raised if the entire range isn't mapped.
"""
self.set(NOT_SET, start=start, stop=stop) | cosqa |
public function moveWorksheet($worksheetName, $position)
{
//check whether worksheet name is set or not
if ($this->worksheetName == '')
throw new Exception('Worksheet name not specified');
$fieldsArray['DestinationWorsheet'] = $worksheetName;
$fieldsArray['Position'] = $position;
$jsonData = json_encode($fieldsArray);
$strURI = Product::$baseProductUri . '/cells/' . $this->getFileName() .
| '/worksheets/' . $this->worksheetName . '/position';
$signedURI = Utils::sign($strURI);
$responseStream = Utils::processCommand($signedURI, 'POST', 'json', $jsonData);
$json = json_decode($responseStream);
if ($json->Code == 200)
return true;
else
return false;
} | csn_ccr |
Finds the key and returns it.
@return string The key. | private function key()
{
$offset = $this->tokens->key();
$op = $this->tokens->getToken($offset - 1);
if ($op
&& isset($this->tokens[$offset - 2])
&& ((DocLexer::T_COLON === $op[0])
|| (DocLexer::T_EQUALS === $op[0]))) {
return $this->tokens->getValue($offset - 2);
}
return null;
} | csn |
def moves_from_last_n_games(self, n, moves, shuffle,
column_family, column):
"""Randomly choose a given number of moves from the last n games.
Args:
n: number of games at the end of this GameQueue to source.
moves: number of moves to be sampled from `n` games.
shuffle: if True, shuffle the selected moves.
column_family: name of the column family containing move examples.
column: name of the column containing move examples.
Returns:
a dataset containing the selected moves.
"""
self.wait_for_fresh_games()
| latest_game = self.latest_game_number
utils.dbg('Latest game in %s: %s' % (self.btspec.table, latest_game))
if latest_game == 0:
raise ValueError('Cannot find a latest game in the table')
start = int(max(0, latest_game - n))
ds = self.moves_from_games(start, latest_game, moves, shuffle,
column_family, column)
return ds | csn_ccr |
@Override
public void close() throws IOException {
if (fis != null) {
try {
fis.close();
fis = null; |
} catch (Throwable th) {
//no-op
}
}
} | csn_ccr |
Get the first tag with a type in this token | def find(self, tagtype, **kwargs):
'''Get the first tag with a type in this token '''
for t in self.__tags:
if t.tagtype == tagtype:
return t
if 'default' in kwargs:
return kwargs['default']
else:
raise LookupError("Token {} is not tagged with the speficied tagtype ({})".format(self, tagtype)) | csn |
def find_creation_date(path):
"""
Try to get the date that a file was created, falling back to when it was last modified if that's not possible.
Parameters
----------
path : str
File's path.
Returns
----------
creation_date : str
Time of file creation.
Example
----------
>>> import neurokit as nk
>>> import datetime
>>>
>>> creation_date = nk.find_creation_date(file)
>>> creation_date = datetime.datetime.fromtimestamp(creation_date)
Notes
----------
*Authors*
- `Dominique Makowski <https://dominiquemakowski.github.io/>`_
- Mark Amery
*Dependencies*
- platform
- os
*See Also*
- http://stackoverflow.com/a/39501288/1709587
"""
| if platform.system() == 'Windows':
return(os.path.getctime(path))
else:
stat = os.stat(path)
try:
return(stat.st_birthtime)
except AttributeError:
print("Neuropsydia error: get_creation_date(): We're probably on Linux. No easy way to get creation dates here, so we'll settle for when its content was last modified.")
return(stat.st_mtime) | csn_ccr |
static function simpleXmlToArrayHelper(&$res, &$key, &$value, &$children)
{
if (isset($res[$key])) {
if (is_string($res[$key]) || (is_array($res[$key]) && is_assoc($res[$key]))) {
$res[$key] = array($res[$key]);
| }
$res[$key][] = CPS_Response::simpleXmlToArray($value);
} else {
$res[$key] = CPS_Response::simpleXmlToArray($value);
}
$children = true;
} | csn_ccr |
Set the standard property for marshalling a fragment only.
@param aMarshaller
The marshaller to set the property. May not be <code>null</code>.
@param bFragment
the value to be set | public static void setFragment (@Nonnull final Marshaller aMarshaller, final boolean bFragment)
{
_setProperty (aMarshaller, Marshaller.JAXB_FRAGMENT, Boolean.valueOf (bFragment));
} | csn |
Submits the job either locally or to a remote server if it is defined.
Args:
queue (int, optional): The number of sub-jobs to run. This argmuent will set the num_jobs attribute of
this object. Defaults to None, meaning the value of num_jobs will be used.
options (list of str, optional): A list of command line options for the condor_submit command. For
details on valid options see: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html.
Defaults to an empty list. | def submit(self, queue=None, options=[]):
"""Submits the job either locally or to a remote server if it is defined.
Args:
queue (int, optional): The number of sub-jobs to run. This argmuent will set the num_jobs attribute of
this object. Defaults to None, meaning the value of num_jobs will be used.
options (list of str, optional): A list of command line options for the condor_submit command. For
details on valid options see: http://research.cs.wisc.edu/htcondor/manual/current/condor_submit.html.
Defaults to an empty list.
"""
if not self.executable:
log.error('Job %s was submitted with no executable', self.name)
raise NoExecutable('You cannot submit a job without an executable')
self._num_jobs = queue or self.num_jobs
self._write_job_file()
args = ['condor_submit']
args.extend(options)
args.append(self.job_file)
log.info('Submitting job %s with options: %s', self.name, args)
return super(Job, self).submit(args) | csn |
protected function writeComposerFile($composer)
{
file_put_contents(
| $this->command->path.'/composer.json',
json_encode($composer, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
);
} | csn_ccr |
// AppendFloats64 encodes the input float64s to json and
// appends the encoded string list to the input byte slice. | func (Encoder) AppendFloats64(dst []byte, vals []float64) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
dst = append(dst, '[')
dst = appendFloat(dst, vals[0], 32)
if len(vals) > 1 {
for _, val := range vals[1:] {
dst = appendFloat(append(dst, ','), val, 64)
}
}
dst = append(dst, ']')
return dst
} | csn |
Generate the expected value.
@return [Integer, Range] Generate the expected value. | def generate_expected_value
if expected_difference.is_a? Range
(before_value + expected_difference.first)..(before_value + expected_difference.end)
else
before_value + expected_difference
end
end | csn |
Add the supplied file to the file system.
Note: If overriding this function, it is advisable to store the file
in the path returned by get_local_path_from_hash as there may be
subsequent uses of the file in the same request.
@param string $pathname Path to file currently on disk
@param string $contenthash SHA1 hash of content if known (performance only)
@return array (contenthash, filesize, newfile) | public function add_file_from_path($pathname, $contenthash = null) {
list($contenthash, $filesize) = $this->validate_hash_and_file_size($contenthash, $pathname);
$hashpath = $this->get_fulldir_from_hash($contenthash);
$hashfile = $this->get_local_path_from_hash($contenthash, false);
$newfile = true;
if (file_exists($hashfile)) {
if (filesize($hashfile) === $filesize) {
return array($contenthash, $filesize, false);
}
if (file_storage::hash_from_path($hashfile) === $contenthash) {
// Jackpot! We have a hash collision.
mkdir("$this->filedir/jackpot/", $this->dirpermissions, true);
copy($pathname, "$this->filedir/jackpot/{$contenthash}_1");
copy($hashfile, "$this->filedir/jackpot/{$contenthash}_2");
throw new file_pool_content_exception($contenthash);
}
debugging("Replacing invalid content file $contenthash");
unlink($hashfile);
$newfile = false;
}
if (!is_dir($hashpath)) {
if (!mkdir($hashpath, $this->dirpermissions, true)) {
// Permission trouble.
throw new file_exception('storedfilecannotcreatefiledirs');
}
}
// Let's try to prevent some race conditions.
$prev = ignore_user_abort(true);
@unlink($hashfile.'.tmp');
if (!copy($pathname, $hashfile.'.tmp')) {
// Borked permissions or out of disk space.
@unlink($hashfile.'.tmp');
ignore_user_abort($prev);
throw new file_exception('storedfilecannotcreatefile');
}
if (file_storage::hash_from_path($hashfile.'.tmp') !== $contenthash) {
// Highly unlikely edge case, but this can happen on an NFS volume with no space remaining.
@unlink($hashfile.'.tmp');
ignore_user_abort($prev);
throw new file_exception('storedfilecannotcreatefile');
}
rename($hashfile.'.tmp', $hashfile);
chmod($hashfile, $this->filepermissions); // Fix permissions if needed.
@unlink($hashfile.'.tmp'); // Just in case anything fails in a weird way.
ignore_user_abort($prev);
return array($contenthash, $filesize, $newfile);
} | csn |
// TrueColorFromRGB builds a TrueColor object passing the three components r, g and b. | func TrueColorFromRGB(r byte, g byte, b byte) TrueColor {
return TrueColor(((uint(r) & 0xff) << 16) | ((uint(g) & 0xff) << 8) | (uint(b) & 0xff))
} | csn |
// Convert_kubeadm_ControlPlaneComponent_To_v1beta2_ControlPlaneComponent is an autogenerated conversion function. | func Convert_kubeadm_ControlPlaneComponent_To_v1beta2_ControlPlaneComponent(in *kubeadm.ControlPlaneComponent, out *ControlPlaneComponent, s conversion.Scope) error {
return autoConvert_kubeadm_ControlPlaneComponent_To_v1beta2_ControlPlaneComponent(in, out, s)
} | csn |
Given a `target` check the execution status of it relative to the current path.
"Execution status" simply refers to where or not we **think** this will execuete
before or after the input `target` element. | function _guessExecutionStatusRelativeTo(target) {
// check if the two paths are in different functions, we can't track execution of these
var targetFuncParent = target.scope.getFunctionParent();
var selfFuncParent = this.scope.getFunctionParent();
if (targetFuncParent !== selfFuncParent) {
return "function";
}
var targetPaths = target.getAncestry();
//if (targetPaths.indexOf(this) >= 0) return "after";
var selfPaths = this.getAncestry();
// get ancestor where the branches intersect
var commonPath;
var targetIndex;
var selfIndex;
for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) {
var selfPath = selfPaths[selfIndex];
targetIndex = targetPaths.indexOf(selfPath);
if (targetIndex >= 0) {
commonPath = selfPath;
break;
}
}
if (!commonPath) {
return "before";
}
// get the relationship paths that associate these nodes to their common ancestor
var targetRelationship = targetPaths[targetIndex - 1];
var selfRelationship = selfPaths[selfIndex - 1];
if (!targetRelationship || !selfRelationship) {
return "before";
}
// container list so let's see which one is after the other
if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) {
return targetRelationship.key > selfRelationship.key ? "before" : "after";
}
// otherwise we're associated by a parent node, check which key comes before the other
var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key);
var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key);
return targetKeyPosition > selfKeyPosition ? "before" : "after";
} | csn |
protected void tokenValueIsFinished()
{
_scanner.tokenIsFinished();
if (IonType.BLOB.equals(_value_type) || IonType.CLOB.equals(_value_type))
{
| int state_after_scalar = get_state_after_value();
set_state(state_after_scalar);
}
} | csn_ccr |
// GetPasswdPrompt prompts the user and returns the password read from the terminal.
// If mask is true, then asterisks are echoed.
// The returned byte array does not include end-of-line characters. | func GetPasswdPrompt(prompt string, mask bool, r FdReader, w io.Writer) ([]byte, error) {
return getPasswd(prompt, mask, r, w)
} | csn |
// fetchLastBlockSeq returns the last block sequence of an endpoint with the given gRPC connection. | func (p *BlockPuller) fetchLastBlockSeq(minRequestedSequence uint64, endpoint string, conn *grpc.ClientConn) (uint64, error) {
env, err := p.seekLastEnvelope()
if err != nil {
p.Logger.Errorf("Failed creating seek envelope for %s: %v", endpoint, err)
return 0, err
}
stream, err := p.requestBlocks(endpoint, NewImpatientStream(conn, p.FetchTimeout), env)
if err != nil {
return 0, err
}
defer stream.abort()
resp, err := stream.Recv()
if err != nil {
p.Logger.Errorf("Failed receiving the latest block from %s: %v", endpoint, err)
return 0, err
}
block, err := extractBlockFromResponse(resp)
if err != nil {
p.Logger.Warningf("Received %v from %s: %v", resp, endpoint, err)
return 0, err
}
stream.CloseSend()
seq := block.Header.Number
if seq < minRequestedSequence {
err := errors.Errorf("minimum requested sequence is %d but %s is at sequence %d", minRequestedSequence, endpoint, seq)
p.Logger.Infof("Skipping pulling from %s: %v", endpoint, err)
return 0, err
}
p.Logger.Infof("%s is at block sequence of %d", endpoint, seq)
return block.Header.Number, nil
} | csn |
This is a utility function that creates the Program
Builder in an Environment if it is not there already.
If it is already there, we return the existing one. | def createProgBuilder(env):
"""This is a utility function that creates the Program
Builder in an Environment if it is not there already.
If it is already there, we return the existing one.
"""
try:
program = env['BUILDERS']['Program']
except KeyError:
import SCons.Defaults
program = SCons.Builder.Builder(action = SCons.Defaults.LinkAction,
emitter = '$PROGEMITTER',
prefix = '$PROGPREFIX',
suffix = '$PROGSUFFIX',
src_suffix = '$OBJSUFFIX',
src_builder = 'Object',
target_scanner = ProgramScanner)
env['BUILDERS']['Program'] = program
return program | csn |
private static synchronized void decrementUseCount() {
final String methodName = "decrementUseCount";
logger.entry(methodName);
--useCount;
if (useCount <= 0) {
if (bootstrap != null) {
bootstrap.group().shutdownGracefully(0, | 500, TimeUnit.MILLISECONDS);
}
bootstrap = null;
useCount = 0;
}
logger.exit(methodName);
} | csn_ccr |
Analogous to DataFrame.apply, for SparseDataFrame
Parameters
----------
func : function
Function to apply to each column
axis : {0, 1, 'index', 'columns'}
broadcast : bool, default False
For aggregation functions, return object of same size with values
propagated
.. deprecated:: 0.23.0
This argument will be removed in a future version, replaced
by result_type='broadcast'.
reduce : boolean or None, default None
Try to apply reduction procedures. If the DataFrame is empty,
apply will use reduce to determine whether the result should be a
Series or a DataFrame. If reduce is None (the default), apply's
return value will be guessed by calling func an empty Series (note:
while guessing, exceptions raised by func will be ignored). If
reduce is True a Series will always be returned, and if False a
DataFrame will always be returned.
.. deprecated:: 0.23.0
This argument will be removed in a future version, replaced
by result_type='reduce'.
result_type : {'expand', 'reduce', 'broadcast, None}
These only act when axis=1 {columns}:
* 'expand' : list-like results will be turned into columns.
* 'reduce' : return a Series if possible rather than expanding
list-like results. This is the opposite to 'expand'.
* 'broadcast' : results will be broadcast to the original shape
of the frame, the original index & columns will be retained.
The default behaviour (None) depends on the return value of the
applied function: list-like results will be returned as a Series
of those. However if the apply function returns a Series these
are expanded to columns.
.. versionadded:: 0.23.0
Returns
-------
applied : Series or SparseDataFrame | def apply(self, func, axis=0, broadcast=None, reduce=None,
result_type=None):
"""
Analogous to DataFrame.apply, for SparseDataFrame
Parameters
----------
func : function
Function to apply to each column
axis : {0, 1, 'index', 'columns'}
broadcast : bool, default False
For aggregation functions, return object of same size with values
propagated
.. deprecated:: 0.23.0
This argument will be removed in a future version, replaced
by result_type='broadcast'.
reduce : boolean or None, default None
Try to apply reduction procedures. If the DataFrame is empty,
apply will use reduce to determine whether the result should be a
Series or a DataFrame. If reduce is None (the default), apply's
return value will be guessed by calling func an empty Series (note:
while guessing, exceptions raised by func will be ignored). If
reduce is True a Series will always be returned, and if False a
DataFrame will always be returned.
.. deprecated:: 0.23.0
This argument will be removed in a future version, replaced
by result_type='reduce'.
result_type : {'expand', 'reduce', 'broadcast, None}
These only act when axis=1 {columns}:
* 'expand' : list-like results will be turned into columns.
* 'reduce' : return a Series if possible rather than expanding
list-like results. This is the opposite to 'expand'.
* 'broadcast' : results will be broadcast to the original shape
of the frame, the original index & columns will be retained.
The default behaviour (None) depends on the return value of the
applied function: list-like results will be returned as a Series
of those. However if the apply function returns a Series these
are expanded to columns.
.. versionadded:: 0.23.0
Returns
-------
applied : Series or SparseDataFrame
"""
if not len(self.columns):
return self
axis = self._get_axis_number(axis)
if isinstance(func, np.ufunc):
new_series = {}
for k, v in self.items():
applied = func(v)
applied.fill_value = func(v.fill_value)
new_series[k] = applied
return self._constructor(
new_series, index=self.index, columns=self.columns,
default_fill_value=self._default_fill_value,
default_kind=self._default_kind).__finalize__(self)
from pandas.core.apply import frame_apply
op = frame_apply(self,
func=func,
axis=axis,
reduce=reduce,
broadcast=broadcast,
result_type=result_type)
return op.get_result() | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.