query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
Set attributes on a CDN container. This updates the attributes (that is, properties) of a container. The following attributes are supported: - 'ttl': Time to life in seconds (int). - 'cdn_enabled': Whether the CDN is enabled (boolean). - 'log_retention': Whether logs are retained (boolean). UNSUPPORTED. Future vers...
public function update($name, $attrs) { $headers = array(); foreach ($attrs as $item => $val) { switch ($item) { case 'ttl': $headers['X-TTL'] = (int) $val; break; case 'enabled': case 'cdn_enabled': if (isset($val) && $val == FALSE) { $fl...
csn
Turns the results of one of the data API calls into a pandas dataframe
def make_dataframe(result): """ Turns the results of one of the data API calls into a pandas dataframe """ import pandas as pd ret = {} if isinstance(result,dict): if 'timeseries' in result: result = result['timeseries'] for uuid, data in result.items(): df = pd.D...
csn
Renders Vies or HTML for form field strategies. @param Model $model @param array $fields @param array $values @param array $errors @return View[]|\string[] @throws StrategyRenderException
protected function renderedFormFieldStrategies(Model $model, array $fields, array $values, array $errors = []) { $views = []; foreach ($fields as $key => $field) { try { $instance = $this->getFormFieldStrategyFactory()->make($field->display_strategy); /...
csn
Adds a node to the ProbModelXML.
def _add_variable(self, variable): """ Adds a node to the ProbModelXML. """ # TODO: Add feature for accepting additional properties of states. variable_data = self.data['probnet']['Variables'][variable] variable_element = etree.SubElement(self.variables, 'Variable', attri...
csn
Save all translated fields.
def save_translated_fields(self): """ Save all translated fields. """ fields = {} # Collect all translated fields {'name': 'value'} for field in self._translated_fields: try: value = self.cleaned_data[field] except KeyError: # Fie...
csn
// // private methods // // read the next rune from the stream. Return an Error if there is a problem // reading from the stream. If the end of stream is reached, return the EOF // Token.
func (l *lexer) read() (rune, Error) { var _r rune var _err error // do we have any unread runes to read? _length := len(l._unread) if _length > 0 { _r = l._unread[_length-1] l._unread = l._unread[:_length-1] // otherwise, attempt to read a new rune } else { _r, _, _err = l._r.ReadRune() if _err == io...
csn
Processes a request_token request and returns the request token on success.
def fetch_request_token(self, oauth_request): """Processes a request_token request and returns the request token on success. """ try: # Get the request token for authorization. token = self._get_token(oauth_request, 'request') except Error: # N...
csn
// UnmarshalText defines how unmarshal in TOML parsing
func (c *Constraint) UnmarshalText(text []byte) error { constraint, err := NewConstraint(string(text)) if err != nil { return err } c.Key = constraint.Key c.MustMatch = constraint.MustMatch c.Regex = constraint.Regex return nil }
csn
// Print a formatted critical message
func (rl *RevelLogger) Critf(msg string, param ...interface{}) { rl.Crit(fmt.Sprintf(msg, param...)) }
csn
Renders the navigation bar for logged in users
def render_navbar(&block) action_link = get_action_link if !action_link action_link = CONFIG[:title_short] end html = content_tag(:div, id: 'navbar') do content_tag(:div, class: 'navbar-inner') do if current_lines_user content_tag(:span, class: 'buttons', &b...
csn
Renders the platform footer. @return Response
public function footerAction() { // TODO: find the lightest way to get that information $version = $this->get('claroline.manager.version_manager')->getDistributionVersion(); $roleUser = $this->roleManager->getRoleByName('ROLE_USER'); $selfRegistration = $this->configHandler->getPara...
csn
// This creates a StatResponse from an error.
func NewStatErrorResponse( err error, entries map[int](map[string]string)) StatResponse { return &genericResponse{ err: err, statEntries: entries, } }
csn
Unicode aware version of wordwrap. @param string $text The text to format. @param integer $width The width to wrap to. Defaults to 72. @param string $break The line is broken using the optional break parameter. Defaults to '\n'. @param boolean $cut If the cut is set to true, the string is always wrapped at the specifi...
public function wordWrap($text, $width = 72, $break = "\n", $cut = false) { if ($cut) { $parts = array(); while (mb_strlen($text) > 0) { $part = mb_substr($text, 0, $width); $parts[] = trim($part); $text = trim(mb_substr($text, mb_strlen($part))); } return implode($break, $parts); } $pa...
csn
// Errorf forwards to Logger.Errorf
func (l logf) Errorf(s string, args ...interface{}) { l.log.Errorf(s, args...) }
csn
Lisp style fold left where the first element builds the basis for an inject.
def foldl(list, &block) return '' if list.empty? list[1..-1].inject(list.first, &block) end
csn
Create a new index that allows duplicate values across all keys. @param name the name of the index; may not be null or empty @param workspaceName the name of the workspace; may not be null @param db the database in which the index information is to be stored; may not be null @param converter the converter from {@link ...
static <T> LocalDuplicateIndex<T> create( String name, String workspaceName, DB db, Converter<T> converter, Serializer<T> valueSerialize...
csn
Convert DEC angle to SEX DMS
public static function DECtoSEX($angle) { // Extract DMS $deg = intval($angle); $min = intval(($angle - $deg) * 60); $sec = ((($angle - $deg) * 60) - $min) * 60; // Result in sexagesimal seconds return $sec + $min * 60 + $deg * 3600; }
csn
call this one after any subtask is finished
function taskMinus() { taskCounter-- if (taskCounter === 0) { // Time to respond if (files.length === 0) { res.send(200, { result: 'no files to upload', files }) } else { res.send(201, { result: 'upload OK', ...
csn
Get terms prefix @param string $word @return string
private static function _getPrefix($word) { $questionMarkPosition = strpos($word, '?'); $astrericPosition = strpos($word, '*'); if ($questionMarkPosition !== false) { if ($astrericPosition !== false) { return substr($word, 0, min($questionMarkPosition, $astre...
csn
`react-native-svg` supports additional props that aren't defined in the spec. This function replaces them in a spec conforming manner. @param {Object} props Properties given to us. @returns {Object} Cleaned object. @private
function prepare(props) { const { translate, scale, rotation, skewX, skewY, originX, originY, fontFamily, fontSize, fontWeight, fontStyle, style, ...clean } = props; const transform = []; if (originX != null || originY != null) { transform.push(`translat...
csn
Add stream entity to changes array @param string $path Path @param Entity_Interface $entity Stream entity @return boolean
public function add($path, Entity_Interface $entity) { $result = false; if (strlen($path)) { $name = null; $subtree = $this->subtree($path, $name, true); $subtree->_ownData[$name] = $entity; $result = true; } return $result; }
csn
Resolves the cache name of a method annotated with a JCACHE annotation. @param method the annotated method. @param methodCacheName the cache name defined on the JCACHE annotation. @param cacheDefaultsAnnotation the {@link javax.cache.annotation.CacheDefaults} annotation instance. @param genera...
public static String getCacheName(Method method, String methodCacheName, CacheDefaults cacheDefaultsAnnotation, boolean generate) { assertNotNull(method, "method parameter must not be null"); assertNotNull(methodCacheName, "methodCacheName parameter must not be null"); String cacheName = methodCacheN...
csn
Update an Asset. @param asset Asset @return {@link CMAAsset} result instance @throws IllegalArgumentException if asset is null. @throws IllegalArgumentException if asset's id is null. @throws IllegalArgumentException if asset's space id is null. @throws IllegalArgumentException if asset's version is null.
public CMAAsset update(CMAAsset asset) { assertNotNull(asset, "asset"); final String assetId = getResourceIdOrThrow(asset, "asset"); final String spaceId = getSpaceIdOrThrow(asset, "asset"); final String environmentId = asset.getEnvironmentId(); final Integer version = getVersionOrThrow(asset, "upda...
csn
Get a Stream of all labels of the specified project. @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @return a Stream of project's labels @throws GitLabApiException if any exception occurs
public Stream<Label> getLabelsStream(Object projectIdOrPath) throws GitLabApiException { return (getLabels(projectIdOrPath, getDefaultPerPage()).stream()); }
csn
Create an output buffer for each task. @return null if there aren't enough buffers left in the pool.
private List<BBContainer> getOutputBuffers(Collection<SnapshotTableTask> tableTasks, boolean noSchedule) { final int desired = tableTasks.size(); while (true) { int available = m_availableSnapshotBuffers.get(); //Limit the number of buffers used concurrently if (...
csn
// ComponentResources returns the v1.ResourceRequirements object needed for allocating a specified amount of the CPU
func ComponentResources(cpu string) v1.ResourceRequirements { return v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceName(v1.ResourceCPU): resource.MustParse(cpu), }, } }
csn
Append entry point strings representing the given Command objects. Args: dct: The dictionary to append with entry point strings. Each key will be a primary command with a value containing a list of entry point strings representing a Command. module_name: The name of the modu...
def _append_commands(dct, # type: typing.Dict[str, typing.Set[str]] module_name, # type: str commands # type:typing.Iterable[_EntryPoint] ): # type: (...) -> None """Append entry point strings representing the given Command objects. Args: ...
csn
// ConfigureCommand applies settings for a circuit
func ConfigureCommand(name string, config CommandConfig) { settingsMutex.Lock() defer settingsMutex.Unlock() timeout := DefaultTimeout if config.Timeout != 0 { timeout = config.Timeout } max := DefaultMaxConcurrent if config.MaxConcurrentRequests != 0 { max = config.MaxConcurrentRequests } volume := Def...
csn
Compare this output buffer to all the fields. This is a utility method that compares the record. @param record The target record. @return True if they are equal.
public boolean compareToBuffer(FieldList record) { boolean bBufferEqual = true; this.resetPosition(); // Start at the first field int iFieldCount = record.getFieldCount(); // Number of fields to read in for (int iFieldSeq = Constants.MAIN_FIELD; iFieldSeq <= iFieldCount + Constants...
csn
Syncs achievement data.
public function syncAchievements() { /** @var Collection $locked */ $locked = AchievementDetails::getUnsyncedByAchiever($this); $self = $this; $locked->each(function ($el) use ($self) { $progress = new AchievementProgress(); $progress->details()->associate($el...
csn
Returns the extension of a file name It basically returns everything after last dot. No validation is done. @param string $filename The file_name to work on @param bool $dot @return null|string The extension if found, `null` otherwise
public static function getExtension($filename = '', $dot = false) { if (empty($filename)) { return ''; } $exploded_file_name = explode('.', $filename); return (strpos($filename, '.') ? ($dot ? '.' : '').end($exploded_file_name) : null); }
csn
// Update takes other, a coordinate for another node, and rtt, a round trip // time observation for a ping to that node, and updates the estimated position of // the client's coordinate. Returns the updated coordinate.
func (c *Client) Update(node string, other *Coordinate, rtt time.Duration) (*Coordinate, error) { c.mutex.Lock() defer c.mutex.Unlock() if err := c.checkCoordinate(other); err != nil { return nil, err } // The code down below can handle zero RTTs, which we have seen in // https://github.com/hashicorp/consul/i...
csn
functional compare for two strings as ignore-case text
public static boolean equalsText(String s1, String s2) { if (s1 == null) { if (s2 != null) { return false; } } else { if (s2 == null) { return false; } } if ((s1 != null) && (s2 != null)) { s1 = s1.replaceAll("\\s", "").toLowerCase(); s2 = s2.replaceAll("\\s", "").toLowerCase(); if ...
csn
Set Load Areas with too high demand to aggregated type. Args ---- peak_current_branch_max: float Max. allowed current for line/cable
def set_nodes_aggregation_flag(self, peak_current_branch_max): """ Set Load Areas with too high demand to aggregated type. Args ---- peak_current_branch_max: float Max. allowed current for line/cable """ for lv_load_area in self.grid_district.lv_load_areas(...
csn
Wrap the callback so we can print the output. @param callable $callback The callback to wrap.
protected function commandCallback($callback) { return ( function ($output) use ($callback) { $this->output .= $output; if (is_callable($callback)) { return call_user_func($callback, $output); } } ); }
csn
Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that would be formatted together following standard formatting rules.
def _get_national_number_groups_without_pattern(numobj): """Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that would be formatted together following standard formatting rules.""" # This will be in the format +CC-D...
csn
Get Range Map by key or all from the actived sheet @param string|int $key Key set by addRow() @return string|array Range string | Key-Range array
public static function getRangeMap($key=NULL) { if ($key) { return isset(self::$_keyRangeMap[$key]) ? self::$_keyRangeMap[$key] : NULL; } else { return self::$_keyRangeMap; } }
csn
Creates a BooleanIsEqual expression from the given expression and constant. @param left The left expression. @param constant The constant to compare to. @return A new BooleanIsEqual binary expression.
public static BooleanIsEqual isEqual(ComparableExpression<Boolean> left, Boolean constant) { return new BooleanIsEqual(left, constant(constant)); }
csn
Have we actually done anything? @return bool
public function doneAnything() { $output = false; foreach( $this->status as $transaction => $transactionStatus ) { foreach( $transactionStatus as $status ) { $output = ( $output || $status === self::SUCCESS ); } } return $output; }
csn
// NewDatabase returns a database which stores data into the folder specified by the argument string.
func NewDatabase(path string) (Database, error) { storage, err := util.NewFileStorage(path) if err != nil { return nil, err } return NewDatabaseWithStorage(storage), nil }
csn
Returns the contents of the paste bin as a HTML string. @return {String} Get the contents of the paste bin.
function getPasteBinHtml() { var html = '', pasteBinClones, i, clone, cloneHtml; // Since WebKit/Chrome might clone the paste bin when pasting // for example: <img style="float: right"> we need to check if any of them contains some useful html. // TODO: Man o man is this ugly. WebKit is...
csn
Validate config and connect signals.
def ready(self): """Validate config and connect signals.""" super(ElasticAppConfig, self).ready() _validate_config(settings.get_setting("strict_validation")) _connect_signals()
csn
Run the subsampler on the input reads, storing the paths to the samples in the assembler_options hash.
def subsample_input if @options[:skip_subsample] logger.info "Skipping subsample step (--skip-subsample is on)" @options[:left_subset] = @options[:left] @options[:right_subset] = @options[:right] return end logger.info "Subsampling reads" seed = @options[:seed]...
csn
Return text position corresponding to given 'pos'. The text alignment in the bounding box should be set accordingly in order to have a good-looking layout. This corresponding text alignment can be obtained by 'get_text_alignment' or 'get_text_position_and_inner_alignment' function.
def get_text_position_in_ax_coord(ax, pos, scale=default_text_relative_padding): """Return text position corresponding to given 'pos'. The text alignment in the bounding box should be set accordingly in order to have a good-looking layout. This corresponding text alignment can be obtained by 'get_text_...
csn
Executes a set of filters against a method by taking a method's main implementation as a callback, and iteratively wrapping the filters around it. This, along with the `Filters` class, is the core of Lithium's filters system. This system allows you to "reach into" an object's methods which are marked as _filterable_, a...
protected function _filter($method, $params, $callback, $filters = []) { $message = '`' . __METHOD__ . '()` has been deprecated in favor of '; $message .= '`\lithium\aop\Filters::run()` and `::apply()`.'; trigger_error($message, E_USER_DEPRECATED); list(, $method) = explode('::', $method); foreach ($filter...
csn
Extract and parse every header of a SIP message.
function getHeader(data, headerStart) { // 'start' position of the header. let start = headerStart; // 'end' position of the header. let end = 0; // 'partial end' position of the header. let partialEnd = 0; // End of message. if (data.substring(start, start + 2).match(/(^\r\n)/)) { return -2; }...
csn
Returns a camel-cased version of a string. :param a_string: any :class:`str` object. Usage: >>> camel_case('foo_bar') "fooBar"
def camel_case(snake_str): """ Returns a camel-cased version of a string. :param a_string: any :class:`str` object. Usage: >>> camel_case('foo_bar') "fooBar" """ components = snake_str.split('_') # We capitalize the first letter of each component except the first one #...
csn
// ReplyFunc allows the developer to define the mock response via a custom function.
func (r *Request) ReplyFunc(replier func(*Response)) *Response { replier(r.Response) return r.Response }
csn
Computes the proportion of names in a factor quantile that were not in that quantile in the previous period. Parameters ---------- quantile_factor : pd.Series DataFrame with date, asset and factor quantile. quantile : int Quantile on which to perform turnover analysis. period: s...
def quantile_turnover(quantile_factor, quantile, period=1): """ Computes the proportion of names in a factor quantile that were not in that quantile in the previous period. Parameters ---------- quantile_factor : pd.Series DataFrame with date, asset and factor quantile. quantile : i...
csn
Close the websocket and connection, sending the specified code and message. The underlying socket object is _not_ closed, that is the responsibility of the initiator.
def close(self, code=1000, message=''): """ Close the websocket and connection, sending the specified code and message. The underlying socket object is _not_ closed, that is the responsibility of the initiator. """ try: message = self._encode_bytes(message) ...
csn
Get the InnerClassAccess in given class with the given method name. @param className the name of the class @param methodName the name of the access method @return the InnerClassAccess object for the method, or null if the method doesn't seem to be an inner class access
public InnerClassAccess getInnerClassAccess(String className, String methodName) throws ClassNotFoundException { Map<String, InnerClassAccess> map = getAccessMapForClass(className); return map.get(methodName); }
csn
Judges whether a table is a wide table or not by considering the width of the table @param tc the object of the table candidates
private void isWideTable(TableCandidate tc) { float docWidth = m_docInfo.getMaxX() - m_docInfo.getMinX(); if ((((tc.getCaptionX() > ((docWidth - 30) / (float) 4.0) + m_docInfo.getMinX())) && (tc.getCaptionX() < docWidth / 2.5)) || (tc.getCaptonEndX() - tc.getCaptionX() > docWidth / (float) 1.85)) { ...
csn
To override these settings @param mixed $callback can override $config(class of FabricateConfig) attributes @return void
public static function config($callback) { $instance = self::getInstance(); $callback($instance->config); $instance->registry->setAdaptor($instance->config->adaptor); if ($instance->config->faker == null) { $instance->config->faker = \Faker\Factory::create(); } ...
csn
// Close closes the file and run the function.
func (r *OnEOFReader) Close() error { err := r.Rc.Close() r.runFunc() return err }
csn
Sets the GSFontMaster alignmentZones from the postscript blue values.
def to_glyphs_blue_values(self, ufo, master): """Sets the GSFontMaster alignmentZones from the postscript blue values.""" zones = [] blue_values = _pairs(ufo.info.postscriptBlueValues) other_blues = _pairs(ufo.info.postscriptOtherBlues) for y1, y2 in blue_values: size = y2 - y1 if y...
csn
// formatBits computes the string representation of u in the given base. // If neg is set, u is treated as negative int64 value.
func formatBits(dst EncodingBuffer, u uint64, base int, neg bool) { if base < 2 || base > len(digits) { panic("strconv: illegal AppendInt/FormatInt base") } // 2 <= base && base <= len(digits) var a [64 + 1]byte // +1 for sign of 64bit value in base 2 i := len(a) if neg { u = -u } // convert bits if bas...
csn
Check in the HTML page the components to generate.
function checkHtmlComponents() { var graphHTMLContainer = d3.select("#" + graph.containerId); var taxonomyHTMLContainer = d3.select("#" + taxonomy.containerId); var queryHTMLContainer = d3.select("#" + queryviewer.containerId); var cypherHTMLContainer = d3.select("#" + cypherviewer.containerId); var...
csn
// DecodeVarint reads a varint-encoded integer from the slice. // It returns the integer and the number of bytes consumed, or // zero if there is not enough.
func DecodeVarint(buf []byte) (x uint32, n int) { if len(buf) < 1 { return 0, 0 } if buf[0] <= 0x80 { return uint32(buf[0]), 1 } var b byte for n, b = range buf { x = x << 7 x |= uint32(b) & 0x7F if (b & 0x80) == 0 { return x, n } } return x, n }
csn
// SearchProjectRoot return project root dir if possible, // searchFromDir will set to current working directory if empty
func SearchProjectRoot( searchFromDir string, mustExist []string, devExist []string, prodExist []string, ) (dir string, err error) { if searchFromDir == "" { if searchFromDir, err = os.Getwd(); err != nil { return } } if dir, err = filepath.Abs(searchFromDir); err != nil { return } for { switch dir...
csn
This function merges datasets into one set.
def merge(self, datasets=None, separate_datasets=False): """This function merges datasets into one set.""" self.logger.info("merging") if separate_datasets: warnings.warn("The option seperate_datasets=True is" "not implemented yet. Performing merging, but" ...
csn
Assign kwargs to the protobuf, and remove them from the kwargs dict.
def FilterArgsFromSemanticProtobuf(protobuf, kwargs): """Assign kwargs to the protobuf, and remove them from the kwargs dict.""" for descriptor in protobuf.type_infos: value = kwargs.pop(descriptor.name, None) if value is not None: setattr(protobuf, descriptor.name, value)
csn
// newCmdCertsUtility returns main command for certs phase
func newCmdCertsUtility() *cobra.Command { cmd := &cobra.Command{ Use: "certs", Aliases: []string{"certificates"}, Short: "Commands related to handling kubernetes certificates", } cmd.AddCommand(newCmdCertsRenewal()) return cmd }
csn
Convert a OpenCensus Distribution to a StackDriver Distribution
@VisibleForTesting static Distribution createDistribution(io.opencensus.metrics.export.Distribution distribution) { Distribution.Builder builder = Distribution.newBuilder() .setBucketOptions(createBucketOptions(distribution.getBucketOptions())) .setCount(distribution.getCount()) ...
csn
// Set sets the data.
func (db *DB) Set(key []byte, value []byte) error { if err := checkKeySize(key); err != nil { return err } else if err := checkValueSize(value); err != nil { return err } var err error key = db.encodeKVKey(key) t := db.kvBatch t.Lock() defer t.Unlock() t.Put(key, value) err = t.Commit() return err ...
csn
// Context returns the middleware context for the cilium health API
func (o *CiliumHealthAPI) Context() *middleware.Context { if o.context == nil { o.context = middleware.NewRoutableContext(o.spec, o, nil) } return o.context }
csn
Return a salt configuration dictionary, master or minion, as a yaml dump
def salt_config_to_yaml(configuration, line_break='\n'): ''' Return a salt configuration dictionary, master or minion, as a yaml dump ''' return salt.utils.yaml.safe_dump( configuration, line_break=line_break, default_flow_style=False)
csn
// String is a user-friendly representation of the handler
func (t *Trace) String() string { return fmt.Sprintf("addr=%v, reqHeaders=%v, respHeaders=%v", t.Addr, t.ReqHeaders, t.RespHeaders) }
csn
Trigger the user to perform a GET to the given URL with the given data. @param string $url @param array $data @return void
public function redirect(string $url, array $data = []) : void { $this->redirectUrl = $url; $this->redirectData = $data; }
csn
// processImportValues merges values from child to parent based on the chart's dependencies' ImportValues field.
func processImportValues(c *chart.Chart) error { reqs, err := LoadRequirements(c) if err != nil { return err } // combine chart values and empty config to get Values cvals, err := CoalesceValues(c, &chart.Config{}) if err != nil { return err } b := make(map[string]interface{}, 0) // import values from each...
csn
// PushContext performs a push to the remote. Returns NoErrAlreadyUpToDate if // the remote was already up-to-date, from the remote named as // FetchOptions.RemoteName. // // The provided Context must be non-nil. If the context expires before the // operation is complete, an error is returned. The context only affects ...
func (r *Repository) PushContext(ctx context.Context, o *PushOptions) error { if err := o.Validate(); err != nil { return err } remote, err := r.Remote(o.RemoteName) if err != nil { return err } return remote.PushContext(ctx, o) }
csn
Extract content formating related subset of widget settings.
def _es_content(settings): """ Extract content formating related subset of widget settings. """ return {k: settings[k] for k in (ConsoleWidget.SETTING_WIDTH, ConsoleWidget.SETTING_ALIGN, ConsoleWidget.SETTI...
csn
Sample the stack in a thread and print it at regular intervals.
def sample_stack_all(count=10, interval=0.1): """Sample the stack in a thread and print it at regular intervals.""" def print_stack_all(l, ll): l1 = list() l1.append("*** STACKTRACE - START ***") code = [] for threadId, stack in sys._current_frames().items(): sub_cod...
csn
Check if this message is compatible with passed call array. @param array $call A call array. @param boolean $withArgs Boolean indicating if matching should take arguments into account. @return boolean
public function match($call, $withArgs = true) { if (preg_match('/^::.*/', $call['name'])) { $call['static'] = true; $call['name'] = substr($call['name'], 2); } if (isset($call['static'])) { if ($call['static'] !== $this->_static) { return...
csn
Gets a list of modules. Note that this function can also be used to get themes. @param url_tpl: a string such as https://drupal.org/project/project_module?page=%s. %s will be replaced with the page number. @param per_page: how many items there are per page. @param css: the elements matched by th...
def modules_get(url_tpl, per_page, css, max_modules=2000, pagination_type=PT.normal): """ Gets a list of modules. Note that this function can also be used to get themes. @param url_tpl: a string such as https://drupal.org/project/project_module?page=%s. %s will be replaced with the page number. ...
csn
Destroys the cluster. It may not be re-started after being destroyed.
public synchronized void destroy() throws IOException { if (mState == State.DESTROYED) { return; } if (!mSuccess) { saveWorkdir(); } mCloser.close(); LOG.info("Destroyed cluster {}", mClusterName); mState = State.DESTROYED; }
csn
process processes all the files with clang and extracts all relevant nodes from the generated AST
def process(self): """ process processes all the files with clang and extracts all relevant nodes from the generated AST """ self.index = cindex.Index.create() self.headers = {} for f in self.files: if f in self.processed: continue ...
csn
Read the file
function(stats, callback) { fs.readFile(file, function(err, data) { callback(err, data, stats); }); }
csn
Process the request and return a response. @param \Symfony\Component\HttpFoundation\Request $request @param DelegateInterface $frame @return \Symfony\Component\HttpFoundation\Response
public function process(Request $request, DelegateInterface $frame) { $response = $frame->next($request); if ($response && $this->app->isInstalled() && $this->config->get('concrete.misc.basic_thumbnailer_generation_strategy') == 'now') { $responseStatusCode = (int) $response->getStatusC...
csn
Download SRA files for each GSM in series. .. warning:: Do not use parallel option (nproc > 1) in the interactive shell. For more details see `this issue <https://stackoverflow.com/questions/23641475/multiprocessing-working-in-python-but-not-in-ipython/23641560#23641560>`_ ...
def download_SRA(self, email, directory='series', filterby=None, nproc=1, **kwargs): """Download SRA files for each GSM in series. .. warning:: Do not use parallel option (nproc > 1) in the interactive shell. For more details see `this issue <https://stacko...
csn
Import essay type question @param array question question array from xml tree @return object question object
public function import_essay($question) { // Get common parts. $qo = $this->import_headers($question); // Header parts particular to essay. $qo->qtype = 'essay'; $qo->responseformat = $this->getpath($question, array('#', 'responseformat', 0, '#'), 'editor'); ...
csn
Tests to see if a PauliTerm or PauliSum is a scalar multiple of identity :param term: Either a PauliTerm or PauliSum :returns: True if the PauliTerm or PauliSum is a scalar multiple of identity, False otherwise :rtype: bool
def is_identity(term): """ Tests to see if a PauliTerm or PauliSum is a scalar multiple of identity :param term: Either a PauliTerm or PauliSum :returns: True if the PauliTerm or PauliSum is a scalar multiple of identity, False otherwise :rtype: bool """ if isinstance(term, PauliTerm): ...
csn
Set the UEFI shell start up @param uefi_shell_startup [String, Symbol] @param uefi_shell_startup_location [String, Symbol] @param uefi_shell_startup_url [String, Symbol] @raise [RuntimeError] if the request failed @return true
def set_uefi_shell_startup(uefi_shell_startup, uefi_shell_startup_location, uefi_shell_startup_url) new_action = { 'UefiShellStartup' => uefi_shell_startup, 'UefiShellStartupLocation' => uefi_shell_startup_location, 'UefiShellStartupUrl' => uefi_shell_startup_url } response = r...
csn
Convenience method for population self._data
def _add(self, isoel, col1, col2, method, meta): """Convenience method for population self._data""" self._data[method][col1][col2]["isoelastics"] = isoel self._data[method][col1][col2]["meta"] = meta # Use advanced slicing to flip the data columns isoel_flip = [iso[:, [1, 0, 2]]...
csn
Removes the beginning hyphen from the string, if any. @param string the string that will have the beginning hyphen removed @return the string without the beginning hyphen
private static String discardBeginningHyphen(String string) { String noHyphenString = string; if (string.startsWith("-")) { noHyphenString = string.substring(1); // Oh well, just throw away // the awful "-". No one // will ever notice... } return noHyphenString; }
csn
// AddNestedContext prepends a context to the field's path.
func (e *errInvalidParam) AddNestedContext(ctx string) { if len(e.nestedContext) == 0 { e.nestedContext = ctx } else { e.nestedContext = fmt.Sprintf("%s.%s", ctx, e.nestedContext) } }
csn
Goes through all related columns and sets the proper values for this row. @param \Illuminate\Database\Eloquent\Model $item @param array $outputRow
public function parseOnTableColumns($item, array &$outputRow) { if (method_exists($item, 'presenter')) { $item = $item->presenter(); } $columns = $this->columnFactory->getColumns(); $includedColumns = $this->columnFactory->getIncludedColumns($this->fieldFactory->...
csn
Updates the given parameter using the corresponding gradient and state. Mixed precision version. Parameters ---------- index : int The unique index of the parameter into the individual learning rates and weight decays. Learning rates and weight decay ...
def update_multi_precision(self, index, weight, grad, state): """Updates the given parameter using the corresponding gradient and state. Mixed precision version. Parameters ---------- index : int The unique index of the parameter into the individual learning ...
csn
Get the ID of the VRP a VM belongs to. If the VM does not belong to any VRP, the returned optional string will not be set to any value. @param vm VirtualMachine to get VRP of @return ID of the VRP @throws InvalidState @throws NotFound @throws RuntimeFault @throws RemoteException
public String getVRPofVM(VirtualMachine vm) throws InvalidState, NotFound, RuntimeFault, RemoteException { return getVimService().getVRPofVM(getMOR(), vm.getMOR()); }
csn
Get all calls Get all active calls for the current agent. @return ApiResponse&lt;InlineResponse200&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<InlineResponse200> getCallsWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = getCallsValidateBeforeCall(null, null); Type localVarReturnType = new TypeToken<InlineResponse200>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
csn
An edge is a table in a many to many relationship that is not a join. @param join join table @return edges for a join.
protected List<String> getEdges(String join) { List<String> results = new ArrayList<>(); for (Many2ManyAssociation a : many2ManyAssociations) { if (a.getJoin().equalsIgnoreCase(join)) { results.add(getMetaModel(a.getSourceClass()).getTableName()); results.add(...
csn
Calculates the noise properties of the volume supplied. This estimates what noise properties the volume has. For instance it determines the spatial smoothness, the autoregressive noise, system noise etc. Read the doc string for generate_noise to understand how these different types of noise interact. ...
def calc_noise(volume, mask, template, noise_dict=None, ): """ Calculates the noise properties of the volume supplied. This estimates what noise properties the volume has. For instance it determines the spatial smoothness, the autoregressive noise,...
csn
Generate a DataONE Exception PyXB object. The PyXB object supports directly reading and writing the individual values that may be included in a DataONE Exception.
def get_pyxb(self): """Generate a DataONE Exception PyXB object. The PyXB object supports directly reading and writing the individual values that may be included in a DataONE Exception. """ dataone_exception_pyxb = dataoneErrors.error() dataone_exception_pyxb.name = sel...
csn
Returns left end of interval for next root.
def next_root_lft last_root = nested_interval_scope.roots.order( rgtp: :desc, rgtq: :desc ).first raise Exception.new("Only one root allowed") if last_root.present? && !self.class.nested_interval.multiple_roots? last_root.try(:right) || 0.to_r end
csn
gen_txt_repr returns a "textual" representation of the provided headers. The output of this function is compatible with the input of parse_txt_hdrs. @param H2Frame|list of HPackHeaders hdrs: the list of headers to convert to textual representation # noqa: E501 @param bool: whet...
def gen_txt_repr(self, hdrs, register=True): # type: (Union[H2Frame, List[HPackHeaders]], Optional[bool]) -> str """ gen_txt_repr returns a "textual" representation of the provided headers. The output of this function is compatible with the input of parse_txt_hdrs. @para...
csn
Renders audio element @param array|string $src @param array $attrs @param string $error Error message can be overriden on demand @return string
public static function audio($src, array $attrs = array(), $error = null) { $node = new Node\Audio($src, $error); return $node->render($attrs); }
csn
For quickly searching if value exist.
function(value, currentKeyArray) { var type = typeof value; var pushAnElement = function() { var access = currentKeyArray.reduce(buildColumnName); if (mongoModelMap[access]) { return; } mongoModelMap[access] = access; mongoModel.push({ displayName: access, access: access,...
csn
Gets the operators value for this ListOperations. @return operators * The desired behavior of each element in the POJO list that this ListOperation corresponds to. This will contain the same number of elements as the corresponding List<>.
public com.google.api.ads.adwords.axis.v201809.cm.ListOperationsListOperator[] getOperators() { return operators; }
csn
// SetDeletionTimestamp sets the DeletionTimestamp field's value.
func (s *PhoneNumber) SetDeletionTimestamp(v time.Time) *PhoneNumber { s.DeletionTimestamp = &v return s }
csn
Add a comment associated to this function. @param string $comment
public function addComment($comment) { if ($this->comments === null) { $this->comments = []; } $this->comments[] = $comment; }
csn
// SetGlobalTableStatus sets the GlobalTableStatus field's value.
func (s *GlobalTableDescription) SetGlobalTableStatus(v string) *GlobalTableDescription { s.GlobalTableStatus = &v return s }
csn