comment
stringlengths
16
255
code
stringlengths
52
3.87M
// SetTextTemplate changes the TextHandler's text formatting template
func (h *TextHandler) SetTextTemplate(t *template.Template) { h.mtx.Lock() defer h.mtx.Unlock() h.template = t }
Make a separator for a prose-like list with `,` between items except for `, and` after the second to last item.
def _oxford_comma_separator(i, length): if length == 1: return None elif length < 3 and i == 0: return ' and ' elif i < length - 2: return ', ' elif i == length - 2: return ', and ' else: return None
Validates a directory according to the spec @param array $result @param string $spec @return bool
public function validateDirectory($result, $spec) { $spec = explode('|', $spec); $valid = false; foreach ($spec as $s) { if (isset($result[$s]) && $result[$s]) { $valid = true; break; } } return $valid; }
// Calls Output to println to the logger.
func (me *Logger) println(priority int, v ...interface{}) { if priority <= me.priority { me.setFullPrefix(priority) me.logger.Println(v...) } }
Delete a flow configuration @param flowId identifier of flow configuration to delete @throws RemoteInvocationException
public void deleteFlowConfigWithStateStore(FlowId flowId) throws RemoteInvocationException { LOG.debug("deleteFlowConfig and state store with groupName " + flowId.getFlowGroup() + " flowName " + flowId.getFlowName()); DeleteRequest<FlowConfig> deleteRequest = _flowconfigsV2RequestBuilders.delete() .id(new ComplexResourceKey<>(flowId, new FlowStatusId())).setHeader(DELETE_STATE_STORE_KEY, Boolean.TRUE.toString()).build(); ResponseFuture<EmptyRecord> response = _restClient.get().sendRequest(deleteRequest); response.getResponse(); }
Validate a SIRET: check its length (14), its final code, and pass it through the Luhn algorithm.
def siret_validator(): """""" def _validate_siret(form, field, siret=""): """SIRET validator. A WTForm validator wants a form and a field as parameters. We also want to give directly a siret, for a scripting use. """ if field is not None: siret = (field.data or "").strip() if len(siret) != 14: msg = _("SIRET must have exactly 14 characters ({count})").format( count=len(siret) ) raise validators.ValidationError(msg) if not all(("0" <= c <= "9") for c in siret): if not siret[-3:] in SIRET_CODES: msg = _( "SIRET looks like special SIRET but geographical " "code seems invalid (%(code)s)", code=siret[-3:], ) raise validators.ValidationError(msg) elif not luhn(siret): msg = _("SIRET number is invalid (length is ok: verify numbers)") raise validators.ValidationError(msg) return _validate_siret
Return a formatted ResponseJson @param array $mdata @param array $mergedData @param null $status @param string $msg @param array $headers @param int $options @return JsonResponse
public static function responseJsonMerge($mdata = array(), $mergedData, $status = null, $msg = '', array $headers = array(), $options = 0) { $response = self::responseMerge($mdata, $mergedData, $status, $msg); return Response::json($response, $response['status'], $headers, $options); }
// New returns a new fully initialized Config struct
func New() *Config { config := Config{} config.LogConfig.Config = make(map[string]string) config.ClusterOpts = make(map[string]string) return &config }
// parseBaggageInt64 searches for the target key in the BaggageItems // and parses it as an int64. It treats keys as case-insensitive.
func (c *spanContext) parseBaggageInt64(key string) int64 { var val int64 c.ForeachBaggageItem(func(k, v string) bool { if strings.ToLower(k) == strings.ToLower(key) { i, err := strconv.ParseInt(v, 10, 64) if err != nil { // TODO handle err return true } val = i return false } return true }) return val }
Returns the host address for an instance of Blob Store service from environment inspection.
def _get_host(self): if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) host = services['predix-blobstore'][0]['credentials']['host'] else: host = predix.config.get_env_value(self, 'host') # Protocol may not always be included in host setting if 'https://' not in host: host = 'https://' + host return host
// MarshalText implements encoding.TextMarshaler.
func (b Uint64) MarshalText() ([]byte, error) { buf := make([]byte, 2, 10) copy(buf, `0x`) buf = strconv.AppendUint(buf, uint64(b), 16) return buf, nil }
Calculate the complex acoth @returns {Complex}
function() { // acoth(c) = log((c+1) / (c-1)) / 2 var a = this['re']; var b = this['im']; if (a === 0 && b === 0) { return new Complex(0, Math.PI / 2); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).atanh() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ? -b / 0 : 0).atanh(); }
Set context value. Args: name (str): The name of the context value to change. value (Any): The new value for the selected context value
def set(self, name, value): curr = self.values parts = name.split('.') for i, part in enumerate(parts[:-1]): try: curr = curr.setdefault(part, {}) except AttributeError: raise InvalidPath('.'.join(parts[:i + 1])) try: curr[parts[-1]] = value except TypeError: raise InvalidPath('.'.join(parts[:-1]))
Marshall the given parameter object.
public void marshall(ListConnectorDefinitionVersionsRequest listConnectorDefinitionVersionsRequest, ProtocolMarshaller protocolMarshaller) { if (listConnectorDefinitionVersionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listConnectorDefinitionVersionsRequest.getConnectorDefinitionId(), CONNECTORDEFINITIONID_BINDING); protocolMarshaller.marshall(listConnectorDefinitionVersionsRequest.getMaxResults(), MAXRESULTS_BINDING); protocolMarshaller.marshall(listConnectorDefinitionVersionsRequest.getNextToken(), NEXTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
/* CRUD is syntactic sugar and a shortcut for registering all JSON API CRUD routes for a compatible storage implementation: Registers handlers for: GET /resource POST /resource GET /resource/:id DELETE /resource/:id PATCH /resource/:id */
func (res *Resource) CRUD(storage store.CRUD) { res.Get(storage.Get) res.Patch(storage.Update) res.Post(storage.Save) res.List(storage.List) res.Delete(storage.Delete) }
Applies a order_by clause :param str attribute: attribute to apply on :param bool ascending: should it apply ascending order or descending :rtype: Query
def order_by(self, attribute=None, *, ascending=True): attribute = self._get_mapping(attribute) or self._attribute if attribute: self._order_by[attribute] = None if ascending else 'desc' else: raise ValueError( 'Attribute property needed. call on_attribute(attribute) ' 'or new(attribute)') return self
{@inheritDoc} @return \Generator
public function iterable() { for ($i = $this->getStart(); $i < $this->getEnd(); $i += $this->step) { yield $i; } }
Pause all cluster nodes - ensure that we store data so that in the future the nodes can be restarted. :return: int - number of failures.
def _pause_all_nodes(self, max_thread_pool_size=0): failed = 0 def _pause_specific_node(node): if not node.instance_id: log.warning("Node `%s` has no instance id." " It is either already stopped, or" " never created properly. Not attempting" " to stop it again.", node.name) return None try: return node.pause() except Exception as err: log.error( "Could not stop node `%s` (instance ID `%s`): %s %s", node.name, node.instance_id, err, err.__class__) node.update_ips() return None nodes = self.get_all_nodes() thread_pool = self._make_thread_pool(max_thread_pool_size) for node, state in zip(nodes, thread_pool.map(_pause_specific_node, nodes)): if state is None: failed += 1 else: self.paused_nodes[node.name] = state return failed
Gets the auto-increment string. @return string @throws EngineException
public function getAutoIncrementString() { if ($this->isAutoIncrement() && IDMethod::NATIVE === $this->getTable()->getIdMethod()) { return $this->getPlatform()->getAutoIncrement(); } elseif ($this->isAutoIncrement()) { throw new EngineException(sprintf( 'You have specified autoIncrement for column "%s", but you have not specified idMethod="native" for table "%s".', $this->name, $this->getTable()->getName() )); } return ''; }
Store an item in the cache for a given number of minutes. @param string $key @param mixed $value @param float|int $minutes @return void
public function put($key, $value, $minutes) { $this->ensureCacheDirectoryExists($path = $this->path($key)); $this->files->put( $path, $this->expiration($minutes).serialize($value), true ); }
Create histogram collection with shared binnning.
def collection(data, bins=10, *args, **kwargs): """""" from physt.histogram_collection import HistogramCollection if hasattr(data, "columns"): data = {column: data[column] for column in data.columns} return HistogramCollection.multi_h1(data, bins, **kwargs)
Compute ground motion mean value.
def _compute_mean(self, C, mag, rjb): # line 1686 in hazgridXnga2.f ffc = self._compute_finite_fault_correction(mag) d = np.sqrt(rjb ** 2 + (C['c7'] ** 2) * (ffc ** 2)) # lines 1663, 1694-1696 in hazgridXnga2.f mean = ( C['c1'] + C['c2'] * (mag - 6.) + C['c3'] * ((mag - 6.) ** 2) - C['c4'] * np.log(d) - C['c6'] * d ) factor = np.log(rjb / 100.) idx = factor > 0 mean[idx] -= (C['c5'] - C['c4']) * factor[idx] return mean
Get all of posible transitions. @param StatableInterface $object @param string $objectIdentifier @return array|null @throws \SM\SMException
public function getPosibleTransitions(StatableInterface $object = null, $objectIdentifier = 'id') { if (empty($object)) { return; } $sm = $this->factory->get($object, $object->getStateGraph()); if (empty($sm)) { return; } $tasks = array(); $accessor = PropertyAccess::createPropertyAccessor(); foreach ($object->getStateTransitions() as $transition) { if ($sm->can($transition)) { $color = $this->getTransitionColor($transition); $tasks[] = array( 'id' => $accessor->getValue($object, $objectIdentifier), 'name' => $transition, 'color' => $color, 'graph' => $object->getStateGraph(), 'label' => $this->getTransition($transition), 'negative' => $this->isNegativeColor($color, 'transition'), 'positive' => $this->isPositiveColor($color, 'transition'), ); } } return empty($tasks) ? null : $tasks; }
Returns the ini file as an array. @param string $ini Full path to the ini file @return array List @throws \Cake\Core\Exception\Exception
public static function parseFile($ini) { if (!file_exists($ini)) { throw new Exception(sprintf('Missing TinyAuth config file (%s)', $ini)); } if (function_exists('parse_ini_file')) { $iniArray = parse_ini_file($ini, true); } else { $content = file_get_contents($ini); if ($content === false) { throw new Exception('Cannot load INI file.'); } $iniArray = parse_ini_string($content, true); } if (!is_array($iniArray)) { throw new Exception(sprintf('Invalid TinyAuth config file (%s)', $ini)); } return $iniArray; }
Get a single value in a position of the raster. @param coordinate the coordinate in which the value is read. @return the value read in the given coordinate.
public double getValueAt( Coordinate coordinate ) { if (geodata == null) { throw new IllegalArgumentException("The data have first to be read!"); } int[] coordinateToNearestRowCol = GrassLegacyUtilities.coordinateToNearestRowCol(inWindow, coordinate); if (coordinateToNearestRowCol != null) { int row = coordinateToNearestRowCol[0]; int col = coordinateToNearestRowCol[1]; if (row > 0 && row < geodata.length) { if (col > 0 && col < geodata[0].length) { return geodata[row][col]; } } } return HMConstants.doubleNovalue; }
@param int $row Current row @param array $tokens Tokens array @return array
protected function getTokenStrings(int $row, array $tokens): array { $pieces = []; foreach ($tokens as $key => $token) { if ($token['line'] > $row) { break; } if ($token['line'] < $row) { continue; } if ($this->verbose) { $type = $token['type']; $content = $token['content']; $content = '`' . str_replace(["\r\n", "\n", "\r", "\t"], ['\r\n', '\n', '\r', '\t'], $content) . '`'; unset($token['type']); unset($token['content']); $token['content'] = $content; $tokenList = []; foreach ($token as $k => $v) { if (is_array($v)) { if (empty($v)) { continue; } $v = json_encode($v); } $tokenList[] = $k . '=' . $v; } $pieces[] = $type . ' (' . $key . ') ' . implode(', ', $tokenList); } else { $pieces[] = $token['type']; } } if ($this->verbose) { return $pieces; } return [implode(' ', $pieces)]; }
Adds a default {@link SizeOfEngine} configuration, that limits the max object size, to the returned builder. @param size the max object size @param unit the max object size unit @return a new builder with the added configuration
public CacheManagerBuilder<T> withDefaultSizeOfMaxObjectSize(long size, MemoryUnit unit) { DefaultSizeOfEngineProviderConfiguration configuration = configBuilder.findServiceByClass(DefaultSizeOfEngineProviderConfiguration.class); if (configuration == null) { return new CacheManagerBuilder<>(this, configBuilder.addService(new DefaultSizeOfEngineProviderConfiguration(size, unit, DEFAULT_OBJECT_GRAPH_SIZE))); } else { ConfigurationBuilder builder = configBuilder.removeService(configuration); return new CacheManagerBuilder<>(this, builder.addService(new DefaultSizeOfEngineProviderConfiguration(size, unit, configuration .getMaxObjectGraphSize()))); } }
// Required by http.Handler interface. This method is invoked by the // http server and will handle all page routing
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) { r.RLock() defer r.RUnlock() //wrap the response writer in our custom interface w := &responseWriter{writer: rw, Router: r} //find a matching Route for _, route := range r.routes { //if the methods don't match, skip this handler //i.e if request.Method is 'PUT' Route.Method must be 'PUT' if req.Method != route.method { continue } //check if Route pattern matches url if !route.regex.MatchString(req.URL.Path) { continue } //get submatches (params) matches := route.regex.FindStringSubmatch(req.URL.Path) //double check that the Route matches the URL pattern. if len(matches[0]) != len(req.URL.Path) { continue } //create the http.Requests context c := NewContext(req) //add url parameters to the context for i, match := range matches[1:] { c.Params.Set(route.params[i], match) } //execute middleware filters for _, filter := range r.filters { filter(w, req) if w.started { return } } //invoke the request handler route.handler(w, req) return } //if no matches to url, throw a not found exception if w.started == false { http.NotFound(w, req) } }
Computes the area under the app curve.
def app_score(self): # compute curve precisions, pct_pred_pos, taus = self.precision_pct_pred_pos_curve(interval=False) # compute area app = 0 total = 0 for k in range(len(precisions)-1): # read cur data cur_prec = precisions[k] cur_pp = pct_pred_pos[k] cur_tau = taus[k] # read next data next_prec = precisions[k+1] next_pp = pct_pred_pos[k+1] next_tau = taus[k+1] # approximate with rectangles mid_prec = (cur_prec + next_prec) / 2.0 width_pp = np.abs(next_pp - cur_pp) app += mid_prec * width_pp total += width_pp return app
factor: relative length (1->no change, 2-> double, 0.5:half)
def resize(line, factor): a = angle(line) mx, my = middle(line) d = length(line) * factor * 0.5 dx = cos(a) * d dy = sin(a) * d return mx - dx, my - dy, mx + dx, my + dy
Print all configuration parameters to the log.
private void logParams(String header) { m_logger.debug(header); for (String paramName : m_serviceParamMap.keySet()) { Object paramValue = m_serviceParamMap.get(paramName); logParam(paramName, paramValue, " "); } }
// Generate accepts a path to an app.json file and generates a template from it
func (g *Generator) Generate(body []byte) (*templatev1.Template, error) { appJSON := &AppJSON{} if err := json.Unmarshal(body, appJSON); err != nil { return nil, err } klog.V(4).Infof("app.json: %#v", appJSON) name := g.Name if len(name) == 0 && len(g.LocalPath) > 0 { name = filepath.Base(g.LocalPath) } template := &templatev1.Template{} template.Name = name template.Annotations = make(map[string]string) template.Annotations["openshift.io/website"] = appJSON.Website template.Annotations["k8s.io/display-name"] = appJSON.Name template.Annotations["k8s.io/description"] = appJSON.Description template.Annotations["tags"] = strings.Join(appJSON.Keywords, ",") template.Annotations["iconURL"] = appJSON.Logo // create parameters and environment for containers allEnv := make(app.Environment) for k, v := range appJSON.Env { if v.EnvVar != nil { allEnv[k] = fmt.Sprintf("${%s}", k) } } envVars := allEnv.List() for _, v := range envVars { env := appJSON.Env[v.Name] if env.EnvVar == nil { continue } e := env.EnvVar displayName := v.Name displayName = strings.Join(strings.Split(strings.ToLower(displayName), "_"), " ") displayName = strings.ToUpper(displayName[:1]) + displayName[1:] param := templatev1.Parameter{ Name: v.Name, DisplayName: displayName, Description: e.Description, Value: e.Value, } switch e.Generator { case "secret": param.Generate = "expression" param.From = "[a-zA-Z0-9]{14}" } if len(param.Value) == 0 && e.Default != nil { switch t := e.Default.(type) { case string: param.Value = t case float64, float32: out, _ := json.Marshal(t) param.Value = string(out) } } template.Parameters = append(template.Parameters, param) } warnings := make(map[string][]string) if len(appJSON.Formation) == 0 { klog.V(4).Infof("No formation in app.json, adding a default web") // TODO: read Procfile for command? appJSON.Formation = map[string]Formation{ "web": { Quantity: 1, }, } msg := "adding a default formation 'web' with scale 1" warnings[msg] = append(warnings[msg], "app.json") } formations := sets.NewString() for k := range appJSON.Formation { formations.Insert(k) } var primaryFormation = "web" if _, ok := appJSON.Formation["web"]; !ok || len(appJSON.Formation) == 1 { for k := range appJSON.Formation { primaryFormation = k break } } imageGen := app.NewImageRefGenerator() buildPath := appJSON.Repository if len(buildPath) == 0 && len(g.LocalPath) > 0 { buildPath = g.LocalPath } if len(buildPath) == 0 { return nil, fmt.Errorf("app.json did not contain a repository URL and no local path was specified") } repo, err := app.NewSourceRepository(buildPath, newapp.StrategyDocker) if err != nil { return nil, err } var ports []string var pipelines app.PipelineGroup baseImage := g.BaseImage if len(baseImage) == 0 { baseImage = appJSON.Image } if len(baseImage) == 0 { return nil, fmt.Errorf("Docker image required: provide an --image flag or 'image' key in app.json") } fakeDockerfile := heredoc.Docf(` # Generated from app.json FROM %s `, baseImage) dockerfilePath := filepath.Join(buildPath, "Dockerfile") if df, err := app.NewDockerfileFromFile(dockerfilePath); err == nil { repo.Info().Dockerfile = df repo.Info().Path = dockerfilePath ports = dockerfile.LastExposedPorts(df.AST()) } // TODO: look for procfile for more info? image, err := imageGen.FromNameAndPorts(baseImage, ports) if err != nil { return nil, err } image.AsImageStream = true image.TagDirectly = true image.ObjectName = name image.Tag = "from" pipeline, err := app.NewPipelineBuilder(name, nil, nil, false).To(name).NewBuildPipeline(name, image, repo, false) if err != nil { return nil, err } // TODO: this should not be necessary pipeline.Build.Source.Name = name pipeline.Build.Source.DockerfileContents = fakeDockerfile pipeline.Name = name pipeline.Image.ObjectName = name klog.V(4).Infof("created pipeline %+v", pipeline) pipelines = append(pipelines, pipeline) var errs []error // create deployments for each formation var group app.PipelineGroup for _, component := range formations.List() { componentName := fmt.Sprintf("%s-%s", name, component) if formations.Len() == 1 { componentName = name } formationName := component formation := appJSON.Formation[component] inputImage := pipelines[0].Image inputImage.ContainerFn = func(c *corev1.Container) { for _, s := range ports { if port, err := strconv.Atoi(s); err == nil { c.Ports = append(c.Ports, corev1.ContainerPort{ContainerPort: int32(port)}) } } if len(formation.Command) > 0 { c.Args = []string{formation.Command} } else { msg := "no command defined, defaulting to command in the Procfile" warnings[msg] = append(warnings[msg], formationName) c.Args = []string{"/bin/sh", "-c", fmt.Sprintf("$(grep %s Procfile | cut -f 2 -d :)", formationName)} } c.Env = append(c.Env, envVars...) c.Resources = resourcesForProfile(formation.Size) } pipeline, err := app.NewPipelineBuilder(componentName, nil, nil, true).To(componentName).NewImagePipeline(componentName, inputImage) if err != nil { errs = append(errs, err) break } if err := pipeline.NeedsDeployment(nil, nil, false); err != nil { return nil, err } if cmd, ok := appJSON.Scripts["postdeploy"]; ok && primaryFormation == component { pipeline.Deployment.PostHook = &app.DeploymentHook{Shell: cmd} delete(appJSON.Scripts, "postdeploy") } group = append(group, pipeline) } if err := group.Reduce(); err != nil { return nil, err } pipelines = append(pipelines, group...) if len(errs) > 0 { return nil, utilerrs.NewAggregate(errs) } acceptors := app.Acceptors{app.NewAcceptUnique(legacyscheme.Scheme), app.AcceptNew} objects := app.Objects{} accept := app.NewAcceptFirst() for _, p := range pipelines { accepted, err := p.Objects(accept, acceptors) if err != nil { return nil, fmt.Errorf("can't setup %q: %v", p.From, err) } objects = append(objects, accepted...) } // create services for each object with a name based on alias. var services []*corev1.Service for _, obj := range objects { switch t := obj.(type) { case *appsv1.DeploymentConfig: ports := app.UniqueContainerToServicePorts(app.AllContainerPorts(t.Spec.Template.Spec.Containers...)) if len(ports) == 0 { continue } svc := app.GenerateService(t.ObjectMeta, t.Spec.Selector) svc.Spec.Ports = ports services = append(services, svc) } } for _, svc := range services { objects = append(objects, svc) } template.Objects = appObjectsToTemplateObjects(objects) // generate warnings warnUnusableAppJSONElements("app.json", appJSON, warnings) if len(warnings) > 0 { allWarnings := sets.NewString() for msg, services := range warnings { allWarnings.Insert(fmt.Sprintf("%s: %s", strings.Join(services, ","), msg)) } if template.Annotations == nil { template.Annotations = make(map[string]string) } template.Annotations[app.GenerationWarningAnnotation] = fmt.Sprintf("not all app.json fields were honored:\n* %s", strings.Join(allWarnings.List(), "\n* ")) } return template, nil }
Deletes all files in directory. @internal for internal use only @param String $dir
public static function deleteAllFilesInDirectory ($dir) { $dirIterator = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS); foreach (new \RecursiveIteratorIterator($dirIterator, \RecursiveIteratorIterator::CHILD_FIRST) as $file) { $file->isDir() ? rmdir($file) : unlink($file); } }
Helper that asserts the model_to_check is the model_reference or one of its subclasses. If not, raise an ImplementationError, using "obj_name" to describe the name of the argument.
def _assert_correct_model(model_to_check, model_reference, obj_name): if not issubclass(model_to_check, model_reference): raise ConfigurationException('The %s model must be a subclass of %s' % (obj_name, model_reference.__name__))
Add another user to the conversation. @since 2.0.0 @access public @param int $ConversationID Unique ID of conversation effected. @param int $UserID Unique ID of current user.
public function AddUserToConversation($ConversationID, $UserID) { if (!is_array($UserID)) $UserID = array($UserID); // First define the current users in the conversation $OldContributorData = $this->GetRecipients($ConversationID); $OldContributorData = Gdn_DataSet::Index($OldContributorData, 'UserID'); $AddedUserIDs = array(); // Get some information about this conversation $ConversationData = $this->SQL ->Select('LastMessageID') ->Select('DateUpdated') ->Select('CountMessages') ->From('Conversation') ->Where('ConversationID', $ConversationID) ->Get() ->FirstRow(); // Add the user(s) if they are not already in the conversation foreach ($UserID as $NewUserID) { if (!array_key_exists($NewUserID, $OldContributorData)) { $AddedUserIDs[] = $NewUserID; $this->SQL->Insert('UserConversation', array( 'UserID' => $NewUserID, 'ConversationID' => $ConversationID, 'LastMessageID' => $ConversationData->LastMessageID, 'CountReadMessages' => 0, 'DateConversationUpdated' => $ConversationData->DateUpdated )); } elseif ($OldContributorData[$NewUserID]->Deleted) { $AddedUserIDs[] = $NewUserID; $this->SQL->Put('UserConversation', array('Deleted' => 0), array('ConversationID' => $ConversationID, 'UserID' => $NewUserID)); } } if (count($AddedUserIDs) > 0) { $Session = Gdn::Session(); // Update the Contributors field on the conversation $Contributors = array_unique(array_merge($AddedUserIDs, array_keys($OldContributorData))); sort($Contributors); $this->SQL ->Update('Conversation') ->Set('Contributors', Gdn_Format::Serialize($Contributors)) ->Where('ConversationID', $ConversationID) ->Put(); $ActivityModel = new ActivityModel(); foreach ($AddedUserIDs as $AddedUserID) { $ActivityModel->Queue(array( 'ActivityType' => 'AddedToConversation', 'NotifyUserID' => $AddedUserID, 'HeadlineFormat' => T('You were added to a conversation.', '{ActivityUserID,User} added you to a <a href="{Url,htmlencode}">conversation</a>.'), 'Route' => '/messages/'.$ConversationID ), 'ConversationMessage' ); } $ActivityModel->SaveQueue(); $this->UpdateUserUnreadCount($AddedUserIDs); } }
Determine if this path is an ancestor of the supplied path. @param AbsolutePathInterface $path The child path. @return boolean True if this path is an ancestor of the supplied path.
public function isAncestorOf(AbsolutePathInterface $path) { if (!$this->matchesDriveOrNull($this->pathDriveSpecifier($path))) { return false; } return parent::isAncestorOf($path); }
Encode a list of integers representing Resource Records to a bitmap field used in the NSEC Resource Record.
def RRlist2bitmap(lst): # RFC 4034, 4.1.2. The Type Bit Maps Field import math bitmap = b"" lst = [abs(x) for x in sorted(set(lst)) if x <= 65535] # number of window blocks max_window_blocks = int(math.ceil(lst[-1] / 256.)) min_window_blocks = int(math.floor(lst[0] / 256.)) if min_window_blocks == max_window_blocks: max_window_blocks += 1 for wb in range(min_window_blocks, max_window_blocks + 1): # First, filter out RR not encoded in the current window block # i.e. keep everything between 256*wb <= 256*(wb+1) rrlist = sorted(x for x in lst if 256 * wb <= x < 256 * (wb + 1)) if not rrlist: continue # Compute the number of bytes used to store the bitmap if rrlist[-1] == 0: # only one element in the list bytes_count = 1 else: max = rrlist[-1] - 256 * wb bytes_count = int(math.ceil(max // 8)) + 1 # use at least 1 byte if bytes_count > 32: # Don't encode more than 256 bits / values bytes_count = 32 bitmap += struct.pack("BB", wb, bytes_count) # Generate the bitmap # The idea is to remove out of range Resource Records with these steps # 1. rescale to fit into 8 bits # 2. x gives the bit position ; compute the corresponding value # 3. sum everything bitmap += b"".join( struct.pack( b"B", sum(2 ** (7 - (x - 256 * wb) + (tmp * 8)) for x in rrlist if 256 * wb + 8 * tmp <= x < 256 * wb + 8 * tmp + 8), ) for tmp in range(bytes_count) ) return bitmap
Get all domains in a subscription. Get all domains in a subscription. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;DomainInner&gt; object
public Observable<Page<DomainInner>> listAsync() { return listWithServiceResponseAsync() .map(new Func1<ServiceResponse<Page<DomainInner>>, Page<DomainInner>>() { @Override public Page<DomainInner> call(ServiceResponse<Page<DomainInner>> response) { return response.body(); } }); }
Generic handler for all HTTP verbs @return void
protected function _handle() { list($finder, $options) = $this->_extractFinder(); $query = $this->_table()->find($finder, $options); $subject = $this->_subject(['success' => true, 'query' => $query]); $this->_trigger('beforePaginate', $subject); $items = $this->_controller()->paginate($subject->query); $subject->set(['entities' => $items]); $this->_trigger('afterPaginate', $subject); $this->_trigger('beforeRender', $subject); }
// Columnize formats the given arguments as columns and returns the formatted output, // note that it appends a new line to the end.
func Columnize(nowFormatted string, latency time.Duration, status, ip, method, path string, message interface{}, headerMessage interface{}) string { titles := "Time | Status | Latency | IP | Method | Path" line := fmt.Sprintf("%s | %v | %4v | %s | %s | %s", nowFormatted, status, latency, ip, method, path) if message != nil { titles += " | Message" line += fmt.Sprintf(" | %v", message) } if headerMessage != nil { titles += " | HeaderMessage" line += fmt.Sprintf(" | %v", headerMessage) } outputC := []string{ titles, line, } output := columnize.SimpleFormat(outputC) + "\n" return output }
Populates the current Toml instance with values from tomlString. @param tomlString String to be read. @return this instance @throws IllegalStateException If tomlString is not valid TOML
public Toml read(String tomlString) throws IllegalStateException { Results results = TomlParser.run(tomlString); if (results.errors.hasErrors()) { throw new IllegalStateException(results.errors.toString()); } this.values = results.consume(); return this; }
Creates a DiGraphIterator. It will iterate once for every node. @param root @param edges
public static <T> DiGraphIterator<T> getInstance(T root, Function<? super T, ? extends Collection<T>> edges) { return new DiGraphIterator<>(root, (y)->edges.apply(y).stream()); }
Execute http get request on given request_url with optional headers
def get_request(request_url, request_headers=dict()): request = Request(request_url) for key, val in request_headers.items(): request.add_header(key, val) try: response = urlopen(request, timeout=_REQUEST_TIMEOUT) response_content = response.read() except (HTTPError, URLError, socket.timeout): response_content = None return response_content
Returns the tree for an annotation given the annotated element and the element's own tree. Returns null if the tree cannot be found.
private JCTree matchAnnoToTree(AnnotationMirror findme, Element e, JCTree tree) { Symbol sym = cast(Symbol.class, e); class Vis extends JCTree.Visitor { List<JCAnnotation> result = null; public void visitPackageDef(JCPackageDecl tree) { result = tree.annotations; } public void visitClassDef(JCClassDecl tree) { result = tree.mods.annotations; } public void visitMethodDef(JCMethodDecl tree) { result = tree.mods.annotations; } public void visitVarDef(JCVariableDecl tree) { result = tree.mods.annotations; } @Override public void visitTypeParameter(JCTypeParameter tree) { result = tree.annotations; } } Vis vis = new Vis(); tree.accept(vis); if (vis.result == null) return null; List<Attribute.Compound> annos = sym.getAnnotationMirrors(); return matchAnnoToTree(cast(Attribute.Compound.class, findme), annos, vis.result); }
Caches the commerce tier price entry in the entity cache if it is enabled. @param commerceTierPriceEntry the commerce tier price entry
@Override public void cacheResult(CommerceTierPriceEntry commerceTierPriceEntry) { entityCache.putResult(CommerceTierPriceEntryModelImpl.ENTITY_CACHE_ENABLED, CommerceTierPriceEntryImpl.class, commerceTierPriceEntry.getPrimaryKey(), commerceTierPriceEntry); finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G, new Object[] { commerceTierPriceEntry.getUuid(), commerceTierPriceEntry.getGroupId() }, commerceTierPriceEntry); finderCache.putResult(FINDER_PATH_FETCH_BY_C_M, new Object[] { commerceTierPriceEntry.getCommercePriceEntryId(), commerceTierPriceEntry.getMinQuantity() }, commerceTierPriceEntry); finderCache.putResult(FINDER_PATH_FETCH_BY_C_ERC, new Object[] { commerceTierPriceEntry.getCompanyId(), commerceTierPriceEntry.getExternalReferenceCode() }, commerceTierPriceEntry); commerceTierPriceEntry.resetOriginalValues(); }
// SetCustomErrorResponses sets the CustomErrorResponses field's value.
func (s *DistributionSummary) SetCustomErrorResponses(v *CustomErrorResponses) *DistributionSummary { s.CustomErrorResponses = v return s }
// Write implements io.WriteCloser for WebSockWriter (that's the reason we're // wrapping the websocket) // // It replaces raw Write() with "Message.Send()"
func (w *WebSockWrapper) Write(data []byte) (n int, err error) { n = len(data) if w.mode == WebSocketBinaryMode { // binary send: err = websocket.Message.Send(w.ws, data) // text send: } else { var utf8 string utf8, err = w.encoder.String(string(data)) err = websocket.Message.Send(w.ws, utf8) } if err != nil { n = 0 } return n, err }
Gets server. @return server, ${serverScheme}://${serverHost}:${serverPort}
public static String getServer() { final StringBuilder serverBuilder = new StringBuilder(getServerScheme()).append("://").append(getServerHost()); final String port = getServerPort(); if (StringUtils.isNotBlank(port) && !"80".equals(port) && !"443".equals(port)) { serverBuilder.append(':').append(port); } return serverBuilder.toString(); }
Example shows quick and simple setup of a webhooks service. This example shows a single inline service that logs new messages.
function startInlineServices() { // Provide a webhook definition var hook = { name: 'Inline Sample', events: ['message.sent'], path: '/inline_sample_message_sent', }; // Register this webhook with Layer's Services webhooksServices.register({ secret: SECRET, url: HOST + ':' + PORT, hooks: [hook] }); // Listen for events from Layer's Services, and call our callbackAsync with each event webhooksServices.listen({ expressApp: app, secret: SECRET, hooks: [hook] }, redis); // Setup your callback to handle the webhook events queue.process(hook.name, 50, function(job, done) { console.log(new Date().toLocaleString() + ': Inline Sample: Message Received from ' + (job.data.message.sender.user_id || job.data.message.sender.name)); done(); }); }
// CommitOnly is used to finalize the transaction and return a new tree, but // does not issue any notifications until Notify is called.
func (t *Txn) CommitOnly() *Tree { nt := &Tree{t.root, t.size} t.writable = nil return nt }
Parse a Pedigree file and return a list of Pedigree objects. @param pedigreePath Path to the Pedigree file @return List of Pedigree objects @throws IOException
public static List<Pedigree> parse(Path pedigreePath) throws IOException { FileUtils.checkFile(pedigreePath); Map<String, Pedigree> pedigreeMap = new HashMap<>(); Map<String, Member> individualMap = new HashMap<>(); String pedigreeName, individualName; Member.Sex sex; Member.AffectionStatus affectionStatus; //String line, key; String[] fields, labels = null; Member member; // Read the whole pedigree file List<String> individualStringLines = Files.readAllLines(pedigreePath); // First loop: initializing individual map for (int i = 0; i < individualStringLines.size(); i++) { String line = individualStringLines.get(i); if (line != null) { fields = line.split("[ \t]"); if (fields.length < 6) { throw new IOException("Pedigree file '" + pedigreePath + "' contains " + fields.length + ", it must contain minimum 6 columns!\n" + line); } if (i == 0 && line.startsWith("#")) { // header with variables, labels are optional labels = line.split("[ \t]"); } else { // normal line pedigreeName = fields[0]; individualName = fields[1]; sex = Member.Sex.getEnum(fields[4]); affectionStatus = Member.AffectionStatus.getEnum(fields[5]); if (!pedigreeMap.containsKey(pedigreeName)) { pedigreeMap.put(pedigreeName, new Pedigree(pedigreeName, new ArrayList<>(), new HashMap<>())); } member = new Member(individualName, sex, affectionStatus); // labels are optional if (labels != null && fields.length > 6 && labels.length == fields.length) { Map<String, Object> attributes = new HashMap<>(); for (int j = 6; j < fields.length; j++) { attributes.put(labels[j], fields[j]); } member.setAttributes(attributes); } pedigreeMap.get(pedigreeName).getMembers().add(member); individualMap.put(pedigreeName + "_" + individualName, member); } } } // second loop: setting fathers, mothers, partners and children for (int i = 1; i < individualStringLines.size(); i++) { String line = individualStringLines.get(i); if (line != null) { fields = line.split("[ \t]"); if (!line.startsWith("#")) { // update father, mother and child Member father = individualMap.get(fields[0] + "_" + fields[2]); Member mother = individualMap.get(fields[0] + "_" + fields[3]); Member child = individualMap.get(fields[0] + "_" + fields[1]); // setting father and children if (father != null) { child.setFather(father); if (father.getMultiples() == null) { Multiples multiples = new Multiples().setType("children").setSiblings(new ArrayList<>()); father.setMultiples(multiples); } father.getMultiples().getSiblings().add(child.getName()); } // setting mother and children if (mother != null) { child.setMother(mother); if (mother.getMultiples() == null) { Multiples multiples = new Multiples().setType("children").setSiblings(new ArrayList<>()); mother.setMultiples(multiples); } mother.getMultiples().getSiblings().add(child.getName()); } } } } // create the list of Pedigree objects from the map return new ArrayList<>(pedigreeMap.values()); }
Returns next paragraph-like element or `null` if reached the end of range. @param {String} [blockTag='p'] Name of a block element which will be established by iterator in block-less elements (see {@link #enforceRealBlocks}).
function( blockTag ) { // The block element to be returned. var block; // The range object used to identify the paragraph contents. var range; // Indicats that the current element in the loop is the last one. var isLast; // Instructs to cleanup remaining BRs. var removePreviousBr, removeLastBr; blockTag = blockTag || 'p'; // We're iterating over nested editable. if ( this._.nestedEditable ) { // Get next block from nested iterator and returns it if was found. block = this._.nestedEditable.iterator.getNextParagraph( blockTag ); if ( block ) { // Inherit activeFilter from the nested iterator. this.activeFilter = this._.nestedEditable.iterator.activeFilter; return block; } // No block in nested iterator means that we reached the end of the nested editable. // Reset the active filter to the default filter (or undefined if this iterator didn't have it). this.activeFilter = this.filter; // Try to find next nested editable or get back to parent (this) iterator. if ( startNestedEditableIterator( this, blockTag, this._.nestedEditable.container, this._.nestedEditable.remaining ) ) { // Inherit activeFilter from the nested iterator. this.activeFilter = this._.nestedEditable.iterator.activeFilter; return this._.nestedEditable.iterator.getNextParagraph( blockTag ); } else { this._.nestedEditable = null; } } // Block-less range should be checked first. if ( !this.range.root.getDtd()[ blockTag ] ) return null; // This is the first iteration. Let's initialize it. if ( !this._.started ) range = startIterator.call( this ); var currentNode = this._.nextNode, lastNode = this._.lastNode; this._.nextNode = null; while ( currentNode ) { // closeRange indicates that a paragraph boundary has been found, // so the range can be closed. var closeRange = 0, parentPre = currentNode.hasAscendant( 'pre' ); // includeNode indicates that the current node is good to be part // of the range. By default, any non-element node is ok for it. var includeNode = ( currentNode.type != CKEDITOR.NODE_ELEMENT ), continueFromSibling = 0; // If it is an element node, let's check if it can be part of the range. if ( !includeNode ) { var nodeName = currentNode.getName(); // Non-editable block was found - return it and move to processing // its nested editables if they exist. if ( CKEDITOR.dtd.$block[ nodeName ] && currentNode.getAttribute( 'contenteditable' ) == 'false' ) { block = currentNode; // Setup iterator for first of nested editables. // If there's no editable, then algorithm will move to next element after current block. startNestedEditableIterator( this, blockTag, block ); // Gets us straight to the end of getParagraph() because block variable is set. break; } else if ( currentNode.isBlockBoundary( this.forceBrBreak && !parentPre && { br: 1 } ) ) { // <br> boundaries must be part of the range. It will // happen only if ForceBrBreak. if ( nodeName == 'br' ) includeNode = 1; else if ( !range && !currentNode.getChildCount() && nodeName != 'hr' ) { // If we have found an empty block, and haven't started // the range yet, it means we must return this block. block = currentNode; isLast = currentNode.equals( lastNode ); break; } // The range must finish right before the boundary, // including possibly skipped empty spaces. (#1603) if ( range ) { range.setEndAt( currentNode, CKEDITOR.POSITION_BEFORE_START ); // The found boundary must be set as the next one at this // point. (#1717) if ( nodeName != 'br' ) this._.nextNode = currentNode; } closeRange = 1; } else { // If we have child nodes, let's check them. if ( currentNode.getFirst() ) { // If we don't have a range yet, let's start it. if ( !range ) { range = this.range.clone(); range.setStartAt( currentNode, CKEDITOR.POSITION_BEFORE_START ); } currentNode = currentNode.getFirst(); continue; } includeNode = 1; } } else if ( currentNode.type == CKEDITOR.NODE_TEXT ) { // Ignore normal whitespaces (i.e. not including &nbsp; or // other unicode whitespaces) before/after a block node. if ( beginWhitespaceRegex.test( currentNode.getText() ) ) includeNode = 0; } // The current node is good to be part of the range and we are // starting a new range, initialize it first. if ( includeNode && !range ) { range = this.range.clone(); range.setStartAt( currentNode, CKEDITOR.POSITION_BEFORE_START ); } // The last node has been found. isLast = ( ( !closeRange || includeNode ) && currentNode.equals( lastNode ) ); // If we are in an element boundary, let's check if it is time // to close the range, otherwise we include the parent within it. if ( range && !closeRange ) { while ( !currentNode.getNext( skipGuard ) && !isLast ) { var parentNode = currentNode.getParent(); if ( parentNode.isBlockBoundary( this.forceBrBreak && !parentPre && { br: 1 } ) ) { closeRange = 1; includeNode = 0; isLast = isLast || ( parentNode.equals( lastNode ) ); // Make sure range includes bookmarks at the end of the block. (#7359) range.setEndAt( parentNode, CKEDITOR.POSITION_BEFORE_END ); break; } currentNode = parentNode; includeNode = 1; isLast = ( currentNode.equals( lastNode ) ); continueFromSibling = 1; } } // Now finally include the node. if ( includeNode ) range.setEndAt( currentNode, CKEDITOR.POSITION_AFTER_END ); currentNode = getNextSourceNode( currentNode, continueFromSibling, lastNode ); isLast = !currentNode; // We have found a block boundary. Let's close the range and move out of the // loop. if ( isLast || ( closeRange && range ) ) break; } // Now, based on the processed range, look for (or create) the block to be returned. if ( !block ) { // If no range has been found, this is the end. if ( !range ) { this._.docEndMarker && this._.docEndMarker.remove(); this._.nextNode = null; return null; } var startPath = new CKEDITOR.dom.elementPath( range.startContainer, range.root ); var startBlockLimit = startPath.blockLimit, checkLimits = { div: 1, th: 1, td: 1 }; block = startPath.block; if ( !block && startBlockLimit && !this.enforceRealBlocks && checkLimits[ startBlockLimit.getName() ] && range.checkStartOfBlock() && range.checkEndOfBlock() && !startBlockLimit.equals( range.root ) ) { block = startBlockLimit; } else if ( !block || ( this.enforceRealBlocks && block.is( listItemNames ) ) ) { // Create the fixed block. block = this.range.document.createElement( blockTag ); // Move the contents of the temporary range to the fixed block. range.extractContents().appendTo( block ); block.trim(); // Insert the fixed block into the DOM. range.insertNode( block ); removePreviousBr = removeLastBr = true; } else if ( block.getName() != 'li' ) { // If the range doesn't includes the entire contents of the // block, we must split it, isolating the range in a dedicated // block. if ( !range.checkStartOfBlock() || !range.checkEndOfBlock() ) { // The resulting block will be a clone of the current one. block = block.clone( false ); // Extract the range contents, moving it to the new block. range.extractContents().appendTo( block ); block.trim(); // Split the block. At this point, the range will be in the // right position for our intents. var splitInfo = range.splitBlock(); removePreviousBr = !splitInfo.wasStartOfBlock; removeLastBr = !splitInfo.wasEndOfBlock; // Insert the new block into the DOM. range.insertNode( block ); } } else if ( !isLast ) { // LIs are returned as is, with all their children (due to the // nested lists). But, the next node is the node right after // the current range, which could be an <li> child (nested // lists) or the next sibling <li>. this._.nextNode = ( block.equals( lastNode ) ? null : getNextSourceNode( range.getBoundaryNodes().endNode, 1, lastNode ) ); } } if ( removePreviousBr ) { var previousSibling = block.getPrevious(); if ( previousSibling && previousSibling.type == CKEDITOR.NODE_ELEMENT ) { if ( previousSibling.getName() == 'br' ) previousSibling.remove(); else if ( previousSibling.getLast() && previousSibling.getLast().$.nodeName.toLowerCase() == 'br' ) previousSibling.getLast().remove(); } } if ( removeLastBr ) { var lastChild = block.getLast(); if ( lastChild && lastChild.type == CKEDITOR.NODE_ELEMENT && lastChild.getName() == 'br' ) { // Remove br filler on browser which do not need it. if ( !CKEDITOR.env.needsBrFiller || lastChild.getPrevious( bookmarkGuard ) || lastChild.getNext( bookmarkGuard ) ) lastChild.remove(); } } // Get a reference for the next element. This is important because the // above block can be removed or changed, so we can rely on it for the // next interation. if ( !this._.nextNode ) this._.nextNode = ( isLast || block.equals( lastNode ) || !lastNode ) ? null : getNextSourceNode( block, 1, lastNode ); return block; }
Calls a class considering all routes. @param *string $class class name @param mixed[, mixed..] $arg arguments @return object
public function call($class) { //argument 1 must be a string Argument::i()->test(1, 'string'); $args = func_get_args(); $class = array_shift($args); return $this->callArray($class, $args); }
// SetStepName sets the StepName field's value.
func (s *StepExecution) SetStepName(v string) *StepExecution { s.StepName = &v return s }
// Back returns the last Element of list l or nil.
func (l *List) Back() *Element { if l.len == 0 { return nil } return l.root.prev }
Set the unique command for this transaction type. @param string $command @return self
public function setCommand($command) { if (! in_array($command, self::VALID_COMMANDS)) { throw new InvalidArgumentException('Invalid command sent'); } $this->command = $command; return $this; }
Implementation of put method (handles vacantChild; overriding methods handle everything else).
void put( Conjunction selector, MatchTarget object, InternTable subExpr) throws MatchingException { vacantChild = nextMatcher(selector, vacantChild); vacantChild.put(selector, object, subExpr); }
Set the supported extensions for this route. @param array $extensions The extensions to set. @return $this
public function setExtensions(array $extensions) { $this->_extensions = []; foreach ($extensions as $ext) { $this->_extensions[] = strtolower($ext); } return $this; }
Checks if an update is available and applicable for the current installation. @since Symphony 2.3.1 @return boolean
public static function isUpgradeAvailable() { if (self::isInstallerAvailable()) { $migration_version = self::getMigrationVersion(); $current_version = Symphony::Configuration()->get('version', 'symphony'); return version_compare($current_version, $migration_version, '<'); } return false; }
Resolve view from given data with the structure. @param StructureInterface $structure @param array $data @return array
private function resolveView(StructureInterface $structure, array $data) { $structure->setWebspaceKey($this->getWebspaceKey()); $view = []; foreach ($structure->getProperties(true) as $child) { if (array_key_exists($child->getName(), $data)) { $child->setValue($data[$child->getName()]); } $contentType = $this->contentTypeManager->get($child->getContentTypeName()); $view[$child->getName()] = $contentType->getViewData($child); } return $view; }
super_fn calls the old function which was overwritten by this mixin.
function super_fn() { if (!oldFn) { return } each(arguments, function(arg, i) { args[i] = arg }) return oldFn.apply(self, args) }
Returns a new set containing the first n elements in this grouped and sorted {@link DataSet}. @param n The desired number of elements for each group. @return A GroupReduceOperator that represents the DataSet containing the elements.
public GroupReduceOperator<T, T> first(int n) { if (n < 1) { throw new InvalidProgramException("Parameter n of first(n) must be at least 1."); } return reduceGroup(new FirstReducer<T>(n)); }
Get all the tags of this block with a specific tag name. @param string $name The tag name to search for. @return array<DocumentationTag> The tags with a matching tag name.
public function tagsByName($name) { $tags = array(); foreach ($this->tags() as $tag) { if ($name === $tag->name()) { $tags[] = $tag; } } return $tags; }
Writes a class' bytecode to an <code>OutputStream</code>. @param cl The <code>Class</code> to write. @param out The <code>OutputStream</code> to write to. @throws IOException If unable to write to <code>out</code>.
public static void writeClassToStream(Class<?> cl, OutputStream out) throws IOException { InputStream in = getClassAsStream(cl); StreamUtil.writeStream(in, out); out.flush(); }
Create a JSON schema validator for the given schema. Args: schema_path: The filename of the JSON schema. schema: A Python object representation of the same schema. Returns: An instance of Draft4Validator.
def load_validator(schema_path, schema): # Get correct prefix based on OS if os.name == 'nt': file_prefix = 'file:///' else: file_prefix = 'file:' resolver = RefResolver(file_prefix + schema_path.replace("\\", "/"), schema) validator = Draft4Validator(schema, resolver=resolver) return validator
Lifts a function to the current Observable and returns a new Observable that when subscribed to will pass the values of the current Observable through the Operator function. @param callable $operatorFactory @return AnonymousObservable
public function lift(callable $operatorFactory) { return new AnonymousObservable(function (ObserverInterface $observer, SchedulerInterface $schedule) use ($operatorFactory) { $operator = $operatorFactory(); return $operator($this, $observer, $schedule); }); }
// NewNode initializes a server node with connection parameters.
func newNode(cluster *Cluster, nv *nodeValidator) *Node { newNode := &Node{ cluster: cluster, name: nv.name, // address: nv.primaryAddress, host: nv.primaryHost, // Assign host to first IP alias because the server identifies nodes // by IP address (not hostname). connections: *newConnectionHeap(cluster.clientPolicy.ConnectionQueueSize), connectionCount: *NewAtomicInt(0), peersGeneration: *NewAtomicInt(-1), partitionGeneration: *NewAtomicInt(-2), referenceCount: *NewAtomicInt(0), failures: *NewAtomicInt(0), active: *NewAtomicBool(true), partitionChanged: *NewAtomicBool(false), supportsFloat: *NewAtomicBool(nv.supportsFloat), supportsBatchIndex: *NewAtomicBool(nv.supportsBatchIndex), supportsReplicas: *NewAtomicBool(nv.supportsReplicas), supportsGeo: *NewAtomicBool(nv.supportsGeo), supportsPeers: *NewAtomicBool(nv.supportsPeers), supportsLUTNow: *NewAtomicBool(nv.supportsLUTNow), supportsTruncateNamespace: *NewAtomicBool(nv.supportsTruncateNamespace), } newNode.aliases.Store(nv.aliases) newNode._sessionToken.Store(nv.sessionToken) newNode.racks.Store(map[string]int{}) // this will reset to zero on first aggregation on the cluster, // therefore will only be counted once. atomic.AddInt64(&newNode.stats.NodeAdded, 1) return newNode }
Executes the given update. @param query The update to execute. @throws DatabaseEngineException If something goes wrong executing the update.
@Override public synchronized int executeUpdate(final Expression query) throws DatabaseEngineException { /* * Reconnection is already assured by "void executeUpdate(final String query)". */ final String trans = translate(query); logger.trace(trans); return executeUpdate(trans); }
// Close cleans up the resources used by the Multiplexer
func (mux *Multiplexer) Close() { safeclose.Close( mux.Consumer, mux.hashSyncProducer, mux.hashAsyncProducer, mux.manSyncProducer, mux.manAsyncProducer) }
Insert default terms.
private function insert_default_terms() { global $wpdb; // Default category $cat_name = __( 'Uncategorized' ); /* translators: Default category slug */ $cat_slug = sanitize_title( _x( 'Uncategorized', 'Default category slug' ) ); if ( global_terms_enabled() ) { $cat_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) ); if ( null === $cat_id ) { $wpdb->insert( $wpdb->sitecategories, [ 'cat_ID' => 0, 'cat_name' => $cat_name, 'category_nicename' => $cat_slug, 'last_updated' => current_time( 'mysql', true ), ] ); $cat_id = $wpdb->insert_id; } update_option( 'default_category', $cat_id ); } else { $cat_id = 1; } $wpdb->insert( $wpdb->terms, [ 'term_id' => $cat_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0, ] ); $wpdb->insert( $wpdb->term_taxonomy, [ 'term_id' => $cat_id, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 0, ] ); }
Replies if the specified column could be replied or ignored. @param column the column. @return <code>true</code> if the given column is selectable, otherwise <code>false</code>
@Pure public boolean isColumnSelectable(DBaseFileField column) { return column != null && (this.selectedColumns.isEmpty() || this.selectedColumns.contains(column)); }
Get value in dictionary for dictionary[keys[0]][keys[1]][keys[..n]] :param dictionary: An input dictionary :param keys: Keys where to store data :return:
def nested_get(dictionary, keys): return reduce(lambda d, k: d[k], keys, dictionary)
Send a bunch of zero-bytes to the YubiHSM, and flush the input buffer.
def reset(stick): nulls = (pyhsm.defines.YSM_MAX_PKT_SIZE - 1) * '\x00' res = YHSM_Cmd(stick, pyhsm.defines.YSM_NULL, payload = nulls).execute(read_response = False) unlock = stick.acquire() try: stick.drain() stick.flush() finally: unlock() return res == 0
Save a value @param string|array $name Name of the value @param mixed $value The value to save
public function set($name, $value = null) { if (is_array($name)) { $this->parameters = array_replace($this->parameters, $name); } else { $this->parameters[trim(strtolower($name))] = is_string($value) ? trim($value) : $value; } }
Removes a Product from the specified ProductSet. @param \Google\Cloud\Vision\V1\RemoveProductFromProductSetRequest $argument input argument @param array $metadata metadata @param array $options call options
public function RemoveProductFromProductSet(\Google\Cloud\Vision\V1\RemoveProductFromProductSetRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.cloud.vision.v1.ProductSearch/RemoveProductFromProductSet', $argument, ['\Google\Protobuf\GPBEmpty', 'decode'], $metadata, $options); }
Set the required fields conditional @return void
protected function setRequiredFieldsConditional() { $requiredFieldsConditional = [ 'currency' => [ 'IDR' => ['bank_code'], 'CNY' => ['bank_branch', 'bank_name'], 'THB' => ['bank_name'] ] ]; $this->requiredFieldsConditional = \Genesis\Utils\Common::createArrayObject($requiredFieldsConditional); $requiredFieldValuesConditional = [ 'currency' => [ 'CNY' => [ [ 'bank_account_number' => new RegexValidator('/^[0-9]{19}$/') ] ] ] ]; $this->requiredFieldValuesConditional = \Genesis\Utils\Common::createArrayObject($requiredFieldValuesConditional); }
// SetCharacterSetName sets the CharacterSetName field's value.
func (s *CharacterSet) SetCharacterSetName(v string) *CharacterSet { s.CharacterSetName = &v return s }
// IsProcessable returns true if decoder is able to decode provided file
func (yd *YAMLDecoder) IsProcessable(file string) bool { for _, ext := range yd.extensions { if strings.HasSuffix(file, ext) { return true } } return false }
// SetFramerateConversionAlgorithm sets the FramerateConversionAlgorithm field's value.
func (s *Mpeg2Settings) SetFramerateConversionAlgorithm(v string) *Mpeg2Settings { s.FramerateConversionAlgorithm = &v return s }
Ensures an error on the passed greenlet crashes self/main greenlet.
def add_pending_greenlet(self, greenlet: Greenlet): def remove(_): self.greenlets.remove(greenlet) self.greenlets.append(greenlet) greenlet.link_exception(self.on_error) greenlet.link_value(remove)
Stops the reporter and shuts down its thread of execution. Uses the shutdown pattern from http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
public void stop() { executor.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { executor.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { LOG.warn(getClass().getSimpleName() + ": ScheduledExecutorService did not terminate"); } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted executor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } }
// convertStructDevices converts between a list of struct and proto Device
func convertStructDevices(in []*Device) []*proto.DetectedDevice { if in == nil { return nil } out := make([]*proto.DetectedDevice, len(in)) for i, d := range in { out[i] = convertStructDevice(d) } return out }
Return the value for the nth header field. Returns null if there are fewer than n fields. This can be used in conjunction with getHeaderFieldKey to iterate through all the headers in the message.
public String getHeaderField(int n) { try { getInputStream(); } catch (Exception e) { return null; } MessageHeader props = properties; return props == null ? null : props.getValue(n); }
// SetNextDue sets the next due timestamp and whether the task has a queue, // and records the source (the now value of the run who reported nextDue).
func (ts *taskScheduler) SetNextDue(nextDue int64, hasQueue bool, source int64) { // TODO(mr): we may need some logic around source to handle if SetNextDue is called out of order. ts.nextDueMu.Lock() defer ts.nextDueMu.Unlock() ts.nextDue = nextDue ts.nextDueSource = source ts.hasQueue = hasQueue }
Copy header into provided writer @param writer repository writer to verify @throws IllegalArgumentException if writer is 'null'
public void copyHeader(LogRepositoryWriter writer) throws IllegalArgumentException { if (writer == null) { throw new IllegalArgumentException("Parameter writer can't be null"); } writer.setHeader(headerBytes); }
Disconnect and cleanup.
def _disconnect(self, exc_info=False): """""" if self._stream: self._stream.close(exc_info=exc_info)
/* Render the report with the render modules supplied in the options. @param {Object} options Doctor options. @param {Object} report Report generated by doctor. @param {function} cb Function to call when rendering is complete.
function render(options, report, cb) { var reportName = options.outputReportName || 'report.json'; var files = {}; files[reportName] = report; var renderFunctions = u.toArray(options.render || 'default'); try { renderFunctions = u.findFunctions(renderFunctions, 'render'); } catch (findError) { return cb(findError); } function eachRender(fn, cb) { fn(options, files, function (err, renderedFiles) { if (err) { return cb(err); } files = renderedFiles; cb(null, files); }); } async.forEachSeries(renderFunctions, eachRender, function (err) { // if (err) { // return cb(err); // } // Object.keys(files).forEach(function (filename, i) { // var file = files[filename]; // if (typeof file !== 'string') { // try { // // if circular references were introduced, this will fail // var fileString = JSON.stringify(file, null, 2); // files[filename] = fileString; // } catch (jsonError) { // return cb(jsonError); // } // } // }); cb(err, files); }); }
// SetCurrentGeneration sets the CurrentGeneration field's value.
func (s *RedshiftInstanceDetails) SetCurrentGeneration(v bool) *RedshiftInstanceDetails { s.CurrentGeneration = &v return s }
Find a Customer by id. @param mixed $id The customer id @return CanalTP\NmmPortalBundle\Entity\Customer
private function findCustomerById ($id) { $customer = $this->getDoctrine() ->getManager() ->getRepository('CanalTPNmmPortalBundle:Customer') ->find($id); return $customer; }
// RegisterSourceAsSchema means you have a datasource, that is going to act // as a named schema. ie, this will not be a nested schema with sub-schemas // and the source will not be re-useable as a source-type.
func RegisterSourceAsSchema(name string, source Source) error { // Since registry is a global, lets first lock that. registryMu.Lock() defer registryMu.Unlock() s := NewSchemaSource(name, source) source.Init() source.Setup(s) if err := registry.SchemaAdd(s); err != nil { return err } return discoverSchemaFromSource(s, registry.applyer) }
Send an erase device command to this object @param passcode[String] a six-char passcode, required for computers & computergroups @return (see .send_mdm_command)
def erase_device(passcode = '', preserve_data_plan: false) self.class.erase_device @id, passcode: passcode, preserve_data_plan: preserve_data_plan, api: @api end
// Run implements distributor.D
func (d *BoundDistributor) Run(desc *dm.Quest_Desc, exAuth *dm.Execution_Auth, prev *dm.JsonResult) (tok distributor.Token, pollbackTime time.Duration, err error) { if err = d.RunError; err != nil { return } pollbackTime = d.PollbackTime tok = MakeToken(exAuth.Id) tsk := &DistributorData{ Auth: exAuth, Desc: desc, State: prev, } tsk.NotifyTopic, tsk.NotifyAuth, err = d.cfg.PrepareTopic(d.c, exAuth.Id) panicIf(err) d.Lock() defer d.Unlock() if d.tasks == nil { d.tasks = map[distributor.Token]*DistributorData{} } d.tasks[tok] = tsk return }
Replace rectangle with its transformation by matrix m.
def transform(self, m): """""" if not len(m) == 6: raise ValueError("bad sequ. length") self.x0, self.y0, self.x1, self.y1 = TOOLS._transform_rect(self, m) return self
Load grid and calculate alpha values from the coverage/2.5.
def load_grid(self, alpha): ''' ''' grid = CRGrid.crt_grid(self.dirs[0] + '/grid/elem.dat', self.dirs[0] + '/grid/elec.dat') self.plotman = CRPlot.plotManager(grid=grid) name = self.dirs[0] + '/inv/coverage.mag' content = np.genfromtxt(name, skip_header=1, skip_footer=1, usecols=([2])) abscov = np.abs(content) if alpha: normcov = np.divide(abscov, 2.5) normcov[np.where(normcov > 1)] = 1 mask = np.subtract(1, normcov) self.alpha = self.plotman.parman.add_data(mask) else: self.alpha = self.plotman.parman.add_data(np.ones(len(abscov)))
Given a list or tuple of logging levels, add a logger instance to each.
def add(self, levels, logger): if isinstance(levels, (list, tuple)): for lvl in levels: self.config[lvl].add(logger) else: self.config[levels].add(logger)
Loads the piwik configuration. @param array $config An array of configuration settings @param \Symfony\Component\DependencyInjection\ContainerBuilder $container A ContainerBuilder instance
public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); if (!$container->hasDefinition('piwik.client')) { $loader->load('piwik.xml'); } $config = $this->mergeConfigs($configs); if (isset($config['connection'])) { $definition = $container->getDefinition('piwik.client'); $arguments = $definition->getArguments(); $arguments[0] = new Reference($config['connection']); $definition->setArguments($arguments); } if (isset($config['url'])) { $container->setParameter('piwik.connection.http.url', $config['url']); } if (isset($config['init'])) { $container->setParameter('piwik.connection.piwik.init', (bool) $config['init']); } if (isset($config['token'])) { $container->setParameter('piwik.client.token', $config['token']); } }
Create a default Cocoa menu that shows 'Services', 'Hide', 'Hide Others', 'Show All', and 'Quit'. Will append the application name to some menu items if it's available.
def _add_app_menu(self): # Set the main menu for the application mainMenu = AppKit.NSMenu.alloc().init() self.app.setMainMenu_(mainMenu) # Create an application menu and make it a submenu of the main menu mainAppMenuItem = AppKit.NSMenuItem.alloc().init() mainMenu.addItem_(mainAppMenuItem) appMenu = AppKit.NSMenu.alloc().init() mainAppMenuItem.setSubmenu_(appMenu) appMenu.addItemWithTitle_action_keyEquivalent_(self._append_app_name(localization["cocoa.menu.about"]), "orderFrontStandardAboutPanel:", "") appMenu.addItem_(AppKit.NSMenuItem.separatorItem()) # Set the 'Services' menu for the app and create an app menu item appServicesMenu = AppKit.NSMenu.alloc().init() self.app.setServicesMenu_(appServicesMenu) servicesMenuItem = appMenu.addItemWithTitle_action_keyEquivalent_(localization["cocoa.menu.services"], nil, "") servicesMenuItem.setSubmenu_(appServicesMenu) appMenu.addItem_(AppKit.NSMenuItem.separatorItem()) # Append the 'Hide', 'Hide Others', and 'Show All' menu items appMenu.addItemWithTitle_action_keyEquivalent_(self._append_app_name(localization["cocoa.menu.hide"]), "hide:", "h") hideOthersMenuItem = appMenu.addItemWithTitle_action_keyEquivalent_(localization["cocoa.menu.hideOthers"], "hideOtherApplications:", "h") hideOthersMenuItem.setKeyEquivalentModifierMask_(AppKit.NSAlternateKeyMask | AppKit.NSCommandKeyMask) appMenu.addItemWithTitle_action_keyEquivalent_(localization["cocoa.menu.showAll"], "unhideAllApplications:", "") appMenu.addItem_(AppKit.NSMenuItem.separatorItem()) # Append a 'Quit' menu item appMenu.addItemWithTitle_action_keyEquivalent_(self._append_app_name(localization["cocoa.menu.quit"]), "terminate:", "q")
Compare version between installed and a new extensions @return void
protected function compareVersion() { $manifest = $this->getManifest(); $extensionEntity = $this->getExtensionEntity(); if (isset($extensionEntity)) { $comparedVersion = version_compare($manifest['version'], $extensionEntity->get('version'), '>='); if ($comparedVersion <= 0) { $this->throwErrorAndRemovePackage('You cannot install an older version of this extension.'); } } }
// RemoveDuplicateField remove the duplicate field
func RemoveDuplicateField(data string) string { fs := []string{} for _, v := range strings.Split(data, ",") { if strings.TrimSpace(v) != "" { fs = append(fs, v) } } fields := xslice.Unique(fs) result := strings.Join(fields.([]string), ",") return result }
Disables a reference to the service :return: True if the bundle was using this reference, else False
def unget_service(self, reference): # type: (ServiceReference) -> bool # Lose the dependency return self.__framework._registry.unget_service( self.__bundle, reference )