query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
Check to see if a DOM element is a descendant of another DOM element. @param {DOM element} container @param {DOM element} contained @param {string} class name of element in container @returns {boolean}
function contains(container, contained, className) { var current = contained; while (current && current.ownerDocument && current.nodeType !== 11) { if (className) { if (current === container) { return false; } if (current.c...
csn
The actual function which filters, transforms and does other funny things with an element. @param {CKEDITOR.filter} that Context. @param {CKEDITOR.htmlParser.element} element The element to be processed. @param {Array} toBeRemoved Array into which elements rejected by the filter will be pushed. @param {Boolean} [opts....
function processElement( that, element, toBeRemoved, opts ) { var status, retVal = 0, callbacksRetVal; // Unprotect elements names previously protected by htmlDataProcessor // (see protectElementNames and protectSelfClosingElements functions). // Note: body, title, etc. are not protected by htmlDataP (or...
csn
Returns an instance to OAuth2 server based on the current configuration. @param string $key Unique identifier for the OAuth2 server that you wish to get. @return array|OAuth2 @throws OAuth2Exception
public static function getInstance($key) { if (isset(self::$instances[$key])) { return self::$instances; } $oauth2Config = OAuth2::getConfig()->get($key, false); if (!$oauth2Config) { throw new OAuth2Exception('Unable to read "OAuth2.' . $key . '" configurat...
csn
Reads a string from the underlying stream.
protected String readStringImpl(int length) throws IOException { StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int ch = is.read(); if (ch < 0x80) sb.append((char) ch); else if ((ch & 0xe0) == 0xc0) { ...
csn
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubjectAccessReview.
func (in *SubjectAccessReview) DeepCopy() *SubjectAccessReview { if in == nil { return nil } out := new(SubjectAccessReview) in.DeepCopyInto(out) return out }
csn
Kick the player with the specified login, with an optional message. Only available to Admin. @param mixed $player Login or player object @param string $message @param bool $multicall @return bool @throws InvalidArgumentException
function kick($player, $message = '', $multicall = false) { $login = $this->getLogin($player); if ($login === false) { throw new InvalidArgumentException('player = ' . print_r($player, true)); } if (!is_string($message)) { throw new InvalidArgumentException('m...
csn
Returns an array of lines of the comments. @param string $docComment @return array
private static function getDocLinesFromComment($docComment) { if (strpos($docComment, "/**") === 0) { $docComment = substr($docComment, 3); } // Let's remove all the \r... $docComment = str_replace("\r", "", $docComment); $commentLines = explode("\n", $docComment); $commentLinesWithoutSta...
csn
Converts a underscored word into a CamelCased word @param string $strName String to be converted @return string The resulting camel-cased word @was QConvertNotation::CamelCaseFromUnderscore
public static function camelCaseFromUnderscore($strName) { $strToReturn = ''; // If entire underscore string is all uppercase, force to all lowercase // (mixed case and all lowercase can remain as is) if ($strName == strtoupper($strName)) { $strName = strtolower($strName...
csn
Respond with data. @param array $data @return Response
public function found(array $data): Response { $this->response->setBody(json_encode(['data' => $data])); return $this->response; }
csn
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodTemplateSpec.
func (in *PodTemplateSpec) DeepCopy() *PodTemplateSpec { if in == nil { return nil } out := new(PodTemplateSpec) in.DeepCopyInto(out) return out }
csn
// LimitsList lists an app's limits.
func LimitsList(appID string) error { c, appID, err := load(appID) if err != nil { return err } config, err := config.List(c, appID) fmt.Printf("=== %s Limits\n\n", appID) fmt.Println("--- Memory") if len(config.Memory) == 0 { fmt.Println("Unlimited") } else { memoryMap := make(map[string]string) f...
csn
Compare chords according to roots. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab') >>> est_intervals, est_labels = mir_eval.util.adjust_intervals( ...
def root(reference_labels, estimated_labels): """Compare chords according to roots. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab') >>> est_interva...
csn
Resume uploading an incomplete file, after a previous upload was interrupted. Returns new file object
def resume(self, data): 'Resume uploading an incomplete file, after a previous upload was interrupted. Returns new file object' if not hasattr(data, 'read'): data = six.BytesIO(data)#StringIO(data) #Check that we actually know from what byte to resume. #If self.size === -1, ...
csn
// UnmarshalText decodes the PHYPayload from base64.
func (p *PHYPayload) UnmarshalText(text []byte) error { b, err := base64.StdEncoding.DecodeString(string(text)) if err != nil { return err } return p.UnmarshalBinary(b) }
csn
reverse method. @method reverse @return object Collection
public function reverse() : self { $list = $this->list; $count = $this->list->getSize(); $newList = new \SplFixedArray($count); foreach ($newList as $index => $val) { $newList[$index] = $list[$count - $index - 1]; } return new static($newList); }
csn
Returns the result of the division of this RationalMoney by the given number. @param BigNumber|number|string $that The divisor. @return RationalMoney @throws MathException If the argument is not a valid number.
public function dividedBy($that) : RationalMoney { $amount = $this->amount->dividedBy($that); return new self($amount, $this->currency); }
csn
// NewExecutionRuleseAccepter creates an Accepter from the provided rules.
func NewExecutionRulesAccepter(rules []imagepolicy.ImageExecutionPolicyRule, integratedRegistryMatcher RegistryMatcher) (Accepter, error) { mapped := make(mappedAccepter) for _, rule := range rules { over, selectors, err := imageConditionInfo(&rule.ImageCondition) if err != nil { return nil, err } rule.Im...
csn
Retrieves a database connection. @param string $connectionName @return \PDO @throws DatabaseException
public function getConnection(string $connectionName): \PDO { if (!isset($this->connections[$connectionName])) { throw new DatabaseException(sprintf('Connection (%s) not found in pool.', $connectionName)); } return $this->connections[$connectionName]; }
csn
Access the Notify Twilio Domain :returns: Notify Twilio Domain :rtype: twilio.rest.notify.Notify
def notify(self): """ Access the Notify Twilio Domain :returns: Notify Twilio Domain :rtype: twilio.rest.notify.Notify """ if self._notify is None: from twilio.rest.notify import Notify self._notify = Notify(self) return self._notify
csn
Refund the reward to the publisher address. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param price: Asset price, int :param consumer_account: Account instance of the...
def refund_reward(event, agreement_id, did, service_agreement, price, consumer_account, publisher_address, condition_ids): """ Refund the reward to the publisher address. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param did:...
csn
Gamma function ported from the apache math package. <b>This should be removed if the apache math lib gets in use by HortonMachine.</b> <p>Returns the natural logarithm of the gamma function &#915;(x). The implementation of this method is based on: <ul> <li><a href="http://mathworld.wolfram.com/GammaFunction.html"> G...
public static double logGamma( double x ) { double ret; if (Double.isNaN(x) || (x <= 0.0)) { ret = Double.NaN; } else { double g = 607.0 / 128.0; double sum = 0.0; for( int i = LANCZOS.length - 1; i > 0; --i ) { sum = sum + (LANCZ...
csn
Find the reference that has the closest length to the translation. Parameters ---------- references: list(list(str)) A list of references. trans_length: int Length of the translation. Returns ------- closest_ref_len: int Length of the reference that is closest to th...
def _closest_ref_length(references, trans_length): """Find the reference that has the closest length to the translation. Parameters ---------- references: list(list(str)) A list of references. trans_length: int Length of the translation. Returns ------- closest_ref_len:...
csn
Pushes a value onto a field array @param string $field field name @param mixed $value value to append to the array @param bool $all whether to remove all (must be array) @return object $this
public function push($field, $value, $all = false) { return $this->update($all ? '$pushAll' : '$push', $field, $value); }
csn
This function tries to parse a single expression at a given offset in a string. Useful for parsing mixed-language formats that embed JavaScript expressions.
function parseExpressionAt(input, pos, options) { var p = new _state.Parser(options, input, pos); p.nextToken(); return p.parseExpression(); }
csn
return an hex representation of a byte string
def to_hex(sep_bytes=false) hx = @bytes.unpack('H*')[0].upcase if sep_bytes sep = "" (0...hx.size).step(2) do |i| sep << " " unless i==0 sep << hx[i,2] end hx = sep end hx end
csn
Restore the application config files. Algorithm: if exists mackup/file if exists home/file are you sure ? if sure rm home/file link mackup/file home/file else link mackup/file home/file
def restore(self): """ Restore the application config files. Algorithm: if exists mackup/file if exists home/file are you sure ? if sure rm home/file link mackup/file home/file else ...
csn
This API can be invoked to determine whether a virtual machine is compatible for Fault Tolerance. The API only checks for VM-specific factors that impact compatibility for Fault Tolerance. Other requirements for Fault Tolerance such as host processor compatibility, logging nic configuration and licensing are not covere...
public LocalizedMethodFault[] queryFaultToleranceCompatibilityEx(Boolean forLegacyFt) throws InvalidState, VmConfigFault, RuntimeFault, RemoteException { return getVimService().queryFaultToleranceCompatibilityEx(getMOR(), forLegacyFt); }
csn
Message received from websocket
def _on_auth(self, sock, authenticated): # pylint: disable=unused-argument """Message received from websocket""" def ack(eventname, error, data): # pylint: disable=unused-argument """Ack""" if error: self.log.error(f"""OnAuth: {error}""") else: ...
csn
Return element closest to the adsorbate in the subsurface layer
def get_under_bridge(self): """Return element closest to the adsorbate in the subsurface layer""" C0 = self.B[-1:] * (3, 3, 1) ads_pos = C0.positions[4] C = self.get_subsurface_layer() * (3, 3, 1) dis = self.B.cell[0][0] * 2 ret = None for ele in C: ...
csn
Creates a precision helper. Args: precision (str): precision of the date and time value, which should be one of the PRECISION_VALUES in definitions. Returns: class: date time precision helper class. Raises: ValueError: if the precision value is unsupported.
def CreatePrecisionHelper(cls, precision): """Creates a precision helper. Args: precision (str): precision of the date and time value, which should be one of the PRECISION_VALUES in definitions. Returns: class: date time precision helper class. Raises: ValueError: if the p...
csn
The result has been received :param result: Call result :param error: Error message
def handle_result(self, result, error): """ The result has been received :param result: Call result :param error: Error message """ if not self._error and not self._result: # Store results, if not already set self._error = error self._...
csn
// CreateApplication creates a cloud controller application in with the given // settings. SpaceGUID and Name are the only required fields.
func (client *Client) CreateApplication(app Application) (Application, Warnings, error) { body, err := json.Marshal(app) if err != nil { return Application{}, nil, err } request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.PostAppRequest, Body: bytes.NewReader(body), }) if err...
csn
Equation of time from PVCDROM. `PVCDROM`_ is a website by Solar Power Lab at Arizona State University (ASU) .. _PVCDROM: http://www.pveducation.org/pvcdrom/2-properties-sunlight/solar-time Parameters ---------- dayofyear : numeric Returns ------- equation_of_time : numeric ...
def equation_of_time_pvcdrom(dayofyear): """ Equation of time from PVCDROM. `PVCDROM`_ is a website by Solar Power Lab at Arizona State University (ASU) .. _PVCDROM: http://www.pveducation.org/pvcdrom/2-properties-sunlight/solar-time Parameters ---------- dayofyear : numeric Retu...
csn
// HandleBytes will return a RespHandler that read the entire body of the request // to a byte array in memory, would run the user supplied f function on the byte arra, // and will replace the body of the original response with the resulting byte array.
func HandleBytes(f func(b []byte, ctx *ProxyCtx) []byte) RespHandler { return FuncRespHandler(func(resp *http.Response, ctx *ProxyCtx) *http.Response { b, err := ioutil.ReadAll(resp.Body) if err != nil { ctx.Warnf("Cannot read response %s", err) return resp } resp.Body.Close() resp.Body = ioutil.NopCl...
csn
Merge this space with another @param other The other space to merge with @return The result space created by joining the two
public Space merge(Space other) { float minx = Math.min(x, other.x); float miny = Math.min(y, other.y); float newwidth = width+other.width; float newheight = height+other.height; if (x == other.x) { newwidth = width; } else { newheight = height; } return new Space(minx, miny, newwidth, newheigh...
csn
Resize an image and return the resized file.
def resize(image, width=None, height=None, crop=False): """ Resize an image and return the resized file. """ # First normalize params to determine which file to get width, height, crop = _normalize_params(image, width, height, crop) try: # Check the image file state for clean close ...
csn
Consumes the next token in the input string and pushes it to the array of tokens. @returns {boolean} whether a token is recognized @throws {Error|Object|SyntaxError} <code>fnResolveBinding</code> may throw <code>SyntaxError</code>; <code>oTokenizer.setIndex()</code> may throw <code>Error</code>; <code>oTokenizer</code...
function consumeToken() { var ch, oBinding, iIndex, aMatches, oToken; oTokenizer.white(); ch = oTokenizer.getCh(); iIndex = oTokenizer.getIndex(); if ((ch === "$" || ch === "%") && sInput[iIndex + 1] === "{") { //binding oBinding = fnResolveBinding(sInput, iIndex + 1); oToken = { id: "BIND...
csn
Create a new snapshot of the volume. @param string $id the id of the volume @param string $name a human-readable name for the volume snapshot @throws HttpException @return SnapshotEntity
public function snapshot($id, $name) { $data = [ 'name' => $name, ]; $snapshot = $this->adapter->post(sprintf('%s/volumes/%s/snapshots', $this->endpoint, $id), $data); $snapshot = json_decode($snapshot); return new SnapshotEntity($snapshot->snapshot); }
csn
Create a SwiftMessage instance from text @param array $from From addresses. An array of (email-address => name) @param array $to To addresses. An array of (email-address => name) @param string $subject the message subject @param string $htmlBody the HTML message bod...
public function createSimpleEmailMessage($from, $to, $subject, $htmlBody, $textBody, $cc = [], $bcc = [], $replyTo = []) { $instance = $this->getMessageInstance(); $this->setupMessageHeaders($instance, $from, $to, $cc, $bcc, $replyTo); $instance->setSubject($subject); // If we do ...
csn
Execute a request on this calls connection and context. @param request @return The response to executing the request.
private HttpResponse executeRequest(HttpPost request) throws Exception { try { HttpClient httpClient = connection.getHttpClient(); HttpContext httpContext = connection.getHttpContext(); HttpResponse response = httpClient.execute(request, httpContext); return respo...
csn
Save current asset configuration into conf file @return \AssetsBundle\AssetFile\AssetFilesConfiguration
public function saveAssetFilesConfiguration() { // Retrieve configuration file path $sConfigurationFilePath = $this->getConfigurationFilePath(); $bFileExists = file_exists($sConfigurationFilePath); // Create dir if needed if (!($bFileExists = file_exists($sConfigurationFil...
csn
Get the queue's number of tasks in each state. Returns dict with queue size for the QUEUED, SCHEDULED, and ACTIVE states. Does not include size of error queue.
def get_queue_sizes(self, queue): """ Get the queue's number of tasks in each state. Returns dict with queue size for the QUEUED, SCHEDULED, and ACTIVE states. Does not include size of error queue. """ states = [QUEUED, SCHEDULED, ACTIVE] pipeline = self.connect...
csn
Sets the http client. @param HttpClient|ClientInterface $httpClient
public function setHttpClient($httpClient): void { if (!$httpClient instanceof ClientInterface && !$httpClient instanceof HttpClient) { throw new \LogicException('Client must be an instance of Http\\Client\\HttpClient or Psr\\Http\\Client\\ClientInterface'); } $this->httpClient ...
csn
// GetUint64 retrieves the value for key from the environment, or the supplied // configuration data, returning it as a uint64. Uses base and bitSize to // parse.
func (ec *Envcfg) GetUint64(key string, base, bitSize int) uint64 { u, _ := strconv.ParseUint(ec.GetKey(key), base, bitSize) return u }
csn
Addes a message at the beginning of the stacktrace.
public static void insertMessage(Throwable onObject, String msg) { try { Field field = Throwable.class.getDeclaredField("detailMessage"); //Method("initCause", new Class[]{Throwable.class}); field.setAccessible(true); if (onObject.getMessage() != null) { field...
csn
Encodes html given name and description.
def enc_name_descr(name, descr, color=a99.COLOR_DESCR): """Encodes html given name and description.""" return enc_name(name, color)+"<br>"+descr
csn
Cache the template part output. @param string $output The template part output. @return bool Whether the transient data was successfully stored.
protected function set_cache( string $output ) : bool { return set_transient( $this->cache_key(), $output, $this->args['cache'] ); }
csn
// ScanAliased works like scan, except that it expects the results in the query to be // prefixed by the given alias. // // For example, if scanning to a field named "name" with an alias of "user" it will // expect to find the result in a column named "user_name". // // See ColumnAliased for a convenient way to generat...
func ScanAliased(dest interface{}, rows Rows, alias string) error { return doScan(dest, rows, alias) }
csn
// SetSharedAwsAccountIds sets the SharedAwsAccountIds field's value.
func (s *DescribeImagePermissionsInput) SetSharedAwsAccountIds(v []*string) *DescribeImagePermissionsInput { s.SharedAwsAccountIds = v return s }
csn
Set the speed and distance position @api @param float $positionX X position @param float $positionY Y position @param float $positionZ (optional) Z position (Z-index) @return static
public function setSpeedAndDistancePosition($positionX, $positionY, $positionZ = null) { $this->setPositionProperty($this->speedAndDistanceProperties, $positionX, $positionY, $positionZ); return $this; }
csn
Build an instance of TranscriptionInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance
def get_instance(self, payload): """ Build an instance of TranscriptionInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance :rtype: twilio.rest.api.v2010.account.recording.transcription...
csn
Builds completely initialized list of callbacks for given context. @param ctx contextual data given by execution service @return
public List<CommandCallback> buildCommandCallback(CommandContext ctx, ClassLoader cl) { List<CommandCallback> callbackList = new ArrayList<CommandCallback>(); if (ctx != null && ctx.getData("callbacks") != null) { logger.debug("Callback: {}", ctx.getData("callbacks")); String[] c...
csn
Resolve token eq node. @param NodeContract $node @return NodeContract|null
public function resolve(NodeContract $node) { $children = $node->getChildren(); if (count($children) > 0) { $this->resolve($node->getChildByIndex(0)); $value = ''; $positions = []; foreach ($node->getChildren() as $child) { if ($child...
csn
Raises a ``MockExpectationError`` with a useful message. :raise: ``MockExpectationError``
def raise_failure_exception(self, expect_or_allow='Allowed'): """Raises a ``MockExpectationError`` with a useful message. :raise: ``MockExpectationError`` """ raise MockExpectationError( "{} '{}' to be called {}on {!r} with {}, but was not. ({}:{})".format( ...
csn
Creates a jarsigner request to do a sign operation. @param jarToSign the location of the jar to sign @param signedJar the optional location of the signed jar to produce (if not set, will use the original location) @return the jarsigner request @throws MojoExecutionException if something wrong occurs
public JarSignerRequest createSignRequest( File jarToSign, File signedJar ) throws MojoExecutionException { JarSignerSignRequest request = new JarSignerSignRequest(); request.setAlias( getAlias() ); request.setKeystore( getKeystore() ); request.setSigfile( getSigfile() );...
csn
Paint the pagination aspects of the WDataTable. @param table the WDataTable being rendered @param xml the string builder in use
private void paintPaginationElement(final WDataTable table, final XmlStringBuilder xml) { TableDataModel model = table.getDataModel(); xml.appendTagOpen("ui:pagination"); if (model instanceof TreeTableDataModel) { // For tree tables, we only include top-level nodes for pagination. TreeNode firstNode = (...
csn
Resume the running of flowlet.
public void resume() { CountDownLatch latch = suspension.getAndSet(null); if (latch != null) { suspendBarrier.reset(); latch.countDown(); } }
csn
Requires the array of files.
function include(list) { var cmd, clazz, i, file, j, name, newname; for(i = 0;i < list.length;i++) { file = list[i]; try { clazz = require(file); // assume it is already instantiated if(typeof clazz === 'object') { cmd = clazz; }else{ cmd = new cla...
csn
Sets the id of the language. @param string $key Id to set
public function setId( $key ) { if( $key !== null ) { $this->setCode($key); $this->_values['id'] = $this->_values['code']; $this->_modified = false; } else { $this->_values['id'] = null; $this->_modified = true; } }
csn
Get javascript tag for use in tracking the website. @return string
public function getTag() { $piwikUrl = $this->getPiwikUrl(); $tag = <<<'EOT' <script type="text/javascript"> var _paq = _paq || []; (function(){ var u=(("https:" == document.location.protocol) ? "%s/" : "%s/"); _paq.push(['setSiteId', %s]); _paq.push(['setTrackerUrl', u+'piwik.php']); _paq.push(['t...
csn
Load a Custodian instance where the jobs are specified from a structure and a spec dict. This allows simple custom job sequences to be constructed quickly via a YAML file. Args: spec (dict): A dict specifying job. A sample of the dict in YAML format for the usual MP ...
def from_spec(cls, spec): """ Load a Custodian instance where the jobs are specified from a structure and a spec dict. This allows simple custom job sequences to be constructed quickly via a YAML file. Args: spec (dict): A dict specifying job. A sample of the dict in...
csn
Compute article slug. @return string
public function computeSlug() { if ($this->is_page) { return $this->alias; } if (! $this->exists) { $category = Category::query()->findOrFail($this->category_id); } else { $category = $this->category; } return $category->slug . '/...
csn
Updates user group memberships based on the GROUPS_CLAIM setting. Args: user (django.contrib.auth.models.User): User model instance claims (dict): Claims from the access token
def update_user_groups(self, user, claims): """ Updates user group memberships based on the GROUPS_CLAIM setting. Args: user (django.contrib.auth.models.User): User model instance claims (dict): Claims from the access token """ if settings.GROUPS_CLAIM is...
csn
Asynchronous operation to modify a knowledgebase. @param kb_id [String] Knowledgebase id. @param update_kb [UpdateKbOperationDTO] Post body of the request. @param custom_headers [Hash{String => String}] A hash of custom headers that will be added to the HTTP request. @return [Operation] operation results.
def update(kb_id, update_kb, custom_headers:nil) response = update_async(kb_id, update_kb, custom_headers:custom_headers).value! response.body unless response.nil? end
csn
Writes a content-changelog entry for a newly-created entry. @param string $contenttype Slug of the record contenttype @param integer $contentid ID of the record @param array $content Record values @param string $comment Editor's comment
private function logInsert($contenttype, $contentid, $content, $comment = null) { $this->app['logger.change']->info( 'Insert record', [ 'action' => 'INSERT', 'contenttype' => $contenttype, 'id' => $contentid, ...
csn
locate the template from the given uri and include it in the current output.
def _include_file(context, uri, calling_uri, **kwargs): """locate the template from the given uri and include it in the current output.""" template = _lookup_template(context, uri, calling_uri) (callable_, ctx) = _populate_self_namespace( context._clean_inheritance_token...
csn
Function to destroy the viewer and clean up everything created by OpenSeadragon. Example: var viewer = OpenSeadragon({ [...] }); //when you are done with the viewer: viewer.destroy(); viewer = null; //important @function
function( ) { if ( !THIS[ this.hash ] ) { //this viewer has already been destroyed: returning immediately return; } this.close(); this.clearOverlays(); this.overlaysContainer.innerHTML = ""; //TODO: implement this... //this.unbindSequenc...
csn
// NewMembersSetPermissionsResult returns a new MembersSetPermissionsResult instance
func NewMembersSetPermissionsResult(TeamMemberId string, Role *AdminTier) *MembersSetPermissionsResult { s := new(MembersSetPermissionsResult) s.TeamMemberId = TeamMemberId s.Role = Role return s }
csn
Return bookkeeping data from a DSK type 2 segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskb02_c.html :param handle: DSK file handle :type handle: int :param dladsc: DLA descriptor :type dladsc: spiceypy.utils.support_types.SpiceDLADescr :return: bookkeeping data from a DSK ...
def dskb02(handle, dladsc): """ Return bookkeeping data from a DSK type 2 segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskb02_c.html :param handle: DSK file handle :type handle: int :param dladsc: DLA descriptor :type dladsc: spiceypy.utils.support_types.SpiceDLADescr ...
csn
Get fresh data with cache. This method call guarantees a fresh copy of them entity in ApiSDK represented by the QueueItem. If the item should be cached, it will be cached at this point. @return mixed
private function getFreshDataWithCache(QueueItem $item) { $sdk = $this->getSdk($item); $entity = $sdk->get($item->getId())->wait(true); if (false === $this->shouldCacheEntity($item->getType(), $item->getId())) { return $entity; } if ($entity) { $this->...
csn
Process one result. Block untill one is available
def _handle_result(self): """Process one result. Block untill one is available """ result = self.inbox.get() if result.success: if self._verbosity >= VERB_PROGRESS: sys.stderr.write("\nuploaded chunk {} \n".format(result.index)) self.results.append...
csn
Add a feature, replacing either the place or manner of articulation, or the height or backness. Returns self.
def <<(*args) args.to_a.flatten.each do |feature| features.subtract Features.set(feature).to_a add! feature end self end
csn
Compile all sources in a given target to object files.
def execute(self): """Compile all sources in a given target to object files.""" def is_cc(source): _, ext = os.path.splitext(source) return ext in self.get_options().cc_extensions targets = self.context.targets(self.is_cpp) # Compile source files to objects. with self.invalidated(targ...
csn
Convert the transaction to its byte representation. @param bool $skipSignature @param bool $skipSecondSignature @return string
public function toBytes(bool $skipSignature = true, bool $skipSecondSignature = true): Buffer { $buffer = new Writer(); $buffer->writeUInt8($this->type); $buffer->writeUInt32($this->timestamp); $buffer->writeHex($this->senderPublicKey); $skipRecipientId = $this->type === Typ...
csn
Updates a formfield with extensions @param FormField $field
public function doUpdateFormField($field) { $this->extend('beforeUpdateFormField', $field); $this->updateFormField($field); $this->extend('afterUpdateFormField', $field); }
csn
Marshall an OutcomeDeclaration object into a DOMElement object. @param \qtism\data\QtiComponent $component An OutcomeDeclaration object. @return \DOMElement The according DOMElement object.
protected function marshall(QtiComponent $component) { $element = parent::marshall($component); $version = $this->getVersion(); // deal with views. // !!! If $arrayViews contain all possible views, it means that the treated // !!! outcome is relevant to all views, as per QTI...
csn
Executes finalize hooks
def _execute_hooks(self, element): """ Executes finalize hooks """ if self.hooks and self.finalize_hooks: self.param.warning( "Supply either hooks or finalize_hooks not both, " "using hooks and ignoring finalize_hooks.") hooks = self.ho...
csn
Substitute the extention of a file. @param file the file. @param newExtention the new extention (without the dot). @return the file with the new extention.
public static File substituteExtention( File file, String newExtention ) { String path = file.getAbsolutePath(); int lastDot = path.lastIndexOf("."); //$NON-NLS-1$ if (lastDot == -1) { path = path + "." + newExtention; //$NON-NLS-1$ } else { path = path.substring(...
csn
Return a set session handler middleware. @param \Psr\Container\ContainerInterface $container @return \Ellipse\Session\SetSessionHandlerMiddleware
public function getSetSessionHandlerMiddleware(ContainerInterface $container): SetSessionHandlerMiddleware { $handler = $container->get(SessionHandlerInterface::class); return new SetSessionHandlerMiddleware($handler); }
csn
Shamelessly copied from redis-py.
def _list_or_args(self, keys, args): """ Shamelessly copied from redis-py. """ # returns a single list combining keys and args try: iter(keys) # a string can be iterated, but indicates # keys wasn't passed as a list if isinstance(ke...
csn
Build Mailgun compatible message array from email entity Documentation at https://mandrillapp.com/api/docs/messages.php.html @param EmailEntity $emails @return array
protected function buildMessage(EmailEntity $email) { // Create attachments array $attachments = json_decode($email->getAttachments(), true) ?: []; // Convert Mandrill format to Mailgun format $attachments = array_map( function ($attachment) { if (isset($...
csn
Return -1L if str is not an index, or the index value as lower 32 bits of the result. Note that the result needs to be cast to an int in order to produce the actual index, which may be negative.
public static long indexFromString(String str) { // The length of the decimal string representation of // Integer.MAX_VALUE, 2147483647 final int MAX_VALUE_LENGTH = 10; int len = str.length(); if (len > 0) { int i = 0; boolean negate = false; ...
csn
Create Owner element. @param DOMDocument Owner DOMDocument @param eZContentObject Owner object @return DOMElement Owner DOMElement, example: <Owner objectID="135" primaryLanguage="nor-NO"> <NameList> <Name locale="nor-NO">Balle Klorin</Name> </NameList> </Owner>
protected function createOwnerDOMElement( DOMDocument $domDocument, eZContentObject $owner ) { $ownerElement = $domDocument->createElement( 'Owner' ); // Set attributes $ownerElement->setAttribute( 'objectID', $owner->attribute( 'id' ) ); $ownerElement->setAttribute( 'primaryLanguag...
csn
Do measuring of read and write operations. @param data: 3-tuple from get_test_data @return: (time readhex, time writehex)
def measure_one(self, data): """Do measuring of read and write operations. @param data: 3-tuple from get_test_data @return: (time readhex, time writehex) """ _unused, hexstr, ih = data tread, twrite = 0.0, 0.0 if self.read: tread = run_readte...
csn
Copying selectlists assignments @param string $sOldId Id from old article @param string $sNewId Id from new article
protected function _copySelectlists($sOldId, $sNewId) { $myUtilsObject = \OxidEsales\Eshop\Core\Registry::getUtilsObject(); $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(); $sQ = "select oxselnid from oxobject2selectlist where oxobjectid = " . $oDb->quote($sOldId); $oRs = $o...
csn
Contains composite key. @param tableInfo the table info @return true, if successful
private boolean containsCompositeKey(TableInfo tableInfo) { return tableInfo.getTableIdType() != null && tableInfo.getTableIdType().isAnnotationPresent(Embeddable.class); }
csn
Set some HTTP parameters for all subsequent requests. This includes ``user`` and ``password`` for HTTP basic authentication, and ``user_agent`` as a header.
def session(context, data): """Set some HTTP parameters for all subsequent requests. This includes ``user`` and ``password`` for HTTP basic authentication, and ``user_agent`` as a header. """ context.http.reset() user = context.get('user') password = context.get('password') if user is...
csn
Return a local map spill index file created earlier @param mapTaskId a map task id @param spillNumber the number
public Path getSpillIndexFile(TaskAttemptID mapTaskId, int spillNumber) throws IOException { return lDirAlloc.getLocalPathToRead(TaskTracker.getIntermediateOutputDir( jobId.toString(), mapTaskId.toString()) + "/spill" + spillNumber + ".out.in...
csn
Regenerates a task that has failed @param integer $id @return void
private function regenerateTaskById($id) { try { $response = $this->taskQueueService->regenerateTask($id); if ($response) { $this->output->writeln("<info>Regeneration succes</info>"); } else { $this->output->writeln("<error>Regeneration suc...
csn
Merge the given results into this results object. A copy of the newly added search runs is made. @param otherResults other results to be merged into this results object @return a reference to the updated results object
public AnalysisResults<SolutionType> merge(AnalysisResults<SolutionType> otherResults){ otherResults.results.keySet().forEach(problemID -> { otherResults.results.get(problemID).keySet().forEach(searchID -> { List<SearchRunResults<SolutionType>> runs = otherResults.results.get(problem...
csn
Removes a Section @access public @param string $section Key of Section to remove @return bool
public function removeSection( $section ) { if( !$this->usesSections() ) throw new RuntimeException( 'Sections are disabled' ); if( !$this->hasSection( $section ) ) throw new InvalidArgumentException( 'Section "'.$section.'" is not existing' ); $index = array_search( $section, $this->sections); unset( $t...
csn
// Convert_v1_StageInfo_To_build_StageInfo is an autogenerated conversion function.
func Convert_v1_StageInfo_To_build_StageInfo(in *v1.StageInfo, out *build.StageInfo, s conversion.Scope) error { return autoConvert_v1_StageInfo_To_build_StageInfo(in, out, s) }
csn
// Flush satisfies the Flusher interface.
func (b *Buffer) Flush() { b.prepare(b.bufferSize()) for i := range b.buffers { if buffer := &b.buffers[i]; buffer.acquire() { buffer.flush(b.Serializer, buffer.len()) buffer.release() } } }
csn
Query the server for an item, parse the JSON, and return the result. Keyword arguments: key -- the key of the item that you'd like to retrieve. Required. cache -- the name of the cache that the item resides in. Defaults to None, which uses self.name. If no name is set, raises a...
def get(self, key, cache=None): """Query the server for an item, parse the JSON, and return the result. Keyword arguments: key -- the key of the item that you'd like to retrieve. Required. cache -- the name of the cache that the item resides in. Defaults to None, which ...
csn
Get start and end times for selected segments of data, bundled together with info. Parameters ---------- annot: instance of Annotations The annotation file containing events and epochs evt_type: list of str, optional Enter a list of event types to get events; otherwise, epochs will ...
def get_times(annot, evt_type=None, stage=None, cycle=None, chan=None, exclude=False, buffer=0): """Get start and end times for selected segments of data, bundled together with info. Parameters ---------- annot: instance of Annotations The annotation file containing events and...
csn
Creates an instance of the design context menu. @return New design context menu.
public static DesignContextMenu create() { return PageUtil.createPage(DesignConstants.RESOURCE_PREFIX + "designContextMenu.fsp", ExecutionContext.getPage()) .get(0).getAttribute("controller", DesignContextMenu.class); }
csn
Builds an array of keyed on the fully-namespaced `Model` with array of fields as values for the given `Query` @param \lithium\data\model\Query $query A Query instance. @param \lithium\data\source\Result|null $resource An optional a result resource. @param object|null $context @return array
public function schema($query, $resource = null, $context = null) { if (is_object($query)) { $query->applyStrategy($this); return $this->_schema($query, $this->_fields($query->fields(), $query)); } $result = []; if (!$resource || !$resource->resource()) { return $result; } $count = $resource->reso...
csn
Translates cmis document object to JCR node. @param cmisObject cmis document node @return JCR node document.
public Document cmisDocument( CmisObject cmisObject ) { org.apache.chemistry.opencmis.client.api.Document doc = (org.apache.chemistry.opencmis.client.api.Document)cmisObject; DocumentWriter writer = newDocument(ObjectId.toString(ObjectId.Type.OBJECT, doc.getId())); ObjectType objectType = cmisO...
csn
Send Report E-mails.
def handle_noargs(self, **options): """Send Report E-mails.""" r = get_r() since = datetime.utcnow() - timedelta(days=1) metrics = {} categories = r.metric_slugs_by_category() for category_name, slug_list in categories.items(): metrics[category_name] = [] ...
csn
for each vector rotation, scale, position
function() { obj.mesh[ propertyName ].set( propertyObject.x, propertyObject.y, propertyObject.z ) }
csn