query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
public int compare(Object o1, Object o2) {
int m1 = ((int[])o1)[0];
int m2 = ((int[])o2)[0];
if (m1 < m2)
| return -1;
if (m1 == m2)
return 0;
return 1;
} | csn_ccr |
Realize an smooth slide to an slide offset passed as argument. This method is the base of
maximize, minimize and close methods.
@param slideOffset to apply
@return true if the view is slided. | private boolean smoothSlideTo(float slideOffset) {
final int topBound = getPaddingTop();
int x = (int) (slideOffset * (getWidth() - transformer.getMinWidthPlusMarginRight()));
int y = (int) (topBound + slideOffset * getVerticalDragRange());
if (viewDragHelper.smoothSlideViewTo(dragView, x, y)) {
V... | csn |
def getVariantSetByName(self, name):
"""
Returns a VariantSet with the specified name, or raises a
VariantSetNameNotFoundException if it | does not exist.
"""
if name not in self._variantSetNameMap:
raise exceptions.VariantSetNameNotFoundException(name)
return self._variantSetNameMap[name] | csn_ccr |
python how to trim trailing zeroes | def __remove_trailing_zeros(self, collection):
"""Removes trailing zeroes from indexable collection of numbers"""
index = len(collection) - 1
while index >= 0 and collection[index] == 0:
index -= 1
return collection[:index + 1] | cosqa |
function ServiceOptions(properties) {
this.uninterpretedOption = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
| if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
} | csn_ccr |
Determine if an identifier is referencing an enclosing function name.
@param {Reference} ref - The reference to check.
@param {ASTNode[]} nodes - The candidate function nodes.
@returns {boolean} True if it's a self-reference, false if not.
@private | function isSelfReference(ref, nodes) {
let scope = ref.from;
while (scope) {
if (nodes.indexOf(scope.block) >= 0) {
return true;
}
scope = scope.upper;
}
return false;
} | csn |
public static function createFromRequest(StreamInterface $stream, ServerRequestInterface $request = null)
{
$result = [];
if ($request === null) {
$headers = \tao_helpers_Http::getHeaders();
$rangeHeader = isset($headers['Range']) ? [$headers['Range']] : null;
| } else {
$rangeHeader = $request->hasHeader('Range') ? $request->getHeader('Range') : null;
}
if ($rangeHeader) {
$ranges = explode(',', $rangeHeader[0]);
foreach($ranges as $range) {
$range = str_replace('bytes=', '', $range);
$... | csn_ccr |
Ask ZBar to convert this image to a new format, returning a new Image.
Not all conversions are possible: for example, if ZBar was built without
JPEG support, it cannot convert JPEGs into anything else. | def convert(format)
ptr = ZBar.zbar_image_convert(@img, format)
if ptr.null?
raise ArgumentError, "conversion failed"
else
Image.new(ptr)
end
end | csn |
Remove a key from the queue, return `False` if no such key exists. | def remove(self, key):
"""Remove a key from the queue, return `False` if no such key exists."""
if key in self.queue:
del self.queue[key]
self.write()
return True
return False | csn |
Recursively deletes a directory and its contents.
@since 1.2.0
@return string | protected function resolveDestination()
{
$dir = '';
$uploads = wp_upload_dir();
if (isset($uploads['basedir'])) {
$dir = $uploads['basedir'] . '/' . $this->plugin . '/_site';
} else {
$dir = WP_CONTENT_DIR . '/uploads/' . $this->plugin . '/_site';
}
... | csn |
Load match info by match_id | public function load()
{
$request = new request(self::STEAM_MATCH_URL, array('match_id' => $this->getMatchId()));
$matchInfo = $request->send();
if (null === $matchInfo) {
return null;
}
$match = new Match();
$players = array();
foreach ($matchInfo... | csn |
Test if a command should be enabled.
@param string $name
@return bool | public function isCommandEnabled($name)
{
if (!empty(self::$config['application']['disabled_commands'])
&& in_array($name, self::$config['application']['disabled_commands'])) {
return false;
}
if (!empty(self::$config['application']['experimental_commands'])
... | csn |
def calc_anchors(preregistration_map, model, model_hemi,
scale=1, sigma=Ellipsis, radius_weight=0, field_sign_weight=0,
invert_rh_field_sign=False):
'''
calc_anchors is a calculator that creates a set of anchor instructions for a registration.
Required afferent parameters:... | '''
wgts = preregistration_map.prop('weight')
rads = preregistration_map.prop('radius')
if np.isclose(radius_weight, 0): radius_weight = 0
ancs = retinotopy_anchors(preregistration_map, model,
polar_angle='polar_angle',
eccentricity='eccentr... | csn_ccr |
Create a SageMaker ``ChainerModel`` object that can be deployed to an ``Endpoint``.
Args:
role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``, which is also used during
transform jobs. If not specified, the role from the Estimator will be used.
model_serv... | def create_model(self, model_server_workers=None, role=None, vpc_config_override=VPC_CONFIG_DEFAULT):
"""Create a SageMaker ``ChainerModel`` object that can be deployed to an ``Endpoint``.
Args:
role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``, which is also used during
... | csn |
Replace the date, datetime or period tuples in obj.value with
appropriate strings. | def transformFromNative(obj):
"""
Replace the date, datetime or period tuples in obj.value with
appropriate strings.
"""
if obj.value and type(obj.value[0]) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = ','.join([d... | csn |
func runRaw(t crossdock.T, disp *yarpc.Dispatcher) {
assert := crossdock.Assert(t)
fatals := crossdock.Fatals(t)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client := raw.New(disp.ClientConfig("yarpc-test"))
_, err := client.Call(ctx, "handlertimeout/raw", nil)
... | {
t.Skipf("handlertimeout/raw method not implemented: %v", err)
return
}
assert.Equal(yarpcerrors.CodeDeadlineExceeded, yarpcerrors.FromError(err).Code(), "is an error with code CodeDeadlineExceeded: %v", err)
} | csn_ccr |
Does the code contain bad comments?
@param string $value
@return bool | protected function containsBadComments($value)
{
foreach (token_get_all($value) as $token) {
if (!is_array($token) || !isset($token[0]) || $token[0] !== T_COMMENT) {
continue;
}
if (substr($token[1], 0, 2) === '//') {
return true;
... | csn |
func (p *Buffer) DecodeFixed64() (x uint64, err error) {
// x, err already 0
i := p.index + 8
if i < 0 || i > len(p.buf) {
err = io.ErrUnexpectedEOF
return
}
p.index = i
x = uint64(p.buf[i-8])
x |= uint64(p.buf[i-7]) << 8
x |= uint64(p.buf[i-6]) << | 16
x |= uint64(p.buf[i-5]) << 24
x |= uint64(p.buf[i-4]) << 32
x |= uint64(p.buf[i-3]) << 40
x |= uint64(p.buf[i-2]) << 48
x |= uint64(p.buf[i-1]) << 56
return
} | csn_ccr |
// createImageExistenceMap returns a map recording on which nodes the images exist, keyed by the images' names. | func createImageExistenceMap(nodes []*v1.Node) map[string]sets.String {
imageExistenceMap := make(map[string]sets.String)
for _, node := range nodes {
for _, image := range node.Status.Images {
for _, name := range image.Names {
if _, ok := imageExistenceMap[name]; !ok {
imageExistenceMap[name] = sets.N... | csn |
// streamFetch performs a streaming fetch. | func (qre *QueryExecutor) streamFetch(conn *connpool.DBConn, parsedQuery *sqlparser.ParsedQuery, bindVars map[string]*querypb.BindVariable, buildStreamComment string, callback func(*sqltypes.Result) error) error {
sql, _, err := qre.generateFinalSQL(parsedQuery, bindVars, nil, buildStreamComment)
if err != nil {
re... | csn |
Return an HTML document that embeds Bokeh Model or Document objects.
The data for the plot is stored directly in the returned HTML, with
support for customizing the JS/CSS resources independently and
customizing the jinja2 template.
Args:
models (Model or Document or seq[Model]) : Bokeh object... | def file_html(models,
resources,
title=None,
template=FILE,
template_variables={},
theme=FromCurdoc,
suppress_callback_warning=False,
_always_new=False):
''' Return an HTML document that embeds Bokeh Model or Document ... | csn |
Gets the rokka image client used by this class.
@since 1.3.0
@throws \RuntimeException
@return \Rokka\Client\Image | public function getRokkaClient()
{
if (null === $this->imageClient) {
$this->imageClient = Factory::getImageClient($this->rokkaOrg, $this->rokkaApiKey, $this->rokkaClientOptions);
}
return $this->imageClient;
} | csn |
Get the properties from a list of classes.
@param array $classes
@return array | public static function getProperties($classes)
{
array_reverse($classes);
$properties = array();
foreach ($classes as $class) {
foreach ($class->getProperties() as $property) {
$properties[$property->getName()] = $property;
}
}
return ... | csn |
// log writes information or error only if the loop has a description. | func (l *loop) logf(isError bool, format string, a ...interface{}) {
if l.descr == "" {
return
}
if isError {
logger.Errorf(format, a...)
} else {
logger.Infof(format, a...)
}
} | csn |
func (adNoun AdjNoun) Generate() string {
if adNoun.Format == nil {
adNoun.Format = GeneratePascalCaseAdjNoun
} |
return adNoun.Format(adNoun.getAdjective(), adNoun.getNoun(), adNoun.getDigit())
} | csn_ccr |
set to null so we can check first time | function isSupported() {
// if not checked before, run check
if (_supported === null) {
var viewMan = Windows.UI.ViewManagement;
_supported = (viewMan.StatusBar && viewMan.StatusBar.getForCurrentView);
}
return _supported;
} | csn |
def check(self, item_id):
"""Check if an analysis is complete
:type item_id: int
:param item_id: task_id to check.
:rtype: bool
:return: Boolean indicating if a report is done or not.
"""
response = self._request("tasks/view/{id}".format(id=item_id))
... | status = content['task']["status"]
if status == 'completed' or status == "reported":
return True
except ValueError as e:
raise sandboxapi.SandboxError(e)
return False | csn_ccr |
Parse the XML response body and return a \SimpleXMLElement.
In order to prevent XXE attacks, this method disables loading external
entities. If you rely on external entities, then you must parse the
XML response manually by accessing the response body directly.
@return \SimpleXMLElement
@throws RuntimeException if th... | public function xml()
{
$errorMessage = null;
$internalErrors = libxml_use_internal_errors(true);
$disableEntities = libxml_disable_entity_loader(true);
libxml_clear_errors();
try {
$xml = new \SimpleXMLElement((string) $this->body ?: '<root />', LIBXML_NONET);
... | csn |
display the page
@access public
@return void
@since 3.0
@package Gcs\Framework\Core\Engine | public function run() {
if (!Config::config()['user']['debug']['maintenance']) {
if ($this->_route == false) {
$this->response->status(404);
$this->addError('routing failed : http://' . $this->request->env('HTTP_HOST') . $this->request->env('REQUEST_URI'), __FILE__, _... | csn |
Execute the custom console command.
@return void | public function handle()
{
$this->info('Starting Custom Witness command...');
foreach ($this->eye->getCustomWitnesses(true) as $witness) {
$this->info('Running: '.$witness->getSafeName());
$status = $this->runWitness($witness);
$witness->saveHistory($status);
... | csn |
Access the specified padding value or fallback to a provided
default.
@param defaultPadding default value if the parameter is 'automatic'
@return padding | double getPaddingValue(double defaultPadding) {
double padding = model.get(RendererModel.Padding.class);
if (padding == AUTOMATIC)
padding = defaultPadding;
return padding;
} | csn |
protected function doTransform(Matrix $mA, $extra = null)
{
$this->assertMatrixIsComplete($mA);
if ($mA->is('empty')) {
return new Matrix(array());
}
$transposed = array();
$data = $mA->toArray();
foreach ($data as $rowKey => $row) {
if (is_ar... | there is a second dimension
foreach ($row as $columnKey => $element) {
$transposed[$columnKey][$rowKey] = $element;
}
}
}
return new Matrix($transposed);
} | csn_ccr |
Find all connections matching the selection criteria
This method looks into the existing known connections to find all
that match the specified parameters.
Firewalled connections are not returned.
@method findConnections
@protected
@param hostName {String} - Host name to search for (null = any host)
@param appName {... | function(hostName, appName) {
var t = this;
return t.connections.filter(function(conn) {
// Host or app matches if not specified or if specified and equal
var matchesHost = !hostName || conn.isThisHost(hostName);
var matchesApp = !appName || appName === conn.get('remoteAppName');
... | csn |
// GetBlockChainInfoAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function
// on the returned instance.
//
// See GetBlockChainInfo for the blocking version and more details. | func (c *Client) GetBlockChainInfoAsync() FutureGetBlockChainInfoResult {
cmd := btcjson.NewGetBlockChainInfoCmd()
return c.sendCmd(cmd)
} | csn |
Create Range from global offsets. Used for backward compatibility with older API. | public TextRange newRange(int startOffset, int endOffset) {
checkMetadata();
return newRangeValidPointers(newPointer(startOffset), newPointer(endOffset), false);
} | csn |
public function findDataByTypesAndNames(string $locale, array $namesByTypes, array $modCombinationIds = []): array
{
$columns = [
't.locale AS locale',
't.type AS type',
't.name AS name',
't.value AS value',
't.description AS description',
... | default:
$conditions[] = '(t.type = :type' . $index . ' AND t.name IN (:names' . $index . '))';
break;
}
$queryBuilder->setParameter('type' . $index, $type)
->setParameter('names' . $index, array_values($... | csn_ccr |
Compiles summary data array of basket item for Paymorrow.
@param int $iLineItemCount
@return array | public function getPaymorrowBasketItemSummary( $iLineItemCount )
{
/** @var OxpsPaymorrowOxBasketItem|oxBasketItem $this */
$sPaymorrowLineItemPrefix = self::getPaymorrowBasketSummaryLineItemPrefix( $iLineItemCount );
return array(
$sPaymorrowLineItemPrefix . 'quantity' =... | csn |
how to exclude multiline comments in python with re | def _ignore_comments(lines_enum):
"""
Strips comments and filter empty lines.
"""
for line_number, line in lines_enum:
line = COMMENT_RE.sub('', line)
line = line.strip()
if line:
yield line_number, line | cosqa |
def estimate_sub_second_time(files, interval=0.0):
'''
Estimate the capture time of a sequence with sub-second precision
EXIF times are only given up to a second of precision. This function
uses the given interval between shots to estimate the time inside that
second that each picture was taken.
... | datetime.timedelta(seconds=interval)
for i, f in tqdm(enumerate(files), desc="Estimating subsecond time"):
m = exif_time(f)
if not m:
pass
if i == 0:
smin = m
smax = m + onesecond
else:
m0 = m - T * i
smin = max(smin, m0)
... | csn_ccr |
Ho, Ho, Ho!
It's Christmas time and our friendly grandpa Santa Claus is busy distributing gifts to all the nice children. With the rising population, Santa's workload every year gets increased and he seeks your help to wrap the gifts with fancy wrapping papers while he gets them distributed.
Everything was going great... | # cook your dish here
def read_i_l(l=False):
m = list(map(int, input().strip().split(" ")))
if l:
return list(m)
else:
return m
def i():
return int(input().strip())
T = i()
L = []
"""for current in range(T):
line = ""
for i in range(current):
line+=str((T-i)%10)
for i... | apps |
protected void bumpLit(final int lit) {
final double maxPriority = 1e300;
final int idx = Math.abs(lit);
double oldPriority;
if (this.scoreIncrement > maxPriority || (oldPriority | = this.decisions.priority(idx)) > maxPriority) {
rescore();
oldPriority = this.decisions.priority(idx);
}
final double newPriority = oldPriority + this.scoreIncrement;
this.decisions.update(idx, newPriority);
} | csn_ccr |
public Filtration optimizeFilterOnly(final DruidQuerySignature querySignature)
{
if (!intervals.equals(ImmutableList.of(eternity()))) {
throw new ISE("Cannot optimizeFilterOnly when intervals are set");
}
final Filtration transformed = transform(
this,
ImmutableList.of(
... | ConvertSelectorsToIns.create(querySignature.getRowSignature())
)
);
if (!transformed.getIntervals().equals(ImmutableList.of(eternity()))) {
throw new ISE("WTF?! optimizeFilterOnly was about to return filtration with intervals?!");
}
return transformed;
} | csn_ccr |
This collection must not contain duplicates.
@return Schemer\Validator\Collection | public function unique() : Collection
{
return $this->pipe(
self::predicate(
function (array $values) : bool {
return array_unique($values) === $values;
},
'not all unique elements'
)
);
} | csn |
python how to delete files on local disk | def _delete_local(self, filename):
"""Deletes the specified file from the local filesystem."""
if os.path.exists(filename):
os.remove(filename) | cosqa |
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
| if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table | csn_ccr |
public synchronized Set<Vulnerability> getVulnerabilities(boolean sorted) {
final Set<Vulnerability> vulnerabilitySet;
if (sorted) {
vulnerabilitySet = new TreeSet<>(vulnerabilities);
} else {
| vulnerabilitySet = vulnerabilities;
}
return Collections.unmodifiableSet(vulnerabilitySet);
} | csn_ccr |
public static function FromString($Parent, $String, $Tag, $Name = 'Configuration') {
$ConfigurationData = self::ParseString($String, $Name);
if ($ConfigurationData === FALSE)
| throw new Exception('Could not parse config string.');
return new Gdn_ConfigurationSource($Parent, 'string', $Tag, $Name, $ConfigurationData);
} | csn_ccr |
JSON aware value comparison function.
@param mixed $a First value to compare
@param mixed $b Second value to compare
@return bool | public static function isEqual($a, $b)
{
if ($a === $b) {
return true;
} elseif ($a instanceof \stdClass) {
return self::isEqual((array) $a, $b);
} elseif ($b instanceof \stdClass) {
return self::isEqual($a, (array) $b);
} else {
return... | csn |
how to switch python version, spyder | def get_versions(reporev=True):
"""Get version information for components used by Spyder"""
import sys
import platform
import qtpy
import qtpy.QtCore
revision = None
if reporev:
from spyder.utils import vcs
revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))
... | cosqa |
Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean | def bool(self):
"""
Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean
"""
v = self.squeeze()
... | csn |
def get_std_dev_area(self, mag, rake):
"""
Standard deviation for WC1994. Magnitude is ignored.
"""
assert rake is None or -180 <= rake <= 180
if rake is None:
| # their "All" case
return 0.24
elif (-45 <= rake <= 45) or (rake >= 135) or (rake <= -135):
# strike slip
return 0.22
elif rake > 0:
# thrust/reverse
return 0.26
else:
# normal
return 0.22 | csn_ccr |
Handle event for add the default buttons for the select mode.
@param GetSelectModeButtonsEvent $event The event.
@return void | public function handleEvent(GetSelectModeButtonsEvent $event)
{
$environment = $event->getEnvironment();
$translator = $environment->getTranslator();
$basicDefinition = $environment->getDataDefinition()->getBasicDefinition();
$buttons = [];
$confirmMessage =... | csn |
@Override
public void process(Map<String, String> varMap, Writer out)
{
try
{
if (templateText == null)
{
templateText = Utils.readFileIntoString(input); |
}
String replacedString = replace(varMap);
out.write(replacedString);
out.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
} | csn_ccr |
func (m UsersAPIAuthMethod) LogoutURL(c context.Context, | dest string) (string, error) {
return user.LogoutURL(c, dest)
} | csn_ccr |
def validate_chord_label(chord_label):
"""Test for well-formedness of a chord label.
Parameters
----------
chord : str
Chord label to validate.
"""
# This monster regexp is pulled from the JAMS chord namespace,
# which is in turn derived from the context-free grammar of
# Hart... | = re.compile(r'''^((N|X)|(([A-G](b*|#*))((:(maj|min|dim|aug|1|5|sus2|sus4|maj6|min6|7|maj7|min7|dim7|hdim7|minmaj7|aug7|9|maj9|min9|11|maj11|min11|13|maj13|min13)(\((\*?((b*|#*)([1-9]|1[0-3]?))(,\*?((b*|#*)([1-9]|1[0-3]?)))*)\))?)|(:\((\*?((b*|#*)([1-9]|1[0-3]?))(,\*?((b*|#*)([1-9]|1[0-3]?)))*)\)))?((/((b*|#*)([1-9]|1... | csn_ccr |
how to parse string into date python | def _parse_date(string: str) -> datetime.date:
"""Parse an ISO format date (YYYY-mm-dd).
>>> _parse_date('1990-01-02')
datetime.date(1990, 1, 2)
"""
return datetime.datetime.strptime(string, '%Y-%m-%d').date() | cosqa |
Output the page information
@param object $quiz the quiz settings.
@param object $cm the course_module object.
@param object $context the quiz context.
@param array $messages any access messages that should be described.
@return string HTML to output. | public function view_information($quiz, $cm, $context, $messages) {
global $CFG;
$output = '';
// Print quiz name and description.
$output .= $this->heading(format_string($quiz->name));
$output .= $this->quiz_intro($quiz, $cm);
// Output any access messages.
if... | csn |
// GetChannelConfig returns an instance of a object that represents
// current channel configuration tree of the specified channel. The
// ConfigProto method of the returned object can be used to get the
// proto representing the channel configuration. | func (*configSupport) GetChannelConfig(channel string) cc.Config {
chains.RLock()
defer chains.RUnlock()
chain := chains.list[channel]
if chain == nil {
peerLogger.Errorf("[channel %s] channel not associated with this peer", channel)
return nil
}
return chain.cs.bundleSource.ConfigtxValidator()
} | csn |
public function participantsString($userId=null, $columns=['first_name'])
{
$selectString = $this->createSelectString($columns);
$participantNames = $this->getConnection()->table($this->getUsersTable())
->join('participants', $this->getUsersTable() . '.id', '=', 'participants.user_id')
... | if ($userId !== null) {
$participantNames->where($this->getUsersTable() . '.id', '!=', $userId);
}
$userNames = $participantNames->lists($this->getUsersTable() . '.name');
return implode(', ', $userNames);
} | csn_ccr |
Ping a host
Return True if alive
Return False if not | def atlas_peer_ping( peer_hostport, timeout=None, peer_table=None ):
"""
Ping a host
Return True if alive
Return False if not
"""
if timeout is None:
timeout = atlas_ping_timeout()
assert not atlas_peer_table_is_locked_by_me()
host, port = url_to_host_port( peer_hostport )... | csn |
return the number of observations for your SASdata object | def obs(self):
"""
return the number of observations for your SASdata object
"""
code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;"
if self.sas.nosub:
print(code)... | csn |
The Super User can modify Anonymous user settings
@param View $view | protected function initViewAnonymousUserSettings($view)
{
if (!Piwik::hasUserSuperUserAccess()) {
return;
}
$userLogin = 'anonymous';
// Which websites are available to the anonymous users?
$anonymousSitesAccess = Request::processRequest('UsersManager.getSitesA... | csn |
We have n chips, where the position of the ith chip is position[i].
We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:
position[i] + 2 or position[i] - 2 with cost = 0.
position[i] + 1 or position[i] - 1 with cost = 1.
Return the minimum co... | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
d = {}
a = 0
b = 0
for i in position:
if i not in d:
d[i]=1
else:
d[i]+=1
for i in d:
if i%2==0:
a +=d[i]
... | apps |
This method counts all nodes within a tree.
@param tree
is a {@link TreeNode} object which nodes are to be calculated.
@param <N>
is the actual tree implementation.
@return An integer is returned containing the number of nodes. If tree is
<code>null</code> 0 is returned. | public static <N extends TreeNode<N>> int countNodes(N tree) {
int result = 0;
if (tree == null) {
return result;
}
List<N> children = tree.getChildren();
for (N node : children) {
result += countNodes(node);
}
return result + 1; // + 1 for self!
} | csn |
func Convert_autoscaling_MetricStatus_To_v2beta1_MetricStatus(in *autoscaling.MetricStatus, | out *v2beta1.MetricStatus, s conversion.Scope) error {
return autoConvert_autoscaling_MetricStatus_To_v2beta1_MetricStatus(in, out, s)
} | csn_ccr |
Checks that the token contains only safe characters
and is no shorter than lower and no longer than upper. | def check_access_token(self, request_token):
"""Checks that the token contains only safe characters
and is no shorter than lower and no longer than upper.
"""
lower, upper = self.access_token_length
return (set(request_token) <= self.safe_characters and
lower <= l... | csn |
public static function formatLink($link, $activeClass, $hasChild = false, $breadcrumbLink = false) {
return "<a".self::href($link).self::title($link).self::htmlClass(($breadcrumbLink ? '' : self::$linkDefaults['a_default'].' ').(isset($link['class']) ? $link['class'] : | ''), $activeClass).self::target($link).self::rel($link).self::htmlID($link).($hasChild ? self::$dropdownLinkExtras : '').">".($breadcrumbLink ? '' : self::fontIcon($link)).self::label($link).($hasChild ? self::$caretElement : '')."</a>";
} | csn_ccr |
// Call this method and pass a username and password to use basic
// authentication with the configured endpoint. | func (pcc *PubControlClient) SetAuthBasic(username, password string) {
pcc.lock.Lock()
pcc.authBasicUser = username
pcc.authBasicPass = password
pcc.lock.Unlock()
} | csn |
// Pending State
// GetPendingBalanceAt returns the wei balance of the given account in the pending state. | func (ec *EthereumClient) GetPendingBalanceAt(ctx *Context, account *Address) (balance *BigInt, _ error) {
rawBalance, err := ec.client.PendingBalanceAt(ctx.context, account.address)
return &BigInt{rawBalance}, err
} | csn |
Perform a dry_run of the import to make sure the import will not
result in errors. If there where no error, save the user
uploaded file to a local temp file that will be used by
'process_import' for the actual import. | def import_action(self, request, *args, **kwargs):
"""
Perform a dry_run of the import to make sure the import will not
result in errors. If there where no error, save the user
uploaded file to a local temp file that will be used by
'process_import' for the actual import.
... | csn |
Unregister a resource. | public static TaskManager unregisterResource(Object resource) {
if (resource == null) return null;
synchronized (resources) {
return resources.remove(resource);
}
} | csn |
func (z *ZipArchive) List(prefixes ...string) []string {
isHasPrefix := len(prefixes) > 0
names := make([]string, 0, | z.NumFiles)
for _, f := range z.files {
if isHasPrefix && !cae.HasPrefix(f.Name, prefixes) {
continue
}
names = append(names, f.Name)
}
return names
} | csn_ccr |
def delete_network_subname(self, sub_name):
"""Delete the network by part of its name, use with caution. """
try:
body = {}
net_list = self.neutronclient.list_networks(body=body)
for net in net_list:
if net.get('name').find(sub_name) != -1:
| self.delete_network_all_subnets(net.get('net_id'))
except Exception as exc:
LOG.error("Failed to get network by subname %(name)s, "
"Exc %(exc)s",
{'name': sub_name, 'exc': str(exc)}) | csn_ccr |
func NewDeleteTask(ctx *middleware.Context, handler DeleteTaskHandler) *DeleteTask {
return | &DeleteTask{Context: ctx, Handler: handler}
} | csn_ccr |
public function getValue()
{
$value = parent::getValue();
if ($value) {
$image = Yii::$app->storage->getImage($value);
/* @var $image \luya\admin\image\Item */
if ($image) {
if ($this->filterName()) {
| return $image->applyFilter($this->filterName())->sourceAbsolute;
}
return $image->source;
}
}
return false;
} | csn_ccr |
def create(global_options, options)
status, body = project_create(global_options, options)
if status == 201
save_message(create_success_message(body))
| true
else
parse_message(body)
false
end
end | csn_ccr |
public static boolean matchesRobotsPattern(String pattern, String path) {
| return robotsPatternToRegexp(pattern).matcher(path).matches();
} | csn_ccr |
Get the logging message URL taking into account OpenShift environmental factors | function getLogMessageURL() {
var url = '';
if (process.env.OPENSHIFT_FEEDHENRY_REPORTER_IP) {
url = 'http://' + process.env.OPENSHIFT_FEEDHENRY_REPORTER_IP + ':' + process.env.OPENSHIFT_FEEDHENRY_REPORTER_PORT;
url += '/sys/admin/reports/TOPIC';
} else {
url = process.env.FH_MESSAGING_SERVER || ''; /... | csn |
def load_preseed():
""" Update JobPriority information from preseed.json
The preseed data has these fields: buildtype, testtype, platform, priority, expiration_date
The expiration_date field defaults to 2 weeks when inserted in the table
The expiration_date field has the format "YYYY-MM-DD", however, i... | queryset = JobPriority.objects.all()
for field in ('testtype', 'buildtype', 'platform'):
if job[field] != '*':
queryset = queryset.filter(**{field: job[field]})
# Deal with the case where we have a new entry in preseed
if not queryset:
create_new_entry... | csn_ccr |
public function doVerifyWithPayPal($request, $charset)
{
$caller = $this->getCaller();
$caller->setRequest($request);
$caller = $this->getCaller();
$curl = $caller->getCurl();
$curl->setConnectionCharset($charset);
$curl->setDataCharset($charset);
$curl->setH... |
$curl->setUrlToCall($this->getPayPalIpnConfig()->getIPNResponseUrl());
$response = oxNew(\OxidEsales\PayPalModule\Model\Response\ResponseDoVerifyWithPayPal::class);
$response->setData($caller->call());
return $response;
} | csn_ccr |
public static function clearAll($check = false)
{
$status = [];
foreach (self::configured() as $config) {
$status[$config] = | self::clear($check, $config);
}
return $status;
} | csn_ccr |
def get_objective_ids_by_objective_banks(self, objective_bank_ids):
"""Gets the list of ``Objective Ids`` corresponding to a list of ``ObjectiveBanks``.
arg: objective_bank_ids (osid.id.IdList): list of objective
bank ``Ids``
return: (osid.id.IdList) - list of objective ``Ids... |
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resource_ids_by_bins
id_l... | csn_ccr |
@MustBeLocked (ELockType.WRITE)
public void updateDocuments (@Nullable final Term aDelTerm,
@Nonnull final Iterable <? extends Iterable <? extends IndexableField>> aDocs) throws IOException
{
long nSeqNum;
if (false)
{
// Delete and than add
nSeqNum = _getWrite... | else
{
// Update directly
nSeqNum = _getWriter ().updateDocuments (aDelTerm, aDocs);
}
if (LOGGER.isDebugEnabled ())
LOGGER.debug ("Last seq# after updateDocuments is " + nSeqNum);
m_aWriterChanges.incrementAndGet ();
} | csn_ccr |
def addinterval(instr, add, interval):
'''
adds string every n character. returns string
'''
if not isinstance(instr, str):
instr = | str(instr)
return add.join(
instr[i:i+interval]
for i in xrange(0,len(instr),interval)) | csn_ccr |
def create_replica(self, clone_member):
"""
create the replica according to the replica_method
defined by the user. this is a list, so we need to
loop through all methods the user supplies
"""
self.set_state('creating replica')
self._sysid = None
... | = self.basebackup(connstring, env, self.config.get(replica_method, {}))
if ret == 0:
logger.info("replica has been created using basebackup")
# if basebackup succeeds, exit with success
break
else:
if not self.data_... | csn_ccr |
Sets the migration references for each valid migrated object.
@param row (see #migrate_row)
@param [Array] migrated the migrated objects
@return [Array] the valid migrated objects | def migrate_valid_references(row, migrated)
# Split the valid and invalid objects. The iteration is in reverse dependency order,
# since invalidating a dependent can invalidate the owner.
ordered = migrated.transitive_closure(:dependents)
ordered.keep_if { |obj| migrated.include?(obj) }.reverse!... | csn |
private void assembleLinkages(List<List<Atom[]>> matchedAtomsOfLinkages,
ProteinModification mod, List<ModifiedCompound> ret) {
ModificationCondition condition = mod.getCondition();
List<ModificationLinkage> modLinks = condition.getLinkages();
int nLink = matchedAtomsOfLinkages.size();
int[] indices = new i... | linkage[0], residues.contains(linkage[0].getGroup()),
linkage[1], residues.contains(linkage[1].getGroup()));
linkages.add(link);
}
ModifiedCompound mc = new ModifiedCompoundImpl(mod, linkages);
if (!identifiedCompounds.contains(mc)) {
ret.add(mc);
identifiedCompounds.add(mc);
}... | csn_ccr |
Specifies the authentication response handler function.
:param callable callback: the auth request handler function
.. deprecated | def auth_request_handler(self, callback):
"""Specifies the authentication response handler function.
:param callable callback: the auth request handler function
.. deprecated
"""
warnings.warn("This handler is deprecated. The recommended approach to have control over "
... | csn |
func (c *chatServiceHandler) ListV1(ctx context.Context, opts listOptionsV1) Reply {
var cl ChatList
var rlimits []chat1.RateLimit
var pagination *chat1.Pagination
client, err := GetChatLocalClient(c.G())
if err != nil {
return c.errReply(err)
}
topicType, err := TopicTypeFromStrDefault(opts.TopicType)
if err... | IdentifyBehavior: keybase1.TLFIdentifyBehavior_CHAT_CLI,
})
if err != nil {
return c.errReply(err)
}
pagination = res.Pagination
rlimits = utils.AggRateLimits(res.RateLimits)
if opts.FailOffline && res.Offline {
return c.errReply(chat.OfflineError{})
}
cl = ChatList{
Offline: res.Offl... | csn_ccr |
TESTING Getter for retriving the specification in the current context.
@param string $element
@return string | public function getSpecification($element = '')
{
if (isset($element) && $element !== '') {
$spec = $this->pattern->specification[$this->getOption('doctype')][$element];
} else {
$spec = $this->pattern->specification[$this->getOption('doctype')];
}
retu... | csn |
Does the Engineering Object enhancement of the EKBCommit object. In this step there may be some inserts updated
or new objects will be added to the updates of the EKBCommit object. Throws an EKBException if an error in the
Engineering Object logic occurs. | private void enhanceEKBCommit(EKBCommit commit) throws EKBException {
LOGGER.debug("Started to enhance the EKBCommit with Engineering Object information");
enhanceCommitInserts(commit);
enhanceCommitUpdates(commit);
// TODO: OPENENGSB-3357, consider also deletions in the enhancement
... | csn |
public function setConfig($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dataproc\V1beta2\ClusterConfig::class); |
$this->config = $var;
return $this;
} | csn_ccr |
// Status reports sink capacity and length. | func (b *SinkHandler) Status() (int, int) {
return b.bufSize, len(b.sinkCh)
} | csn |
Callback called whenever the underlying Receiver undergoes a change
of state. This function can be overridden.
:param previous_state: The previous Receiver state.
:type previous_state: ~uamqp.constants.MessageReceiverState
:param new_state: The new Receiver state.
:type new_stat... | def on_state_changed(self, previous_state, new_state):
"""Callback called whenever the underlying Receiver undergoes a change
of state. This function can be overridden.
:param previous_state: The previous Receiver state.
:type previous_state: ~uamqp.constants.MessageReceiverState
... | csn |
Creates a code chunk representing the given Soy operator applied to the given operands.
<p>Cannot be used for {@link Operator#AND}, {@link Operator#OR}, or {@link
Operator#CONDITIONAL}, as they require access to a {@link Generator} to generate temporary
variables for short-circuiting. Use {@link Expression#and}, {@lin... | public static Expression operation(Operator op, List<Expression> operands) {
Preconditions.checkArgument(operands.size() == op.getNumOperands());
Preconditions.checkArgument(
op != Operator.AND && op != Operator.OR && op != Operator.CONDITIONAL);
switch (op.getNumOperands()) {
case 1:
... | csn |
def generate_subplots(self):
"""
Generates the subplots for the number of given models.
"""
| _, axes = plt.subplots(len(self.models), sharex=True, sharey=True)
return axes | csn_ccr |
func (c CPUMap) Total() int {
var count int
for _, value := range c {
| count += value
}
return count
} | csn_ccr |
func getIsImportRepositoryInfo(isi *imagev1.ImageStreamImport) *metrics.ImportErrorInfo {
if isi.Status.Repository == nil || isi.Spec.Repository == nil {
return nil
}
ref := isi.Spec.Repository.From
if ref.Kind != "DockerImage" {
return nil
}
imgRef, err := imageapi.ParseDockerImageReference(ref.Name)
if err... |
utilruntime.HandleError(fmt.Errorf(
"failed to parse isi.spec.repository.from.name %q: %v",
ref.Name, err))
return nil
}
info := mkImportInfo(imgRef.DockerClientDefaults().Registry, &isi.Status.Repository.Status)
return &info
} | csn_ccr |
def content_length
# http://greenbytes.de/tech/webdav/rfc7230.html#rfc.section.3.3.3
# Clause 3: "If a message is received with both a Transfer-Encoding
# and a Content-Length header field, the Transfer-Encoding overrides the Content-Length.
return nil if @headers.include?(Headers::TRANSFER_ENCO... | value = @headers[Headers::CONTENT_LENGTH]
return nil unless value
begin
Integer(value)
rescue ArgumentError
nil
end
end | csn_ccr |
func ValidateReplicaSetStatusUpdate(rs, oldRs *apps.ReplicaSet) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&rs.ObjectMeta, | &oldRs.ObjectMeta, field.NewPath("metadata"))...)
allErrs = append(allErrs, ValidateReplicaSetStatus(rs.Status, field.NewPath("status"))...)
return allErrs
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.