query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
Returns the alias of a "expr AS alias" expression.
private static String alias(SqlNode item) { assert item instanceof SqlCall; assert item.getKind() == SqlKind.AS; final SqlIdentifier identifier = ((SqlCall) item).operand(1); return identifier.getSimple(); }
csn
Return cloud cache data for target. .. note:: Only works with glob matching tgt Glob Target to match minion ids provider Cloud Provider CLI Example: .. code-block:: bash salt-run cache.cloud 'salt*' salt-run cache.cloud glance.example.org provider=openstack
def cloud(tgt, provider=None): ''' Return cloud cache data for target. .. note:: Only works with glob matching tgt Glob Target to match minion ids provider Cloud Provider CLI Example: .. code-block:: bash salt-run cache.cloud 'salt*' salt-run cache.cloud gla...
csn
Call calculation functions and write stats file. This function takes a list of DataFrames, and will create a column for each in the tab separated output.
def write_stats(datadfs, outputfile, names=[]): """Call calculation functions and write stats file. This function takes a list of DataFrames, and will create a column for each in the tab separated output. """ if outputfile == 'stdout': output = sys.stdout else: output = open(out...
csn
Return a local dash app asset, served up through the Django static framework
def app_assets(request, **kwargs): 'Return a local dash app asset, served up through the Django static framework' get_params = request.GET.urlencode() extra_part = "" if get_params: redone_url = "/static/dash/assets/%s?%s" %(extra_part, get_params) else: redone_url = "/static/dash/as...
csn
Get the default environment in a list. @param array $environments An array of environments, keyed by ID. @return string|null
public function getDefaultEnvironmentId(array $environments) { // If there is only one environment, use that. if (count($environments) <= 1) { $environment = reset($environments); return $environment ? $environment->id : null; } // Check if there is only one...
csn
// buildInstanceSpec builds an instance spec from the provided args // and returns it. This includes pulling the simplestreams data for the // machine type, region, and other constraints.
func (env *environ) buildInstanceSpec(args environs.StartInstanceParams) (*instances.InstanceSpec, error) { arches := args.Tools.Arches() series := args.Tools.OneSeries() spec, err := findInstanceSpec( env, &instances.InstanceConstraint{ Region: env.cloud.Region, Series: series, Arches: arc...
csn
queue a delete on the solr index @param InputInterface $input @param OutputInterface $output @return int
protected function executeDelete(InputInterface $input, OutputInterface $output) { $this->doIndexCleanup($input->getArgument('id')); $this->doIndexCommit(); return 0; }
csn
Returns the reflected property. @param object|string $object @param string $name @return \ReflectionProperty
protected function getProperty($object, $name) { $class = new \ReflectionClass($object); while (!$class->hasProperty($name)) { $class = $class->getParentClass(); } return $class->getProperty($name); }
csn
// Mount is used to expose a logical backend at a given prefix, using a unique salt, // and the barrier view for that path.
func (r *Router) Mount(backend logical.Backend, prefix string, mountEntry *MountEntry, storageView *BarrierView) error { r.l.Lock() defer r.l.Unlock() // prepend namespace prefix = mountEntry.Namespace().Path + prefix // Check if this is a nested mount if existing, _, ok := r.root.LongestPrefix(prefix); ok && e...
csn
private _prepareExtension - replace property null to empty string return object with property or empty if extension didn't set
function _prepareExtension(extension) { var ext = {}; try { if ( ({}).toString.call(extension) === '[object Object]' ) { ext.userInfo = extension; ext = JSON.parse( JSON.stringify(ext).replace(/null/g, "\"\"") ); } else { throw new Error('Invalid type of "ext...
csn
Pre-flight ``Bucket`` name validation. :type name: str or :data:`NoneType` :param name: Proposed bucket name. :rtype: str or :data:`NoneType` :returns: ``name`` if valid.
def _validate_name(name): """Pre-flight ``Bucket`` name validation. :type name: str or :data:`NoneType` :param name: Proposed bucket name. :rtype: str or :data:`NoneType` :returns: ``name`` if valid. """ if name is None: return # The first and las characters must be alphanumer...
csn
Returns the query parameter values. @param param a parameter name @param ctx ctx @return a list of values
public static List<String> queryParams(String param, ContainerRequestContext ctx) { return ctx.getUriInfo().getQueryParameters().get(param); }
csn
This function indicates that an adhoc task was not completed successfully and should be retried. @param \core\task\adhoc_task $task
public static function adhoc_task_failed(adhoc_task $task) { global $DB; $delay = $task->get_fail_delay(); // Reschedule task with exponential fall off for failing tasks. if (empty($delay)) { $delay = 60; } else { $delay *= 2; } // Max of...
csn
Highlight an item in the results dropdown
function select_dropdown_item (item) { if(item) { if(selected_dropdown_item) { deselect_dropdown_item($(selected_dropdown_item)); } item.addClass($(input).data("settings").classes.selectedDropdownItem); selected_dropdown_item = item.ge...
csn
Asserts that an alert is present on the page. This information will be logged and recorded, with a screenshot for traceability and added debugging support. @param seconds the number of seconds to wait
public void alertPresent(double seconds) { try { double timeTook = popup(seconds); checkAlertPresent(seconds, timeTook); } catch (TimeoutException e) { checkAlertPresent(seconds, seconds); } }
csn
Set the tornado ioloop to use Defaults to tornado.ioloop.IOLoop.current() if set_ioloop() is not called or if ioloop=None. Must be called before start()
def set_ioloop(self, ioloop=None): """Set the tornado ioloop to use Defaults to tornado.ioloop.IOLoop.current() if set_ioloop() is not called or if ioloop=None. Must be called before start() """ ioloop = ioloop or tornado.ioloop.IOLoop.current() self.ioloop = ioloop ...
csn
Called when a new file or directory is created. Todo: This should be also used (extended from another class?) to watch for some special name file (like ".boussole-watcher-stop" create to raise a KeyboardInterrupt, so we may be able to unittest the watcher (click....
def on_created(self, event): """ Called when a new file or directory is created. Todo: This should be also used (extended from another class?) to watch for some special name file (like ".boussole-watcher-stop" create to raise a KeyboardInterrupt, so we may be...
csn
// NewListFirewallRulesCommand returns a command to list firewall rules.
func NewListFirewallRulesCommand() cmd.Command { cmd := &listFirewallRulesCommand{} cmd.newAPIFunc = func() (ListFirewallRulesAPI, error) { root, err := cmd.NewAPIRoot() if err != nil { return nil, errors.Trace(err) } return firewallrules.NewClient(root), nil } return modelcmd.Wrap(cmd) }
csn
Opens a connection to the MySQL Server and selects the specified database @access public @param string $dbname
function Connect() { $this->handler->Log(DBH_LOG_INFO, "Opening Connection..."); if ($this->dbopen) { $this->handler->Log(DBH_LOG_WARNING, "Connection Already Open"); } else { $this->adapter = new DataAdapter($this->csetting); try { $this->adapter->Open(); } catch (Exce...
csn
Export the current report to the specified output format @param stream output stream to write the exported report @throws ReportRunnerException if FluentReportRunner object is not correctly configured @return true if export process finished, or false if export process was stopped @throws NoDataFoundException if repor...
public boolean run(OutputStream stream) throws ReportRunnerException, NoDataFoundException { if ((stream == null) && !TABLE_FORMAT.equals(format) && !ALARM_FORMAT.equals(format) && !INDICATOR_FORMAT.equals(format) && !DISPLAY_FORMAT.equals(format)) { throw new ReportRunnerException("OutputStream cannot be nul...
csn
The number of leaf category nodes under this category. Returns 1 if this category has no sub-categories.
def leaf_count(self): """ The number of leaf category nodes under this category. Returns 1 if this category has no sub-categories. """ if not self._sub_categories: return 1 return sum(category.leaf_count for category in self._sub_categories)
csn
Validate the docstring for the given func_name Parameters ---------- func_name : function Function whose docstring will be evaluated (e.g. pandas.read_csv). Returns ------- dict A dictionary containing all the information obtained from validating the docstring.
def validate_one(func_name): """ Validate the docstring for the given func_name Parameters ---------- func_name : function Function whose docstring will be evaluated (e.g. pandas.read_csv). Returns ------- dict A dictionary containing all the information obtained from v...
csn
Build a notebook model from database record.
def _notebook_model_from_path(self, path, content=False, format=None): """ Build a notebook model from database record. """ model = base_model(path) model["type"] = "notebook" if self.fs.isfile(path): model["last_modified"] = model["created"] = self.fs.lstat(p...
csn
Pads a list of sequences such that they form a matrix. :param sequences: a list of sequences of varying lengths. :param padding: the value of padded cells. :param pad_len: the length of the maximum padded sequence.
def pad(cls, sequences, padding, pad_len=None): """ Pads a list of sequences such that they form a matrix. :param sequences: a list of sequences of varying lengths. :param padding: the value of padded cells. :param pad_len: the length of the maximum padded sequence. """ ...
csn
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ActiveDirectoryConfig.
func (in *ActiveDirectoryConfig) DeepCopy() *ActiveDirectoryConfig { if in == nil { return nil } out := new(ActiveDirectoryConfig) in.DeepCopyInto(out) return out }
csn
Readable if the jar is readable and the path refers to a file.
public boolean canRead(String path) { try { ZipEntry entry = getZipEntry(path); return entry != null && ! entry.isDirectory(); } catch (IOException e) { log.log(Level.FINE, e.toString(), e); return false; } }
csn
Start a transaction by turning autocommit off
public function startTransaction() { # Ensure we have a connection to start the transaction on $this->connect(); switch ($this->mode) { case "mysql": $result = $this->server->autocommit(false); break; case "postgres": ...
csn
// fillStringTemplate returns the string template filled
func fillStringTemplate(tmpl string, vars interface{}) (string, error) { myTemplate := template.Must(template.New("").Parse(tmpl)) data := new(bytes.Buffer) if err := myTemplate.Execute(data, vars); err != nil { return "", err } return data.String(), nil }
csn
Sets the content of the "main" text to the given value.
@Override public void setText(String text) { if (text == null) { if (headerElem != null) { removeChild(headerElem); headerElem = null; } return; } if (headerElem == null) { headerElem = Document.get().createHEle...
csn
Search for file give in "executable". If it is not found, we try the environment PATH. Returns either the absolute path to the found executable, or None if the executable couldn't be found.
def _search_for_executable(self, executable): """ Search for file give in "executable". If it is not found, we try the environment PATH. Returns either the absolute path to the found executable, or None if the executable couldn't be found. """ if os.path.isfile(executable...
csn
Get provider by key @param string $key @return object
public function getProvider($key) { if (!isset($this->providers[$key])) { return null; } return $this->providers[$key]; }
csn
Convert closure to an executable command. @return string
protected function serializeClosure(Closure $closure) { $closure = (new Serializer())->serialize($closure); $serializedClosure = \http_build_query([$closure]); $crunzRoot = CRUNZ_BIN; return PHP_BINARY . " {$crunzRoot} closure:run {$serializedClosure}"; }
csn
Returns the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask pattern conditions. @throws InvalidArgumentException if an invalid mask pattern was supplied
public static function getDataMaskBit(int $maskPattern, int $x, int $y) : bool { switch ($maskPattern) { case 0: $intermediate = ($y + $x) & 0x1; break; case 1: $intermediate = $y & 0x1; break; case 2: ...
csn
Filters and returns only valid IP objects.
def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value pas...
csn
Updates all documents that pass the filter with the update value Will upsert a new document if upsert=True and no document is filtered
def update_many(cls, filter, update, upsert=False): """ Updates all documents that pass the filter with the update value Will upsert a new document if upsert=True and no document is filtered """ return cls.collection.update_many(filter, update, upsert).raw_result
csn
Returns the underlying type of the tree if it is an annotated type, or the tree itself otherwise.
public static JCExpression typeIn(JCExpression tree) { switch (tree.getTag()) { case ANNOTATED_TYPE: return ((JCAnnotatedType)tree).underlyingType; case IDENT: /* simple names */ case TYPEIDENT: /* primitive name */ case SELECT: /* qualified name */ case TYPEA...
csn
Stores config parameter value in config @param string $name config parameter name @param mixed $value config parameter value
public function setConfigParam($name, $value) { if (isset($this->_aConfigParams[$name])) { $this->_aConfigParams[$name] = $value; } elseif (isset($this->$name)) { $this->$name = $value; } else { $this->_aConfigParams[$name] = $value; } }
csn
Try to read a value named ``key`` from the GET parameters.
def get_from_params(request, key): """Try to read a value named ``key`` from the GET parameters. """ data = getattr(request, 'json', None) or request.values value = data.get(key) return to_native(value)
csn
Fetch a request token from `self.request_token_url`.
def _get_request_token(self): """ Fetch a request token from `self.request_token_url`. """ params = { 'oauth_callback': self.get_callback_url() } response, content = self.client().request(self.request_token_url, "POST", b...
csn
Publishes a block version @param BlockOwnerInterface $block @param boolean|integer $version
public function publish(BlockInterface $block) { if (!($block instanceof BlockOwnerInterface) && !$block->isShared()) { throw new \Exception ('Can only publish blocks of type BlockOwner or shared'); } $this->killLoggableListener(); $this->killSoftDeletableListener(); ...
csn
filter a dir based on filter rules @param {String} dir @param {Array} rules @param {Array} root @param {Boolean} included @return {Promise}
function listdir(dir, rules, root, included) { return fs.readdir(dir) .then(function(files) { return when.all(files.map(function(f) { f = path.join(dir, f); return when(fs.stat(f), function(stat) { return { path: f, isDirectory: stat.isDirectory() }; }); ...
csn
fetch all option @param null $type @return array @throws DatabaseException @throws \Exception
public function fetchAll($type = null) { try { if ($this->res === false) { throw new DatabaseException(__METHOD__ . " No ressource has been given", MySQL::NO_RESSOURCE, MySQL::SEVERITY_DEBUG, __FILE__, __LINE__); } switch ($type) { case My...
csn
Generate a JWT token by specifying data and options @param array|null $data @param array $options @return string
public function generateToken($data, $options = array()) { return $this->encodeToken( $this->buildClaims($options + array('data' => $data)), $this->secret ); }
csn
Add or change a translation @param string $key Key of translation @param string $value Message of translation @param string $language Language to add translation
public function setTranslation($key, $value, $language) { $messageFile = $this->getMessageFile($language); $messageFile->setMessage($key, $value); $messageFile->save(); $this->messages[$language][$key] = $value; }
csn
Aborts all registered processes by joining with the parent process. Args: timeout (int): number of seconds to wait for processes to join, where None represents no timeout.
def _AbortJoin(self, timeout=None): """Aborts all registered processes by joining with the parent process. Args: timeout (int): number of seconds to wait for processes to join, where None represents no timeout. """ for pid, process in iter(self._processes_per_pid.items()): logger....
csn
Returns the data error for the given json doc in the list
public static DataError findErrorForDoc(List<DataError> list, JsonNode node) { for (DataError x : list) { if (x.entityData == node) { return x; } } return null; }
csn
visit an FunctionDef node to become astroid
def _visit_functiondef(self, cls, node, parent): """visit an FunctionDef node to become astroid""" self._global_names.append({}) node, doc = self._get_doc(node) newnode = cls(node.name, doc, node.lineno, node.col_offset, parent) if node.decorator_list: decorators = se...
csn
Execute current command on given resource. @param ApiResourceInterface $resource @return bool|mixed
protected function executeOn(ApiResourceInterface $resource) { $response = $this->execute($resource); if (method_exists($this, 'handleResponse')) { return $this->handleResponse($response, $resource); } return true; }
csn
// connectForReplication create a MySQL connection ready to use for replication.
func connectForReplication(cp *mysql.ConnParams) (*mysql.Conn, error) { params, err := dbconfigs.WithCredentials(cp) if err != nil { return nil, err } ctx := context.Background() conn, err := mysql.Connect(ctx, params) if err != nil { return nil, err } // Tell the server that we understand the format of e...
csn
Iterates through hash to clean up and normalize. @param mixed $item Reference to the view var value. @param string $key View var key. @return void
protected function _checkViewVars(&$item, $key) { if ($item instanceof Exception) { $item = (string)$item; } if (is_resource($item) || $item instanceof Closure || $item instanceof PDO ) { throw new RuntimeException(sprintf( ...
csn
Paginates through news items stored on the WeChat servers. @param int $offset - The offset from which to start showing items. @param int $count - The number of items to show. @return Paginated\NewsResultSet @throws Exception
public function paginateNews ($offset = 0, $count = 20) { $json = $this->paginate(MediaType::ARTICLE, $offset, $count); $resultSet = []; foreach ($json->item as $item) { $resultSet[] = $this->expandNews( $item->content->news_item, new Pagi...
csn
removes unfinished applications. Applications, which are in Draft Mode for more than 24 hours.
protected function cleanupAction() { $days = 2; $date = new \DateTime(); $date->modify("-$days day"); $filter = array("before" => $date->format("Y-m-d"), "isDraft" => 1); $applications = $this->fetchApplications($filter); $document...
csn
Adds kingside and queenside castling moves if legal :type: position: Board
def add_castle(self, position): """ Adds kingside and queenside castling moves if legal :type: position: Board """ if self.has_moved or self.in_check(position): return if self.color == color.white: rook_rank = 0 else: rook_ran...
csn
Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_in...
def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``...
csn
Get a stringified version of the param for use in error messages to indicate which param caused the error.
def get_error_hint(self, ctx): """Get a stringified version of the param for use in error messages to indicate which param caused the error. """ hint_list = self.opts or [self.human_readable_name] return ' / '.join('"%s"' % x for x in hint_list)
csn
Returns issues by keys from repository @param string[] $keys Issue keys @return Issue[]
private function getIssuesFromRepositoryByKeys(array $keys) { $issues = []; if ($keys) { $query = $this->issueQuery; $query['jql'] = 'key IN (' . implode(',', $keys) . ')'; $issues = $this->dispatcher->getIssues($query); } return $issues; }
csn
Exception method convenience wrapper.
def exception(message): """Exception method convenience wrapper.""" def decorator(method): """Inner decorator so we can accept arguments.""" @wraps(method) def wrapper(self, *args, **kwargs): """Innermost decorator wrapper - this is confusing.""" if self.message...
csn
Return config value @param string $configName - config parameter name were stored arrays od extended classes @return array
protected function getConfigValue($configName) { $db = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(); $config = \OxidEsales\Eshop\Core\Registry::getConfig(); $configKey = $config->getConfigParam('sConfigKey'); $select = "SELECT DECODE( `oxvarvalue` , " . $db->quote($configKey) . ...
csn
Write zero or more high-scoring segment pairs with the specified print writer. @param hsps zero or more high-scoring segment pairs to write, must not be null @param writer print writer to write high-scoring segment pairs with, must not be null
public static void write(final Iterable<HighScoringPair> hsps, final PrintWriter writer) { checkNotNull(hsps); checkNotNull(writer); for (HighScoringPair hsp : hsps) { writer.println(hsp.toString()); } }
csn
Returns whether an item with given name is defined. @param string $id The name of the item @return bool @throws InvalidArgumentException if the item name is invalid.
public function has($id) { $id = (string) $id; $this->validateName($id); return isset($this->items[$id]); }
csn
Main entry point for the program. @param {string} inputDir The directory in which to run the sample. @returns {Promise<void>}
async function main(inputDir) { const index = new Index(); try { const files = await readdir(inputDir); // Get a list of all files in the directory (filter out other directories) const allImageFiles = (await Promise.all( files.map(async file => { const filename = path.join(inputDir, file)...
csn
How much event data to process at once.
def _get_total_read_size(self): """How much event data to process at once.""" if self.read_size: read_size = EVENT_SIZE * self.read_size else: read_size = EVENT_SIZE return read_size
csn
Get a link of file >>> file_link = nd.getFileLink('/Picture/flower.png') :param full_path: The full path of file to get file link. Path should start and end with '/'. :return: ``Shared url`` or ``False`` if failed to share a file or directory through url
def getFileLink(self, full_path): """Get a link of file >>> file_link = nd.getFileLink('/Picture/flower.png') :param full_path: The full path of file to get file link. Path should start and end with '/'. :return: ``Shared url`` or ``False`` if failed to share a file or di...
csn
Validates a creator user ID @return boolean|null
protected function validateCreatorOrder() { $field = 'creator'; $value = $this->getSubmitted($field); if (!isset($value) && $this->isUpdating()) { $this->unsetSubmitted($field); return null; } if (empty($value)) { return null; } ...
csn
Returns the Helmholtz energy of an adsorbed molecule. Parameters ---------- temperature : numeric temperature in K electronic_energy : numeric energy in eV verbose : boolean whether to print ASE thermochemistry output Returns ...
def get_helmholtz_energy(self, temperature, electronic_energy=0, verbose=False): """Returns the Helmholtz energy of an adsorbed molecule. Parameters ---------- temperature : numeric temperature in K electronic_energy : numeric energy in eV verbose...
csn
Register routing.
protected function registerRouting() { $this->app->singleton('router', function ($app) { return new \Nano7\Http\Routing\Router($app); }); }
csn
// WithConsentChallenge adds the consentChallenge to the get consent request params
func (o *GetConsentRequestParams) WithConsentChallenge(consentChallenge string) *GetConsentRequestParams { o.SetConsentChallenge(consentChallenge) return o }
csn
Create a new matrix of specified dimensions, and filled with a specified value If the column argument isn't provided, then a square matrix will be created @param $value @param $rows @param null $columns @return Matrix @throws Exception
public static function createFilledMatrix($value, $rows, $columns = null) { if ($columns === null) { $columns = $rows; } $rows = Matrix::validateRow($rows); $columns = Matrix::validateColumn($columns); return new Matrix( array_fill( 0...
csn
Determines Selenium's 'By' object using Webdriver @return By: the Selenium object
public By defineByElement() { // consider adding strengthening By byElement = null; switch (type) { // determine which locator type we are interested in case XPATH: byElement = By.xpath(locator); break; case ID: byElement = ...
csn
Performs the given action into database. @param string $action datamapper function to execute @return bool
protected function execute(string $action) { if (!$this->getCollectionName()) { return false; } $options = [ 'writeConcern' => new WriteConcern($this->getWriteConcern()), ]; if ($result = $this->getDataMapper()->$action($this, $options)) { ...
csn
// GetManifest reads the manifest.json file in the public assets folder // and returns a map of its mappings. Returns error if manifest.json not found.
func GetManifest(publicPath string) (map[string]string, error) { manifestPath := filepath.Join(publicPath, "assets", "manifest.json") contents, err := ioutil.ReadFile(manifestPath) if err != nil { return nil, err } if len(contents) == 0 { return nil, errors.New("manifest.json is empty") } manifest := map[st...
csn
Returns the EntryView for the specified key. **Warning: This method returns a clone of original mapping, modifying the returned value does not change the actual value in the map. One should put modified value back to make changes visible to all nodes.** **Warning 2: This method uses __...
def get_entry_view(self, key): """ Returns the EntryView for the specified key. **Warning: This method returns a clone of original mapping, modifying the returned value does not change the actual value in the map. One should put modified value back to make changes visible to all...
csn
Retrieve all running workflow instances for a given name and version @param workflowName the name of the workflow @param version the version of the wokflow definition. Defaults to 1. @return the list of running workflow instances
public List<String> getRunningWorkflow(String workflowName, Integer version) { Preconditions.checkArgument(StringUtils.isNotBlank(workflowName), "Workflow name cannot be blank"); return getForEntity("workflow/running/{name}", new Object[]{"version", version}, new GenericType<List<String>>() { },...
csn
// Create new account
func (c *Client) CreateAccount(ctx context.Context, path string, payload *CreateAccountPayload, contentType string) (*http.Response, error) { req, err := c.NewCreateAccountRequest(ctx, path, payload, contentType) if err != nil { return nil, err } return c.Client.Do(ctx, req) }
csn
Returns the target with the given name. @param string $targetName The target name. @return InstallTarget The target. @throws NoSuchTargetException If the target does not exist.
public function get($targetName) { if (InstallTarget::DEFAULT_TARGET === $targetName) { return $this->getDefaultTarget(); } if (!isset($this->targets[$targetName])) { throw NoSuchTargetException::forTargetName($targetName); } return $this->targets[$t...
csn
Copies the extracted package to its final destination. @param bool $clearDestination Set to true to delete the destination directory if already exists. Defaults to false; an error will occur if destination already exists. Useful for upgrade tasks @return bool True on success
protected function _copyPackage($clearDestination = false) { $source = new Folder($this->_workingDir); $destinationPath = normalizePath(ROOT . "/plugins/{$this->_plugin['name']}/"); // allow to install from destination folder if ($this->_workingDir === $destinationPath) { ...
csn
This context manager decorated method allows cache-specific operations to be conducted before and after the execution of a job in worker.py
def open(self, job): """ This context manager decorated method allows cache-specific operations to be conducted before and after the execution of a job in worker.py """ # Create a working directory for the job startingDir = os.getcwd() self.localTempDir = makePubl...
csn
Update routine for the Firewall. Check if FW is already cfgd using the below function if self.fwid_attr[tenant_id].is_fw_complete() or is_fw_drvr_create_needed(): The above two functions will take care of whether FW is already cfgd or about to be cfgd in case of error. I...
def _fw_update(self, drvr_name, data): """Update routine for the Firewall. Check if FW is already cfgd using the below function if self.fwid_attr[tenant_id].is_fw_complete() or is_fw_drvr_create_needed(): The above two functions will take care of whether FW is already cf...
csn
Logs the request details. @param string $name The name of the operation. @param string $url API endpoint. @param array $headers Associative array of HTTP headers. @param string $body The XML body of the POST request.
private function logRequest($url, $name, $headers, $body) { if ($this->logger) { $this->logger->debug('Request', array( 'url' => $url, 'name' => $name, 'headers' => $headers, 'body' => $body )); } }
csn
Returns a list of objects from the database. The kwargs parameter can contain any number of attributes. Only objects which contain all listed attributes and in which all values match for all listed attributes will be returned.
def filter(self, **kwargs): """ Returns a list of objects from the database. The kwargs parameter can contain any number of attributes. Only objects which contain all listed attributes and in which all values match for all listed attributes will be returned. """ ...
csn
Handle a `POST` request. @param event the event @param channel the channel
@RequestHandler(patterns = "/form,/form/**") public void onPost(Request.In.Post event, IOSubchannel channel) { FormContext ctx = channel .associated(this, FormContext::new); ctx.request = event.httpRequest(); ctx.session = event.associated(Session.class).get(); event.setR...
csn
// SLALevel returns the current sla level for the model.
func (c *ModelConfigAPI) SLALevel() (params.StringResult, error) { result := params.StringResult{} level, err := c.backend.SLALevel() if err != nil { return result, errors.Trace(err) } result.Result = level return result, nil }
csn
Given one question_states record, return the answer recoded pointing to all the restored stuff for truefalse questions if not empty, answer is one question_answers->id
public function recode_legacy_state_answer($state) { $answer = $state->answer; $result = ''; if ($answer) { $result = $this->get_mappingid('question_answer', $answer); } return $result; }
csn
Generate a unique string
function () { var text = '' var regx = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' for (var idx = 0; idx < 8; idx++) { text = text + regx.charAt(Math.floor(Math.random() * regx.length)) } return text }
csn
// nameRequired returns true if the route requires a name.
func (app *App) nameRequired(r *http.Request) bool { route := mux.CurrentRoute(r) if route == nil { return true } routeName := route.GetName() return routeName != v2.RouteNameBase && routeName != v2.RouteNameCatalog }
csn
Writes the updated DocBlock to the model's file
public function writePhpDoc() { $fileContents = file_get_contents($this->getFileName()); $existingDoc = $this->getDocComment(); $serializer = new DocBlock\Serializer(); $newDoc = $serializer->getDocComment($this->classDocBlock); // PhpDocumentor inserts a space between @Sup...
csn
Read IPv6-Route unknown type data. Structure of IPv6-Route unknown type data [RFC 8200][RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type | Segments Left | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
def _read_data_type_none(self, length): """Read IPv6-Route unknown type data. Structure of IPv6-Route unknown type data [RFC 8200][RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type | Segments Left | ...
csn
If `text` is an SArray of strings or an SArray of lists of strings, the occurances of word are counted for each row in the SArray. If `text` is an SArray of dictionaries, the keys are tokenized and the values are the counts. Counts for the same word, in the same row, are added together. This outpu...
def count_words(text, to_lower=True, delimiters=DEFAULT_DELIMITERS): """ If `text` is an SArray of strings or an SArray of lists of strings, the occurances of word are counted for each row in the SArray. If `text` is an SArray of dictionaries, the keys are tokenized and the values are the counts. C...
csn
Save array as an include file. @param string $file @param array $array
private function saveArray($file, $array) { if (file_put_contents($file, '<?php return ' . var_export($array, true) . ';' . PHP_EOL, LOCK_EX) === false) { throw new RuntimeException('Plugin Manager is not able to save ' . $file . '.'); // @codeCoverageIgnore } }
csn
Create a new wrapper. @param string $url The URL. @param DataTablesProviderInterface $provider The provider. @param UserInterface $user The user. @return DataTablesWrapperInterface Returns a wrapper.
public static function newWrapper($url, DataTablesProviderInterface $provider, UserInterface $user = null) { $dtWrapper = new DataTablesWrapper(); $dtWrapper->getMapping()->setPrefix($provider->getPrefix()); $dtWrapper->setMethod($provider->getMethod()); $dtWrapper->setProvider($provide...
csn
Returns an array with the content between the position and limit of "buffer". This may be the buffer's backing array itself. Does not modify position or limit of the buffer.
private static byte[] toByteArray(final ByteBuffer buffer) { if (buffer.hasArray() && buffer.arrayOffset() == 0 && buffer.position() == 0 && buffer.array().length == buffer.limit()) { return buffer.array(); } else { final byte[] retVal = new byte[buffer.remaining()]; ...
csn
Terms must be one-per-line. Blank lines will be skipped.
def update_tracking_terms(self): """ Terms must be one-per-line. Blank lines will be skipped. """ import codecs with codecs.open(self.filename,"r", encoding='utf8') as input: # read all the lines lines = input.readlines() # build a set...
csn
// handleOverride handles an override notification.
func (sc *syncClient) handleOverride(sn *SyncNote) { log.V(1).Infoln("Sync client received override notification") if o := sn.VserverOverride; o != nil { sc.engine.queueOverride(o) } if o := sn.DestinationOverride; o != nil { sc.engine.queueOverride(o) } if o := sn.BackendOverride; o != nil { sc.engine.que...
csn
Create a new RecordingInstance :param unicode recording_status_callback_event: The recording status changes that should generate a callback :param unicode recording_status_callback: The callback URL on each selected recording event :param unicode recording_status_callback_method: The HTTP metho...
def create(self, recording_status_callback_event=values.unset, recording_status_callback=values.unset, recording_status_callback_method=values.unset, trim=values.unset, recording_channels=values.unset): """ Create a new RecordingInstance :param unico...
csn
Scan file specs and remove duplicates. @param files {Array} List of resolved file specs. @param duplicates {Array} Optional list of resolved file specs to consider duplicates.
function removeDuplicates(files, duplicates) { var i; var ret = []; var found = {}; if (duplicates) { for (i=0; i < duplicates.length; i++) { found[duplicates[i].dst] = true; } } for (i=0; i < files.length; i++) { if (...
csn
Sets a validator for the field @param string $validator_class_name The name of the validation class @param array $constraints Optional constraints @return self
public function setValidator(string $validator_class_name, array $constraints = []) : self { $this->validator = $validator_class_name; $this->constraints = $constraints; return $this; }
csn
List devices in the device catalog. Example usage, listing all registered devices in the catalog: .. code-block:: python filters = { 'state': {'$eq': 'registered' } } devices = api.list_devices(order='asc', filters=filters) for idx, d in enumerate(devices): ...
def list_devices(self, **kwargs): """List devices in the device catalog. Example usage, listing all registered devices in the catalog: .. code-block:: python filters = { 'state': {'$eq': 'registered' } } devices = api.list_devices(order='asc', filters=filters) ...
csn
omp parallel for
def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t): X,Y = t.shape pt = np.zeros((X,Y)) "omp parallel for" for i in range(X): for j in range(Y): for k in t: tmp = 6368.* np.arccos( np.cos(xmin+step*i)*np.cos( k[0] ) * np.cos((ymin+step*j)-k[1])+ np.sin...
csn
Get the exception message using the requested locale. @param locale locale for message @return exception message
public String getMessage(Locale locale) { if (getCause() != null) { String message = getShortMessage(locale) + ", " + translate("ROOT_CAUSE", locale) + " "; if (getCause() instanceof GeomajasException) { return message + ((GeomajasException) getCause()).getMessage(locale); } return message + getCause(...
csn
Get first direct child for name. @param node element to find children @param elementName name of child element @return found first child or null if not found @since 1.4.0
@Nullable public static Element findFirstElement(@Nonnull final Element node, @Nonnull final String elementName) { Element result = null; for (final Element l : Utils.findDirectChildrenForName(node, elementName)) { result = l; break; } return result; }
csn