query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
Concat collections. :param left: left collection :param rights: right collections, can be a DataFrame object or a list of DataFrames :param distinct: whether to remove duplicate entries. only available when axis == 0 :param axis: when axis == 0, the DataFrames are merged vertically, otherwise horizonta...
def concat(left, rights, distinct=False, axis=0): """ Concat collections. :param left: left collection :param rights: right collections, can be a DataFrame object or a list of DataFrames :param distinct: whether to remove duplicate entries. only available when axis == 0 :param axis: when axis =...
csn
Returns an array filled with TeamSpeak3_Node_Client objects. @param array $filter @return array | TeamSpeak3_Node_Client[]
public function clientList(array $filter = array()) { $clients = array(); foreach($this->getParent()->clientList() as $client) { if($client["cid"] == $this->getId()) { $clients[$client->getId()] = $client; } } return $this->filterList($clients, $filter); }
csn
// SendEmail sends a plain text email. Note that from must be a verified // address in the AWS control panel.
func (c *Config) SendEmail(from, to, subject, body string) (string, error) { data := make(url.Values) data.Add("Action", "SendEmail") data.Add("Source", from) data.Add("Destination.ToAddresses.member.1", to) data.Add("Message.Subject.Data", subject) data.Add("Message.Body.Text.Data", body) data.Add("AWSAccessKey...
csn
// Ping sends a Status.Ping message to the specified server and // returns true if healthy, false if an error occurred
func (p *ConnPool) Ping(dc string, addr net.Addr, version int, useTLS bool) (bool, error) { var out struct{} err := p.RPC(dc, addr, version, "Status.Ping", useTLS, struct{}{}, &out) return err == nil, err }
csn
Installs the default skills, updates all others
def install_defaults(self): """Installs the default skills, updates all others""" def install_or_update_skill(skill): if skill.is_local: self.update(skill) else: self.install(skill, origin='default') return self.apply(install_or_update_sk...
csn
Create a VM in Xen The configuration for this function is read from the profile settings. .. code-block:: bash salt-cloud -p some_profile xenvm01
def create(vm_): ''' Create a VM in Xen The configuration for this function is read from the profile settings. .. code-block:: bash salt-cloud -p some_profile xenvm01 ''' name = vm_['name'] record = {} ret = {} # fire creating event __utils__['cloud.fire_event']( ...
csn
Load realm users from properties file. The property file maps usernames to password specs followed by an optional comma separated list of role names. @param config Filename or url of user properties file. @exception IOException
public void load(String config) throws IOException { _config=config; if(log.isDebugEnabled())log.debug("Load "+this+" from "+config); Properties properties = new Properties(); Resource resource=Resource.newResource(config); properties.load(resource.getInputStream()); ...
csn
Convert supplied object to of action if possible.
protected Action toAction(Object item) { if (item instanceof Action) { return (Action) item; } else if (item instanceof String) { final String definition = (String) item; return new DefaultAction( definition + "@" + RANDOM.nextInt(), re...
csn
Adds available site routes to locals @param {express.Router} router @returns {Function}
function addAvailableRoutes(router) { return (req, res, next) => { const routes = router.stack .filter((r) => r.route && r.route.path) // grab only the defined routes (not api stuff) .map((r) => r.route.path); // pull out their paths res.locals.routes = routes; // and add them to the locals n...
csn
Converts the string to a time, using the given format for parsing. @param pString the string to convert. @param pType the type to convert to. PropertyConverter implementations may choose to ignore this parameter. @param pFormat the format used for parsing. PropertyConverter implementations may choose to ignore this pa...
public Object toObject(String pString, Class pType, String pFormat) throws ConversionException { if (StringUtil.isEmpty(pString)) return null; TimeFormat format; try { if (pFormat == null) { // Use system default format ...
csn
Renders a page given its id and path. @param string $id Page id @param string $path Page path @return Response Generated response @throws NotFoundHttpException Page not found
public function renderByIdAction($id, $path = '') { /** * @var PageInterface $page */ $page = $this ->pageRepository ->findOneById($id); return $this ->pageResponseTransformer ->createResponseFromPage( $page, ...
csn
Retrieves potential filename from the "Content-Disposition" header.
def filename_from_content_disposition(content_disposition) content_disposition = content_disposition.to_s escaped_filename = content_disposition[/filename\*=UTF-8''(\S+)/, 1] || content_disposition[/filename="([^"]*)"/, 1] || content_disposition[/filename=(\S+)/, 1] filename ...
csn
// restore is called when a new volume store is created. // It's primary purpose is to ensure that all drivers' refcounts are set based // on known volumes after a restart. // This only attempts to track volumes that are actually stored in the on-disk db. // It does not probe the available drivers to find anything that...
func (s *VolumeStore) restore() { var ls []volumeMetadata s.db.View(func(tx *bolt.Tx) error { ls = listMeta(tx) return nil }) ctx := context.Background() chRemove := make(chan *volumeMetadata, len(ls)) var wg sync.WaitGroup for _, meta := range ls { wg.Add(1) // this is potentially a very slow operation...
csn
Insert a send receive pair above the supplied scanNode. @param scanNode that needs to be distributed @return return the newly created receive node (which is linked to the new sends)
protected static AbstractPlanNode addSendReceivePair(AbstractPlanNode scanNode) { SendPlanNode sendNode = new SendPlanNode(); sendNode.addAndLinkChild(scanNode); ReceivePlanNode recvNode = new ReceivePlanNode(); recvNode.addAndLinkChild(sendNode); return recvNode; }
csn
// complete returns a Result for a completed healthcheck.
func complete(start time.Time, msg string, success bool, err error) *Result { // TODO(jsing): Make this clock skew safe. duration := time.Since(start) return &Result{msg, success, duration, err} }
csn
// Generates a "Variant 1" style UUID. This uses the machines MAC address, and // the time since 15 October 1582 in nanoseconds, divided by 100. // // This form of UUID is useful when you do not care if you leak MAC info, can // be sure that MAC addresses are not duplicated on your network, and can // be sure that no m...
func Variant1() (u UUID) { // Format is as follows // Time stamp (60 bits): aaabbbbcccccccc // clock id (16 bits): dddd // node id (48 bits): eeeeeeeeeeee // Output is: cccccccc-bbbb-1aaa-dddd-Eeeeeeeeeeee // where 1 is mandated, and E must have its MSB set. setupOnce.Do(setNodeName) // UUID uses time as nano...
csn
Should be the same as in common_attention, avoiding import.
def _mixed_precision_is_enabled(hparams): """Should be the same as in common_attention, avoiding import.""" activation_dtype = hparams.activation_dtype weight_dtype = hparams.weight_dtype return activation_dtype == tf.float16 and weight_dtype == tf.float32
csn
// Marks a port so that it will be released if this operation Commits
func (op *PortAllocationOperation) ReleaseDeferred(port int) { op.releaseDeferred = append(op.releaseDeferred, port) }
csn
Compare two sympy matrices that are not necessarily expanded. Calls `deep_compare_expressions` for each element in the matrices. Private function. Use `sympy_expressions_equal`. The former should be able to compare everything. :param matrix_left: :param matrix_right: :return:
def _sympy_matrices_equal(matrix_left, matrix_right): """ Compare two sympy matrices that are not necessarily expanded. Calls `deep_compare_expressions` for each element in the matrices. Private function. Use `sympy_expressions_equal`. The former should be able to compare everything. :param ma...
csn
Sends differences in the device state to the MicroBitPad as events.
def handle_input(self): """Sends differences in the device state to the MicroBitPad as events.""" difference = self.check_state() if not difference: return self.events = [] self.handle_new_events(difference) self.update_timeval() self.events.ap...
csn
List the names of the policies associated with the specified user. :type user_name: string :param user_name: The name of the user the policy is associated with. :type marker: string :param marker: Use this only when paginating results and only in follow-up reques...
def get_all_user_policies(self, user_name, marker=None, max_items=None): """ List the names of the policies associated with the specified user. :type user_name: string :param user_name: The name of the user the policy is associated with. :type marker: string :param mark...
csn
tryLog will attempt to write output to local stream. If unable, will kick-off re-open attempt @param string $msg @param int $tries
protected function tryLog($msg, $tries = 0) { if ((bool)@fwrite($this->stream, $msg)) return; if (0 < $tries) { trigger_error(sprintf('%s - Unable to log message: "%s"', get_called_class(), $tries, $msg)); return; } $this->attemptStreamRe...
csn
"format=y", and "tenant=z", if present, to rest parameters.
private String extractQueryParam(HttpServletRequest request, Map<String, String> restParams) { String query = request.getQueryString(); if (Utils.isEmpty(query)) { return ""; } StringBuilder buffer = new StringBuilder(query); // Split query component i...
csn
Return a string for the file, row and column of the term.
def file_ref(self): """Return a string for the file, row and column of the term.""" from metatab.util import slugify assert self.file_name is None or isinstance(self.file_name, str) if self.file_name is not None and self.row is not None: parts = split(self.file_name); ...
csn
Adds an RDF description of page links to the given RDF model. This method may be overridden in subclasses. @param model
public void addControls( final Model model ) { final URIBuilder pagedURL; try { pagedURL = new URIBuilder( fragmentURL ); } catch ( URISyntaxException e ) { throw new IllegalArgumentException( e ); } final Resource fragmentId = model.createRes...
csn
Registers an operation with a non-void return value.
@SuppressWarnings("unchecked") private void registerValueMethod(Class type, Method method) { executor.register(type, wrapValueMethod(method)); }
csn
// NewFilteredSampleInformer constructs a new informer for Sample type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server.
func NewFilteredSampleInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options v1.ListOptions) (run...
csn
Creates a D-dimensional grid of n linearly spaced points :param D: dimension of the grid :param n: number of points :param min_max: (min, max) list
def linear_grid(D, n = 100, min_max = (-100, 100)): """ Creates a D-dimensional grid of n linearly spaced points :param D: dimension of the grid :param n: number of points :param min_max: (min, max) list """ g = np.linspace(min_max[0], min_max[1], n) G = np.ones((n, D)) return G*...
csn
// NewSession creates a new session for specified query language. // It returns nil if language was not registered.
func NewSession(qs graph.QuadStore, lang string) Session { if l := languages[lang]; l.Session != nil { return l.Session(qs) } return nil }
csn
Return a binding site name from a given agent.
def get_binding_site_name(agent): """Return a binding site name from a given agent.""" # Try to construct a binding site name based on parent grounding = agent.get_grounding() if grounding != (None, None): uri = hierarchies['entity'].get_uri(grounding[0], grounding[1]) # Get highest leve...
csn
Return the transpose of this matrix @param Matrix $matrix The matrix whose transpose we wish to calculate @return Matrix @throws Exception
public static function transpose(Matrix $matrix) { $grid = call_user_func_array( 'array_map', array_merge( [null], $matrix->toArray() ) ); return new Matrix($grid); }
csn
Set the id for a peer. This peer, which previously had no id, has finished handshaking and now has an ID.
def idSet(peer) @peersById.each do |e| return if e.eql?(peer) end @peersById.pushToList(peer.trackerPeer.id, peer) end
csn
Copies the phar cacert from a phar into the temp directory. @param string $pharCacertPath Path to the phar cacert. For example: 'phar://aws.phar/Guzzle/Http/Resources/cacert.pem' @return string Returns the path to the extracted cacert file. @throws \RuntimeException Throws if the phar cacert cannot be found or the fi...
public static function extractPharCacert($pharCacertPath) { // Copy the cacert.pem file from the phar if it is not in the temp // folder. $certFile = sys_get_temp_dir() . '/guzzle-cacert.pem'; if (!file_exists($pharCacertPath)) { throw new \RuntimeException("Could not fi...
csn
Sets elements considered option by RSS spec
def set_optional_elements(self): """Sets elements considered option by RSS spec""" self.set_categories() self.set_copyright() self.set_generator() self.set_image() self.set_language() self.set_last_build_date() self.set_managing_editor() self.set_p...
csn
// Mark ticks the counters.
func (m *CountMeter) Mark(i int64) { m.mtx.Lock() defer m.mtx.Unlock() m.counters[0] += i m.overall += i }
csn
// safeDeletePublicIP deletes public IP by removing its reference first.
func (az *Cloud) safeDeletePublicIP(service *v1.Service, pipResourceGroup string, pip *network.PublicIPAddress, lb *network.LoadBalancer) error { // Remove references if pip.IPConfiguration is not nil. if pip.PublicIPAddressPropertiesFormat != nil && pip.PublicIPAddressPropertiesFormat.IPConfiguration != nil && l...
csn
Determines whether the JTS instance is recoverable. @return Indicates whether the JTS is recoverable.
public static final boolean isRecoverable() { if (tc.isEntryEnabled()) Tr.entry(tc, "isRecoverable"); // This JTS is recoverable if there is a server name. // boolean result = (serverName != null); // JTA2 - we are recoverable if we have a working log... // We ca...
csn
// SetServiceCache set the Services's cache with specific key and TTL
func (c *Context) SetServiceCache(key string, val interface{}, ttl time.Duration) error { expiresAt := time.Now().Add(ttl) serviceID := c.getServiceID() key = strings.ToLower(key) if val == nil { err := c.db.C("services_cache").Remove(bson.M{"service": serviceID, "key": key}) return err } _, err := c.db.C("...
csn
Download data for all users including shared data files. :param target_dir: This field is the target directory to download data. :param source: This field is the data source. It's default value is None. :param project_data: This field is data related to particular project. ...
def download_all(self, target_dir, source=None, project_data=False, memberlist=None, excludelist=None, max_size=MAX_SIZE_DEFAULT, id_filename=False): """ Download data for all users including shared data files. :param target_dir: This field is the targe...
csn
Reports an error with the given message and details and throws it. @param {sap.ui.model.odata.v4.ODataMetaModel} oMetaModel The OData metadata model @param {string} sMessage Error message @param {string} sDetails Error details @throws {Error}
function reportAndThrowError(oMetaModel, sMessage, sDetails) { var oError = new Error(sDetails + ": " + sMessage); oMetaModel.oModel.reportError(sMessage, sODataMetaModel, oError); throw oError; }
csn
Shutdown jersey server and release resources
@Override public void stop() { // Run jersey shutdown lifecycle if (container != null) { container.stop(); container = null; } // Destroy the jersey service locator if (jerseyHandler != null && jerseyHandler.getDelegate() != null) { Service...
csn
// NewDeployCommand returns a command to deploy applications.
func NewDeployCommand() modelcmd.ModelCommand { steps := []DeployStep{ &RegisterMeteredCharm{ PlanURL: romulus.DefaultAPIRoot, RegisterPath: "/plan/authorize", QueryPath: "/charm", }, &ValidateLXDProfileCharm{}, } deployCmd := &DeployCommand{ Steps: steps, } deployCmd.NewAPIRoot = func() (...
csn
Method to search vip's based on extends search. :param search: Dict containing QuerySets to find vip's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override def...
def search(self, **kwargs): """ Method to search vip's based on extends search. :param search: Dict containing QuerySets to find vip's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param ...
csn
// Close flushes all buffered spans and then kills open connections to LightStep, releasing resources
func (e *Exporter) Close(ctx context.Context) { e.tracer.Close(ctx) }
csn
module needs to be initialized by 'init'. Can be called with parser to use a pre-built parser, otherwise a simple default parser is created
def init(parser = None): """ module needs to be initialized by 'init'. Can be called with parser to use a pre-built parser, otherwise a simple default parser is created """ global p,subparsers if parser is None: p = argparse.ArgumentParser() else: p = parser arg = p.ad...
csn
Create a new DBInstance Read Replica. :type id: str :param id: Unique identifier for the new instance. Must contain 1-63 alphanumeric characters. First character must be a letter. May not end with a hyphen or contain two consecutive hyphens ...
def create_dbinstance_read_replica(self, id, source_id, instance_class=None, port=3306, availability_zone=None, auto_minor_version_upgrade=None): """ ...
csn
// isCheckpointPathExist only suitable for runc runtime now
func isCheckpointPathExist(runtime string, v interface{}) bool { if v == nil { return false } switch runtime { case plugin.RuntimeRuncV1, plugin.RuntimeRuncV2: if opts, ok := v.(*options.CheckpointOptions); ok && opts.ImagePath != "" { return true } case plugin.RuntimeLinuxV1: if opts, ok := v.(*runct...
csn
Jackson serialization only
@JsonProperty public Serializable getSerializable() { return new Serializable(type, value == null ? null : Utils.nativeValueToBlock(type, value)); }
csn
Method called to associate a ChildDealerFolder object to this object through the ChildDealerFolder foreign key attribute. @param ChildDealerFolder $l ChildDealerFolder @return \Dealer\Model\Dealer The current object (for fluent API support)
public function addDealerFolder(ChildDealerFolder $l) { if ($this->collDealerFolders === null) { $this->initDealerFolders(); $this->collDealerFoldersPartial = true; } if (!in_array($l, $this->collDealerFolders->getArrayCopy(), true)) { // only add it if the **same** ...
csn
Convenience method that returns the root of the Neo4j Api. @param string|null $conn The alias of the connection to use @return mixed
public function getRoot($conn = null) { $command = $this->invoke('simple_command', $conn); $httpResponse = $command->execute(); return $this->handleHttpResponse($httpResponse); }
csn
// NewNodeAlias creates a new instance of a NodeAlias. Verification is // performed on the passed string to ensure it meets the alias requirements.
func NewNodeAlias(s string) (NodeAlias, error) { var n NodeAlias if len(s) > 32 { return n, fmt.Errorf("alias too large: max is %v, got %v", 32, len(s)) } if !utf8.ValidString(s) { return n, &ErrInvalidNodeAlias{} } copy(n[:], []byte(s)) return n, nil }
csn
Save registration info locally so it can be retrieved when registration needs to be updated @param stdClass $formdata data from {@link site_registration_form}
public static function save_site_info($formdata) { $cleanhuburl = clean_param(HUB_MOODLEORGHUBURL, PARAM_ALPHANUMEXT); foreach (self::FORM_FIELDS as $field) { set_config('site_' . $field . '_' . $cleanhuburl, $formdata->$field, 'hub'); } // Even if the the connection with moo...
csn
// Sleeps randomly between n and m seconds.
func randSleep(n, m int) { r := m if m-n > 0 { r = rand.Intn(m-n) + n } time.Sleep(time.Duration(r) * time.Second) }
csn
Add a validation rule to the field @param \sndsgd\field\Rule $rule @return \sndsgd\Field The field instance
public function addRule(Rule $rule) { $classname = $rule->getClass(); if ($this->hasRule($classname) === true) { throw new Exception( "failed to add rule; the field {$this->name} already has an ". "instance of '$classname'" ); } ...
csn
Attempt to convert an array of data into an integer index. Parameters ---------- data : The data to convert. copy : Whether to copy the data or not. name : The name of the index returned. Returns ------- int_index : data converted to either an Int64Index...
def _try_convert_to_int_index(cls, data, copy, name, dtype): """ Attempt to convert an array of data into an integer index. Parameters ---------- data : The data to convert. copy : Whether to copy the data or not. name : The name of the index returned. R...
csn
// syncLocalKeys synchronizes all local keys with the kvstore
func (s *SharedStore) syncLocalKeys() error { // Create a copy of all local keys so we can unlock and sync to kvstore // without holding the lock s.mutex.RLock() keys := []LocalKey{} for _, key := range s.localKeys { keys = append(keys, key) } s.mutex.RUnlock() for _, key := range keys { if err := s.syncLo...
csn
// SetMinSeconds sets the MinSeconds field's value.
func (s *DurationRange) SetMinSeconds(v int64) *DurationRange { s.MinSeconds = &v return s }
csn
Tracing is also added for debugging purposes
protected void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { if (TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINER)) { LoggingUtil.SESSION_LOGGER_CORE.entering(CLASS_NAME, "setScheduledExecutorService", scheduledExecutor...
csn
Download scenese from Google Storage or Amazon S3 if bands are provided :param scenes: A list of scene IDs :type scenes: List :param bands: A list of bands. Default value is None. :type scenes: List :returns: (List) in...
def download(self, scenes, bands=None): """ Download scenese from Google Storage or Amazon S3 if bands are provided :param scenes: A list of scene IDs :type scenes: List :param bands: A list of bands. Default value is None. :type scene...
csn
handle layout command
def cmd_layout(self, args): '''handle layout command''' from MAVProxy.modules.lib import win_layout if len(args) < 1: print("usage: layout <save|load>") return if args[0] == "load": win_layout.load_layout(self.mpstate.settings.vehicle_name) eli...
csn
Creates a penalty satisfaction list Given a sampleSet and a bqm object, will create a binary list informing whether the penalties introduced during degree reduction are satisfied for each sample in sampleSet Args: response (:obj:`.SampleSet`): Samples corresponding to provided bqm bqm...
def penalty_satisfaction(response, bqm): """ Creates a penalty satisfaction list Given a sampleSet and a bqm object, will create a binary list informing whether the penalties introduced during degree reduction are satisfied for each sample in sampleSet Args: response (:obj:`.SampleSet`): S...
csn
// NewProperty node constructor
func NewProperty(Variable node.Node, Expr node.Node, PhpDocComment string) *Property { return &Property{ FreeFloating: nil, PhpDocComment: PhpDocComment, Variable: Variable, Expr: Expr, } }
csn
Normalize a node key @param mixed $key @return mixed
protected function normalizeKey($key) { if (null !== $this->keyNormalizer) { return call_user_func($this->keyNormalizer, $key); } return static::fixNodeName($key); }
csn
Returns the class associated to the class name given in parameter @param classname the class name @return the class
public static Class<?> getClass(String classname) { Class<?> clazz = null; try { clazz = Class.forName(classname); } catch (Exception e) { // Try the second approach } if (null == clazz) { Exception classNotFoundEx = null; try { clazz = Class.forName(classname, true, new ClassLoaderResourceUt...
csn
The read_log method returns a memory efficient generator for rows in a Bro log. Usage: rows = my_bro_reader.read_log(logfile) for row in rows: do something with row Args: logfile: The Bro Log file.
def read_log(self, logfile): """The read_log method returns a memory efficient generator for rows in a Bro log. Usage: rows = my_bro_reader.read_log(logfile) for row in rows: do something with row Args: logfile: The Bro Log file. """...
csn
Iterate over the defined Instancees.
def instances(self): """Iterate over the defined Instancees.""" definstance = lib.EnvGetNextInstance(self._env, ffi.NULL) while definstance != ffi.NULL: yield Instance(self._env, definstance) definstance = lib.EnvGetNextInstance(self._env, definstance)
csn
// NewMockLXDProfileUnit creates a new mock instance
func NewMockLXDProfileUnit(ctrl *gomock.Controller) *MockLXDProfileUnit { mock := &MockLXDProfileUnit{ctrl: ctrl} mock.recorder = &MockLXDProfileUnitMockRecorder{mock} return mock }
csn
Adds the heuristic costs for disk to the current heuristic disk costs for this Costs object. @param cost The heuristic disk cost to add.
public void addHeuristicDiskCost(double cost) { if (cost <= 0) { throw new IllegalArgumentException("Heuristic costs must be positive."); } this.heuristicDiskCost += cost; // check for overflow if (this.heuristicDiskCost < 0) { this.heuristicDiskCost = Double.MAX_VALUE; } }
csn
Configure's the internal Weave requirements. @return null
protected function configureContainerInternal() { $this->container->add( 'instantiator', function () { return function ($name) { return $this->container->get($name); }; } ); $this->container->add(\Weave\Middleware\Middleware::class) ->withArgument(\Weave\Middleware\MiddlewareAdaptorInter...
csn
// WatchResources watches for new versions of specific resources and sends them // into the given out channel. // // A call to this method blocks until a version greater than lastVersion is // available. Therefore, every call must be done in a separate goroutine. // A watch can be canceled by canceling the given contex...
func (w *ResourceWatcher) WatchResources(ctx context.Context, typeURL string, lastVersion uint64, node *envoy_api_v2_core.Node, resourceNames []string, out chan<- *VersionedResources) { defer close(out) watchLog := log.WithFields(logrus.Fields{ logfields.XDSVersionInfo: lastVersion, logfields.XDSClientNode: no...
csn
// ToStorageNode converts a Node structure to an exported gRPC StorageNode struct
func (s *Node) ToStorageNode() *StorageNode { node := &StorageNode{ Id: s.Id, SchedulerNodeName: s.SchedulerNodeName, Cpu: s.Cpu, MemTotal: s.MemTotal, MemUsed: s.MemUsed, MemFree: s.MemFree, AvgLoad: int64(s.Avgload), Status: ...
csn
Returns the part of the KSS Comment Block that contains the compatibility notice @return string
protected function getCompatibilityComment() { $compatibilityComment = null; foreach ($this->getCommentSections() as $commentSection) { // Compatible in IE6+, Firefox 2+, Safari 4+. // Compatibility: IE6+, Firefox 2+, Safari 4+. // Compatibility untested. ...
csn
Returns the integer attribute number for the passed attribute name.
private int attributeMap(String name) { Integer num = map.get(name); if (num == null) { return 0; } return num.intValue(); }
csn
// SetStatus sets data which will be used in the template execution, which is // previously set through NewStatusBar function.
func (bar *StatusBar) SetStatus(data interface{}) { bar.Lock() defer bar.Unlock() bar.status = data }
csn
Returns the value of the property. An IllegalArgument exception is thrown if the value is not an instance of java.lang.String.
private void taskProperty(RESTRequest request, RESTResponse response) { String taskID = RESTHelper.getRequiredParam(request, APIConstants.PARAM_TASK_ID); String property = RESTHelper.getRequiredParam(request, APIConstants.PARAM_PROPERTY); String taskPropertyText = getMultipleRoutingHelper().get...
csn
// Section 12.2.5.4.11.
func inCaptionIM(p *parser) bool { switch p.tok.Type { case StartTagToken: switch p.tok.DataAtom { case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Td, a.Tfoot, a.Thead, a.Tr: if p.popUntil(tableScope, a.Caption) { p.clearActiveFormattingElements() p.im = inTableIM return false } else { // Igno...
csn
// isSubsetOf returns true if all strings in s are also in t. // It assumes both sets are sorted.
func (s stringSet) isSubsetOf(t stringSet) bool { j := 0 for _, ss := range s { for j < len(t) && t[j] < ss { j++ } if j >= len(t) || t[j] != ss { return false } } return true }
csn
For a list of objects associated with a classification result, return the results as a DataFrame and dict of taxa info. Parameters ---------- field : {'readcount_w_children', 'readcount', 'abundance'} Which field to use for the abundance/count of a particular taxon in a samp...
def _collate_results(self, field=None): """For a list of objects associated with a classification result, return the results as a DataFrame and dict of taxa info. Parameters ---------- field : {'readcount_w_children', 'readcount', 'abundance'} Which field to use for ...
csn
Answers the field Ajax config for the receiver. @return array
protected function getFieldAjaxConfig() { $config = $this->getAjaxConfig(); if (!isset($config['url'])) { $config['url'] = $this->Link('search'); } return $config; }
csn
Returns all the public attributes of a module referenced by name. .. note:: The returned list *not* include subpackages or modules of `modname`,nor does it include private attributes (those that beginwith '_' or are not in `__all__`). Parameters ---------- modname : str ...
def find_mod_objs(modname, onlylocals=False): """ Returns all the public attributes of a module referenced by name. .. note:: The returned list *not* include subpackages or modules of `modname`,nor does it include private attributes (those that beginwith '_' or are not in `__all__`). ...
csn
Make a global commit of all changes made into request @throws ErrorException Generated when is not possible commit the changes
private static function commit() { $transaction = env('SIMPLES_TRANSACTION_CLASS', '\\Simples\\Persistence\\Transaction'); if (!class_exists($transaction)) { return; } if (!method_exists($transaction, 'commit')) { throw new ErrorException("The transaction com...
csn
// NewServerBitmap returns a bitmap that can hold 'count' bits.
func NewServerBitmap(count int) Bitmap { byteSize := (count + 7) / 8 return Bitmap{ data: make([]byte, byteSize), count: count, } }
csn
should we load this class as a check?
def should_we_load(kls): """ should we load this class as a check? """ # we don't load abstract classes if kls.__name__.endswith("AbstractCheck"): return False # and we only load checks if not kls.__name__.endswith("Check"): return False mro = kls.__mro__ # and the class need...
csn
Debugging output of a single SimRun slice. :param run_addr: Address of the SimRun. :return: A string representation.
def dbg_repr_run(self, run_addr): """ Debugging output of a single SimRun slice. :param run_addr: Address of the SimRun. :return: A string representation. """ if self.project.is_hooked(run_addr): ss = "%#x Hooked\n" % run_addr else: ...
csn
Returns the filters from the request. @param \Symfony\Component\HttpFoundation\Request $request @return array
protected function getFiltersFromRequest(Request $request) { return $this->extractValues($this->getValuesFromRequest($request), $this->getFilterPrefix()); }
csn
// PushDockerImageToECR pushes a local Docker image to an ECR repository
func PushDockerImageToECR(localImageTag string, ecrRepoName string, awsSession *session.Session, logger *logrus.Logger) (string, error) { stsSvc := sts.New(awsSession) ecrSvc := ecr.New(awsSession) // 1. Get the caller identity s.t. we can get the ECR URL which includes the // account name stsIdentityOutput, ...
csn
Compares the specified string to this string to determine if the specified string is a suffix. @param suffix the suffix to look for. @return {@code true} if the specified string is a suffix of this string, {@code false} otherwise. @throws NullPointerException if {@code suffix} is {@code null}.
public boolean endsWith(CharSequence suffix) { int suffixLen = suffix.length(); return regionMatches(length() - suffixLen, suffix, 0, suffixLen); }
csn
Output all assets using a generator @param {Generator} generator @param {Output} output @return {Promise<Output>}
function generateAssets(generator, output) { var assets = output.getAssets(); var logger = output.getLogger(); // Is generator ignoring assets? if (!generator.onAsset) { return Promise(output); } return Promise.reduce(assets, function(out, assetFile) { logger.debug.ln('copy ass...
csn
Set 'XmlTorg12Metadata' value @param \AgentSIB\Diadoc\Api\Proto\Documents\BilateralDocument\BasicDocumentMetadata $value
public function setXmlTorg12Metadata(\AgentSIB\Diadoc\Api\Proto\Documents\BilateralDocument\BasicDocumentMetadata $value = null) { $this->XmlTorg12Metadata = $value; }
csn
// New makes a new Mocker for the specified package directory.
func New(src, packageName string) (*Mocker, error) { srcPkg, err := pkgInfoFromPath(src, packages.LoadSyntax) if err != nil { return nil, fmt.Errorf("Couldn't load source package: %s", err) } pkgPath := srcPkg.PkgPath if len(packageName) == 0 { packageName = srcPkg.Name } else { mockPkgPath := filepath.Joi...
csn
Initialize test queue table. @throws Exception
private function createTable(): void { $statement = 'CREATE TABLE tests ( id INTEGER PRIMARY KEY, command TEXT NOT NULL UNIQUE, file_name TEXT NOT NULL, reserved_by_process_id INTEGER, ...
csn
Displays the screen to register a constant definition. @Action @Logged @param string $name @param string $selfedit
public function register($name = null, $defaultvalue = null, $value = null, $type = null, $comment = null, $fetchFromEnv = null, $selfedit = "false") { $this->selfedit = $selfedit; if ($selfedit == "true") { $this->moufManager = MoufManager::getMoufManager(); } else { $this->moufManager = MoufManag...
csn
callback to be executed when the call to stat completes or immediately if a stat object was passed as an argument
function doReadFile(stat) { if (stat.size > (FileUtils.MAX_FILE_SIZE)) { callback(FileSystemError.EXCEEDS_MAX_FILE_SIZE); } else { appshell.fs.readFile(path, encoding, function (_err, _data, encoding, preserveBOM) { if (_err) { ...
csn
Add a row to the table if it does not already exist @param cells String...
public void addRow(final String... cells){ final Row row = new Row((Object[]) cells); if(!rows.contains(row)){ rows.add(row); } }
csn
Insert or update nested dicts recursively into db tables
def _recursive_upsert(context, params, data): """Insert or update nested dicts recursively into db tables""" children = params.get("children", {}) nested_calls = [] for child_params in children: key = child_params.get("key") child_data_list = ensure_list(data.pop(key)) if isinsta...
csn
Build an instance of VariableInstance :param dict payload: Payload response from the API :returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
def get_instance(self, payload): """ Build an instance of VariableInstance :param dict payload: Payload response from the API :returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.Variabl...
csn
Register the callbacks we need to properly pop and push the app-local context for a component. Args: app (flask.Flask): The app who this context belongs to. This is the only sender our Blinker signal will listen to. key (str): The key on ``_CONTEXT_LOCALS`` that ...
def _context_callbacks(app, key, original_context=_CONTEXT_MISSING): """Register the callbacks we need to properly pop and push the app-local context for a component. Args: app (flask.Flask): The app who this context belongs to. This is the only sender our Blinker si...
csn
// SetClientTimeout sets the client request timeout
func (c *Client) SetClientTimeout(timeout time.Duration) { c.modifyLock.RLock() c.config.modifyLock.Lock() defer c.config.modifyLock.Unlock() c.modifyLock.RUnlock() c.config.Timeout = timeout }
csn
Set column properties from the specified column data. @param array column details @return void
protected function setColumnPropertiesFor($column) { $columnName = $column['name']; if ($column['searchable'] == 'true' && ! in_array($columnName, config('laratables.non_searchable_columns'))) { $this->searchColumns[] = $columnName; } if ($this->isCustomColumn($columnNa...
csn
Start the main console with the given width and height and return the root console. Call the consoles drawing functions. Then remember to use L{tdl.flush} to make what's drawn visible on the console. Args: width (int): width of the root console (in tiles) height (int): height of the r...
def init(width, height, title=None, fullscreen=False, renderer='SDL'): """Start the main console with the given width and height and return the root console. Call the consoles drawing functions. Then remember to use L{tdl.flush} to make what's drawn visible on the console. Args: width (in...
csn