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-... | 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 ... | 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... | 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);
configurat... | 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);
... | 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";
HttpRespon... |
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.getNu... | 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
... | 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... | + '+' + self._codec.__content_subtype__)
headers.extend((
('te', 'trailers'),
('content-type', content_type),
('user-agent', USER_AGENT),
))
metadata, = await self._dispatch.send_request(
self._metadata,
... | 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)
r... | 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;
... | 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) &... | 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... | 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_... | 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
... | $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']... | 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... | 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=batc... | 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' => '... | 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, $... | 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 ... | public function parsePalettes(
array $palettes,
array $subPaletteProperties = [],
array $selectorFieldNames = [],
PaletteCollectionInterface $collection = null
) {
if (!$collection) {
$collection = new PaletteCollection();
}
if (isset($palettes['_... | 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") #... | 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... | 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... | 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]);... | 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) { bi... | 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 handl... | 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('paramete... | $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->extram... | 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 != "":
... | 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(s... | 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 g... | """
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 tr... | 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->st... | 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->r... | 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_NA... | "_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->_oCountryLis... | 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:
re... |
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 a... | csn |
public function data()
{
return [
'property' => $this->property(),
'table' => $this->table(),
'value' => $this->value(),
'func' => $this->func(),
'operator' => $this->operator(),
'conjunction' => $this->conjunct... | '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[]... | 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(Dispatch... | 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) {
... | = getTestSuite(configuration, dataset);
assert testSuite != null;
TestExecution results = null;
try {
results = validate(configuration, dataset, testSuite);
} catch (TestCaseExecutionException e) {
// TODO catch error
}
assert results != null;
... | 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.
.. versionad... | 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'] = $p... | '/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
retu... | 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->token... | 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... | 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,... | 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 tagg... | 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
... | 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... | 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... | 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 o... | 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, ']')
retu... | 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 o... | 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);
$... | 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... | 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, New... | 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
... | 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
... | 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'}
... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.