query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
Getter for subpackage specific settings @param string $subpackage @return array
public static function subpackage_settings($subpackage) { $s = self::settings(); if (isset($s[$subpackage])) { return $s[$subpackage]; } }
csn
public function isAllowed(Authenticatable $user = null): bool { $user = $user ?: Auth::user(); foreach ($this->authorizationStack as $auth) { if (is_callable($auth)) { if (!$auth($user)) { return false; }
} elseif ($user && $user->cannot($auth)) { return false; } } return true; }
csn_ccr
returning 0's for jobs with no JobInfo present.
protected int neededTasks(JobInfo info, TaskType taskType) { if (info == null) return 0; return taskType == TaskType.MAP ? info.neededMaps : info.neededReduces; }
csn
public function start(array $options = null) { $sessionStatus = \session_status(); if ($sessionStatus === PHP_SESSION_DISABLED) { throw new \RuntimeException('PHP sessions are disabled'); } if ($sessionStatus === PHP_SESSION_ACTIVE) { throw new \RuntimeExcep...
$this->cookieParams['lifetime'], $this->cookieParams['path'], $this->cookieParams['domain'], $this->cookieParams['secure'], $this->cookieParams['httponly'] ); if ($options === null) { $options = []; } if (!isset($options[...
csn_ccr
Returns this comma list as an ArrayNode. @return ArrayNode
public function toArrayNode() { return ($this->parent instanceof ArrayNode) ? clone $this->parent : Parser::parseExpression('[' . $this->getText() . ']'); }
csn
def send_zone_event(self, zone_id, event_name, *args): """ Send an event to a zone. """ cmd = "EVENT %s!%s %s"
% ( zone_id.device_str(), event_name, " ".join(str(x) for x in args)) return (yield from self._send_cmd(cmd))
csn_ccr
Is user member of the given group @param AccountInterface $account @param Group $group @return bool
public function userIsMember(AccountInterface $account, Group $group) { // @todo fix this, cache that return (bool)$this ->database ->query( "SELECT 1 FROM {ucms_group_access} WHERE group_id = :group AND user_id = :user", [':group' => $group->g...
csn
public static function generate($mixed=null) { // create a sha1 signature of the array with a salt $hash = hash( Config::get('keys', 'algo'), json_encode(array($mixed, Config::get('keys',
'salt')), JSON_NUMERIC_CHECK) ); // get last 10 and first 10 chars together, convert to uppercase, return the key return(strtoupper(substr($hash, -10) . substr($hash, 0, 10))); }
csn_ccr
Performs the http call. @param string $method @param array $arguments @return Response @throws ClientException
public function call(string $method, array $arguments): Response { try { return $this->request('GET', $method, [ 'query' => $arguments ]); } catch (\Exception $e) { throw new ClientException($e->getMessage(), $e->getCode(), $e); } }
csn
def create_alarm(panel_json, abode, area='1'): """Create a new alarm device from a panel response.""" panel_json['name'] = CONST.ALARM_NAME panel_json['id'] =
CONST.ALARM_DEVICE_ID + area panel_json['type'] = CONST.ALARM_TYPE panel_json['type_tag'] = CONST.DEVICE_ALARM panel_json['generic_type'] = CONST.TYPE_ALARM return AbodeAlarm(panel_json, abode, area)
csn_ccr
returns a clean string. @param string $dirty dirty string to cleanup @param string $languageCode @return string clean string
public function cleanup($dirty, $languageCode = null) { $replacers = $this->replacers['default']; if (null !== $languageCode) { $replacers = array_merge( $replacers, (isset($this->replacers[$languageCode]) ? $this->replacers[$languageCode] : []) ...
csn
Add a SRE.
protected void addSRE() { final AddSREInstallWizard wizard = new AddSREInstallWizard( createUniqueIdentifier(), this.sreArray.toArray(new ISREInstall[this.sreArray.size()])); final WizardDialog dialog = new WizardDialog(getShell(), wizard); if (dialog.open() == Window.OK) { final ISREInstall result = w...
csn
// length of -1 means all
func (s *storage) fetch(ctx context.Context, br blob.Ref, offset, length int64) (rc io.ReadCloser, size uint32, err error) { meta, err := s.meta(br) if err != nil { return nil, 0, err } if meta.file >= len(s.fds) { return nil, 0, fmt.Errorf("diskpacked: attempt to fetch blob from out of range pack file %d > %d...
csn
protected function _list_messages($folder='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0) { if (!strlen($folder)) { return array(); } $this->set_sort_order($sort_field, $sort_order); $page = $page ? $page : $this->list_page; // use saved message se...
return array(); } $from = ($page-1) * $this->page_size; $to = $from + $this->page_size; $index->slice($from, $to - $from); if ($slice) { $index->slice(-$slice, $slice); } // fetch reqested messages headers $a_index = $index->get...
csn_ccr
func validTaskName(name string) bool { var match bool match, err :=
regexp.MatchString("^[a-z0-9]+(-[a-z0-9]+)*$", name) if err != nil { return false } return match }
csn_ccr
def connect(servers=None, framed_transport=False, timeout=None, retry_time=60, recycle=None, round_robin=None, max_retries=3): """ Constructs a single ElasticSearch connection. Connects to a randomly chosen server on the list. If the connection fails, it will attempt to connect to each serv...
Default: 60 :keyword recycle: Max time in seconds before an open connection is closed and returned to the pool. Default: None (Never recycle) :keyword max_retries: Max retry time on connection down :keyword round_robin: *DEPRECATED* :return ES client """ if server...
csn_ccr
// Next returns the next data point on the wrapped diode. If there is not any // new data, it will Wait for set to be called or the context to be done. // If the context is done, then nil will be returned.
func (w *Waiter) Next() GenericDataType { w.mu.Lock() defer w.mu.Unlock() for { data, ok := w.Diode.TryNext() if !ok { if w.isDone() { return nil } w.c.Wait() continue } return data } }
csn
function(index) { if(lang.isNumber(index)&& this._elColgroup) { var nextSibling = this._elColgroup.childNodes[index] || null;
this._elColgroup.insertBefore(document.createElement("col"), nextSibling); } }
csn_ccr
Given a list of parts, return all of the nested file parts.
def _search_for_files(parts): """ Given a list of parts, return all of the nested file parts. """ file_parts = [] for part in parts: if isinstance(part, list): file_parts.extend(_search_for_files(part)) elif isinstance(part, FileToken): file_parts.append(part) ret...
csn
def _get_search_text(self, cli): """ The text we are searching for. """ # When the search buffer has focus, take that text. if self.preview_search(cli) and
cli.buffers[self.search_buffer_name].text: return cli.buffers[self.search_buffer_name].text # Otherwise, take the text of the last active search. else: return self.get_search_state(cli).text
csn_ccr
Draw the icon.
@Override public void draw(Canvas canvas, Projection pj) { if (mIcon == null) return; if (mPosition == null) return; pj.toPixels(mPosition, mPositionPixels); int width = mIcon.getIntrinsicWidth(); int height = mIcon.getIntrinsicHeight(); Rect ...
csn
private void extractAndAssignValue(String line, int lineNumber, ColumnInfo<Object> columnInfo, String columnStr, int linePos, Object target, ParseError parseError) { Object value = extractValue(line, lineNumber, columnInfo, columnStr, linePos, target, parseError); if (value == null) { assignParseErrorFields(p...
parseError.setErrorType(ErrorType.INTERNAL_ERROR); parseError .setMessage("setting value for field '" + columnInfo.getFieldName() + "' error: " + e.getMessage()); assignParseErrorFields(parseError, columnInfo, columnStr); parseError.setLinePos(linePos); } }
csn_ccr
def _normalized_levenshtein_distance(s1, s2, acceptable_differences): """ This function calculates the levenshtein distance but allows for elements in the lists to be different by any number in the set acceptable_differences. :param s1: A list. :param s2: A...
1] for index1, num1 in enumerate(s1): if num2 - num1 in acceptable_differences: new_distances.append(distances[index1]) else: new_distances.append(1 + min((distances[index1], distances[index1+1], ...
csn_ccr
func SetBit64(value uint64, pos uint) (uint64, error) { if pos >= 64 { return value,
fmt.Errorf("invalid position(%v)", pos) } return (value | (uint64(1) << pos)), nil }
csn_ccr
Returns prefix for variable according to variable type @param string $strType The type of variable for which the prefix is needed @return string The variable prefix @was QString::PrefixFromType
public static function prefixFromType($strType) { switch ($strType) { case Type::ARRAY_TYPE: return "obj"; case Type::BOOLEAN: return "bln"; case Type::DATE_TIME: return "dtt"; case Type::FLOAT: r...
csn
// return a new error with additional context
func (e *merryErr) WithValue(key, value interface{}) Error { if e == nil { return nil } return &merryErr{ err: e, key: key, value: value, } }
csn
Return true if the passed object as argument is a class being to the Pigalle framework. # Arguments kls: The class to check. # Returns: bool: * True if class is Pigalle. * False else.
def is_pigalle_class(kls: ClassVar) -> bool: """ Return true if the passed object as argument is a class being to the Pigalle framework. # Arguments kls: The class to check. # Returns: bool: * True if class is Pigalle. * False else. ...
csn
def radviz(self, column_names, transforms=dict(), **kwargs): """ Radviz plot. Useful for exploratory visualization, a radviz plot can show multivariate data in 2D. Conceptually, the variables (here, specified in `column_names`) are distributed evenly around the unit circle. Th...
#radviz """ # make a copy of data x = self.data[column_names].copy() for k, v in transforms.items(): x[k] = v(x[k]) def normalize(series): mn = min(series) mx = max(series) return (series - mn) / (mx - mn) df = x.apply(...
csn_ccr
def vrconf_format(self, vrconfig): """Formats a vrrp configuration dictionary to match the information as presented from the get and getall methods. vrrp configuration dictionaries passed to the create method may contain data for setting properties which results in a default valu...
fixed['secondary_ip'] = sorted(fixed['secondary_ip']) # ip_version: default, no, None results in value of 2 if fixed['ip_version'] in ('no', 'default', None): fixed['ip_version'] = 2 # timers_advertise: default, no, None results in value of 1 if fixed['timers_adv...
csn_ccr
Given a binary tree, return the vertical order traversal of its nodes values. For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1). Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report t...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque class Solution: def bfs(self, root, col_table): min_col = 0 max_col = 0 ...
apps
private static function findDesignBase( eZINI $ini, $siteAccess = false ) { if( $siteAccess ) { $ini = eZSiteAccess::getIni( $siteAccess, 'site.ini' ); $standardDesign = $ini->variable( 'DesignSettings', 'StandardDesign' ); $siteDesign = $ini->variable( 'Desi...
$designStartPath = eZTemplateDesignResource::designStartPath(); $extensions = eZTemplateDesignResource::designExtensions(); foreach ( $siteDesignList as $design ) { foreach ( $extensions as $extension ) { $path = "$extensionDirectory/$extens...
csn_ccr
function for checking dtype in python
def is_string_dtype(arr_or_dtype): """ Check whether the provided array or dtype is of the string dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of the string dtype. E...
cosqa
A cmp function for determining which forward segment to rely on more when computing coordinates.
function compareForwardSlotSegs(seg1, seg2) { // put higher-pressure first return seg2.forwardPressure - seg1.forwardPressure || // put segments that are closer to initial edge first (and favor ones with no coords yet) (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) || // do normal sorting... compareSlo...
csn
static void unbox(GeneratorAdapter mg, Type type) { switch (type.getSort()) { case Type.VOID: return; case Type.BOOLEAN: mg.visitTypeInsn(CHECKCAST, "java/lang/Boolean"); mg.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", ...
Type.SHORT: mg.visitTypeInsn(CHECKCAST, "java/lang/Short"); mg.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S"); break; case Type.INT: mg.visitTypeInsn(CHECKCAST, "java/lang/Integer"); ...
csn_ccr
Patch the python logging handlers with out mixed-in classes
def patch_python_logging_handlers(): ''' Patch the python logging handlers with out mixed-in classes ''' logging.StreamHandler = StreamHandler logging.FileHandler = FileHandler logging.handlers.SysLogHandler = SysLogHandler logging.handlers.WatchedFileHandler = WatchedFileHandler logging...
csn
private static function fixBackgroundPosition($css) { $replaced = preg_replace_callback( self::$patterns['bg_horizontal_percentage'], array('self', 'calculateNewBackgroundPosition'), $css ); if ($replaced !== null) { // preg_replace_callback() sometimes returns null $css = $replaced;
} $replaced = preg_replace_callback( self::$patterns['bg_horizontal_percentage_x'], array('self', 'calculateNewBackgroundPosition'), $css ); if ($replaced !== null) { $css = $replaced; } return $css; }
csn_ccr
If object is sharded, see if we need to add a new column to the "current shards" row.
private void checkForNewShard(DBObject dbObj) { int shardNumber = m_tableDef.getShardNumber(dbObj); if (shardNumber > 0) { SpiderService.instance().verifyShard(m_tableDef, shardNumber); } }
csn
def main_hrun(): """ parse command line options and run commands.""" parser = argparse.ArgumentParser(description="Tools for http(s) test. Base on rtsf.") parser.add_argument( '--log-level', default='INFO', help="Specify logging level, default is INFO.") p...
'--log-file', help="Write logs to specified file path.") parser.add_argument( 'case_file', help="yaml testcase file") color_print("httpdriver {}".format(__version__), "GREEN") args = parser.parse_args() logger.setup_logger(args.log_level, args.log_file) ...
csn_ccr
public function javascriptIncludeTag($sources = "application", $attributes = []) { // E.g. javascript_include_tag('app'); => app-9fcd9b50e5cb047af35d3c5a4b55f73f.js $args = func_get_args(); if (is_array(last($args))) { $attributes = array_pop($args); } else { ...
$attributes = $attributes + $defaults; $javascript_tags = []; foreach ((array) $sources as $source) { $sourceName = "$source.js"; $javascript_tags[] = app('html')->script($this->assetPath($sourceName, $assetsOptions), $attributes); } return implode($javascri...
csn_ccr
Shut down the SparkContext.
def stop(self): """ Shut down the SparkContext. """ if getattr(self, "_jsc", None): try: self._jsc.stop() except Py4JError: # Case: SPARK-18523 warnings.warn( 'Unable to cleanly shutdown Spark JVM...
csn
func (q *errQueryOutOfBounds) Error() string { return fmt.Sprintf("search
for entry with dn=%q would search outside of the base dn specified (dn=%q)", q.queryDN, q.baseDN) }
csn_ccr
Gets a list of content types acceptable by the client browser @return array List of content types in preferable order @api
public function getAcceptableContentTypes() { if (null !== $this->acceptableContentTypes) { return $this->acceptableContentTypes; } $acceptableContentTypes = $this->headers->getParameterListAsObject('ACCEPT'); return $this->acceptableContentTypes = $acceptableContentTyp...
csn
func NewLocation(msg string, a ...interface{}) Location
{ msg = fmt.Sprintf(msg, a...) return Location{ error: errors.New(msg), } }
csn_ccr
def dirty(name, target, user=None, username=None, password=None, ignore_unversioned=False): ''' Determine if the working directory has been changed.
''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} return _fail(ret, 'This function is not implemented yet.')
csn_ccr
public static function removeDir(string $dir) { foreach (scandir($dir) as $file) { if ('.' === $file || '..' === $file) { continue; } if (is_dir($dir . '/' . $file)) {
self::removeDir($dir . '/' . $file); } else { unlink($dir . '/' . $file); } } rmdir($dir); }
csn_ccr
python regex on folder of filenames
def match_files(files, pattern: Pattern): """Yields file name if matches a regular expression pattern.""" for name in files: if re.match(pattern, name): yield name
cosqa
private DbOperation hasOptimisticLockingException(List<DbOperation> operationsToFlush, Throwable cause) { BatchExecutorException batchExecutorException = ExceptionUtil.findBatchExecutorException(cause); if (batchExecutorException != null) { int failedOperationIndex = batchExecutorException.getSuccessfu...
DbOperation failedOperation = operationsToFlush.get(failedOperationIndex); if (isOptimisticLockingException(failedOperation, cause)) { return failedOperation; } } } return null; }
csn_ccr
// Get the value without updating the expiration
func (c *ExpireCache) Peek(key interface{}) (value interface{}, ok bool) { defer c.mutex.Unlock() c.mutex.Lock() if record, hit := c.cache[key]; hit { return record.Value, true } return nil, false }
csn
Return a ``Transactions`` object in an inclusive date range. Args: start_date: A ``datetime.Date`` object that marks the inclusive start date for the range. stop_date: A ``datetime.Date`` object that marks the inclusive end date for the range. field...
def range(self, start_date=None, stop_date=None, field=lambda x: x.xfer): """Return a ``Transactions`` object in an inclusive date range. Args: start_date: A ``datetime.Date`` object that marks the inclusive start date for the range. stop_date: A ``datetime.Date`` o...
csn
public static function bound($number, $min = 0, $max = PHP_INT_MAX) { $number = (int)$number; $min = (int)$min;
$max = (int)$max; return min(max($number, $min), $max); }
csn_ccr
def get_parameters(self): """ Get common attributes and it'll used for Model.relationship clone process """ d = {} for k in ['label',
'verbose_name', 'required', 'hint', 'placeholder', 'choices', 'default', 'validators', 'max_length']: d[k] = getattr(self, k) return d
csn_ccr
def _displayattrs(attrib, expandattrs): """ Helper function to display the attributes of a Node object in lexicographic order. :param attrib: dictionary with the attributes :param expandattrs: if True also displays the value of the attributes """ if not attrib: return
'' if expandattrs: alist = ['%s=%r' % item for item in sorted(attrib.items())] else: alist = list(attrib) return '{%s}' % ', '.join(alist)
csn_ccr
Zonal Computing Olympiad 2013, 10 Nov 2012 N teams participate in a league cricket tournament on Mars, where each pair of distinct teams plays each other exactly once. Thus, there are a total of (N × (N-1))/2 matches. An expert has assigned a strength to each team, a positive integer. Strangely, the Martian crowds love...
# cook your dish here # cook your dish here from itertools import combinations n = int(input()) t = list(combinations(list(map(int, input().split())), 2)) ar = 0 for i in t: ar += abs(i[0] - i[1]) print(ar)
apps
Scans process list trying to terminate processes matching paths specified. Uses checksums to identify processes that are duplicates of those specified to terminate. `paths` List of full paths to executables for processes to terminate.
def _stop_processes(paths): """ Scans process list trying to terminate processes matching paths specified. Uses checksums to identify processes that are duplicates of those specified to terminate. `paths` List of full paths to executables for processes to terminate. """ ...
csn
Wrapper for commands to be run as root
def root_cmd(command, tty, sudo, allow_failure=False, **kwargs): ''' Wrapper for commands to be run as root ''' logging_command = command sudo_password = kwargs.get('sudo_password', None) if sudo: if sudo_password is None: command = 'sudo {0}'.format(command) log...
csn
def _determine_hpp_url(self, platform, action): """This returns the Adyen HPP endpoint based on the provided platform, and action. Args: platform (str): Adyen platform, ie 'live' or 'test'. action (str): the HPP action to perform.
possible actions: select, pay, skipDetails, directory """ base_uri = settings.BASE_HPP_URL.format(platform) service = action + '.shtml' result = '/'.join([base_uri, service]) return result
csn_ccr
@Override public void indicateProgress(int number, int total) { progressIndicatorActive = true; String currMsg =
lastMessage; try { updateStatus(currMsg + ' ' + number + " of " + total); } finally { lastMessage = currMsg; } }
csn_ccr
saving figure as pdf python
def save_pdf(path): """ Saves a pdf of the current matplotlib figure. :param path: str, filepath to save to """ pp = PdfPages(path) pp.savefig(pyplot.gcf()) pp.close()
cosqa
Get the ping binary.
protected function makeCommand() { return sprintf( '%s %s', $this->target->resource->binary, $this->target->resource->command ); }
csn
python 3 check if object is defined
def is_defined(self, objtxt, force_import=False): """Return True if object is defined""" return self.interpreter.is_defined(objtxt, force_import)
cosqa
check if arg is function python
def is_callable(*p): """ True if all the args are functions and / or subroutines """ import symbols return all(isinstance(x, symbols.FUNCTION) for x in p)
cosqa
public void doUnload(final Wave wave) { this.eventList = new ArrayList<>(); final Collection<BallModel> list
= new ArrayList<>(this.ballMap.values()); for (final BallModel ballModel : list) { unregisterBall(ballModel); } }
csn_ccr
Add text before processing each child
@Override public void manipulateChildElements(List<HierarchyWrapper> children) { if (!children.isEmpty()) { builder.append(baseIndent).append("children=").append("\n"); } }
csn
public function createCredit() { $copy = $this->copy(); $detailsCopy = new $this->details; foreach ($copy->details as $detail) { $detail->setData(array( 'amount' => $detail->amount * -1 ));
$detailsCopy->append($detail); } $copy->setData(array( 'details' => $detailsCopy )); return $copy; }
csn_ccr
Merge a list of where clauses and bindings :param wheres: A list of where clauses :type wheres: list :param bindings: A list of bindings :type bindings: list :rtype: None
def merge_wheres(self, wheres, bindings): """ Merge a list of where clauses and bindings :param wheres: A list of where clauses :type wheres: list :param bindings: A list of bindings :type bindings: list :rtype: None """ self.wheres = self.where...
csn
verifies the entire string is upper case and contains eventually an underscore used to avoid RegExp for non RegExp aware environment
function isPublicStatic(key) { for(var c, i = 0; i < key.length; i++) { c = key.charCodeAt(i); if ((c < 65 || 90 < c) && c !== 95) { return false; } } return true; }
csn
private static AFPChain partitionAFPchain(AFPChain afpChain, Atom[] ca1, Atom[] ca2, int order) throws StructureException{ int[][][] newAlgn = new int[order][][]; int repeatLen = afpChain.getOptLength()/order; //Extract all the residues considered in the first chain of the alignment List<Integer> alignedRe...
newAlgn[su] = new int[2][]; newAlgn[su][0] = new int[repeatLen]; newAlgn[su][1] = new int[repeatLen]; for (int i=0; i<repeatLen; i++){ newAlgn[su][0][i] = alignedRes.get(repeatLen*su+i); newAlgn[su][1][i] = alignedRes.get( (repeatLen*(su+1)+i)%alignedRes.size()); } } return Alignment...
csn_ccr
def linear_trend_timewise(x, param): """ Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature uses the index of the time series to fit the model, which must be of a datetime dtype. The parame...
""" ix = x.index # Get differences between each timestamp and the first timestamp in seconds. # Then convert to hours and reshape for linear regression times_seconds = (ix - ix[0]).total_seconds() times_hours = np.asarray(times_seconds / float(3600)) linReg = linregress(times_hours, x.valu...
csn_ccr
// pascalCase combines the given words using PascalCase. // // If allowAllCaps is true, when an all-caps word that is not a known // abbreviation is encountered, it is left unchanged. Otherwise, it is // Titlecased.
func pascalCase(allowAllCaps bool, words ...string) string { for i, chunk := range words { if len(chunk) == 0 { // foo__bar continue } // known initalism init := strings.ToUpper(chunk) if _, ok := commonInitialisms[init]; ok { words[i] = init continue } // Was SCREAMING_SNAKE_CASE and not a...
csn
Add a renderer. @access public @param \Zepi\Web\General\Template\RendererAbstract $renderer @return boolean
public function addRenderer(RendererAbstract $renderer) { $extension = $renderer->getExtension(); if (isset($this->renderer[$extension])) { return false; } $this->renderer[$extension] = $renderer; return true; }
csn
Obtains the shape of the preview of the preference's color from a specific typed array. @param typedArray The typed array, the shape should be obtained from, as an instance of the class {@link TypedArray}. The typed array may not be null
private void obtainPreviewShape(@NonNull final TypedArray typedArray) { int defaultValue = getContext().getResources() .getInteger(R.integer.color_picker_preference_default_preview_shape); setPreviewShape(PreviewShape.fromValue(typedArray .getInteger(R.styleable.AbstractC...
csn
Create a flattened object by calling a method on all values provided. @param mixed $values The traversable values to flatten. @param string $method The method name to call on all values. @return \stdClass|array|null The flatten values.
public static function byObjectMethod($values, $method) { if (isset($values) && Inspector::isTraversable($values)) { if (is_array($values)) { $flat_values = array(); $setter = 'setArrayValue'; } else { $flat_values = new \stdClass(); ...
csn
// UnmarshalJSON implements the json.Unmarshaler interface for // TypoToleranceOption.
func (o *TypoToleranceOption) UnmarshalJSON(data []byte) error { if string(data) == "null" { o.value = typoToleranceTrue return nil } var v string if err := json.Unmarshal(data, &v); err == nil { o.value = v return nil } var b bool if err := json.Unmarshal(data, &b); err == nil { o.value = fmt.Sprint...
csn
// NewCompactData parses a CompactData from a start element. // If delim is explicitly passed, it will override the DELIMITER element value, which defaults to \t. Pass // empty string to automatically parse DELIMITER value or fallback to default of \t.
func NewCompactData(start xml.StartElement, decoder *xml.Decoder, delim string) (CompactData, error) { cd := CompactData{} cd.Element = start.Name.Local cd.Attr = map[string]string{} for _, a := range start.Attr { cd.Attr[a.Name.Local] = a.Value } err := decoder.DecodeElement(&cd, &start) if err != nil { ret...
csn
public function setParent($parent) { if (empty($parent) || $this->getRefId() == $parent->getRefId() || $parent->hasAncestor($this) || $this->hasReachedAncestorLimit()) { return false; } unset($this->parent);
unset($parent->children); $this->trigger(static::$eventParentChanged); $parent->trigger(static::$eventChildAdded); return $this->{$this->parentAttribute} = $parent->getRefId(); }
csn_ccr
Update an image. @param resource_group_name [String] The name of the resource group. @param image_name [String] The name of the image. @param parameters [ImageUpdate] Parameters supplied to the Update Image operation. @param custom_headers [Hash{String => String}] A hash of custom headers that will be added to t...
def begin_update_with_http_info(resource_group_name, image_name, parameters, custom_headers:nil) begin_update_async(resource_group_name, image_name, parameters, custom_headers:custom_headers).value! end
csn
// EngageAsScript calls the engage endpoint, but doesn't set IP, city, country, on the profile.
func (m *Mixpanel) EngageAsScript(distinctID string, props Properties, op *Operation) error { return m.engage(distinctID, props, op, sourceScript) }
csn
function (token) { if (!token) { return ''; } if (typeof token === 'string') { return token; } if (typeof token.content === 'string')
{ return token.content; } return token.content.map(stringifyToken).join(''); }
csn_ccr
public int[] toIntArray(final int[] dst) { if (dst.length == size) { System.arraycopy(elements, 0, dst,
0, dst.length); return dst; } else { return Arrays.copyOf(elements, size); } }
csn_ccr
Find the diff chunks @param array $lines output lines for the diff @throws \InvalidArgumentException
private function findChunks(array $lines) { $arrayChunks = Utilities::pregSplitArray( $lines, '/^@@ -(\d+,\d+)|(\d+) \+(\d+,\d+)|(\d+) @@(.*)$/' ); foreach ($arrayChunks as $chunkLines) { $this->chunks[] = new DiffChunk($chunkLines); } }
csn
The encoding type used by the API to calculate offsets. Generated from protobuf field <code>.google.cloud.language.v1.EncodingType encoding_type = 3;</code> @param int $var @return $this
public function setEncodingType($var) { GPBUtil::checkEnum($var, \Google\Cloud\Language\V1\EncodingType::class); $this->encoding_type = $var; return $this; }
csn
public function hasAccess(string $privilegeTarget, array $parameters = []): bool { if (!$this->securityContext->canBeInitialized()) {
return false; } return $this->privilegeManager->isPrivilegeTargetGranted($privilegeTarget, $parameters); }
csn_ccr
def _postback(self): """ Perform PayPal PDT Postback validation. Sends the transaction ID and business token to PayPal which responses
with SUCCESS or FAILED. """ return requests.post(self.get_endpoint(), data=dict(cmd="_notify-synch", at=IDENTITY_TOKEN, tx=self.tx)).content
csn_ccr
func (f *JSONConfigFile) SetDeviceID(did keybase1.DeviceID) (err error) { f.userConfigWrapper.Lock() defer f.userConfigWrapper.Unlock() f.G().Log.Debug("| Setting DeviceID to %v\n", did) var u *UserConfig if u, err = f.getUserConfigWithLock(); err != nil
{ } else if u == nil { err = NoUserConfigError{} } else { u.SetDevice(did) err = f.setUserConfigWithLock(u, true) } return }
csn_ccr
how to take the average value each day on group of datetime strings in python
def mean_date(dt_list): """Calcuate mean datetime from datetime list """ dt_list_sort = sorted(dt_list) dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort] avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel) return dt_list_sort[0] + avg_timedelta
cosqa
math library for safe math operations without eval
function MathFormula() { this.addInput("x", "number"); this.addInput("y", "number"); this.addOutput("", "number"); this.properties = { x: 1.0, y: 1.0, formula: "x+y" }; this.code_widget = this.addWidget( "text", "F(x,y)", this.propertie...
csn
public void delete(String dn) throws NamingException { DirContext ctx = new InitialDirContext(env);
ctx.destroySubcontext(dn); ctx.close(); }
csn_ccr
public function iconAction() { header('Content-Type: image/x-icon'); // open our file
$fp = fopen(__DIR__.'/../Resources/assets/favicon.ico', 'r'); fpassthru($fp); fclose($fp); exit; }
csn_ccr
def _make_loaders(self, paths, packages): """Initialize the template loaders based on the supplied paths and packages. :param list[str] paths: List of paths to search for templates :param list[str] packages: List of assets package names :return: A list of loaders
to be used for loading the template assets :rtype: list[FileSystemLoader|PackageLoader] """ loaders = [] # add loaders for paths for path in paths: loaders.append(FileSystemLoader(path)) # add loaders for all specified packages for package in package...
csn_ccr
// intersectTags returns the tags of interest from a specified list of AWS tags; // because we only add tags, this set of tags of interest is the tags that occur in the desired set.
func intersectTags(tags []*ec2.Tag, desired map[string]string) map[string]string { if tags == nil { return nil } actual := make(map[string]string) for _, t := range tags { k := aws.StringValue(t.Key) v := aws.StringValue(t.Value) if _, found := desired[k]; found { actual[k] = v } } if len(actual) ==...
csn
Start Hello REEF job with Driver and Client sharing the same process. @param args command line parameters - not used. @throws InjectionException configuration error.
public static void main(final String[] args) throws InjectionException { try (final REEFEnvironment reef = REEFEnvironment.fromConfiguration( LOCAL_DRIVER_MODULE, DRIVER_CONFIG, ENVIRONMENT_CONFIG)) { reef.run(); final ReefServiceProtos.JobStatusProto status = reef.getLastStatus(); LOG.lo...
csn
Splits a Registry path and returns the hive and key. @type path: str @param path: Registry path. @rtype: tuple( int, str ) @return: Tuple containing the hive handle and the subkey path. The hive handle is always one of the following integer constants: - L{win...
def _split_path(self, path): """ Splits a Registry path and returns the hive and key. @type path: str @param path: Registry path. @rtype: tuple( int, str ) @return: Tuple containing the hive handle and the subkey path. The hive handle is always one of the ...
csn
Compute objective value and gradients of dual objective. Parameters ---------- alpha: array, shape = len(a) beta: array, shape = len(b) Current iterate of dual potentials. a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). ...
def dual_obj_grad(alpha, beta, a, b, C, regul): """ Compute objective value and gradients of dual objective. Parameters ---------- alpha: array, shape = len(a) beta: array, shape = len(b) Current iterate of dual potentials. a: array, shape = len(a) b: array, shape = len(b) ...
csn
Clear and update the screen. stats: Stats database to display cs_status: "None": standalone or server mode "Connected": Client is connected to the server "Disconnected": Client is disconnected from the server
def flush(self, stats, cs_status=None): """Clear and update the screen. stats: Stats database to display cs_status: "None": standalone or server mode "Connected": Client is connected to the server "Disconnected": Client is disconnected from the server ...
csn
private function isNestedField(string $resourceClass, string $property): bool
{ return null !== $this->getNestedFieldPath($resourceClass, $property); }
csn_ccr
Casts provided data as a EnTT instance of given type @export @param {any} data Data to cast @param {any} EntityClass Extended EnTT class to cast as - if not provided, will cast to EnTT class this static method is being called from - if empty array provided, will cast to array of instances of EnTT class this static meth...
function cast(data, EntityClass) { // Check if/how EntityClass is defined or implied if (!EntityClass && !_lodash2.default.isArray(data)) { // No explicit class definition, casting data not array return _dataManagement2.default.cast(data, this); } else if (!EntityClass && _lodash2.defa...
csn
public boolean prove(String value, String state) { Nonce nonce = _map.remove(state + ':' + value);
return nonce != null && !nonce.hasExpired(); }
csn_ccr
Save all formats image. @param string $path The path to the file. @param UploadedFile $file The path to the source file. ```php return Yii::$app->image->saveImage('var/www/site/data/img/author', $image); ``` @return bool|string
public function saveImage ($path, $file, $resize = false) { $filename = UuidHelper::generate() . '.' . $file->extension; $name = $filename[ 0 ] . DIRECTORY_SEPARATOR . $filename[ 1 ] . DIRECTORY_SEPARATOR . $filename; $filepath = $path . DIRECTORY_SEPARATOR . $name; if ($resize) { $data = []; f...
csn
Computes a hashCode given the input objects. @param initialNonZeroOddNumber a non-zero, odd number used as the initial value. @param multiplierNonZeroOddNumber a non-zero, odd number used as the multiplier. @param objs the objects to compute hash code. @return the computed hashCode.
public static int hash( int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object...objs ) { int result = initialNonZeroOddNumber; for ( Object obj : objs ) { result = multiplierNonZeroOddNumber * result + ( obj != null ? obj.hashCode() : 0 ); } return r...
csn
func (actor Actor) CreateUser(username string, password string, origin string) (User, Warnings, error) { uaaUser, err := actor.UAAClient.CreateUser(username, password, origin) if err != nil { return User{}, nil, err }
ccUser, ccWarnings, err := actor.CloudControllerClient.CreateUser(uaaUser.ID) return User(ccUser), Warnings(ccWarnings), err }
csn_ccr