query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
// NewCredentialsWithClient returns a pointer to a new Credentials object wrapping // the EC2RoleProvider. Takes a EC2Metadata client to use when connecting to EC2 // metadata service.
func NewCredentialsWithClient(client *ec2metadata.EC2Metadata, options ...func(*EC2RoleProvider)) *credentials.Credentials { p := &EC2RoleProvider{ Client: client, } for _, option := range options { option(p) } return credentials.NewCredentials(p) }
csn
An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. Max of 25 groups. :param groups_to_display: Unsubscribe groups to display :type groups_to_display: GroupsToDisplay, list(int), optional
def groups_to_display(self, value): """An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. Max of 25 groups. :param groups_to_display: Unsubscribe groups to display :type groups_to_display: GroupsToDisplay, list(int), optio...
csn
Actually replace specials in source. This method can be used by subclassing macros. @param source String to encode @return encoded Encoded string
protected String replace(String source) { StringBuffer tmp = new StringBuffer(); StringTokenizer stringTokenizer = new StringTokenizer(source, specialString, true); String previous = ""; while (stringTokenizer.hasMoreTokens()) { String current = stringTokenizer.nextToken(); if (special.conta...
csn
Helper function to create a KeyHook object for a given KeyBinding object. @param key the Minecraft KeyBinding object we are wrapping @return an ExternalAIKey object to replace the original Minecraft KeyBinding object
private KeyHook create(KeyBinding key) { if (key != null && key instanceof KeyHook) { return (KeyHook)key; // Don't create a KeyHook to replace this KeyBinding, since that has already been done at some point. // (Minecraft keeps a pointer to every KeyBinding that gets created...
csn
// OnCUserMessageCrosshairAngle registers a callback for EBaseUserMessages_UM_CrosshairAngle
func (c *Callbacks) OnCUserMessageCrosshairAngle(fn func(*dota.CUserMessageCrosshairAngle) error) { c.onCUserMessageCrosshairAngle = append(c.onCUserMessageCrosshairAngle, fn) }
csn
Set various flags to control rendering behavior.
function( value ) { var nametableFlag = value & 0x3, incrementFlag = value & 0x4, spriteFlag = value & 0x8, backgroundFlag = value & 0x10, sizeFlag = value & 0x20, nmiFlag = value & 0x80; this.background.setNameTable( nametableFlag ); this.increment = incrementFlag ? 32 : 1; this.sprites.baseTa...
csn
ColReorder provides column visibility control for DataTables @class ColReorder @constructor @param {object} dt DataTables settings object @param {object} opts ColReorder options
function( dt, opts ) { var oDTSettings; if ( $.fn.dataTable.Api ) { oDTSettings = new $.fn.dataTable.Api( dt ).settings()[0]; } // 1.9 compatibility else if ( dt.fnSettings ) { // DataTables object, convert to the settings object oDTSettings = dt.fnSettings(); } else if ( typeof dt === 'string' ) { // j...
csn
// GetKeyGeneratorCurrentNumber - Gets the auto increment number of an object store. Only meaningful when objectStore.autoIncrement is true. // securityOrigin - Security origin. // databaseName - Database name. // objectStoreName - Object store name. // Returns - currentNumber - the current value of key generator, to ...
func (c *IndexedDB) GetKeyGeneratorCurrentNumber(securityOrigin string, databaseName string, objectStoreName string) (float64, error) { var v IndexedDBGetKeyGeneratorCurrentNumberParams v.SecurityOrigin = securityOrigin v.DatabaseName = databaseName v.ObjectStoreName = objectStoreName return c.GetKeyGeneratorCurre...
csn
// GetCertIDFromTrust fetches the database id of the certificate in the trust relation with the given id. // Returns the mentioned id and any errors that happen. // It wraps the sql.ErrNoRows error in order to avoid passing not existing row errors to upper levels. // In that case it returns -1 with no error.
func (db *DB) GetCertIDFromTrust(trustID int64) (id int64, err error) { id = -1 err = db.QueryRow("SELECT cert_id FROM trust WHERE id=$1", trustID).Scan(&id) if err == sql.ErrNoRows { return -1, nil } return }
csn
Return user session @return \Sonic\Resource\Session
public function session () { if (!($this->session instanceof Session)) { $this->session = Session::singleton ($this->sessionID); } return $this->session; }
csn
List role assignments CLI Example: .. code-block:: bash salt '*' keystoneng.role_assignment_list
def role_assignment_list(auth=None, **kwargs): ''' List role assignments CLI Example: .. code-block:: bash salt '*' keystoneng.role_assignment_list ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.list_role_assignments(**kwargs)
csn
Throws an illegal argument exception indicating that the given value is not one of the expected types for the given attribute.
protected static IllegalArgumentException invalidType( String view, String attribute, Object value, Class<?>... expectedTypes) { Object expected = expectedTypes.length == 1 ? expectedTypes[0] : "one of " + Arrays.toString(expectedTypes); throw new IllegalArgumentException( "invalid type " ...
csn
Prepares an object map of variables of the correct type based on the provided variable definitions and arbitrary input. If the input cannot be coerced to match the variable definitions, a Error will be thrown. @param Schema $schema @param array $asts @param array $inputs @return array @throws \Exception
public static function getVariableValues(Schema $schema, array $asts, array $inputs) { $values = []; foreach ($asts as $ast) { $variable = $ast->get('variable')->get('name')->get('value'); $values[$variable] = self::getvariableValue($schema, $ast, isset($inputs[$variable]) ? ...
csn
Get real ip address. @return false|string
public static function ip() { $whip = new Whip( Whip::CLOUDFLARE_HEADERS | Whip::REMOTE_ADDR, [ Whip::CLOUDFLARE_HEADERS => self::CLOUDFLARE_IP, ] ); return $whip->getValidIpAddress(); }
csn
Initial external parameters are set here. The size if fixed.
protected void initParams(Database database, String baseFileName) { fileName = baseFileName + ".data.tmp"; this.database = database; fa = FileUtil.getDefaultInstance(); int cacheSizeScale = 10; cacheFileScale = 8; Error.printSystemOut("cache_size_scale...
csn
Calculates the minimum experience needed for the given level @param int $level @return int
public function levelToXp($level) { $xp = 0; for ($i = 1; $i < $level; $i++) { $xp += floor($i + 300 * pow(2, ($i / 7))); } $xp = floor($xp / 4); // Check if our value is above 200m, if so return 200m, otherwise our value return ($xp > 200000000 ? 20000...
csn
// ParsePodSpec is part of the ContainerEnvironProvider interface.
func (kubernetesEnvironProvider) ParsePodSpec(in string) (*caas.PodSpec, error) { spec, err := parseK8sPodSpec(in) if err != nil { return nil, errors.Trace(err) } return spec, spec.Validate() }
csn
finds a single entity @param string $documentId id of entity to find @param boolean $forceClear if we should clear the repository prior to fetching @throws NotFoundException @return Object
public function find($documentId, $forceClear = false) { if ($forceClear) { $this->repository->clear(); } $result = $this->repository->find($documentId); if (empty($result)) { throw new NotFoundException("Entry with id " . $documentId . " not found!"); ...
csn
Adds a record to this CSV file. @param key the key @param status the status @param masterValue the master value, may be <code>null</code> @param value the value
protected void add(String key, Status status, String masterValue, String value) { textNodeMap.put(key, new TextNode(key, status, masterValue, value)); }
csn
Gets the full message body to send to APN @return array
public function getMessageBody() { $payloadBody = $this->apsBody; if (!empty($this->customData)) { $payloadBody = array_merge($payloadBody, $this->customData); } return $payloadBody; }
csn
This implementation always returns true for this method. @param mixed $source the source data @param string $targetType the type to convert to. @return boolean true if this TypeConverter can convert from $source to $targetType, false otherwise. @api
public function canConvertFrom($source, $targetType) { return (preg_match(self::PATTERN_MATCH_SESSIONIDENTIFIER, $source) === 1) && ($targetType === $this->targetType); }
csn
Parse arguments to method, returning a dictionary.
def _parse_arguments(self, method, parameters): """Parse arguments to method, returning a dictionary.""" # TODO: Consider raising an exception if there are extra arguments. arguments = _fetch_arguments(self, method) arg_dict = {} errors = [] for key, properties in parameters: if key i...
csn
Run an array of coroutines :param corogen: a generator that generates coroutines :return: list or returns of the coroutines
async def runall(corogen): """ Run an array of coroutines :param corogen: a generator that generates coroutines :return: list or returns of the coroutines """ results = [] for c in corogen: result = await c results.append(result) return results
csn
Smart find, uses findBySlug or findById @param {*} param
function find(param) { var fn , asInt = Number(param); fn = isNaN(asInt) ? findBySlug : findById; fn.apply(null, arguments); }
csn
Execute command against the LaunchDarkly API. This command is generally not used directly, instead it is called as a part of running the ``playback()`` function. :param project: LaunchDarkly project key. :param environment: LaunchDarkly environment key. :param feature: LaunchDarkly feature key. ...
def update_ld_api(project: str, environment: str, feature: str, state: str): """ Execute command against the LaunchDarkly API. This command is generally not used directly, instead it is called as a part of running the ``playback()`` function. :param project: LaunchDarkly project key. :param en...
csn
// OrdererGroupRunner returns a runner that can be used to start and stop all // orderers in a network.
func (n *Network) OrdererGroupRunner() ifrit.Runner { members := grouper.Members{} for _, o := range n.Orderers { members = append(members, grouper.Member{Name: o.ID(), Runner: n.OrdererRunner(o)}) } return grouper.NewParallel(syscall.SIGTERM, members) }
csn
// Return a map of pool_update references to pool_update records for all pool_updates known to the system.
func (_class PoolUpdateClass) GetAllRecords(sessionID SessionRef) (_retval map[PoolUpdateRef]PoolUpdateRecord, _err error) { _method := "pool_update.get_all_records" _sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID) if _err != nil { return } _result, _err := _...
csn
Return available Packet datacenter locations. CLI Example: .. code-block:: bash salt-cloud --list-locations packet-provider salt-cloud -f avail_locations packet-provider
def avail_locations(call=None): ''' Return available Packet datacenter locations. CLI Example: .. code-block:: bash salt-cloud --list-locations packet-provider salt-cloud -f avail_locations packet-provider ''' if call == 'action': raise SaltCloudException( ...
csn
// GetIndexName returns the docker index server from a docker URL.
func GetIndexName(dockerURL string) string { index, _ := docker.SplitReposName(dockerURL) return index }
csn
Signs the message ``message`` using the secret key ``sk`` and returns the signed message. :param message: bytes :param sk: bytes :rtype: bytes
def crypto_sign(message, sk): """ Signs the message ``message`` using the secret key ``sk`` and returns the signed message. :param message: bytes :param sk: bytes :rtype: bytes """ signed = ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES) signed_len = ffi.new("unsigned l...
csn
// ScanColumn scans the columns and appends them to `ints`
func (ints *Ints) ScanColumn(colIdx int, colName string, rd types.Reader, n int) error { num, err := types.ScanInt64(rd, n) if err != nil { return err } *ints = append(*ints, num) return nil }
csn
Adds the given class hierarchy as resources. @param \ReflectionClass $class @return $this
public function addClassResource(\ReflectionClass $class) { if (!$this->trackResources) { return $this; } do { if (is_file($class->getFileName())) { $this->addResource(new FileResource($class->getFileName())); } } while ($class = $...
csn
Notifies all registered listeners, that the default value of a specific preference should be restored. @param preference The preference, whose default value should be restored, as an instance of the class {@link Preference}. The preference may not be null @param currentValue The current value of the preference, whose ...
private boolean notifyOnRestoreDefaultValueRequested(@NonNull final Preference preference, final Object currentValue) { boolean result = true; for (RestoreDefaultsListener listener : restoreDefaultsListeners) { result &= listener.onRe...
csn
// SetUser - sets a user info.
func (adm *AdminClient) SetUser(accessKey, secretKey string, status AccountStatus) error { if !auth.IsAccessKeyValid(accessKey) { return auth.ErrInvalidAccessKeyLength } if !auth.IsSecretKeyValid(secretKey) { return auth.ErrInvalidSecretKeyLength } data, err := json.Marshal(UserInfo{ SecretKey: secretKey,...
csn
Auxiliary function to plot discrete-violinplots.
def cat_hist(val, shade, ax, **kwargs_shade): """Auxiliary function to plot discrete-violinplots.""" bins = get_bins(val) binned_d, _ = np.histogram(val, bins=bins, normed=True) bin_edges = np.linspace(np.min(val), np.max(val), len(bins)) centers = 0.5 * (bin_edges + np.roll(bin_edges, 1))[:-1] ...
csn
// AddEncryption appends Encryption and is shorthand for AddEncryptionKey.
func (s Session) AddEncryption(e Encryption) Session { return s.AddEncryptionKey(e.Method, e.Key) }
csn
Return true if string after last separator is numeric @param pattern @return
public static final boolean isListItem(String pattern) { int idx = pattern.lastIndexOf(Lim); if (idx != -1) { try { Integer.parseInt(pattern.substring(idx+1)); return true; } catch (NumberFormatExceptio...
csn
Terminate instance with given EC2 ID or nametag.
def terminate(self, arg): """ Terminate instance with given EC2 ID or nametag. """ instance = self.get(arg) with self.msg("Terminating %s (%s): " % (instance.name, instance.id)): instance.rename("old-%s" % instance.name) instance.terminate() wh...
csn
Return a list of nodes that are relevant for the query. Parameters ---------- query_nodes : list[str] A list of node names to query for. relevance_network : str The UUID of the NDEx network to query relevance in. relevance_node_lim : int The number of top relevant nodes to r...
def _find_relevant_nodes(query_nodes, relevance_network, relevance_node_lim): """Return a list of nodes that are relevant for the query. Parameters ---------- query_nodes : list[str] A list of node names to query for. relevance_network : str The UUID of the NDEx network to query rel...
csn
Fail if any elements in ``sequence`` aren't separated by the expected ``fequency``. Parameters ---------- sequence : iterable frequency : timedelta msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be us...
def assertDateTimesFrequencyEqual(self, sequence, frequency, msg=None): '''Fail if any elements in ``sequence`` aren't separated by the expected ``fequency``. Parameters ---------- sequence : iterable frequency : timedelta msg : str If not provided, t...
csn
Processes the data structure produced by the parser. Args: parser_mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. date_time (dfdatetime.DateTimeValues): date and time values. syslog_tokens (dict[str, str]): na...
def Process(self, parser_mediator, date_time, syslog_tokens, **kwargs): """Processes the data structure produced by the parser. Args: parser_mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. date_time (dfdatetime....
csn
Generates a safe path to a node. Typically, a node will be id|Name of the node. @param string $id of the node. @param string $name of the node, will be URL encoded. @param string $root to append the node on, must be a result of this function. @return string path to the node.
protected function build_node_path($id, $name = '', $root = '') { $path = $id; if (!empty($name)) { $path .= '|' . urlencode($name); } if (!empty($root)) { $path = trim($root, '/') . '/' . $path; } return $path; }
csn
Determine whether the field should be included. @param Field $field @param array $previousValues @return bool
public function includeField(Field $field, array $previousValues) { foreach ($field->getConditions() as $previousField => $condition) { $previousFieldObject = $this->getField($previousField); if ($previousFieldObject === false || !isset($previousValues[$previousField]...
csn
Get files to purge.
def get_purge_files(root, output, output_schema, descriptor, descriptor_schema): """Get files to purge.""" def remove_file(fn, paths): """From paths remove fn and dirs before fn in dir tree.""" while fn: for i in range(len(paths) - 1, -1, -1): if fn == paths[i]: ...
csn
Return the status for a service. If the name contains globbing, a dict mapping service name to PID or empty string is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signatu...
def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to PID or empty string is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the ser...
csn
Extract the class name from the file at the given path. @param string $path @return string|null
public function findClass($path) { $namespace = null; $tokens = token_get_all(file_get_contents($path)); foreach ($tokens as $key => $token) { if ($this->tokenIsNamespace($token)) { $namespace = $this->getNamespace($key + 2, $tokens); } elseif ($this->...
csn
Displays a Bootstrap form buttons "default". @param array $args The arguments. @return string Returns the Bootstrap form button "Default".
public function bootstrapFormButtonDefaultFunction(array $args = []) { $cancelButton = $this->bootstrapFormButtonCancelFunction(["href" => ArrayHelper::get($args, "cancel_href")]); $submitButton = $this->bootstrapFormButtonSubmitFunction(); // Return the HTML. return implode(" ", [$can...
csn
Read fields from pdo source. @return array<int, array> @throws Exception\ConnectionException @throws \Soluble\Metadata\Exception\EmptyQueryException @throws \Soluble\Metadata\Exception\InvalidQueryException
protected function readFields(string $sql): array { if (trim($sql) === '') { throw new Exception\EmptyQueryException('Cannot read fields for an empty query'); } $sql = $this->getEmptiedQuery($sql); $stmt = $this->pdo->prepare($sql); if ($stmt->execute() !== true...
csn
Callback called after fetching the object
def _did_retrieve(self, connection): """ Callback called after fetching the object """ response = connection.response try: self.from_dict(response.data[0]) except: pass return self._did_perform_standard_operation(connection)
csn
Compose an error template. @param mixed $view @param array $data @param int $status @return \Illuminate\Http\Response
public function composeError($view, array $data = [], int $status = 404): Response { $engine = $this->view; $file = "errors.{$status}"; $view = $engine->exists($file) ? $engine->make($file, $data) : "{$status} Error"; return new Response($view, $status); }
csn
Get the log view of the requested analysis
def analysis_log_view(self): """Get the log view of the requested analysis """ service = self.get_analysis_or_service() if not self.can_view_logs_of(service): return None view = api.get_view("auditlog", context=service, request=self.request) view.update() ...
csn
Main function. Will be called on an ArrayDB or Array object. @q [Object]: the query. If it's the only one argument and it has a 'query' property, it's used to specify other arguments, e.g.: { query: <the query>, limit: <the limit>, offset: <the offset>, strict: <strict mode?>, reverse: <reversed query?> } @limit [Numbe...
function query( q, limit, offset ) { var i, _l, res, strict = true, reverse = false; if ( this.length === 0 || arguments.length === 0 ) { return []; } if ( typeof q === 'object' && q != null && 'query' in q && arguments.l...
csn
Setter for the target of the dependency class. This method is intend to set the target of the dependency class. @param string $target The target of the dependency class @author Benjamin Carl <opensource@clickalicious.de> @return Doozr_Di_Map_Fluent Instance of this class (for method chaining)
public function id($target) { if (null === $this->currentDependency) { throw new Doozr_Form_Service_Exception( sprintf('Please call className() before trying to set an Id via %s', __METHOD__) ); } return $this->target($target); }
csn
Purpose is to generate a neighboring decision variable value for a single decision variable value being perturbed by the DDS optimization algorithm. New DV value respects the upper and lower DV bounds. Coded by Bryan Tolson, Nov 2005. I/O variable definitions: x_cur - current decision variable (DV) value x_min - min D...
private double neigh_value(double x_cur, double x_min, double x_max, double r) { double ranval, zvalue, new_value; double work3, work2 = 0, work1 = 0; double x_range = x_max - x_min; // ------------ generate a standard normal random variate (zvalue) ------------------- // perturb cur...
csn
Launches a file using the operating system's standard launcher. Args: filename: file to launch raise_if_fails: raise any exceptions from ``subprocess.call(["xdg-open", filename])`` (Linux) or ``os.startfile(filename)`` (otherwise)? If not, exceptions are suppress...
def launch_external_file(filename: str, raise_if_fails: bool = False) -> None: """ Launches a file using the operating system's standard launcher. Args: filename: file to launch raise_if_fails: raise any exceptions from ``subprocess.call(["xdg-open", filename])`` (Linux) ...
csn
create new Context @param directory [String] directory to use as a base for finding partials @param data [Hash] include another latex file into the current template
def partial( template, data={} ) context = self.class.new( @directory, data ) ErbLatex::File.evaluate(Pathname.new(template), context.getBinding, @directory) end
csn
Set 'ForwardedDocumentId' value @param \AgentSIB\Diadoc\Api\Proto\Forwarding\ForwardedDocumentId $value
public function setForwardedDocumentId(\AgentSIB\Diadoc\Api\Proto\Forwarding\ForwardedDocumentId $value = null) { $this->ForwardedDocumentId = $value; }
csn
Returns values to include in the dropdown. @return string[]
protected function getDropdownValues() { if ($source = array_get($this->field->options(), 'value_source')) { $values = $this->getDropdownValuesFromSource($source); if (false !== $values) { return $values; } } return array_get($this->fiel...
csn
Returns a new wrapper instance with only the nodes of the current wrapper instance that match the provided predicate function. @param {ShallowWrapper} wrapper @param {Function} predicate @returns {ShallowWrapper}
function filterWhereUnwrapped(wrapper, predicate) { return wrapper.wrap(wrapper.getNodesInternal().filter(predicate).filter(Boolean)); }
csn
// VisitAll visits the command-line flags in lexicographical order, calling fn // for each. It visits all flags, even those not set.
func (s *Set) VisitAll(fn func(Option)) { sort.Sort(s.options) for _, opt := range s.options { fn(opt) } }
csn
Move to the "trim_horizon" or "latest" of the entire stream.
def _move_stream_endpoint(coordinator, position): """Move to the "trim_horizon" or "latest" of the entire stream.""" # 0) Everything will be rebuilt from DescribeStream. stream_arn = coordinator.stream_arn coordinator.roots.clear() coordinator.active.clear() coordinator.buffer.clear() # 1) ...
csn
// AddFlag does literally what its name says.
func (c *Command) AddFlag(newFlag Flag) { c.Flags = append(c.Flags, newFlag) }
csn
NORMALIZE QUERY SO IT CAN STILL BE JSON
def wrap(query, container, namespace): """ NORMALIZE QUERY SO IT CAN STILL BE JSON """ if is_op(query, QueryOp) or query == None: return query query = wrap(query) table = container.get_table(query['from']) schema = table.schema output = QueryO...
csn
Get all locales used by Blogs. @return array
public function getUsedLocales() { $queryBuilder = $this->createQueryBuilder('blog') ->select('DISTINCT(b_translation.locale) AS locale') ->join('blog.translations', 'b_translation'); $locales = []; foreach ($queryBuilder->getQuery()->getResult() as $locale) { ...
csn
resize the img element and the containing modal
function () { // get the window dimensions var windowWidth = $window.innerWidth; var windowHeight = $window.innerHeight; // calculate the max/min dimensions for the image var imageDimensionLimits = Lightbox.calculateImageDimensionLimits({ 'windowWidth': windowWidth, ...
csn
Return an array of stores and attach a language code to them, Varien_Object style @param string $langCode (optional) if passed, only stores using that langCode are returned. @return array of Mage_Core_Model_Store, keyed by StoreId. Each store has a new magic getter 'getLanguageCode()'
public function getStores($langCode = null) { $stores = array(); foreach (Mage::app()->getWebsites() as $website) { $stores = array_replace($stores, $this->getWebsiteStores($website, $langCode)); } return $stores; }
csn
// NewMetadata returns a new Metadata for a state backup archive. Only // the start time and the version are set.
func NewMetadata() *Metadata { return &Metadata{ FileMetadata: filestorage.NewMetadata(), // TODO(fwereade): 2016-03-17 lp:1558657 Started: time.Now().UTC(), Origin: Origin{ Version: jujuversion.Current, }, } }
csn
Write current upload chunk to file descriptor @todo It is not supported yet (callback missing in EventBuffer->write()) @param mixed $fd File destriptor @param callable $cb Callback @return boolean Success
public function writeChunkToFd($fd, $cb = null) { return false; // It is not supported yet (callback missing in EventBuffer->write()) if (!$this->curChunkSize) { return false; } $this->write($fd, $this->curChunkSize); $this->curChunkSize = null; return tru...
csn
Prepare the actual |anntools.SeasonalANN| object for calculations. Dispite all automated refreshings explained in the general documentation on class |anntools.SeasonalANN|, it is still possible to destroy the inner consistency of a |anntools.SeasonalANN| instance, as it stores its |annt...
def refresh(self) -> None: """Prepare the actual |anntools.SeasonalANN| object for calculations. Dispite all automated refreshings explained in the general documentation on class |anntools.SeasonalANN|, it is still possible to destroy the inner consistency of a |anntools.SeasonalANN| in...
csn
Determines the local locations for the distribution to use given the supplied configuration.
public LocalDistribution getDistribution(WrapperConfiguration configuration) { String baseName = getDistName(configuration.getDistribution()); String distName = removeExtension(baseName); String rootDirName = rootDirName(distName, configuration); String d...
csn
Move the screen page up through the history buffer. Page size is defined by ``history.ratio``, so for instance ``ratio = .5`` means that half the screen is restored from history on page switch.
def prev_page(self): """Move the screen page up through the history buffer. Page size is defined by ``history.ratio``, so for instance ``ratio = .5`` means that half the screen is restored from history on page switch. """ if self.history.position > self.lines and self.his...
csn
checks if parameter is empty Parameter is empty if its value is null or an empty string. @return bool
public function isEmpty() { return $this->isNull() || (is_array($this->value) && count($this->value) === 0) || $this->length() === 0; }
csn
Roll back the current transaction. Discard all statements executed since the transaction was begun.
def rollback(self): """Roll back the current transaction. Discard all statements executed since the transaction was begun. """ if hasattr(self.local, 'tx') and self.local.tx: tx = self.local.tx.pop() tx.rollback() self._flush_tables()
csn
Creates a SEPAAccount model from array. @param array $array @return SEPAAccount
protected function createModelFromArray(array $array) { $account = new SEPAAccount(); $account->setIban($array[1]); $account->setBic($array[2]); $account->setAccountNumber($array[3]); $account->setSubAccount($array[4]); $account->setBlz($array[6]); return $ac...
csn
Configure the state priorities @param priorities array of String. eg, STATE,priorityValue
public void configurePriorities(final String[] priorities) { // Set the non defined state in the property at 0 priority // Enumeration of existing state int priority; // Get the custom priority for (final String state : priorities) { // count the token separated by ",...
csn
// EnvInit is a middleware that allocates an environment map if it is nil. While // it's impossible in general to ensure that Env is never nil in a middleware // stack, in most common cases placing this middleware at the top of the stack // will eliminate the need for repetative nil checks.
func EnvInit(c *web.C, h http.Handler) http.Handler { return envInit{c, h} }
csn
Writes the contents of the report download response to the specified file. @param string $filePath the path to the file to which the contents are saved @throws RuntimeException in case the stream of this download result is read more than once
public function saveToFile($filePath) { $this->adsUtilityRegistry->addUtility( AdsUtility::REPORT_DOWNLOADER_FILE ); $this->reportDownloadResultDelegate->saveToFile($filePath); }
csn
Updates the config.xml of the project with the same ID with the XML provided @param {string} configXml @param {string} projectId @return {Promise<void>}
function updateConfigWithId(configXml, projectId) { return fetchProject(projectId) .then((project) => { return updateConfig(configXml, project); }) .catch((error) => { console.trace(error); throw error; }); }
csn
// handleImplicitFlow completes an implicit OAuth2 flow. The id_token and state will be contained // in the URL fragment. The javascript client first redirects to the callback URL, supplying the // state nonce for verification, as well as looking up the return URL. Once verified, the client // stores the id_token from ...
func (a *ClientApp) handleImplicitFlow(w http.ResponseWriter, r *http.Request, state string) { type implicitFlowValues struct { CookieName string ReturnURL string } vals := implicitFlowValues{ CookieName: common.AuthCookieName, } if state != "" { appState, err := a.verifyAppState(state) if err != nil { ...
csn
Convert a given language identifier into an ISO 639 Part 2 code, such as "eng" or "deu". This will accept language codes in the two- or three- letter format, and some language names. If the given string cannot be converted, ``None`` will be returned.
def iso_639_alpha3(code): """Convert a given language identifier into an ISO 639 Part 2 code, such as "eng" or "deu". This will accept language codes in the two- or three- letter format, and some language names. If the given string cannot be converted, ``None`` will be returned. """ code = norma...
csn
Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script
def script_template(state, host, template_filename, chdir=None, **data): ''' Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script ''' temp_file = state.get_temp_fil...
csn
Sets the client addresses that will be allowed to access the API. @param addrs the client addresses that will be allowed to access the API. @since 2.6.0
public void setPermittedAddresses(List<DomainMatcher> addrs) { if (addrs == null || addrs.isEmpty()) { ((HierarchicalConfiguration) getConfig()).clearTree(ADDRESS_KEY); this.permittedAddresses = Collections.emptyList(); this.permittedAddressesEnabled = Collections.empty...
csn
We expect status code 404 for a successful authentication, otherwise the endpoint will return 401 unauthorized @return boolean @throws \Http\Client\Exception
public function checkCredentials() { try { $requestHeader = array_merge_recursive($this->httpHeader, $this->config->getShopHeader()); $request = $this->messageFactory->createRequest( 'GET', $this->config->getBaseUrl() . '/engine/rest/merchants/', ...
csn
Generates the Express middleware to associate the allowed values to the route.
function generate(allows) { return function (req, res, next) { req.route.allows = allows; next(); }; }
csn
Checks if the given file is readable. If so, the file is read an unserialized. No further checking of the content is performed! If the file is not readable (e.g. it does not exist or has no read permissions) a \InvalidArgumentException is thrown. @param \SplFileInfo $file The file to read the serialized array from @r...
public function getAnswers(\SplFileInfo $file): array { if($file->isReadable()) { return unserialize($file->openFile()->fread($file->getSize())); } throw new \InvalidArgumentException(sprintf('Given file does not exist or is not readable: "%s"', $file->getPathname())); }
csn
Gets post body content @return string
public function getBody() { if (!isset($this->body)) { if (function_exists('http_get_request_body')) { $this->body = http_get_request_body(); } else { $this->body = @file_get_contents('php://input'); } } return $this->body; ...
csn
// periodicCheckKeyUpgrade is used to watch for key rotation events as a standby
func (c *Core) periodicCheckKeyUpgrade(ctx context.Context, stopCh chan struct{}) { opCount := new(int32) for { select { case <-time.After(keyRotateCheckInterval): count := atomic.AddInt32(opCount, 1) if count > 1 { atomic.AddInt32(opCount, -1) continue } go func() { // Bind locally, as t...
csn
Store the routing table in cache @return array $data @return int $ttl @return bool
public function dump($data, $ttl=null) { return $this->getCache() ->setNamespace(self::CACHE_NAMESPACE) ->set(self::CACHE_NAME, $data, $ttl === null ? self::DEFAULTTTL : intval($ttl)); }
csn
Invoke the underlying method, catching any InvocationTargetException and rethrowing the target exception
private Object invokeTarget(Object target, Method method, Object[] args) throws Throwable { Object returnValue; try { returnValue = method.invoke(target, args); } catch(InvocationTargetException ite) { throw ite.getTargetException(); } return returnValue; ...
csn
Import localities from a CSV file. :param path: Path to the CSV file containing the localities.
def import_localities(path, delimiter=';'): """ Import localities from a CSV file. :param path: Path to the CSV file containing the localities. """ creates = [] updates = [] with open(path, mode="r") as infile: reader = csv.DictReader(infile, delimiter=str(delimiter)) wit...
csn
Remove vendors without packages @param Storage $storage @param callable $callback function called after the vendor removal @return integer
public function cleanupVendors(Storage $storage, callable $callback = null) { $count = 0; $storageNode = $storage->node(); $query = new FlowQuery([$storageNode]); $query = $query->find('[instanceof Neos.MarketPlace:Vendor]'); foreach ($query as $vendor) { /** @var...
csn
Detect the group from the content type using cURL. @return null|string
protected function detectGroupFromContentType() { if (extension_loaded('curl')) { $this->getLogger()->warning('Attempting to determine asset group using cURL. This may have a considerable effect on application speed.'); $handler = curl_init($this->absolutePath); ...
csn
Set a comment for section or key :param str section: Section to add comment to :param str comment: Comment to add :param str key: Key to add comment to
def _set_comment(self, section, comment, key=None): """ Set a comment for section or key :param str section: Section to add comment to :param str comment: Comment to add :param str key: Key to add comment to """ if '\n' in comment: comment = '\n# '.j...
csn
Decodes a TTB-encoded TsRow into a list :param tsrow: the TTB decoded TsRow to decode. :type tsrow: TTB dncoded row :param tsct: the TTB decoded column types (atoms). :type tsct: list :param convert_timestamp: Convert timestamps to datetime objects :type tsobj: boolean ...
def decode_timeseries_row(self, tsrow, tsct, convert_timestamp=False): """ Decodes a TTB-encoded TsRow into a list :param tsrow: the TTB decoded TsRow to decode. :type tsrow: TTB dncoded row :param tsct: the TTB decoded column types (atoms). :type tsct: list :par...
csn
Log sent message @param string $recipient Recipient email address @param string $headers Email headers string @param string $email Email content @param string $method Send method @return void
protected function Log ($recipient, $headers, $email, $method) { // Set filename $filename = date ('Y-m-d_H-i-s') . '_' . $method . '_' . $recipient . '.txt'; // Log @file_put_contents (EMAIL_LOG_PATH . $filename, $headers . $email); }
csn
Render node children
def render_children(node: Node, **child_args): """Render node children""" for xml_node in node.xml_node.children: child = render(xml_node, **child_args) node.add_child(child)
csn
// Identify identifies the format and file type of the data in the ReadSeeker.
func Identify(r io.ReadSeeker) (format Format, fileType FileType, err error) { b, err := readBytes(r, 11) if err != nil { return } _, err = r.Seek(-11, io.SeekCurrent) if err != nil { err = fmt.Errorf("could not seek back to original position: %v", err) return } switch { case string(b[0:4]) == "fLaC": ...
csn
Set the current table @param string $table @return $this
public function setTable($table) { if(false === is_string($table)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($table)), E_USER_ERROR); } $this -> table = $table; return $this; }
csn
Process incoming messages from socket.
def _read_socket(self): """ Process incoming messages from socket. """ while True: base_bytes = self._socket.recv(BASE_SIZE) base = basemessage.parse(base_bytes) payload_bytes = self._socket.recv(base.payload_length) self._handle_message(packet.parse(base_...
csn
Sets the color scheme to use when printing help. @param colorScheme the new color scheme @see #execute(String...) @see #usage(PrintStream) @see #usage(PrintWriter) @see #getUsageMessage() @since 4.0
public CommandLine setColorScheme(Help.ColorScheme colorScheme) { this.colorScheme = Assert.notNull(colorScheme, "colorScheme"); for (CommandLine sub : getSubcommands().values()) { sub.setColorScheme(colorScheme); } return this; }
csn