comment
stringlengths
16
255
code
stringlengths
52
3.87M
Internal: Returns all parents for path path - String absolute filename or directory root - String path to stop at (default: system root) Returns an Array of String paths.
def path_parents(path, root = nil) root = "#{root}#{File::SEPARATOR}" if root parents = [] loop do parent = File.dirname(path) break if parent == path break if root && !path.start_with?(root) parents << path = parent end parents end
ItemProcFunc for container items removes items of the children chain from the list of selectable containers if the element itself already is a container @param array $params An array containing the items and parameters for the list of items
public function containerItemsProcFunc(array &$params) { $this->init($params['row']['pid']); $possibleContainers = []; $this->removeItemsFromListOfSelectableContainers($params, $possibleContainers); if (!empty($possibleContainers)) { $params['items'] = array_merge($params['items'], $possibleContainers); } $itemUidList = ''; if (count($params['items']) > 1) { foreach ($params['items'] as $container) { if ($container[1] > 0) { $itemUidList .= $itemUidList ? ',' . $container[1] : $container[1]; } } } if ($itemUidList) { $this->deleteDisallowedContainers($params, $itemUidList); } }
Creates a text component with content, and optional color. @param content the plain text content @param color the color @return the text component
public static TextComponent of(final @NonNull String content, final @Nullable TextColor color) { return of(content, color, Collections.emptySet()); }
Return true if alert severity has changed more than X times in Y seconds
def is_flapping(self, alert, window=1800, count=2): pipeline = [ {'$match': { 'environment': alert.environment, 'resource': alert.resource, 'event': alert.event, 'customer': alert.customer }}, {'$unwind': '$history'}, {'$match': { 'history.updateTime': {'$gt': datetime.utcnow() - timedelta(seconds=window)}, 'history.type': 'severity' }}, {'$group': {'_id': '$history.type', 'count': {'$sum': 1}}} ] responses = self.get_db().alerts.aggregate(pipeline) for r in responses: if r['count'] > count: return True return False
Profile a function.
def profile(fun, *args, **kwargs): timer_name = kwargs.pop("prof_name", None) if not timer_name: module = inspect.getmodule(fun) c = [module.__name__] parentclass = labtypes.get_class_that_defined_method(fun) if parentclass: c.append(parentclass.__name__) c.append(fun.__name__) timer_name = ".".join(c) start(timer_name) ret = fun(*args, **kwargs) stop(timer_name) return ret
Convert this variable to a pandas.Index
def to_index(self): """""" # n.b. creating a new pandas.Index from an old pandas.Index is # basically free as pandas.Index objects are immutable assert self.ndim == 1 index = self._data.array if isinstance(index, pd.MultiIndex): # set default names for multi-index unnamed levels so that # we can safely rename dimension / coordinate later valid_level_names = [name or '{}_level_{}'.format(self.dims[0], i) for i, name in enumerate(index.names)] index = index.set_names(valid_level_names) else: index = index.set_names(self.name) return index
进行正则替换 replace中的$1 $9 分别对应group(1-9) @param str 需要处理的字符串 @param regex 正则表达式 @param replace 替换的字符串 @return 进行正则表达式替换
public String replace(String str, String regex, String replace) { if (str == null) return ""; if (regex == null) return str; if(replace == null) replace = ""; return str.replaceAll(regex, replace); }
Creates a new HTTP session scope.
private void newHttpSessionScope() { SessionScopeAdvisor advisor = SessionScopeAdvisor.create(context); this.sessionScope = new HttpSessionScope(advisor); setAttribute(SESSION_SCOPE_ATTRIBUTE_NAME, this.sessionScope); }
Deletes all requests and responses for the given flows. Args: session_ids: A lists of flows to destroy. request_limit: A limit on the number of requests to delete. Returns: A list of requests that were deleted.
def MultiDestroyFlowStates(self, session_ids, request_limit=None): subjects = [session_id.Add("state") for session_id in session_ids] to_delete = [] deleted_requests = [] for subject, values in self.MultiResolvePrefix( subjects, self.FLOW_REQUEST_PREFIX, limit=request_limit): for _, serialized, _ in values: request = rdf_flow_runner.RequestState.FromSerializedString(serialized) deleted_requests.append(request) # Drop all responses to this request. response_subject = self.GetFlowResponseSubject(request.session_id, request.id) to_delete.append(response_subject) # Mark the request itself for deletion. to_delete.append(subject) # Drop them all at once. self.DeleteSubjects(to_delete, sync=True) return deleted_requests
// Create and return PIDGatherer lazily
func (p *Procstat) getPIDFinder() (PIDFinder, error) { if p.finder == nil { f, err := p.createPIDFinder() if err != nil { return nil, err } p.finder = f } return p.finder, nil }
Decodes the next value @returns {string} Next value
function decode() { var beg = i; var ch; var r = ""; // iterate until we reach the end of the string or "~" or ")" while (i < len && (ch = s[i]) !== "~" && ch !== ")") { switch (ch) { case "*": if (beg < i) { r += s.substring(beg, i); } if (s[i + 1] === "*") { // Unicode characters > 0xff (255), which are encoded as "**[4-digit code]" r += String.fromCharCode(parseInt(s.substring(i + 2, i + 6), 16)); beg = (i += 6); } else { // Unicode characters <= 0xff (255), which are encoded as "*[2-digit code]" r += String.fromCharCode(parseInt(s.substring(i + 1, i + 3), 16)); beg = (i += 3); } break; case "!": if (beg < i) { r += s.substring(beg, i); } r += "$"; beg = ++i; break; default: i++; } } return r + s.substring(beg, i); }
Sends a custom message. See the docs for all the possible options @see https://docs.emaildirect.com/#RelaySendCustomEmail
def send(options) response = EmailDirect.post "/RelaySends/#{category_id}", :body => options.to_json Hashie::Mash.new(response) end
/*Mfi - Money Flow Index Input = High, Low, Close, Volume Output = double Optional Parameters ------------------- optInTimePeriod:(From 2 to 100000) Number of period */
func Mfi(high, low, close, volume []float64, timePeriod int32) []float64 { var outBegIdx C.int var outNBElement C.int outReal := make([]float64, len(high)) C.TA_MFI(0, C.int(len(high)-1), (*C.double)(unsafe.Pointer(&high[0])), (*C.double)(unsafe.Pointer(&low[0])), (*C.double)(unsafe.Pointer(&close[0])), (*C.double)(unsafe.Pointer(&volume[0])), C.int(timePeriod), &outBegIdx, &outNBElement, (*C.double)(unsafe.Pointer(&outReal[0]))) return outReal[:outNBElement] }
创建 ColumnField @param column @return
public static ColumnField build(IntrospectedColumn column) { ColumnField field = new ColumnField(); field.setColumnName(column.getActualColumnName()); field.setJdbcType(column.getJdbcTypeName()); field.setFieldName(column.getJavaProperty()); field.setRemarks(column.getRemarks()); FullyQualifiedJavaType type = column.getFullyQualifiedJavaType(); field.setType(type); field.setTypePackage(type.getPackageName()); field.setShortTypeName(type.getShortName()); field.setFullTypeName(type.getFullyQualifiedName()); field.setIdentity(column.isIdentity()); field.setNullable(column.isNullable()); field.setSequenceColumn(column.isSequenceColumn()); field.setBlobColumn(column.isBLOBColumn()); field.setStringColumn(column.isStringColumn()); field.setJdbcCharacterColumn(column.isJdbcCharacterColumn()); field.setJdbcDateColumn(column.isJDBCDateColumn()); field.setJdbcTimeColumn(column.isJDBCTimeColumn()); field.setLength(column.getLength()); field.setScale(column.getScale()); return field; }
End hash element. @param string $name
public function endHashElement($name) { $this->checkEndHashElement($name); $this->json = $this->json->getParent(); }
Delete a permission module @author Steve Montambeault @link http://stevemo.ca @param $id @return \Illuminate\Http\RedirectResponse
public function destroy($id) { if ( $this->permissions->delete($id) ) { return Redirect::route('cpanel.permissions.index') ->with('success', Lang::get('cpanel::permissions.delete_success')); } else { return Redirect::route('cpanel.permissions.index') ->with('error', Lang::get('cpanel::permissions.model_not_found')); } }
Create user REST: POST /cloud/project/{serviceName}/user @param description [required] User description @param role [required] Openstack keystone role name @param serviceName [required] Service name
public OvhUserDetail project_serviceName_user_POST(String serviceName, String description, OvhRoleEnum role) throws IOException { String qPath = "/cloud/project/{serviceName}/user"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "role", role); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhUserDetail.class); }
This function searches for LaTeX expressions, delimited by $ and $$. It then adds backticks (``) around the expression, so that is does not get modifed by Markdown or BBcode. @param PostWillBeSaved $event
public function findExpressions(PostWillBeSaved $event) { // get the text from the post, comment or answer $text = $event->post->content; // this is the regular expresssion used. To check what it does use regex101.com $regex = '/(?<!\\\\)(?: ((?<!\\$)(?<!\\`)(?<!\\`\\n)\\${1,2}(?!\\n\\`)(?!\\`)(?!\\$)))(.*(?R)?.*)(?<!\\\\)(?: ((?<!\\$)(?<!\\`)(?<!\\`\\n)\\1(?!\\n\\`)(?!\\`)(?!\\$)))/mxU'; // run the replace and edit the post content $event->post->content = preg_replace($regex, '`\\1\\2\\3`', $text); }
Parsing the sent input
private function parse(){ $inputs = explode('&',$this->input); foreach($inputs as $input){ $exp = explode('=',$input); if(count($exp)==2) $this->content[urldecode($exp[0])] = urldecode($exp[1]); } }
Add a Download Feed @param int $downloadFeedUrl @return models\Download\Feed\DownloadFeed @throws \GuzzleHttp\Exception\GuzzleException @throws \alphayax\freebox\Exception\FreeboxApiException
public function addFeed($downloadFeedUrl) { $rest = $this->callService('POST', self::API_DOWNLOAD_FEEDS, [ 'url' => $downloadFeedUrl, ]); return $rest->getModel(models\Download\Feed\DownloadFeed::class); }
/* This function will return all the menu and sub-menu items that can be directly (the shortcut directly corresponds) and indirectly (the ALT-enabled char corresponds to the shortcut) associated with the keyCode.
@SuppressWarnings("deprecation") void findItemsWithShortcutForKey(List<MenuItem> items, int keyCode, KeyEvent event) { final boolean qwerty = isQwertyMode(); final int metaState = event.getMetaState(); final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData(); // Get the chars associated with the keyCode (i.e using any chording combo) final boolean isKeyCodeMapped = event.getKeyData(possibleChars); // The delete key is not mapped to '\b' so we treat it specially if (!isKeyCodeMapped && (keyCode != KeyEvent.KEYCODE_DEL)) { return; } // Look for an item whose shortcut is this key. final int N = mItems.size(); for (int i = 0; i < N; i++) { MenuItem item = mItems.get(i); if (item.hasSubMenu()) { ((Menu) item.getSubMenu()).findItemsWithShortcutForKey(items, keyCode, event); } final char shortcutChar = qwerty ? item.getAlphabeticShortcut() : item.getNumericShortcut(); if (((metaState & (KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON)) == 0) && (shortcutChar != 0) && (shortcutChar == possibleChars.meta[0] || shortcutChar == possibleChars.meta[2] || (qwerty && shortcutChar == '\b' && keyCode == KeyEvent.KEYCODE_DEL)) && item.isEnabled()) { items.add(item); } } }
Marshall the given parameter object.
public void marshall(RegistrationConfig registrationConfig, ProtocolMarshaller protocolMarshaller) { if (registrationConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(registrationConfig.getTemplateBody(), TEMPLATEBODY_BINDING); protocolMarshaller.marshall(registrationConfig.getRoleArn(), ROLEARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Returns all Days of Showtimes by a Movie. @param Carbon $date @return TheaterShowtimeDay|null
public function getShowtimeDayByMovie(Carbon $date) { $showDay = new TheaterShowtimeDay(); $theaters = $this->parseTheaters(); if (count($theaters) > 0) { $showDay->setTheaters($theaters); $showDay->setDate($date); return $showDay; } return null; }
Merges relationships with this instance's relationships. @param array $toAdd @return self
private function mergeRelationships(array $toAdd) { $this->relationships = array_merge($this->relationships, $toAdd); ksort($this->relationships); return $this; }
Callback called before any specs processing. @param array $args The suite arguments array.
public function start($args) { parent::start($args); $this->_dotWidth = max($this->_columns - 11 - strlen($this->_total) * 2, 10); $this->write("\n"); }
Form Header. @param out The html out stream. @param reg The resources object.
public void printHtmlHeader(PrintWriter out, ResourceBundle reg) { String strTitle = this.getProperty("title"); // Menu page if ((strTitle == null) || (strTitle.length() == 0)) strTitle = ((BasePanel)this.getScreenField()).getTitle(); String strHTMLStart = reg.getString("htmlHeaderStart"); String strHTMLEnd = reg.getString("htmlHeaderEnd"); // Note: don't free the reg key (DBServlet will) this.printHtmlHeader(out, strTitle, strHTMLStart, strHTMLEnd); }
// DEPRECATED: Use EnableAuditWithOptions instead
func (c *Sys) EnableAudit( path string, auditType string, desc string, opts map[string]string) error { return c.EnableAuditWithOptions(path, &EnableAuditOptions{ Type: auditType, Description: desc, Options: opts, }) }
Generates a Dataframe with the predictions for the provided data file. The data file should contain the text of one observation per row. @param datasetURI @return
public Dataframe predict(URI datasetURI) { //create a dummy dataset map Map<Object, URI> dataset = new HashMap<>(); dataset.put(null, datasetURI); TrainingParameters trainingParameters = (TrainingParameters) knowledgeBase.getTrainingParameters(); Dataframe testDataset = Dataframe.Builder.parseTextFiles(dataset, AbstractTextExtractor.newInstance(trainingParameters.getTextExtractorParameters()), knowledgeBase.getConfiguration() ); predict(testDataset); return testDataset; }
Eval. @param _permissionSet the PermissionSet @throws EFapsException on error
public static void eval(final PermissionSet _permissionSet) throws EFapsException { Evaluation.LOG.debug("Evaluating PermissionSet {}", _permissionSet); final Person person = Person.get(_permissionSet.getPersonId()); final Set<Long> ids = new HashSet<>(person.getRoles()); ids.addAll(person.getGroups()); ids.add(person.getId()); final QueryBuilder userAttrQueryBldr = new QueryBuilder(CIAdminAccess.AccessSet2UserAbstract); userAttrQueryBldr.addWhereAttrEqValue(CIAdminAccess.AccessSet2UserAbstract.UserAbstractLink, ids.toArray()); final QueryBuilder typeAttrQueryBldr = new QueryBuilder(CIAdminAccess.AccessSet2DataModelType); typeAttrQueryBldr.addWhereAttrEqValue(CIAdminAccess.AccessSet2DataModelType.DataModelTypeLink, _permissionSet .getTypeId()); final QueryBuilder queryBldr = new QueryBuilder(CIAdminAccess.AccessSet2Type); queryBldr.addWhereAttrInQuery(CIAdminAccess.AccessSet2Type.AccessSetLink, typeAttrQueryBldr.getAttributeQuery( CIAdminAccess.AccessSet2DataModelType.AccessSetLink)); queryBldr.addWhereAttrInQuery(CIAdminAccess.AccessSet2Type.AccessSetLink, userAttrQueryBldr.getAttributeQuery( CIAdminAccess.AccessSet2UserAbstract.AccessSetLink)); final CachedMultiPrintQuery multi = queryBldr.getCachedPrint4Request(); multi.addAttribute(CIAdminAccess.AccessSet2Type.AccessTypeLink); multi.executeWithoutAccessCheck(); while (multi.next()) { _permissionSet.addAccessTypeId(multi.<Long>getAttribute(CIAdminAccess.AccessSet2Type.AccessTypeLink)); } final Type type = Type.get(_permissionSet.getTypeId()); if (type.isCheckStatus()) { final QueryBuilder statusQueryBldr = new QueryBuilder(CIAdminAccess.AccessSet2Status); statusQueryBldr.addWhereAttrInQuery(CIAdminAccess.AccessSet2Status.AccessSetLink, typeAttrQueryBldr .getAttributeQuery(CIAdminAccess.AccessSet2DataModelType.AccessSetLink)); statusQueryBldr.addWhereAttrInQuery(CIAdminAccess.AccessSet2Status.AccessSetLink, userAttrQueryBldr .getAttributeQuery(CIAdminAccess.AccessSet2UserAbstract.AccessSetLink)); final CachedMultiPrintQuery statusMulti = statusQueryBldr.getCachedPrint4Request(); statusMulti.addAttribute(CIAdminAccess.AccessSet2Status.SatusLink); statusMulti.executeWithoutAccessCheck(); while (statusMulti.next()) { final Long statusId = statusMulti.getAttribute(CIAdminAccess.AccessSet2Status.SatusLink); final Status status = Status.get(statusId); if (status.getStatusGroup().getId() == type.getStatusAttribute().getLink().getId()) { _permissionSet.addStatusId(statusId); } } } Evaluation.LOG.debug("Evaluated PermissionSet {}", _permissionSet); }
// OrElse returns the float64 value or a default value if the value is not present.
func (f Float64) OrElse(v float64) float64 { if f.Present() { return *f.value } return v }
Checks if the class represented by className implements DelegatedFacesServlet. @param className @return
private boolean isDelegatedFacesServlet(String className) { if (className == null) { // The class name can be null if this is e.g., a JSP mapped to // a servlet. return false; } try { Class<?> clazz = Class.forName(className); return DELEGATED_FACES_SERVLET_CLASS.isAssignableFrom(clazz); } catch (ClassNotFoundException cnfe) { return false; } }
Return true if the transport and content negotiators have finished.
public boolean isFullyEstablished() { boolean result = true; MediaNegotiator mediaNeg = getMediaNegotiator(); if ((mediaNeg == null) || !mediaNeg.isFullyEstablished()) { result = false; } TransportNegotiator transNeg = getTransportNegotiator(); if ((transNeg == null) || !transNeg.isFullyEstablished()) { result = false; } return result; }
Returns the indices that would sort an array. @param array Array. @param ascending Ascending order. @return Array of indices.
public static int[] Argsort(final float[] array, final boolean ascending) { Integer[] indexes = new Integer[array.length]; for (int i = 0; i < indexes.length; i++) { indexes[i] = i; } Arrays.sort(indexes, new Comparator<Integer>() { @Override public int compare(final Integer i1, final Integer i2) { return (ascending ? 1 : -1) * Float.compare(array[i1], array[i2]); } }); return asArray(indexes); }
Mark the current job as complete
public function complete() { $this->stopped(); $this->setStatus(Job::STATUS_COMPLETE); $this->redis->zadd(Queue::redisKey($this->queue, 'processed'), time(), $this->payload); Stats::incr('processed', 1); Stats::incr('processed', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_COMPLETE, $this); }
Execute this task. @throws BuildException Description of the Exception
public function main() { if ($this->remove) { if ($this->name === null || $this->name === "") { throw new BuildException("The 'name' attribute is required with 'unset'."); } $this->removeProperty($this->name); return; } if ($this->file === null) { // check for the required name attribute if ($this->name === null || $this->name === '') { throw new BuildException("The 'name' attribute is required."); } // adjust the property value if necessary -- is this necessary? // Doesn't Ant do this automatically? $this->value = $this->getProject()->replaceProperties($this->value); // set the property $this->forceProperty($this->name, $this->value); } else { if (!$this->file->exists()) { throw new BuildException($this->file->getAbsolutePath() . " does not exists."); } $this->loadFile($this->file); } }
Get video params @return $this
public function getParams() { preg_match_all('/https?:\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)(?:$|\/|\?)/', $this->url, $matches); $id = isset($matches[3][0]) ? $matches[3][0] : false; $this->params['id'] = $id; return $this; }
Looks for handle identifiers in the misc txt of the citation elements When finding an hdl, creates a new HDL element. @param citation_elements: (list) elements to process
def look_for_hdl(citation_elements): for el in list(citation_elements): matched_hdl = re_hdl.finditer(el['misc_txt']) for match in reversed(list(matched_hdl)): hdl_el = {'type': 'HDL', 'hdl_id': match.group('hdl_id'), 'misc_txt': el['misc_txt'][match.end():]} el['misc_txt'] = el['misc_txt'][0:match.start()] citation_elements.insert(citation_elements.index(el) + 1, hdl_el)
Sets a new fault @param \GoetasWebservices\SoapServices\SoapClient\Envelope\SoapEnvelope12\Parts\Fault $fault @return self
public function setFault(\GoetasWebservices\SoapServices\SoapClient\Envelope\SoapEnvelope12\Parts\Fault $fault) { $this->fault = $fault; return $this; }
Remove this remote message filter. @param messageFilter The message filter to remove. @param bFreeFilter If true, free the remote filter.
public boolean removeRemoteMessageFilter(BaseMessageFilter messageFilter, boolean bFreeFilter) throws RemoteException { BaseTransport transport = this.createProxyTransport(REMOVE_REMOTE_MESSAGE_FILTER); transport.addParam(FILTER, messageFilter); // Don't use COMMAND transport.addParam(FREE, bFreeFilter); Object strReturn = transport.sendMessageAndGetReply(); Object objReturn = transport.convertReturnObject(strReturn); if (objReturn instanceof Boolean) return ((Boolean)objReturn).booleanValue(); return true; }
Set a specific character of the current string. @param int $offset Offset (can be negative and unbound). @param string $value Value. @return self
public function offsetSet($offset, $value) { $head = null; $offset = $this->computeOffset($offset); if (0 < $offset) { $head = \mb_substr($this->_string, 0, $offset); } $tail = \mb_substr($this->_string, $offset + 1); $this->_string = $head . $value . $tail; $this->_direction = null; return $this; }
not publish group action @param $class @return boolean
protected function notPublishGroupAction($class) { try { if ( ! $class::whereIn('id', $this->request->id)->update(['is_publish' => false])) { throw new UpdateException($this->request->id, 'group not not published'); } event(new $this->events['success']($this->request->id)); return true; } catch (UpdateException $e) { event(new $this->events['fail']($e->getDatas())); return false; } }
Find all snapshots associated with this deployment's lineage
def find_snapshots unless @lineage s = @servers.first kind_params = s.transform_parameters(s.parameters) @lineage = kind_params['DB_LINEAGE_NAME'].gsub(/text:/, "") end snapshots = Ec2EbsSnapshot.find_by_cloud_id(@servers.first.cloud_id).select { |n| n.nickname =~ /#{@lineage}.*$/ } end
open file and truncate content @since 0.9
public function openWithTruncate() { $this->open(); $this->content->truncate(0); $time = time(); $this->lastAccessed = $time; $this->lastModified = $time; }
Pack a OmemoBundleElement containing our key material. @param userDevice our OmemoDevice. @return OmemoBundleElement @throws CorruptedOmemoKeyException when a key could not be loaded
OmemoBundleElement_VAxolotl packOmemoBundle(OmemoDevice userDevice) throws CorruptedOmemoKeyException { int currentSignedPreKeyId = loadCurrentOmemoSignedPreKeyId(userDevice); T_SigPreKey currentSignedPreKey = loadOmemoSignedPreKeys(userDevice).get(currentSignedPreKeyId); return new OmemoBundleElement_VAxolotl( currentSignedPreKeyId, keyUtil().signedPreKeyPublicForBundle(currentSignedPreKey), keyUtil().signedPreKeySignatureFromKey(currentSignedPreKey), keyUtil().identityKeyForBundle(keyUtil().identityKeyFromPair(loadOmemoIdentityKeyPair(userDevice))), keyUtil().preKeyPublicKeysForBundle(loadOmemoPreKeys(userDevice)) ); }
// Create a backend to be used for L7 load balancing. This L7 pool has backend protocol, L7 members, L7 health monitor and session affinity. L7 pool is associated with L7 policies.
func (r Network_LBaaS_L7Pool) CreateL7Pool(loadBalancerUuid *string, l7Pool *datatypes.Network_LBaaS_L7Pool, l7Members []datatypes.Network_LBaaS_L7Member, l7HealthMonitor *datatypes.Network_LBaaS_L7HealthMonitor, l7SessionAffinity *datatypes.Network_LBaaS_L7SessionAffinity) (resp datatypes.Network_LBaaS_LoadBalancer, err error) { params := []interface{}{ loadBalancerUuid, l7Pool, l7Members, l7HealthMonitor, l7SessionAffinity, } err = r.Session.DoRequest("SoftLayer_Network_LBaaS_L7Pool", "createL7Pool", params, &r.Options, &resp) return }
Returns list of annotated methods for given class. This list will be cached on per-class basis to avoid costly annotations look up.
static List<EventMethod> getMethodsForTarget(@NonNull Object target) { if (target instanceof Class) { return getMethodsFromClass((Class<?>) target, true); } else { return getMethodsFromClass(target.getClass(), false); } }
A datetime property.
def Datetime(null=True, **kwargs): """""" return Property( types=datetime.datetime, convert=util.local_timezone, load=dateutil.parser.parse, null=null, **kwargs )
Получить значение из запроса
public function fetchValue($sql, $col = null, $values = null, $connection = null) { $st = $this->query($sql, $values, $connection); if (!$row = $st->fetch(\PDO::FETCH_ASSOC)) { return false; } if (!$col) { return current($row); } if (!array_key_exists($col, $row)) { Exception::ThrowError(Exception::COLUMN_NOT_EXISTS, $col); } return $row[$col]; }
Create a simplified character representation of the data row, which can be pattern matched with a regex
def picture(self, row): template = '_Xn' types = (type(None), binary_type, int) def guess_type(v): try: v = text_type(v).strip() except ValueError: v = binary_type(v).strip() #v = v.decode('ascii', 'replace').strip() if not bool(v): return type(None) for t in (float, int, binary_type, text_type): try: return type(t(v)) except: pass def p(e): tm = t = None try: t = guess_type(e) tm = self.type_map.get(t, t) return template[types.index(tm)] except ValueError as e: raise ValueError("Type '{}'/'{}' not in the types list: {} ({})".format(t, tm, types, e)) return ''.join(p(e) for e in row)
Apply search filters to a SQL query column. Apply collation rules to MySQL. @param Builder $query @param Expression|string $field @param string[] $search_terms
private function whereSearch(Builder $query, $field, array $search_terms): void { if ($field instanceof Expression) { $field = $field->getValue(); } foreach ($search_terms as $search_term) { $query->whereContains(DB::raw($field), $search_term); } }
Crumbs @param array $segments dedd @return array
public function crumbs($segments) { $item = ''; $crumbs = []; foreach ($segments as $segment): $item = $item . "/" . $segment; $crumbs["{$segment}"] = $item; endforeach; return $crumbs; }
Checks whether the given file is inside the given directory. @param file the file @param directory the directory @return {@literal true} if the file is in the directory (or any subdirectories), {@literal false} otherwise.
public static boolean isInDirectory(File file, File directory) { try { return FilenameUtils.directoryContains(directory.getCanonicalPath(), file.getCanonicalPath()); } catch (IOException e) { //NOSONAR return false; } }
Read - Maps -----
public function getNameValueMapByType( $parentId, $parentType, $type ) { $config = []; $config[ 'conditions' ][ 'parentId' ] = $parentId; $config[ 'conditions' ][ 'parentType' ] = $parentType; $config[ 'conditions' ][ 'type' ] = $type; return $this->getNameValueMap( $config ); }
Encodes the message into binary format. The resulting binary message is stored in C{self.rawMessage}
def _marshal(self, newSerial=True, oobFDs=None): flags = 0 if not self.expectReply: flags |= 0x1 if not self.autoStart: flags |= 0x2 # may be overriden below, depending on oobFDs _headerAttrs = self._headerAttrs # marshal body before headers to know if the 'unix_fd' header is needed if self.signature: binBody = b''.join( marshal.marshal( self.signature, self.body, oobFDs=oobFDs )[1] ) if oobFDs: # copy class based _headerAttrs to add a unix_fds header this # time _headerAttrs = list(self._headerAttrs) _headerAttrs.append(('unix_fds', 9, False)) self.unix_fds = len(oobFDs) else: binBody = b'' self.headers = [] for attr_name, code, _ in _headerAttrs: hval = getattr(self, attr_name, None) if hval is not None: if attr_name == 'path': hval = marshal.ObjectPath(hval) elif attr_name == 'signature': hval = marshal.Signature(hval) elif attr_name == 'unix_fds': hval = marshal.UInt32(hval) self.headers.append([code, hval]) self.bodyLength = len(binBody) if newSerial: self.serial = DBusMessage._nextSerial DBusMessage._nextSerial += 1 binHeader = b''.join(marshal.marshal( _headerFormat, [ self.endian, self._messageType, flags, self._protocolVersion, self.bodyLength, self.serial, self.headers ], lendian=self.endian == ord('l') )[1]) headerPadding = marshal.pad['header'](len(binHeader)) self.rawHeader = binHeader self.rawPadding = headerPadding self.rawBody = binBody self.rawMessage = b''.join([binHeader, headerPadding, binBody]) if len(self.rawMessage) > self._maxMsgLen: raise error.MarshallingError( 'Marshalled message exceeds maximum message size of %d' % (self._maxMsgLen,), )
Double the hash table size and rehash the entries. Assumes total lock.
@SuppressWarnings("unchecked") void rehash() { Entry<K,V>[] src = entries; if (src == null) { throw new CacheClosedException(cache); } int i, sl = src.length, n = sl * 2, _mask = n - 1, idx; Entry<K,V>[] tab = new Entry[n]; long _count = 0; Entry _next, e; for (i = 0; i < sl; i++) { e = src[i]; while (e != null) { _count++; _next = e.another; idx = modifiedHashCode(e.hashCode) & _mask; e.another = tab[idx]; tab[idx] = e; e = _next; } } entries = tab; calcMaxFill(); }
Redirection workaround See http://www.php.net/manual/ro/function.curl-setopt.php#102121 for more infos. @return int : redirect count
private function follow() { $status = 0; $redirectCount = 0; $newurl = $this->url; $maxRedirect = $this->maxRedirect; $session = curl_copy_handle($this->session); curl_setopt($session, CURLOPT_HEADER, true); curl_setopt($session, CURLOPT_NOBODY, true); curl_setopt($session, CURLOPT_FORBID_REUSE, false); do { curl_setopt($session, CURLOPT_URL, $newurl); $response = curl_exec($session); $infos = curl_getinfo($session); $this->parseError(curl_errno($session), curl_error($session)); if (empty($this->error)) { $response = $this->parseResponse($response, $infos); $status = $response['status']; if (($status == 301 || $status == 302) && isset($response['headers']['location'])) { $redirectCount++; $newurl = $response['headers']['location']; if (!preg_match('#^https?:#i', $newurl)) { $newurl = $this->url.$newurl; } } } $maxRedirect--; } while ($status != 200 && $maxRedirect > 0); curl_close($session); if ($maxRedirect == 0 && ($status == 0 || $status == 301 || $status == 302)) { $this->error = 'Too many redirects...'; $this->cwsDebug->error($this->error); return false; } curl_setopt($this->session, CURLOPT_URL, $newurl); return $redirectCount; }
更新状态 @return array
public function actionUpdateStatus() { $ids = \Yii::$app->request->post('ids'); $status = intval(\Yii::$app->request->post('status')); if ($status != 0) { $status = 1; } foreach (StringHelper::explode($ids, ',', true, true) as $id) { $obj = DpAdminMenuUrl::find() ->findByUrlId($id) ->one(); if ($obj) { $obj->status = $status; $obj->save(); } } return $this->renderSuccess('状态更新成功'); }
<p> Environment Variables for the branch. </p> @param environmentVariables Environment Variables for the branch. @return Returns a reference to this object so that method calls can be chained together.
public CreateBranchRequest withEnvironmentVariables(java.util.Map<String, String> environmentVariables) { setEnvironmentVariables(environmentVariables); return this; }
get unique identifier of this container :return: str
def get_id(self): if self._id is None: self._id = graceful_get(self.inspect(refresh=True), "ID") return self._id
// NewEndpoint creates a new ipv6 endpoint.
func (p *protocol) NewEndpoint(nicid tcpip.NICID, addr tcpip.Address, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, linkEP stack.LinkEndpoint) (stack.NetworkEndpoint, *tcpip.Error) { return &endpoint{ nicid: nicid, id: stack.NetworkEndpointID{LocalAddress: addr}, linkEP: linkEP, linkAddrCache: linkAddrCache, dispatcher: dispatcher, }, nil }
Validate the incoming request. :param request: The incoming :class:`oauth2.web.Request`. :return: Returns ``True`` if data is valid. :raises: :class:`oauth2.error.OAuthInvalidError`
def read_validate_params(self, request): self.refresh_token = request.post_param("refresh_token") if self.refresh_token is None: raise OAuthInvalidError( error="invalid_request", explanation="Missing refresh_token in request body") self.client = self.client_authenticator.by_identifier_secret(request) try: access_token = self.access_token_store.fetch_by_refresh_token( self.refresh_token ) except AccessTokenNotFound: raise OAuthInvalidError(error="invalid_request", explanation="Invalid refresh token") refresh_token_expires_at = access_token.refresh_expires_at self.refresh_grant_type = access_token.grant_type if refresh_token_expires_at != 0 and \ refresh_token_expires_at < int(time.time()): raise OAuthInvalidError(error="invalid_request", explanation="Invalid refresh token") self.data = access_token.data self.user_id = access_token.user_id self.scope_handler.parse(request, "body") self.scope_handler.compare(access_token.scopes) return True
Assert that key exists in array and it's value not empty. @param mixed $value @param string|integer $key @param string $message @param string $propertyPath @return void @throws Exception
static public function notEmptyKey($value, $key, $message = null, $propertyPath = null) { static::keyExists($value, $key, $message, $propertyPath); static::notEmpty($value[$key], $message, $propertyPath); }
Performs lookup on key and returns appropriate replacement string. @param array $matches Array of 1 el containing key to search for. @return string Text with which to replace key or value of key if none is found.
private function replaceTokenCallback($matches) { $key = $matches[1]; /* Get tokens from tokensource and merge them with the * tokens given directly via build file. This should be * done a bit more elegantly */ if ($this->_alltokens === null) { $this->_alltokens = []; $count = count($this->_tokensources); for ($i = 0; $i < $count; $i++) { $source = $this->_tokensources[$i]; $this->_alltokens = array_merge($this->_alltokens, $source->getTokens()); } $this->_alltokens = array_merge($this->_tokens, $this->_alltokens); } $tokens = $this->_alltokens; $replaceWith = null; $count = count($tokens); for ($i = 0; $i < $count; $i++) { if ($tokens[$i]->getKey() === $key) { $replaceWith = $tokens[$i]->getValue(); } } if ($replaceWith === null) { $replaceWith = $this->_beginToken . $key . $this->_endToken; $this->log("No token defined for key \"" . $this->_beginToken . $key . $this->_endToken . "\""); } else { $this->log( "Replaced \"" . $this->_beginToken . $key . $this->_endToken . "\" with \"" . $replaceWith . "\"", Project::MSG_VERBOSE ); } return $replaceWith; }
Returns the content to display on course/overview page, formatted and passed through filters if $options['context'] is not specified, the module context is used @param array|stdClass $options formatting options, see {@link format_text()} @return string
public function get_formatted_content($options = array()) { $this->obtain_view_data(); if (empty($this->content)) { return ''; } if ($this->contentisformatted) { return $this->content; } // Improve filter performance by preloading filter setttings for all // activities on the course (this does nothing if called multiple // times) filter_preload_activities($this->get_modinfo()); $options = (array)$options; if (!isset($options['context'])) { $options['context'] = $this->get_context(); } return format_text($this->content, FORMAT_HTML, $options); }
对一段文本进行分词,返回list类型的分词结果 Keyword arguments: lower -- 是否将单词小写(针对英文) use_stop_words -- 若为True,则利用停止词集合来过滤(去掉停止词) use_speech_tags_filter -- 是否基于词性进行过滤。若为True,则使用self.default_speech_tag_filter过滤。否则,不过滤。
def segment(self, text, lower=True, use_stop_words=True, use_speech_tags_filter=False): jieba_result = cut_for_search(text) jieba_result = [w for w in jieba_result] # 去除特殊符号 word_list = [w.strip() for w in jieba_result] word_list = [word for word in word_list if len(word) > 0] if use_speech_tags_filter == False: jieba_result = [w for w in jieba_result] if lower: word_list = [word.lower() for word in word_list] if use_stop_words: word_list = [word.strip() for word in word_list if word.strip() not in self.stop_words] return word_list
/* Get all edit-config tags
function(platform) { var platform_tag = this.doc.find('./platform[@name="' + platform + '"]'); var platform_edit_configs = platform_tag ? platform_tag.findall('edit-config') : []; var edit_configs = this.doc.findall('edit-config').concat(platform_edit_configs); return edit_configs.map(function(tag) { var editConfig = { file : tag.attrib['file'], target : tag.attrib['target'], mode : tag.attrib['mode'], id : 'config.xml', xmls : tag.getchildren() }; return editConfig; }); }
@param array|CloudMessage|Message $message @throws InvalidArgumentException @throws InvalidMessage @return array
public function validate($message): array { if (\is_array($message)) { $message = CloudMessage::fromArray($message); } if (!($message instanceof Message)) { throw new InvalidArgumentException( 'Unsupported message type. Use an array or a class implementing %s'.Message::class ); } try { $response = $this->messagingApi->validateMessage($message); } catch (NotFound $e) { throw (new InvalidMessage($e->getMessage(), $e->getCode())) ->withResponse($e->response()); } return JSON::decode((string) $response->getBody(), true); }