comment
stringlengths
16
255
code
stringlengths
52
3.87M
Returns the region name for the current language. @return string|null
public function getRegionName(): ?string { return $this->region ? (static::regions()[$this->region] ?? $this->region) : null; }
This method returns a stream of RDF triples associated with this target resource @param limit is the number of child resources returned in the response, -1 for all @param resource the fedora resource @return {@link RdfStream}
private RdfStream getResourceTriples(final int limit, final FedoraResource resource) { final PreferTag returnPreference; if (prefer != null && prefer.hasReturn()) { returnPreference = prefer.getReturn(); } else if (prefer != null && prefer.hasHandling()) { returnPrefere...
R(n) ratio expected from theory for given noise type alpha = b + 2
def rn_theory(af, b): # From IEEE1139-2008 # alpha beta ADEV_mu MDEV_mu Rn_mu # -2 -4 1 1 0 Random Walk FM # -1 -3 0 0 0 Flicker FM # 0 -2 -1 -1 0 White FM # 1 -1 -2 -2 0 ...
Checks whether any Comparator is equal to rhs. Args: # rhs: can be anything Returns: bool
def equals(self, rhs): for comparator in self._comparators: if comparator.equals(rhs): return True return False
// SignRS384 signs data with rsa-sha384
func SignRS384(r *rsa.PrivateKey, data []byte) ([]byte, error) { h := sha512.New384() h.Write(data) d := h.Sum(nil) return rsa.SignPKCS1v15(rand.Reader, r, crypto.SHA384, d) }
Convert a string to a pure title case for each word, replacing special characters by space. @param string The string to convert (must not be <code>null</code>). @return The string in title case. @throws LionEngineException If invalid arguments.
public static String toTitleCaseWord(String string) { Check.notNull(string); final String[] words = SPACE.split(REPLACER.matcher(string).replaceAll(Constant.SPACE)); final StringBuilder title = new StringBuilder(string.length()); for (int i = 0; i < words.length; i++) ...
<code>optional string domainSocketPath = 5;</code>
public java.lang.String getDomainSocketPath() { java.lang.Object ref = domainSocketPath_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8...
See bidirectional LSTM's conversion function for its output shapes.
def calculate_bidirectional_lstm_output_shapes(operator): ''' ''' check_input_and_output_numbers(operator, input_count_range=[1, 5], output_count_range=[1, 5]) check_input_and_output_types(operator, good_input_types=[FloatTensorType]) input_shape = operator.inputs[0].type.shape # LSTM acc...
Computes an array that contains current content data; it can also lighten result according to requested format. @param integer $format @return array
public function jsonSerialize($format = self::JSON_DEFAULT_FORMAT) { $data = [ 'uid' => $this->_uid, 'label' => $this->_label, 'type' => $this->getContentType(), 'state' => $this->_state, 'created' => $this->_created->getT...
Displays a list of available time zones. Use this list when setting a time zone using ``timezone.set_zone`` :return: a list of time zones :rtype: list CLI Example: .. code-block:: bash salt '*' timezone.list_zones
def list_zones(): ''' ''' ret = salt.utils.mac_utils.execute_return_result( 'systemsetup -listtimezones') zones = salt.utils.mac_utils.parse_return(ret) return [x.strip() for x in zones.splitlines()]
Get the default connection name. This method is used to get the fallback connection name if an instance is created through the EndpointRegistry without a connection. @return string @see \Muffin\Webservice\Model\EndpointRegistry::get()
public static function defaultConnectionName() { $namespaceParts = explode('\\', get_called_class()); $plugin = array_slice(array_reverse($namespaceParts), 3, 2); return Inflector::underscore(current($plugin)); }
@param QueryString|string $query @return Uri
public function setQuery($query) { if (!($query instanceof QueryString)) { $this->query = new QueryString($query); return $this; } $this->query = $query; return $this; }
Sort within buckets, then batch, then shuffle batches. Partitions data into chunks of size 100*batch_size, sorts examples within each chunk using sort_key, then batch these examples and shuffle the batches.
def pool(data, batch_size, key, batch_size_fn=lambda new, count, sofar: count, random_shuffler=None, shuffle=False, sort_within_batch=False): if random_shuffler is None: random_shuffler = random.shuffle for p in batch(data, batch_size * 100, batch_size_fn): p_batch = batch(sorted(p...
Adds the required data used in the service template @param \Aimeos\MW\View\Iface $view View object @return \Aimeos\MW\View\Iface View object with assigned parameters
protected function addViewData( \Aimeos\MW\View\Iface $view ) { $manager = \Aimeos\MShop::create( $this->getContext(), 'media/property/type' ); $search = $manager->createSearch( true )->setSlice( 0, 10000 ); $search->setConditions( $search->compare( '==', 'media.property.type.domain', 'service' ) ); $search->...
Write a local variable table entry for every registered variable.
void generateTableEntries(CodeBuilder ga) { for (Variable var : allVariables) { try { var.local.tableEntry(ga); } catch (Throwable t) { throw new RuntimeException("unable to write table entry for: " + var.local, t); } } }
Get the authentication object. @param string $errorOnNull If true, throw an exception if auth null. @return MyAllocator\phpsdk\src\Object\Auth API Authentication object. @throws MyAllocator\phpsdk\src\Exception\ApiException
public function getAuth($errorOnNull = false) { if ($errorOnNull && !$this->auth) { $msg = 'No Auth object provided. (HINT: Set your Auth data using ' . '"$API->setAuth(Auth $auth)" or $API\' constructor. ' . 'See https://TODO for details.'; throw ...
Get page favicon url @return string url
public function getPageFavicon() { if (!$this->parser) { return; } $node = $this->parser->find('link[rel=shortcut], link[rel=icon], link[rel=shortcut icon]', 0); if ($node) { return $node->getAttribute('href'); } }
// refresh prints the progress of all downloads to the terminal
func (c *ConsoleClient) refresh() { // clear lines for incomplete downloads if c.inProgress > 0 { fmt.Printf("\033[%dA\033[K", c.inProgress) } // print newly completed downloads for i, resp := range c.responses { if resp != nil && resp.IsComplete() { if resp.Err() != nil { c.failed++ fmt.Fprintf(os...
This method is intended for internal use only. Returns the marshaled request configured with additional parameters to enable operation dry-run.
@Override public Request<ModifyInstancePlacementRequest> getDryRunRequest() { Request<ModifyInstancePlacementRequest> request = new ModifyInstancePlacementRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
Populate from an array. @param array $data
public function populate($data = array()) { if (isset($data['name']) && $data['name'] !== null) { $this->name = $data['name']; } if (isset($data['type']) && $data['type'] !== null) { $this->type = $data['type']; } }
/* (non-Javadoc) @see net.roboconf.doc.generator.internal.transformers.AbstractRoboconfTransformer #getConfiguredLayout()
@Override public Layout<AbstractType,String> getConfiguredLayout() { return new StaticLayout<AbstractType,String>( this.graph, this, getGraphDimension()); }
// UpdateJobs mocks base method
func (m *MockInstance) UpdateJobs(arg0 manifest.Manifest, arg1 ui.Stage) error { ret := m.ctrl.Call(m, "UpdateJobs", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
This mehtod will render the JavaScript associated with the id lookup if id has been set. @param request @param id @return
private String renderNameAndId(HttpServletRequest request, String id) { // if id is not set then we need to exit if (id == null) return null; // Legacy Java Script support -- This writes out a single table with both the id and names // mixed. This is legacy support to m...
Marshall the given parameter object.
public void marshall(CreateAliasRequest createAliasRequest, ProtocolMarshaller protocolMarshaller) { if (createAliasRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createAliasRequest.getFun...
this method will generate a new container node that prevent control transformation to be applied to the shadow effect (which makes it looks as a real shadow)
public static Node createMaterialNode(Node control, int level) { Node container = new Pane(control){ @Override protected double computeMaxWidth(double height) { return computePrefWidth(height); } @Override protected double computeMaxHe...
Add file to package from content @param content @param target Target path like /opt/application/bin/foo @return @throws IOException
@Override public FileBuilder addFile(ByteBuffer content, Path target) throws IOException { checkTarget(target); FileBuilder fb = new FileBuilder(); fb.content = content; fb.target = target; fb.size = content.limit(); fb.compressFilename(); fileBuilders.add...
dataURL 转成 blob 对象 @param dataURL @returns blob
function dataURLtoBlob(dataUrl) { let pos = dataUrl.indexOf(',', 0) let arr = [ dataUrl.slice(0, pos), dataUrl.slice(pos+1) ] let mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n) while(n--) { u8arr[n] = bstr.charCodeAt(n) ...
Extract a token from a request object.
def _get_token(self, request, refresh_token=False): if self.config.cookie_set(): token = self._get_token_from_cookies(request, refresh_token) if token: return token else: if self.config.cookie_strict(): raise excep...
Get the usage for the remote exectuion options :return Usage for the remote execution options
def usage(self): # Retrieve the text for just the arguments usage = self.parser.format_help().split("optional arguments:")[1] # Remove any blank lines and return return "Remote Options:" + os.linesep + \ os.linesep.join([s for s in usage.splitlines() if s])
Create first user
public function createUser() { $data['name'] = $this->ask('Administrator name'); $data['email'] = $this->ask('Administrator email'); $data['password'] = bcrypt($this->secret('Administrator password')); $data['role_id'] = 1; User::create($data); $this->info('Us...
Remove a selection criteria from the subscription
public void removeSelectionCriteria(SelectionCriteria selCriteria) throws SIResourceException { if (tc.isEntryEnabled()) SibTr.entry(tc, "removeSelectionCriteria", new Object[] { selCriteria }); // If the selection criteria was removed then this is an indication that it w...
// UnmarshalJSON converts the string to a LangID
func (lng *LangID) UnmarshalJSON(p []byte) error { if len(p) == 0 { return nil } if p[0] != '"' { var u uint16 if err := json.Unmarshal(p, &u); err != nil { return err } *lng = LangID(u) return nil } var s string if err := json.Unmarshal(p, &s); err != nil { return err } u, err := strconv.Parse...
processing error
public JavaCompiler doProcessing(Context context, List<JCCompilationUnit> roots, List<ClassSymbol> classSymbols, Iterable<? extends PackageSymbol> pckSymbols, Log.DeferredD...
// NewStickerMessage function
func NewStickerMessage(packageID, stickerID string) *StickerMessage { return &StickerMessage{ PackageID: packageID, StickerID: stickerID, } }
Copies the shell items to a path. Returns: str: converted shell item list path or None.
def CopyToPath(self): number_of_path_segments = len(self._path_segments) if number_of_path_segments == 0: return None strings = [self._path_segments[0]] number_of_path_segments -= 1 for path_segment in self._path_segments[1:]: # Remove a trailing \ except for the last path segment....
// SetFilters sets the Filters field's value.
func (s *DescribeMaintenanceWindowsInput) SetFilters(v []*MaintenanceWindowFilter) *DescribeMaintenanceWindowsInput { s.Filters = v return s }
Creates an answer from a functional interface - allows for a strongly typed answer to be created ideally in Java 8 @param answer interface to the answer - a void method @param <A> input parameter type 1 @return the answer object to use @since 2.1.0
@Incubating public static <A> Answer<Void> answerVoid(VoidAnswer1<A> answer) { return toAnswer(answer); }
// SetValuesToAdd sets the ValuesToAdd field's value.
func (s *ModifyDBClusterSnapshotAttributeInput) SetValuesToAdd(v []*string) *ModifyDBClusterSnapshotAttributeInput { s.ValuesToAdd = v return s }
Returns the collection of events provided by the given service interface. @param serviceInterface the service interface @return the events provided by the given service interface
public static Map<EventType, Method> getEventMap(Class<?> serviceInterface) { if (!serviceInterface.isInterface()) { Class type = serviceInterface; Map<EventType, Method> events = new HashMap<>(); while (type != Object.class) { for (Class<?> iface : type.getInterfaces()) { events...
Outputs the HTML for an &lt;option&gt; field. @param array $values The options to output. @param mixed $selected_value A string or an array with the selected values that should be selected. @return string The HTML string.
public function select_option($values, $selected_value) { $content = ''; foreach ($values as $value => $title) { if (is_array($title)) { $label = $this->_escape($value); $content .= "<optgroup label=\"{$label}\">"; $content .= $this->select_option($title, $selected_value); $content .= "</optgro...
获取样式 @param {Object} dom DOM节点 @param {String} name 样式名 @param {Any} defaultValue 默认值 @return {String} 属性值
function getStyle(dom, name, defaultValue) { try { if (window.getComputedStyle) { return window.getComputedStyle(dom, null)[name]; } return dom.currentStyle[name]; } catch (e) { if (!Util.isNil(defaultValue)) { return defaultValue; } return null; } }
Set the Root.Description, possibly splitting long descriptions across multiple terms.
def set_wrappable_term(self, v, term): import textwrap for t in self['Root'].find(term): self.remove_term(t) for l in textwrap.wrap(v, 80): self['Root'].new_term(term, l)
Subclasses may override this. This method calls handleGetMonthLength() to obtain the calendar-specific month length.
protected int handleComputeJulianDay(int bestField) { boolean useMonth = (bestField == DAY_OF_MONTH || bestField == WEEK_OF_MONTH || bestField == DAY_OF_WEEK_IN_MONTH); int year; if (bestField == WEEK_OF_YEAR) { // Nota Bene! It is critical that YE...
Returns the number of rows matching the dynamic query. @param dynamicQuery the dynamic query @param projection the projection to apply to the query @return the number of rows matching the dynamic query
@Override public long dynamicQueryCount(DynamicQuery dynamicQuery, Projection projection) { return cpDefinitionInventoryPersistence.countWithDynamicQuery(dynamicQuery, projection); }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
@Override public void eUnset(int featureID) { switch (featureID) { case XbasePackage.XINSTANCE_OF_EXPRESSION__TYPE: setType((JvmTypeReference)null); return; case XbasePackage.XINSTANCE_OF_EXPRESSION__EXPRESSION: setExpression((XExpression)null); return; } super.eUnset(featureID); }
Luckily `opts` is always the 2nd argument
function withPlugins(fn) { return function() { const args = Array.from(arguments); let plugins = (args[1] && args[1].plugins) || []; if (!isArray(plugins)) { plugins = Object.values(plugins); } args[1] = Object.assign({}, args[1], { plugins: internalPlugins.concat(plugins) }); ...
Marshall the given parameter object.
public void marshall(PlainTextMessageType plainTextMessageType, ProtocolMarshaller protocolMarshaller) { if (plainTextMessageType == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(plainTextMessageTyp...
*------------------------------ Date converter --------------------------*//
public static function parseFromFormat($format, $date) { // reverse engineer date formats $keys = [ 'Y' => ['year', '\d{4}'], 'y' => ['year', '\d{2}'], 'm' => ['month', '\d{2}'], 'n' => ['month', '\d{1,2}'], 'M' => ['month', '[A-Z][a-z]{3}'...
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MasterVolumeConfig.
func (in *MasterVolumeConfig) DeepCopy() *MasterVolumeConfig { if in == nil { return nil } out := new(MasterVolumeConfig) in.DeepCopyInto(out) return out }
// SetApplicationName sets the ApplicationName field's value.
func (s *UpdateApplicationInput) SetApplicationName(v string) *UpdateApplicationInput { s.ApplicationName = &v return s }
Given a table comment this method tries to extract a typehint for Doctrine Type, or returns the type given as default. @param string|null $comment @param string $currentType @return string
public function extractDoctrineTypeFromComment($comment, $currentType) { if ($comment !== null && preg_match('(\(DC2Type:(((?!\)).)+)\))', $comment, $match)) { return $match[1]; } return $currentType; }
Directive array @return string[]
protected static function directiveArray() { return array( self::DIRECTIVE_ALLOW, self::DIRECTIVE_DISALLOW, self::DIRECTIVE_HOST, self::DIRECTIVE_USERAGENT, self::DIRECTIVE_SITEMAP, self::DIRECTIVE_CRAWL_DELAY, self::DIRECTI...
Clip images based on bounds provided Implementation is borrowed from https://github.com/brendan-ward/rasterio/blob/e3687ce0ccf8ad92844c16d913a6482d5142cf48/rasterio/rio/convert.py
def clip(self): self.output("Clipping", normal=True) # create new folder for clipped images path = check_create_folder(join(self.scene_path, 'clipped')) try: temp_bands = copy(self.bands) temp_bands.append('QA') for i, band in enumerate(tem...
Add sorting hat enrichment fields
def get_item_sh(self, item, roles=None, date_field=None): """""" eitem_sh = {} created = str_to_datetime(date_field) for rol in roles: identity = self.get_sh_identity(item, rol) eitem_sh.update(self.get_item_sh_fields(identity, created, rol=rol)) if...
Plot the data. @param string $chart_title @param string[] $x_axis @param string $x_axis_title @param int[][] $ydata @param string $y_axis_title @param string[] $z_axis @param int $y_axis_type @return string
private function myPlot( string $chart_title, array $x_axis, string $x_axis_title, array $ydata, string $y_axis_title, array $z_axis, int $y_axis_type ): string { if (!count($ydata)) { return I18N::translate('This information is not availab...
// UnmarshalJSON populates a new Manifest struct from JSON data.
func (m *DeserializedManifest) UnmarshalJSON(b []byte) error { m.canonical = make([]byte, len(b)) // store manifest in canonical copy(m.canonical, b) // Unmarshal canonical JSON into Manifest object var manifest Manifest if err := json.Unmarshal(m.canonical, &manifest); err != nil { return err } if manifest...
Save the current values in all the widgets back to the persistent data storage. :param validate: whether to validate the saved data or not. :raises: InvalidFields if any invalid data is found.
def save(self, validate): invalid = [] for column in self._columns: for widget in column: if widget.is_valid or not validate: if widget.name is not None: # This relies on the fact that we are passed the actual ...
// dec decodes the encoding s into z.
func (m *matcher) dec(z *nstate, s string) { b := append(m.buf[:0], s...) m.buf = b z.needFlag = syntax.EmptyOp(b[0]) b = b[1:] i, n := binary.Uvarint(b) if n <= 0 { bug() } b = b[n:] z.flag = flags(i) z.q.Reset() last := ^uint32(0) for len(b) > 0 { i, n = binary.Uvarint(b) if n <= 0 { bug() } ...
// Inputs returns the array of inputs that defines the Env.
func (tri EnvTriangle) Inputs() []Input { (&tri).defaults() d := tri.Dur.Mul(C(0.5)) return Env{ Levels: []Input{C(0), tri.Level, C(0)}, Times: []Input{d, d}, }.Inputs() }
Write request to the server. @param mixed $request The request to write @throws ValidationException
public function write($request) { if ($this->isComplete) { throw new ValidationException("Cannot call write() after streaming call is complete."); } if ($this->writesClosed) { throw new ValidationException("Cannot call write() after calling closeWrite()."); } ...
Add any relevant project dependencies to the classpath. Indirectly takes includePluginDependencies and ExecutableDependency into consideration.
protected void addExtraPluginDependencies(Set<Artifact> artifacts) throws MojoExecutionException { if (extraPluginDependencyArtifactId == null && extendedPluginDependencyArtifactId == null) { return; } Set<Artifact> deps = new HashSet<Artifact>(this.pluginDependencies); for ...
###################################
private static ReadConfiguration getLocalConfiguration(String shortcutOrFile) { File file = new File(shortcutOrFile); if (file.exists()) return getLocalConfiguration(file); else { int pos = shortcutOrFile.indexOf(':'); if (pos<0) pos = shortcutOrFile.length(); ...
// Returns the number of items
func (m *SyncMap) Size() int { size := 0 for _, shard := range m.shards { shard.RLock() size += len(shard.items) shard.RUnlock() } return size }
Returns true if polyline_a overlaps polyline_b.
private static boolean polylineOverlapsPolyline_(Polyline polyline_a, Polyline polyline_b, double tolerance, ProgressTracker progress_tracker) { // Quick rasterize test to see whether the the geometries are disjoint. if (tryRasterizedContainsOrDisjoint_(polyline_a, polyline_b, tolerance, false) == Relatio...
If sub-classed, run any shutdown operations on this method.
def shutdown(self, exitcode=0, exitmsg=None): ''' ''' log.info('The salt-api is shutting down..') msg = 'The salt-api is shutdown. ' if exitmsg is not None: exitmsg = msg + exitmsg else: exitmsg = msg.strip() super(SaltAPI, self).s...
Returns seed signature for given request.
public static String getChunkSeedSignature(Request request, String region, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException { String contentSha256 = request.header("x-amz-content-sha256"); DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date")); Sign...
Returns a polygon containing the bounding box of the catalogue
def get_catalogue_bounding_polygon(catalogue): ''' ''' upper_lon = np.max(catalogue.data['longitude']) upper_lat = np.max(catalogue.data['latitude']) lower_lon = np.min(catalogue.data['longitude']) lower_lat = np.min(catalogue.data['latitude']) return Polygon([Point(lower_lon, upper_la...
Boot the role model Attach event listener to remove the many-to-many records when trying to delete Will NOT delete any records if the role model uses soft deletes. @return void|bool
public static function boot() { parent::boot(); static::deleting(function ($role) { if (!method_exists(config('access.role'), 'bootSoftDeletes')) { $role->users()->sync([]); $role->perms()->sync([]); } return true; }); ...
// UnmarshalJSON sets the object from the provided JSON representation
func (l *ElasticBeanstalkConfigurationTemplateSourceConfigurationList) UnmarshalJSON(buf []byte) error { // Cloudformation allows a single object when a list of objects is expected item := ElasticBeanstalkConfigurationTemplateSourceConfiguration{} if err := json.Unmarshal(buf, &item); err == nil { *l = ElasticBean...
new line, with a specific height @access protected @param float $h @param integer $curr real current position in the text, if new line in the write of a text
protected function _setNewLine($h, $curr = null) { $this->pdf->Ln($h); $this->_setNewPositionForNewLine($curr); }
// WeekdayShort returns the locales short weekday given the 'weekday' provided
func (ka *ka_GE) WeekdayShort(weekday time.Weekday) string { return ka.daysShort[weekday] }
Get the guest's group, containing only the 'guests' group model. @return \Flarum\Group\Group
public function getGroupsAttribute() { if (! isset($this->attributes['groups'])) { $this->attributes['groups'] = $this->relations['groups'] = Group::where('id', Group::GUEST_ID)->get(); } return $this->attributes['groups']; }
// SetEvalResourceName sets the EvalResourceName field's value.
func (s *ResourceSpecificResult) SetEvalResourceName(v string) *ResourceSpecificResult { s.EvalResourceName = &v return s }
Parse a WELCOME and update user state, then dispatch a WELCOME event.
def _parse_welcome(client, command, actor, args): """""" _, _, hostmask = args.rpartition(' ') client.user.update_from_hostmask(hostmask) client.dispatch_event("WELCOME", hostmask)
Write status message and line break to file descriptor.
def writeln (self, msg): """""" self.fd.write(u"%s%s" % (msg, unicode(os.linesep)))
从query字符中获取值,也就是获取$_GET的值 @param $key @param string $def @param null|string $filter @return null|string @throws Exception
public function getQuery($key, $def = "", $filter = null) { $val = $this->query[$key]; if ($filter) { $val = Filter::factory($val, $filter); } return $val === null ? $def : $val; }
Check the project file for the REPLACE_FOLDER card. If it exists, append it's value to create the batch directory path. This is the directory output is written to when run in batch mode.
def _getBatchDirectory(self, projectRootDirectory): # Set output directory to main directory as default batchDirectory = projectRootDirectory # Get the replace folder card replaceFolderCard = self.getCard('REPLACE_FOLDER') if replaceFolderCard: replaceDir =...
Returns default, changed and command-line ini settings @param array $loadedConfig All current ini settings @param array $iniConfig Settings from user ini files @return string
private function mergeLoadedConfig(array $loadedConfig, array $iniConfig) { $content = ''; foreach ($loadedConfig as $name => $value) { // Value will either be null, string or array (HHVM only) if (!is_string($value) || strpos($name, 'xdebug') === 0 ...
The asynchronous method of {@link #executeCommandAndCommitIfNeeded(ContextBuilder, VisitableCommand, int)}.
private <T> CompletableFuture<T> executeCommandAndCommitIfNeededAsync(ContextBuilder contextBuilder, VisitableCommand command, int keyCount) { InvocationContext ctx = contextBuilder.create(keyCount); checkLockOwner(ctx, command); //noinspection unchecked return isTxInjected(ctx) ? ex...
Sets opt out cookie @param {boolean} optOutState true - user opted out of tracking, false - user did not opted out @private @returns {boolean} Info about the success
function setCookie(optOutState) { switch (optOutState) { case true: document.cookie = `${disableStr}=true; expires=Thu, 18 Jan 2038 03:13:59 UTC; path=/`; window[disableStr] = true; break; case false: document.cookie = `${disableStr}=false; expires=Thu, 01 Jan 1970 00:00:01 UTC; path=...
Get the number of names that have ever existed Return {'status': True, 'count': count} on success Return {'error': ...} on error
def rpc_get_num_names_cumulative( self, **con_info ): db = get_db_state(self.working_dir) num_names = db.get_num_names(include_expired=True) db.close() return self.success_response( {'count': num_names} )
Get Pubtator Bioconcepts from Pubmed Abstract Re-configure the denotations into an annotation dictionary format and collapse duplicate terms so that their spans are in a list.
def get_pubtator(pmid): r = get_url(PUBTATOR_TMPL.replace("PMID", pmid), timeout=10) if r and r.status_code == 200: pubtator = r.json()[0] else: log.error( f"Cannot access Pubtator, status: {r.status_code} url: {PUBTATOR_TMPL.replace('PMID', pmid)}" ) return ...
// recv is a long running goroutine that accepts new data
func (s *Session) recv() { if err := s.recvLoop(); err != nil { s.exitErr(err) } }
shutdown all process @param int $signal
public function shutdown($signal = SIGTERM) { foreach ($this->processes as $process) { if ($process->isRunning()) { $process->shutdown(true, $signal); } } }
Auto Generated Code
def get_stp_mst_detail_output_cist_migrate_time(self, **kwargs): config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") cist = ET.SubElement(output, "cist") ...
// ValidateAppNameEnv ensures that the environment variable specifying the // entrypoint of this process is set correctly.
func ValidateAppNameEnv(want string) (r results) { if got := os.Getenv(appNameEnv); got != want { r = append(r, fmt.Errorf("%s not set appropriately (need %q, got %q)", appNameEnv, want, got)) } return }
Return the deposited instance of the OmemoRatchet for the given manager. If there is none yet, create a new one, deposit it and return it. @param manager OmemoManager we want to have the ratchet for. @return OmemoRatchet instance
protected OmemoRatchet<T_IdKeyPair, T_IdKey, T_PreKey, T_SigPreKey, T_Sess, T_Addr, T_ECPub, T_Bundle, T_Ciph> getOmemoRatchet(OmemoManager manager) { OmemoRatchet<T_IdKeyPair, T_IdKey, T_PreKey, T_SigPreKey, T_Sess, T_Addr, T_ECPub, T_Bundle, T_Ciph> omemoRatchet = omemoRatchets.get(manager...
Returns relevant URL. @return \moodle_url
public function get_url() { $params = $this->other; // Skip search area and course filters (MDL-33188). if (isset($params['areaids'])) { unset($params['areaids']); } if (isset($params['courseids'])) { unset($params['courseids']); } return ...
// Equals returns true if all the fields of this RPC match the // provided RPC. // // This function performs a deep comparison.
func (v *RPC) Equals(rhs *RPC) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } if !bytes.Equal(v.SpanContext, rhs.SpanContext) { return false } if !(v.CallerName == rhs.CallerName) { return false } if !(v.ServiceName == rhs.ServiceName) { return false } if !(v.Encoding =...
Get setter name. "setName" -> "name" @param m Method object. @return Property name of this setter.
private static String getSetterName(Method m) { String name = m.getName(); if (name.startsWith("set") && (name.length() >= 4) && m.getReturnType().equals(void.class) && (m.getParameterTypes().length == 1) ) { return Character.toLowerCase(name.charAt(3)...
Enable the given modules. @param $modules
public function enableModules($modules) { foreach ($modules as $moduleToEnable => $value) { $module = $this->module->get($moduleToEnable); $module->enable(); } }
Rate single type. TODO: Memoize using `$classname` or something (abort for anonymous types!) @type {constructor} target @type {constructor} type @returns {number} The degree of ancestral separation (-1 for none)
function(target, type) { var r = 0, rating = -1, parent = target; if (target === type) { rating = 0; } else { while ((parent = gui.Class.parent(parent))) { r++; if (parent === type) { parent = null; rating = r; } } /* This would rate the degree of descendant separation ... ...
Resolve data by splicing in the completed object @param $databaseResult
public function resolve($databaseResult) { $className = $this->className; try { $object = new $className(); $this->loader ->mapObjectWithOptions($object, $databaseResult); $databaseResult->{$this->fieldName} = $object; } catch (\Exceptio...
Override polymorphic default to put the subclass-specific fields first
def get_fieldsets(self, request, obj=None): ''' ''' # If subclass declares fieldsets, this is respected if (hasattr(self, 'declared_fieldset') and self.declared_fieldsets) \ or not self.base_fieldsets: return super(PolymorphicChildModelAdmin, self).get_fieldsets(request, ...
Sets the index to the given index without validating. If the index is out of bound the consecutive token() call will throw a runtime exception. @param indexToNavigateTo value to set the cursor's index to.
void index(int indexToNavigateTo) { this.index = 0; this.offset = 0; this.nextSplit = StringUtil.indexOf(path, '.', 0); this.token = null; for (int i = 1; i <= indexToNavigateTo; i++) { if (!advanceToNextToken()) { throw new IndexOutOfBoundsException(...
Returns the method meta data for the given method. @param method the method. @return an instance of {@link MethodMetaData}.
private MethodMetaData<? extends Annotation> getMethodMetaData(Method method) { MethodMetaData<? extends Annotation> methodMetaData = methodMetaDataCache.get(method); if (methodMetaData == null) { final String cacheName; final Annotation cacheAnnotation; final AggregatedParameter...
Try selecting abstract page by request parameter. @param string $key @return null|AbstractPage
private function searchPageByRequestKey($key) { $pageId = $this->getRequestParameter($key); if (empty($pageId)) { return null; } return $this->getEntityManager() ->find(AbstractPage::CN(), $pageId); }
This method allows to remove graph from the GraphServer instance @param graphId
public void dropGraph(long graphId) { val builder = new FlatBufferBuilder(128); val off = FlatDropRequest.createFlatDropRequest(builder, graphId); builder.finish(off); val req = FlatDropRequest.getRootAsFlatDropRequest(builder.dataBuffer()); val v = blockingStub.forgetGraph(re...
map a function over a glob pattern, relative to a directory
def map_over_glob(fn, path, pattern): """""" return [fn(x) for x in glob.glob(os.path.join(path, pattern))]
解析locale字符串。 <p> Locale字符串是符合下列格式:<code>language_country_variant</code>。 </p> @param localeString 要解析的字符串 @return <code>Locale</code>对象,如果locale字符串为空,则返回<code>null</code>
public static Locale parseLocale(String localeString) { if (localeString == null || localeString.length() == 0) { return Locale.getDefault(); } localeString = localeString.trim(); if (localeString == null) { return null; } String language = ""; ...