comment
stringlengths
16
255
code
stringlengths
52
3.87M
// acquireChan wraps a signal chan with a func that can be used with rateLimit. // should only be called by rate limiting funcs (that implement deadlock avoidance).
func acquireChan(tokenCh <-chan struct{}) func(context.Context, bool) bool { if tokenCh == nil { // always false: acquire never succeeds; panic if told to block (to avoid deadlock) return func(ctx context.Context, block bool) bool { if block { select { case <-ctx.Done(): default: panic("deadlock detected: block should never be true when the token chan is nil") } } return false } } return func(ctx context.Context, block bool) bool { if block { select { case <-tokenCh: // tie breaker prefers Done select { case <-ctx.Done(): default: return true } case <-ctx.Done(): } return false } select { case <-tokenCh: return true default: return false } } }
Collects garbage - removes files from the file system. @return \Zend\Stdlib\ResponseInterface
public function collectAction() { // @todo json $service = $this->getGarbageCollector(); if ($service->collect()) { return $this->redirect()->toRoute('sc-admin/content-manager'); } return $this->redirect() ->toRoute( 'sc-admin/file/delete', ['random' => Stdlib::randomKey(6)] ) ->setStatusCode(303); }
// Str2JSType extract a JavaScript type from a string
func Str2JSType(s string) JSType { var ( output JSType ) s = strings.TrimSpace(s) // santize the given string switch { case isBool(s): output = Bool case isFloat(s): output = Float case isInt(s): output = Int case isNull(s): output = Null default: output = String // if all alternatives have been eliminated, the input is a string } return output }
The parser fires this each time one path has been parsed @param string $path xml path which parsing has ended
public function after_path($path) { $toprocess = false; // If the path being closed matches (same or parent) the first path in the stack // we process pending startend notifications until one matching end is found if ($element = reset($this->startendinfo)) { $elepath = $element['path']; $eleaction = $element['action']; if (strpos($elepath, $path) === 0) { $toprocess = true; } // Also, if the stack of startend notifications is empty, we can process current end // path safely } else { $toprocess = true; } if ($this->path_is_selected($path)) { $this->startendinfo[] = array('path' => $path, 'action' => 'end'); } // Send all the pending startend notifications if decided to do so if ($toprocess) { $this->process_pending_startend_notifications($path, 'end'); } }
// sendCommand is an auxiliary function to send commands to the AIP1640Driver module
func (a *AIP1640Driver) sendCommand(cmd byte) { a.pinData.Off() a.send(cmd) a.pinData.On() }
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B // prepareCopyURLsTypeE - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs { copyURLsCh := make(chan URLs) go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs) { defer close(copyURLsCh) for _, sourceURL := range sourceURLs { for cpURLs := range prepareCopyURLsTypeC(sourceURL, targetURL, isRecursive, encKeyDB) { copyURLsCh <- cpURLs } } }(sourceURLs, targetURL, copyURLsCh) return copyURLsCh }
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SourceStrategyOptions.
func (in *SourceStrategyOptions) DeepCopy() *SourceStrategyOptions { if in == nil { return nil } out := new(SourceStrategyOptions) in.DeepCopyInto(out) return out }
/* $order array of the fields and the order
public function selectAll($where=false, $order=false, $limit=false) { $clause = false; $values = array(); if ( is_array($where) ) { $retval = self::extractWhere($where, $clause, $values); if ( is_string($retval) ) throw new \Exception($val); } $orderby = ''; if ( is_string($order) ) { $orderby = self::extractOrder($order); if ( $orderby === false ) throw new \Exception('Invalid Order value'); } $sql = "SELECT KVS.id AS id, json_body, KVS.created_at, KVS.updated_at FROM $this->KVS_TABLE AS KVS WHERE $this->KVS_FK_NAME = :foreign_key"; if ( $clause ) $sql .= ' AND '.$clause; if ( $orderby ) $sql .= ' '.$orderby; $values[':foreign_key'] = $this->KVS_FK; $rows = $this->PDOX->allRowsDie($sql, $values); return $rows; }
Write current root class hierarchy with resolved generics. Use custom writer to modify type rendering (on each line). @param typeWriter custom type writer @return current hierarchy with resolved generics
public String toStringHierarchy(final TypeWriter typeWriter) { final StringBuilder res = new StringBuilder(types.size() * 50); writeHierarchy(root, "", "", res, typeWriter); return res.toString(); }
Start application.
def main(args=None): """""" parser = _parser() # Python 2 will error 'too few arguments' if no subcommand is supplied. # No such error occurs in Python 3, which makes it feasible to check # whether a subcommand was provided (displaying a help message if not). # argparse internals vary significantly over the major versions, so it's # much easier to just override the args passed to it. In this case, print # the usage message if there are no args. if args is None and len(sys.argv) <= 1: sys.argv.append('--help') options = parser.parse_args(args) # pass options to subcommand options.func(options) return 0
Displace this atom in place
def displace!(x,y,z) self.x += x self.y += y self.z += z end
--------------------------------------------------------- private functions /* get message or service definition class
function getMessageFromPackage(messageType, type, callback) { var packageName = getPackageNameFromMessageType(messageType); var messageName = getMessageNameFromMessageType(messageType); packages.findPackage(packageName, function(error, directory) { var filePath; filePath = path.join(directory, type, messageName + '.' + type); getMessageFromFile(messageType, filePath, type, callback); }); }
Figure out the sections in drbdadm status
def _analyse_status_type(line): ''' ''' spaces = _count_spaces_startswith(line) if spaces is None: return '' switch = { 0: 'RESOURCE', 2: {' disk:': 'LOCALDISK', ' role:': 'PEERNODE', ' connection:': 'PEERNODE'}, 4: {' peer-disk:': 'PEERDISK'} } ret = switch.get(spaces, 'UNKNOWN') # isinstance(ret, str) only works when run directly, calling need unicode(six) if isinstance(ret, six.text_type): return ret for x in ret: if x in line: return ret[x] return 'UNKNOWN'
Build the client from a dsn Examples: udp+influxdb://username:pass@localhost:4444/databasename @param string $dsn @return Client|Database @throws ClientException
public static function fromDSN($dsn) { $connParams = parse_url($dsn); $schemeInfo = explode('+', $connParams['scheme']); $modifier = null; $scheme = $schemeInfo[0]; $dbName = isset($connParams['path']) ? substr($connParams['path'], 1) : null; if (isset($schemeInfo[1])) { $modifier = strtolower($schemeInfo[0]); $scheme = $schemeInfo[1]; } if ($scheme != 'influxdb') { throw new ClientException($scheme . ' is not a valid scheme'); } if (!in_array($modifier, ['udp'])) { throw new ClientException(sprintf("%s modifier specified in DSN is not supported", $modifier)); } $driver = null; // set the UDP driver when the DSN specifies UDP if ($modifier == 'udp') { $driver = new UDP($connParams['host'], $connParams['port']); } $client = new self($driver); return ($dbName ? $client->selectDB($dbName) : $client); }
@param InputInterface $input @param OutputInterface $output @return bool|int|null
protected function execute(InputInterface $input, OutputInterface $output) { $this->init($input); $function = $input->getArgument('function'); $idChart = $input->getOption('idChart'); switch ($function) { case 'maj-player': if ($idChart) { $chart = $this->doctrine->getRepository('VideoGamesRecordsCoreBundle:Chart')->find($idChart); $this->updateCharts([$chart]); } else { $this->majPlayer($output); } break; } $this->end($output); return true; }
Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
@XmlElementDecl(namespace = "http://www.drugbank.ca", name = "rs-id", scope = SnpAdverseDrugReactionType.class) public JAXBElement<String> createSnpAdverseDrugReactionTypeRsId(String value) { return new JAXBElement<String>(_SnpAdverseDrugReactionTypeRsId_QNAME, String.class, SnpAdverseDrugReactionType.class, value); }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
public EClass getGCBEZ() { if (gcbezEClass == null) { gcbezEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(488); } return gcbezEClass; }
Get a firmware image with provided image_id. :param str image_id: The firmware ID for the image to retrieve (Required) :return: FirmwareImage
def get_firmware_image(self, image_id): api = self._get_api(update_service.DefaultApi) return FirmwareImage(api.firmware_image_retrieve(image_id))
/* (non-Javadoc) @see com.ibm.ws.sib.processor.runtime.SIMPTopicSpaceControllable#deleteLocalSubscriptionControlByID(java.lang.String)
public void deleteLocalSubscriptionControlByID(String id) throws SIMPInvalidRuntimeIDException, SIMPControllableNotFoundException, SIMPException, SIDurableSubscriptionNotFoundException, SIDestinationLockedException, SIResourceException, SIIncorrectCallException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "deleteLocalSubscriptionControlByID", id); assertMessageHandlerNotCorrupt(); ControllableSubscription sub = getSubscription(id); if (!sub.isDurable()) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit( tc, "deleteLocalSubscriptionControlByID", "SIMPIncorrectCallException"); throw new SIMPIncorrectCallException( nls.getFormattedMessage( "SUBSCRIPTION_DELETE_ERROR_CWSIP0272", new Object[]{id}, null)); } HashMap durableSubs = destinationManager.getDurableSubscriptionsTable(); synchronized (durableSubs) { // Look up the consumer dispatcher for this subId in the system durable subs list ConsumerDispatcher cd = (ConsumerDispatcher) durableSubs.get(sub.getConsumerDispatcherState().getSubscriberID()); // Does the subscription exist, if it doesn't, throw a // SIDestinationNotFoundException if (cd == null) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "deleteSubscription", "SIMPControllableNotFoundException"); throw new SIMPControllableNotFoundException( nls.getFormattedMessage( "SUBSCRIPTION_DOESNT_EXIST_ERROR_CWSIP0146", new Object[] { sub.getConsumerDispatcherState().getSubscriberID(), messageProcessor.getMessagingEngineName() }, null)); } // Obtain the destination from the queueing points DestinationHandler destination = cd.getDestination(); // Call the deleteDurableSubscription method on the destination // NOTE: this assumes the durable subscription is always local destination.deleteDurableSubscription(sub.getConsumerDispatcherState().getSubscriberID(), messageProcessor.getMessagingEngineName()); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "deleteLocalSubscriptionControlByID"); }
使用账号密码方式登录授权 @param string $username 用户名 @param string $password 密码 @return void
public function login($username, $password) { $response = $this->http->get($this->getUrl('oauth2/access_token'), array( 'grant_type' => 'password ', 'username' => $username, 'password' => $password, 'client_id' => $this->appid, 'client_secret' => $this->appSecret, )); $this->result = $response->json(true); if(!isset($this->result['error_code'])) { return $this->accessToken = $this->result['access_token']; } else { throw new ApiException(isset($this->result['error']) ? $this->result['error'] : '', $this->result['error_code']); } }
Automatically generated run method @param Request $request @return Response
public function run(Request $request) { $id = $this->getParam('id'); $sport = SportQuery::create() ->leftJoinGroup() ->leftJoinSkill() ->findOneById($id); $pictures = PictureQuery::create() ->useSkillQuery() ->filterBySportId($id) ->endUse() ->count(); $videos = VideoQuery::create() ->useSkillQuery() ->filterBySportId($id) ->endUse() ->count(); $references = ReferenceQuery::create() ->useSkillReferenceQuery() ->useSkillQuery() ->filterBySportId($id) ->endUse() ->endUse() ->count(); $statistics = [ 'skills' => $sport->countSkills(), 'groups' => $sport->countGroups(), 'pictures' => $pictures, 'videos' => $videos, 'references' => $references ]; return $this->responder->run($request, new Blank($statistics)); }
把资源存放到当前上下文 @param IPoolResource $resource @return void
private static function pushResourceToRequestContext(IPoolResource $resource) { $poolResources = RequestContext::get('poolResources', []); $instance = $resource->getInstance(); $poolResources[spl_object_hash($instance)] = $resource; RequestContext::set('poolResources', $poolResources); }
Emit an alert monitor.down, which is in the OK state. @param ctx Rule evaluation context.
@Override public void transform(Context<MutableTimeSeriesCollectionPair> ctx) { DateTime now = ctx.getTSData().getCurrentCollection().getTimestamp(); ctx.getTSData().getCurrentCollection().addMetrics(MONITOR_GROUP, get_metrics_(now, ctx)); ctx.getAlertManager().accept(new Alert(now, MONITOR_DOWN_ALERT, () -> "builtin rule", Optional.of(false), Duration.ZERO, "builtin rule: monitor is not running for some time", EMPTY_MAP)); }
MySQL SELECT Query/Statement. @param string $table @param array $column @param array $arrayWhere @param string $other @return self type: array/error
public function select($table = '', $column = [], $arrayWhere = [], $other = '') { // handle column array data if (!is_array($column)) { $column = []; } // get field if pass otherwise use * $sField = count($column) > 0 ? implode(', ', $column) : '*'; // check if table name not empty if (!empty($table)) { // if more then 0 array found in where array if (count($arrayWhere) > 0 && is_array($arrayWhere)) { // set class where array $this->data = $arrayWhere; // parse where array and get in temp var with key name and val if (strstr(key($arrayWhere), ' ')) { $tmp = $this->customWhere($this->data); // get where syntax with namespace $where = $tmp['where']; } else { $tmp = []; foreach ($arrayWhere as $k => $v) { $tmp[] = "$k = :s_$k"; } // join temp array with AND condition $where = implode(' AND ', $tmp); } // unset temp var unset($tmp); // set class sql property $this->sql = "SELECT $sField FROM `$table` WHERE $where $other;"; } else { $this->sql = "SELECT $sField FROM `$table` $other;"; // if no where condition pass by user } // pdo prepare statement with sql query $this->STH = $this->prepare($this->sql); // if where condition has valid array number if (count($arrayWhere) > 0 && is_array($arrayWhere)) { $this->_bindPdoNameSpace($arrayWhere); // bind pdo param } // use try catch block to get pdo error try { // check if pdo execute if ($this->STH->execute()) { // set class property with affected rows $this->affectedRows = $this->STH->rowCount(); // set class property with sql result $this->results = $this->STH->fetchAll(); // close pdo $this->STH->closeCursor(); // return self object return $this; } else { self::error($this->STH->errorInfo()); // catch pdo error } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); } // end try catch block to get pdo error } else { // if table name empty self::error('Table name not found..'); } }
Is required to repaint the control or its snippet? @param string snippet name @return bool
public function isControlInvalid($snippet = NULL) { if ($snippet === NULL) { if (count($this->invalidSnippets) > 0) { return TRUE; } else { $queue = [$this]; do { foreach (array_shift($queue)->getComponents() as $component) { if ($component instanceof IRenderable) { if ($component->isControlInvalid()) { // $this->invalidSnippets['__child'] = TRUE; // as cache return TRUE; } } elseif ($component instanceof Nette\ComponentModel\IContainer) { $queue[] = $component; } } } while ($queue); return FALSE; } } elseif (isset($this->invalidSnippets[$snippet])) { return $this->invalidSnippets[$snippet]; } else { return isset($this->invalidSnippets["\0"]); } }
This method removes the option-bar widget from DOM and re-attaches it at it's original position.<p> Use to avoid mouse-over and mouse-down malfunction.<p>
private void resetOptionbar() { if (m_elementOptionBar != null) { if (getWidgetIndex(m_elementOptionBar) >= 0) { m_elementOptionBar.removeFromParent(); } updateOptionBarPosition(); insert(m_elementOptionBar, 0); } }
// GetBucketNotification - get bucket notification at a given path.
func (c Client) GetBucketNotification(bucketName string) (bucketNotification BucketNotification, err error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return BucketNotification{}, err } notification, err := c.getBucketNotification(bucketName) if err != nil { return BucketNotification{}, err } return notification, nil }
Get the documentation name. @return string
protected function getDocName() { $name = $this->option('name') ?: $this->name; if (! $name) { $this->comment('A name for the documentation was not supplied. Use the --name option or set a default in the configuration.'); exit; } return $name; }
run all patterns in the playbook
def run(self): ''' ''' plays = [] matched_tags_all = set() unmatched_tags_all = set() # loop through all patterns and run them self.callbacks.on_start() for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs): play = Play(self, play_ds, play_basedir) matched_tags, unmatched_tags = play.compare_tags(self.only_tags) matched_tags_all = matched_tags_all | matched_tags unmatched_tags_all = unmatched_tags_all | unmatched_tags # if we have matched_tags, the play must be run. # if the play contains no tasks, assume we just want to gather facts if (len(matched_tags) > 0 or len(play.tasks()) == 0): plays.append(play) # if the playbook is invoked with --tags that don't exist at all in the playbooks # then we need to raise an error so that the user can correct the arguments. unknown_tags = set(self.only_tags) - (matched_tags_all | unmatched_tags_all) unknown_tags.discard('all') if len(unknown_tags) > 0: unmatched_tags_all.discard('all') msg = 'tag(s) not found in playbook: %s. possible values: %s' unknown = ','.join(sorted(unknown_tags)) unmatched = ','.join(sorted(unmatched_tags_all)) raise errors.AnsibleError(msg % (unknown, unmatched)) for play in plays: if not self._run_play(play): break # summarize the results results = {} for host in self.stats.processed.keys(): results[host] = self.stats.summarize(host) return results
Calls jsonrpc service's method and returns its return value in a JSON string or None if there is none. Arguments: jsondata -- remote method call in jsonrpc format
def call(self, jsondata): result = yield self.call_py(jsondata) if result is None: defer.returnValue(None) else: defer.returnValue(json.dumps(result))
// RemoveAllBlocksForController removes all the blocks for the controller. // It does not prevent new blocks from being added during / after // removal.
func (st *State) RemoveAllBlocksForController() error { blocks, err := st.AllBlocksForController() if err != nil { return errors.Trace(err) } ops := []txn.Op{} for _, blk := range blocks { ops = append(ops, txn.Op{ C: blocksC, Id: blk.Id(), Remove: true, }) } // Use runRawTransaction as we might be removing docs across // multiple models. return st.runRawTransaction(ops) }
/* (non-Javadoc) @see org.mobicents.isup.messages.ISUPMessage#decodeOptionalBody(byte[], byte)
protected void decodeOptionalBody(ISUPParameterFactory parameterFactory, byte[] parameterBody, byte parameterCode) throws ParameterException { switch (parameterCode & 0xFF) { case CauseIndicators._PARAMETER_CODE: CauseIndicators cpn = parameterFactory.createCauseIndicators(); ((AbstractISUPParameter) cpn).decode(parameterBody); this.setCauseIndicators(cpn); break; default: throw new ParameterException("Unrecognized parameter index for optional part: " + parameterCode); } }
handle layout command
def cmd_layout(self, args): '''''' from MAVProxy.modules.lib import win_layout if len(args) < 1: print("usage: layout <save|load>") return if args[0] == "load": win_layout.load_layout(self.mpstate.settings.vehicle_name) elif args[0] == "save": win_layout.save_layout(self.mpstate.settings.vehicle_name)
Get the filename and key of the config name @param $name @return array
public function getInfo($name) { $keys = explode('.', $name); if (is_array($keys)) { $file = array_shift($keys); $key = implode('.', $keys); } else { $file = $name; $key = null; } return ['file' => $file, 'key' => $key]; }
// SetOptions sets the Options field's value.
func (s *IndexFieldStatus) SetOptions(v *IndexField) *IndexFieldStatus { s.Options = v return s }
Checks if a logged event is to be muted for debugging purposes. Also goes through the solo list - only items in there will be logged! :param what: :return:
def is_muted(what): state = False for item in solo: if item not in what: state = True else: state = False break for item in mute: if item in what: state = True break return state
// Validate inspects the fields of the type to determine if they are valid.
func (s *JobOperation) Validate() error { invalidParams := request.ErrInvalidParams{Context: "JobOperation"} if s.LambdaInvoke != nil { if err := s.LambdaInvoke.Validate(); err != nil { invalidParams.AddNested("LambdaInvoke", err.(request.ErrInvalidParams)) } } if s.S3PutObjectAcl != nil { if err := s.S3PutObjectAcl.Validate(); err != nil { invalidParams.AddNested("S3PutObjectAcl", err.(request.ErrInvalidParams)) } } if s.S3PutObjectCopy != nil { if err := s.S3PutObjectCopy.Validate(); err != nil { invalidParams.AddNested("S3PutObjectCopy", err.(request.ErrInvalidParams)) } } if s.S3PutObjectTagging != nil { if err := s.S3PutObjectTagging.Validate(); err != nil { invalidParams.AddNested("S3PutObjectTagging", err.(request.ErrInvalidParams)) } } if invalidParams.Len() > 0 { return invalidParams } return nil }
Differential cross section dsigma/dEg = Amax(Tp) * F(Tp,Egamma)
def _diffsigma(self, Ep, Egamma): Tp = Ep - self._m_p diffsigma = self._Amax(Tp) * self._F(Tp, Egamma) if self.nuclear_enhancement: diffsigma *= self._nuclear_factor(Tp) return diffsigma
// MarshalBinary implements encoding BinaryMarshaler interface
func (l *Locale) MarshalBinary() ([]byte, error) { obj := new(LocaleEncoding) obj.DefaultDomain = l.defaultDomain obj.Domains = make(map[string][]byte) for k, v := range l.Domains { var err error obj.Domains[k], err = v.MarshalBinary() if err != nil { return nil, err } } obj.Lang = l.lang obj.Path = l.path var buff bytes.Buffer encoder := gob.NewEncoder(&buff) err := encoder.Encode(obj) return buff.Bytes(), err }
Function to publish staging or prod version from local tree, or to promote staging to prod, per passed arg. @param {string} pubScope the scope to publish to.
function mdlPublish(pubScope) { let cacheTtl = null; let src = null; let dest = null; if (pubScope === 'staging') { // Set staging specific vars here. cacheTtl = 0; src = 'dist/*'; dest = bucketStaging; } else if (pubScope === 'prod') { // Set prod specific vars here. cacheTtl = 60; src = 'dist/*'; dest = bucketProd; } else if (pubScope === 'promote') { // Set promote (essentially prod) specific vars here. cacheTtl = 60; src = `${bucketStaging}/*`; dest = bucketProd; } let infoMsg = `Publishing ${pubScope}/${pkg.version} to GCS (${dest})`; if (src) { infoMsg += ` from ${src}`; } console.log(infoMsg); // Build gsutil commands: // The gsutil -h option is used to set metadata headers. // The gsutil -m option requests parallel copies. // The gsutil -R option is used for recursive file copy. const cacheControl = `-h "Cache-Control:public,max-age=${cacheTtl}"`; const gsutilCacheCmd = `gsutil -m setmeta ${cacheControl} ${dest}/**`; const gsutilCpCmd = `gsutil -m cp -r -z html,css,js,svg ${src} ${dest}`; gulp.src('').pipe($.shell([gsutilCpCmd, gsutilCacheCmd])); }
Generates chunks of audio that represent the wakeword stream
def generate_wakeword_pieces(self, volume): """""" while True: target = 1 if random() > 0.5 else 0 it = self.pos_files_it if target else self.neg_files_it sample_file = next(it) yield self.layer_with(self.normalize_volume_to(load_audio(sample_file), volume), target) yield self.layer_with(np.zeros(int(pr.sample_rate * (0.5 + 2.0 * random()))), 0)
Called by TransitionManager to play the transition. This calls createAnimators() to set things up and create all of the animations and then runAnimations() to actually start the animations.
void playTransition(@NonNull ViewGroup sceneRoot) { mStartValuesList = new ArrayList<TransitionValues>(); mEndValuesList = new ArrayList<TransitionValues>(); matchStartAndEnd(mStartValues, mEndValues); ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators(); synchronized (sRunningAnimators) { int numOldAnims = runningAnimators.size(); Object windowId = ViewUtils.getWindowId(sceneRoot); for (int i = numOldAnims - 1; i >= 0; i--) { Animator anim = runningAnimators.keyAt(i); if (anim != null) { AnimationInfo oldInfo = runningAnimators.get(anim); if (oldInfo != null && oldInfo.view != null && oldInfo.windowId == windowId) { TransitionValues oldValues = oldInfo.values; View oldView = oldInfo.view; TransitionValues startValues = getTransitionValues(oldView, true); TransitionValues endValues = getMatchedTransitionValues(oldView, true); if (startValues == null && endValues == null) { endValues = mEndValues.viewValues.get(oldView); } boolean cancel = (startValues != null || endValues != null) && oldInfo.transition.isTransitionRequired(oldValues, endValues); if (cancel) { if (anim.isRunning() || AnimatorUtils.isAnimatorStarted(anim)) { if (DBG) { Log.d(LOG_TAG, "Canceling anim " + anim); } anim.cancel(); } else { if (DBG) { Log.d(LOG_TAG, "removing anim from info list: " + anim); } runningAnimators.remove(anim); } } } } } } createAnimators(sceneRoot, mStartValues, mEndValues, mStartValuesList, mEndValuesList); runAnimators(); }
Gets the after advice result. @param <T> the generic type @param aspectId the aspect id @return the after advice result
@SuppressWarnings("unchecked") public <T> T getAfterAdviceResult(String aspectId) { return (aspectAdviceResult != null ? (T)aspectAdviceResult.getAfterAdviceResult(aspectId) : null); }
将Json转换成对象. @param json @param valueType @return
@Override public <T> T toObject(String json, Class<T> clazz) { return toObject(json, clazz, false); }
Adds a command to the library @return Application
public function add($command) { $tasks = $this->prepper ->load(get_class($command)) ->describe(); $this->library->add(['task' => $tasks, 'class' => $command]); return $this; }
Warn等级日志,小于Error @param log 日志对象 @param format 格式文本,{} 代表变量 @param arguments 变量对应的参数
public static void warn(Log log, String format, Object... arguments) { warn(log, null, format, arguments); }
sets paragraph format @param PHPRtfLite_ParFormat $parFormat
public function setParFormat(PHPRtfLite_ParFormat $parFormat) { $this->_rtf->registerParFormat($parFormat); $this->_parFormat = $parFormat; }
Performs a pre-processing operation on the input string in the given input language @param input The input text @param inputLanguage The language of the input @return The post-processed text
public final String apply(String input, Language inputLanguage) { if (input != null && Config.get(this.getClass(), inputLanguage, "apply").asBoolean(true)) { return performNormalization(input, inputLanguage); } return input; }
Requests permissions immediately, <b>must be invoked during initialization phase of your application</b>.
@Override @NonNull @CheckReturnValue public Observable<Permission> requestEach(@NonNull final String... permissions) { return Observable.just(TRIGGER) .compose(ensureEach(permissions)); }
Retrieve the information for a zone entity.
def get(self, zone_id): """""" path = '/'.join(['zone', zone_id]) return self.rachio.get(path)
Counts additional occurrences of a property as property in references. @param usageStatistics statistics object where count is stored @param property the property to count @param count the number of times to count the property
private void countPropertyReference(UsageStatistics usageStatistics, PropertyIdValue property, int count) { addPropertyCounters(usageStatistics, property); usageStatistics.propertyCountsReferences.put(property, usageStatistics.propertyCountsReferences.get(property) + count); }
Retrieve all data of repository, paginated @param int $per_page @param array $columns @param string $page_name @param int|null $page @return \Illuminate\Contracts\Pagination\Paginator
public function simplePaginate($per_page = null, $columns = ['*'], $page_name = 'page', $page = null) { $this->newQuery(); // Get the default per page when not set $per_page = $per_page ?: config('repositories.per_page', 15); return $this->query->simplePaginate($per_page, $columns, $page_name, $page); }
Private function to get the common type from the information of the field @param string $fieldName @param string $nativeType @return string
private function getCommonType($fieldName, $nativeType) { static $types = [ // integers 'int' => CommonTypes::TINT, 'tinyint' => CommonTypes::TINT, 'smallint' => CommonTypes::TINT, 'bigint' => CommonTypes::TINT, // floats 'float' => CommonTypes::TNUMBER, 'real' => CommonTypes::TNUMBER, 'decimal' => CommonTypes::TNUMBER, 'numeric' => CommonTypes::TNUMBER, 'money' => CommonTypes::TNUMBER, 'smallmoney' => CommonTypes::TNUMBER, // dates 'date' => CommonTypes::TDATE, 'time' => CommonTypes::TTIME, 'datetime' => CommonTypes::TDATETIME, 'smalldatetime' => CommonTypes::TDATETIME, // bool 'bit' => CommonTypes::TBOOL, // text 'char' => CommonTypes::TTEXT, 'varchar' => CommonTypes::TTEXT, 'text' => CommonTypes::TTEXT, ]; if (isset($this->overrideTypes[$fieldName])) { return $this->overrideTypes[$fieldName]; } $nativeType = strtolower($nativeType); $type = CommonTypes::TTEXT; if (array_key_exists($nativeType, $types)) { $type = $types[$nativeType]; } return $type; }
Filters a context This will return a new context with only the resources that are actually available for use. Uses tags and command line options to make determination.
def filtered_context(context): """""" ctx = Context(context.opt) for resource in context.resources(): if resource.child: continue if resource.filtered(): ctx.add(resource) return ctx
Runs this {@see DayEnumExample}. @param integer $argc The number of arguments. @param string[] $argv The arguments. @return integer Always `0`.
public static function main($argc, array $argv = []) { $firstDay = new self(DayEnum::MONDAY()); $firstDay->tellItLikeItIs(); $thirdDay = new self(DayEnum::WEDNESDAY()); $thirdDay->tellItLikeItIs(); $fifthDay = new self(DayEnum::FRIDAY()); $fifthDay->tellItLikeItIs(); $sixthDay = new self(DayEnum::SATURDAY()); $sixthDay->tellItLikeItIs(); $seventhDay = new self(DayEnum::SUNDAY()); $seventhDay->tellItLikeItIs(); return 0; }
@param int $level @throws \OutOfBoundsException
private function checkLevel(int $level) { if ($level <= 0 || $level > self::MAX_LEVEL_DEPTH) { throw new OutOfBounds( sprintf('Administrative level should be an integer in [1,%d], %d given', self::MAX_LEVEL_DEPTH, $level) ); } }
Filters out boolish items that resemble none "truthy" values. @return array
public static function compact($array, $reindex = false) { $out = array_filter($array, function ($item) { return false !== (bool)$item; }); return false !== $reindex && self::isList($out) ? array_values($out) : $out; }
Handles adding a contact. @param int $userid The id of the user who requested to be a contact @param int $contactid The id of the contact
public static function add_contact(int $userid, int $contactid) { global $DB; $messagecontact = new \stdClass(); $messagecontact->userid = $userid; $messagecontact->contactid = $contactid; $messagecontact->timecreated = time(); $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact); $eventparams = [ 'objectid' => $messagecontact->id, 'userid' => $userid, 'relateduserid' => $contactid, 'context' => \context_user::instance($userid) ]; $event = \core\event\message_contact_added::create($eventparams); $event->add_record_snapshot('message_contacts', $messagecontact); $event->trigger(); }
Marshall the given parameter object.
public void marshall(ExportSnapshotRecord exportSnapshotRecord, ProtocolMarshaller protocolMarshaller) { if (exportSnapshotRecord == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(exportSnapshotRecord.getName(), NAME_BINDING); protocolMarshaller.marshall(exportSnapshotRecord.getArn(), ARN_BINDING); protocolMarshaller.marshall(exportSnapshotRecord.getCreatedAt(), CREATEDAT_BINDING); protocolMarshaller.marshall(exportSnapshotRecord.getLocation(), LOCATION_BINDING); protocolMarshaller.marshall(exportSnapshotRecord.getResourceType(), RESOURCETYPE_BINDING); protocolMarshaller.marshall(exportSnapshotRecord.getState(), STATE_BINDING); protocolMarshaller.marshall(exportSnapshotRecord.getSourceInfo(), SOURCEINFO_BINDING); protocolMarshaller.marshall(exportSnapshotRecord.getDestinationInfo(), DESTINATIONINFO_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Validates that x is a multiple of the reference (`x % ref == 0`)
def is_multiple_of(ref): def is_multiple_of_ref(x): if x % ref == 0: return True else: raise IsNotMultipleOf(wrong_value=x, ref=ref) # raise Failure('x % {ref} == 0 does not hold for x={val}'.format(ref=ref, val=x)) is_multiple_of_ref.__name__ = 'is_multiple_of_{}'.format(ref) return is_multiple_of_ref
// AddFunc takes a function and runs it repeatedly, adding the return values // as fields. // The function should return error when it has exhausted its values
func (f *fieldHolder) AddFunc(fn func() (string, interface{}, error)) error { for { key, rawVal, err := fn() if err != nil { // fn is done giving us data break } f.AddField(key, rawVal) } return nil }
Deregister removed documents. @param RemoveEvent $event
public function handleRemove(RemoveEvent $event) { $document = $event->getDocument(); $this->documentRegistry->deregisterDocument($document); }
// CheckAddresses returns the uri scheme if the address is valid.
func CheckAddresses(uriList []string, schemes []string) (scheme string) { count := len(uriList) if count < 1 { panic(ErrURIListEmpty) } u, err := url.Parse(uriList[0]) if err != nil { panic(err) } scheme = u.Scheme if sort.SearchStrings(schemes, scheme) == len(schemes) { panic(errors.New("This client desn't support " + scheme + " scheme.")) } for i := 1; i < count; i++ { u, err := url.Parse(uriList[i]) if err != nil { panic(err) } if scheme != u.Scheme { panic(ErrNotSupportMultpleProtocol) } } return }
// SetBudgetName sets the BudgetName field's value.
func (s *Budget) SetBudgetName(v string) *Budget { s.BudgetName = &v return s }
redis key: records:tablename: id1 | id2 | id3... eg: the user has three primarykeys id1=1,id2=2,id3=3, so the redisKey is 'records:user:1|2|3'. @return redis key
private String redisKey(ModelExt<?> m) { Table table = m.table(); StringBuilder key = new StringBuilder(); key.append(RECORDS); key.append(table.getName()); key.append(":"); //fetch primary keys' values String[] primaryKeys = table.getPrimaryKey(); //format key for (int idx = 0; idx < primaryKeys.length; idx++) { Object primaryKeyVal = m.get(primaryKeys[idx]); if (null != primaryKeyVal) { if (idx > 0) { key.append("|"); } key.append(primaryKeyVal); } } return key.toString(); }
Return a deferred.
def delete(self, **params): """""" d = self.request('delete', self.instance_url(), params) return d.addCallback(self.refresh_from).addCallback(lambda _: self)
file can be null, meaning stdin
function readSpecFile(file, options) { if (options.verbose > 1) { file ? console.error('GET ' + file) : console.error('GET <stdin>'); } if (!file) { // standard input return readFileStdinAsync(); } else if (file && file.startsWith('http')) { // remote file return fetch(file).then(res => { if (res.status !== 200) { throw new Error(`Received status code ${res.status}`); } return res.text(); }) } else { // local file // TODO error handlers? return readFileAsync(file, 'utf8'); } }
Returns the renderer for the given format. @param string $format @throws \AltThree\Badger\Exceptions\InvalidRendererException @return \AltThree\Badger\Render\RenderInterface
protected function getRendererForFormat(string $format) { if (!isset($this->renderers[$format])) { throw new InvalidRendererException('No renders found for the given format: '.$format); } return $this->renderers[$format]; }
Preprocess string to transform all diacritics and remove other special characters than appropriate :param string: :return:
def preprocess(string): string = unicode(string, encoding="utf-8") # convert diacritics to simpler forms string = regex1.sub(lambda x: accents[x.group()], string) # remove all rest of the unwanted characters return regex2.sub('', string).encode('utf-8')
Build a summary list of all the methods in this context
def build_method_summary_list(path_prefix="") collect_methods unless @methods meths = @methods.sort res = [] meths.each do |meth| res << { "name" => CGI.escapeHTML(meth.name), "aref" => "#{path_prefix}\##{meth.aref}" } end res end
Returns the first subset of a given set in this UBTree. @param set the set to search for @return the first subset which is found for the given set or {@code null} if there is none
public SortedSet<T> firstSubset(SortedSet<T> set) { if (this.rootNodes.isEmpty() || set == null || set.isEmpty()) { return null; } return firstSubset(set, this.rootNodes); }
Extracts task enterprise column values. @param id task unique ID @param task task instance @param taskVarData task var data @param metaData2 task meta data
private void processTaskEnterpriseColumns(Integer id, Task task, Var2Data taskVarData, byte[] metaData2) { if (metaData2 != null) { int bits = MPPUtility.getInt(metaData2, 29); task.set(TaskField.ENTERPRISE_FLAG1, Boolean.valueOf((bits & 0x0000800) != 0)); task.set(TaskField.ENTERPRISE_FLAG2, Boolean.valueOf((bits & 0x0001000) != 0)); task.set(TaskField.ENTERPRISE_FLAG3, Boolean.valueOf((bits & 0x0002000) != 0)); task.set(TaskField.ENTERPRISE_FLAG4, Boolean.valueOf((bits & 0x0004000) != 0)); task.set(TaskField.ENTERPRISE_FLAG5, Boolean.valueOf((bits & 0x0008000) != 0)); task.set(TaskField.ENTERPRISE_FLAG6, Boolean.valueOf((bits & 0x0001000) != 0)); task.set(TaskField.ENTERPRISE_FLAG7, Boolean.valueOf((bits & 0x0002000) != 0)); task.set(TaskField.ENTERPRISE_FLAG8, Boolean.valueOf((bits & 0x0004000) != 0)); task.set(TaskField.ENTERPRISE_FLAG9, Boolean.valueOf((bits & 0x0008000) != 0)); task.set(TaskField.ENTERPRISE_FLAG10, Boolean.valueOf((bits & 0x0010000) != 0)); task.set(TaskField.ENTERPRISE_FLAG11, Boolean.valueOf((bits & 0x0020000) != 0)); task.set(TaskField.ENTERPRISE_FLAG12, Boolean.valueOf((bits & 0x0040000) != 0)); task.set(TaskField.ENTERPRISE_FLAG13, Boolean.valueOf((bits & 0x0080000) != 0)); task.set(TaskField.ENTERPRISE_FLAG14, Boolean.valueOf((bits & 0x0100000) != 0)); task.set(TaskField.ENTERPRISE_FLAG15, Boolean.valueOf((bits & 0x0200000) != 0)); task.set(TaskField.ENTERPRISE_FLAG16, Boolean.valueOf((bits & 0x0400000) != 0)); task.set(TaskField.ENTERPRISE_FLAG17, Boolean.valueOf((bits & 0x0800000) != 0)); task.set(TaskField.ENTERPRISE_FLAG18, Boolean.valueOf((bits & 0x1000000) != 0)); task.set(TaskField.ENTERPRISE_FLAG19, Boolean.valueOf((bits & 0x2000000) != 0)); task.set(TaskField.ENTERPRISE_FLAG20, Boolean.valueOf((bits & 0x4000000) != 0)); } }
Parse service name from request @return string|boolean
protected function fetchService() { $service = $this->getRouteParam('service'); $service = $this->parseCanonicalName($service, true); if (preg_match($this->servicePattern, $service)) { return $service; } else { return false; } }
// SetIdentityAttributeValues sets the IdentityAttributeValues field's value.
func (s *TypedLinkSpecifier) SetIdentityAttributeValues(v []*AttributeNameAndValue) *TypedLinkSpecifier { s.IdentityAttributeValues = v return s }
This is more expensive than normal.
@Override public void clear() { // iterate over all keys in originalMap and set them to null in deltaMap for (K key : originalMap.keySet()) { deltaMap.put(key, ErasureUtils.<Collection<V>>uncheckedCast(removedValue)); } }
// removeOpcode will remove any opcode matching ``opcode'' from the opcode // stream in pkscript
func removeOpcode(pkscript []parsedOpcode, opcode byte) []parsedOpcode { retScript := make([]parsedOpcode, 0, len(pkscript)) for _, pop := range pkscript { if pop.opcode.value != opcode { retScript = append(retScript, pop) } } return retScript }
Set language. @param \BlackForest\PiwikBundle\Entity\PiwikLanguage|null $language @return PiwikVisit
public function setLanguage(\BlackForest\PiwikBundle\Entity\PiwikLanguage $language = null) { $this->language = $language; return $this; }
:nocov: @visibility private
def inspect ['{config', *each.map{|key, value| " "+qualified_key(*key)+" => "+value.inspect },'}'].join("\n") end
// SetBudgetName sets the BudgetName field's value.
func (s *DeleteSubscriberInput) SetBudgetName(v string) *DeleteSubscriberInput { s.BudgetName = &v return s }
Get the extension that matches given mimetype. @param string $mimetype @return mixed null when not found, extension (string) when found.
public function getExtension($mimetype) { if (!($extension = array_search($mimetype, $this->mainMimeTypes))) { $extension = array_search($mimetype, $this->mimeTypes); } return !$extension ? null : $extension; }
Public API for generating a URL pathname from a path and parameters.
function generatePath(path = "/", params = {}) { return path === "/" ? path : compilePath(path)(params, { pretty: true }); }
// SetScheduleTimezone sets the ScheduleTimezone field's value.
func (s *GetMaintenanceWindowOutput) SetScheduleTimezone(v string) *GetMaintenanceWindowOutput { s.ScheduleTimezone = &v return s }
Get a dimension. @param Image $image The source image. @param string $field The requested field. @return double|null The dimension.
public function getDimension(Image $image, $field) { if ($this->{$field}) { return (new Dimension($image, $this->getDpr()))->get($this->{$field}); } }
Remove HashTable item @param PHPExcel_IComparable $pSource Item to remove @throws PHPExcel_Exception
public function remove(PHPExcel_IComparable $pSource = null) { $hash = $pSource->getHashCode(); if (isset($this->_items[$hash])) { unset($this->_items[$hash]); $deleteKey = -1; foreach ($this->_keyMap as $key => $value) { if ($deleteKey >= 0) { $this->_keyMap[$key - 1] = $value; } if ($value == $hash) { $deleteKey = $key; } } unset($this->_keyMap[count($this->_keyMap) - 1]); } }
Loop forever, pushing out stats.
def run(self): """""" self.graphite.start() while True: log.debug('Graphite pusher is sleeping for %d seconds', self.period) time.sleep(self.period) log.debug('Pushing stats to Graphite') try: self.push() log.debug('Done pushing stats to Graphite') except: log.exception('Exception while pushing stats to Graphite') raise
// CheckShell checks that a shell is supported, and returns the correct command name
func CheckShell(shell string) (string, error) { if _, ok := ValidShells[shell]; !ok { return "", fmt.Errorf("unsupported shell: %q", shell) } switch shell { case "powershell": if _, err := exec.LookPath("powershell"); err == nil { return "powershell", nil } else if _, err := exec.LookPath("pwsh"); err == nil { return "pwsh", nil } else { return "", fmt.Errorf("powershell/pwsh not on path") } case "modd": // When testing, we're running under a special compiled test executable, // so we look for an instance of modd on our path. if shellTesting { return exec.LookPath("modd") } return os.Executable() default: return exec.LookPath(shell) } }
// Roll updates the checksum of the window from the entering byte. You // MUST initialize a window with Write() before calling this method.
func (d *Adler32) Roll(b byte) { // This check costs 10-15% performance. If we disable it, we crash // when the window is empty. If we enable it, we are always correct // (an empty window never changes no matter how much you roll it). //if len(d.window) == 0 { // return //} // extract the entering/leaving bytes and update the circular buffer. enter := uint32(b) leave := uint32(d.window[d.oldest]) d.window[d.oldest] = b d.oldest += 1 if d.oldest >= len(d.window) { d.oldest = 0 } // See http://stackoverflow.com/questions/40985080/why-does-my-rolling-adler32-checksum-not-work-in-go-modulo-arithmetic d.a = (d.a + Mod + enter - leave) % Mod d.b = (d.b + (d.n*leave/Mod+1)*Mod + d.a - (d.n * leave) - 1) % Mod }
Delete a single item with the given ID
def delete(self, id): '''''' if not self._item_path: raise AttributeError('delete is not available for %s' % self._item_name) target = self._item_path % id self._redmine.delete(target) return None
// Refer to the Mailgun documentation for more information.
func (m *Message) SetTrackingOpens(trackingOpens bool) { m.trackingOpens = trackingOpens m.trackingOpensSet = true }
// Not reverses the results of its given child matcher. // // Example usage: // Not(Eq(5)).Matches(4) // returns true // Not(Eq(5)).Matches(5) // returns false
func Not(x interface{}) Matcher { if m, ok := x.(Matcher); ok { return notMatcher{m} } return notMatcher{Eq(x)} }
Set limit on the number of propagations.
def prop_budget(self, budget): if self.minisat: pysolvers.minisatgh_pbudget(self.minisat, budget)
设置缓存 @param string $key @param mixed $value @param int $expire -1 永不过期 0默认配置 @throws \Error
public static function set($key, $value, $expire = 0) { try { self::getCache()->set($key, $value, $expire); self::release(); } catch (\RuntimeException $e) { self::release(); throw $e; } catch (\Error $e) { self::release(); throw $e; } }
Outputs the FontAwesomeText object as an HTML string @access protected @return string HTML string of text element
protected function output() { $attrs = ''; $classes = 'fa-layers-text'; $transforms = ''; if (!empty($this->classes) && count($this->classes) > 0) { $classes .= ' ' . implode(' ', $this->classes); } if (!empty($this->attributes) && count($this->attributes) > 0) { foreach ($this->attributes as $attr => $val) { $attrs .= ' ' . $attr . '="' . $val . '"'; } } if (!empty($this->transforms) && count($this->transforms) > 0) { $transformList = array(); foreach ($this->transforms as $transform) { $transformList[] = implode('-', $transform); } $transforms = ' data-fa-transform="' . implode(' ', $transformList) . '"'; } return sprintf(self::TEXT_HTML, $classes, $attrs, $transforms, $this->text); }
Return a single frame.
@SuppressWarnings("unused") // called through reflection by RequestServer public FramesV3 fetch(int version, FramesV3 s) { FramesV3 frames = doFetch(version, s); // Summary data is big, and not always there: null it out here. You have to call columnSummary // to force computation of the summary data. for (FrameBaseV3 a_frame: frames.frames) { ((FrameV3)a_frame).clearBinsField(); } return frames; }
Performs all data validation that is appicable to the data value itself @param object - the data value @throws DataValidationException if any of the data constraints are violated
@SuppressWarnings("unchecked") public void postValidate(Object object) throws DataValidationException { if (_values != null || _ranges != null) { if (_values != null) for (Object value: _values) { if (value.equals(object)) return; } if (_ranges != null) for (@SuppressWarnings("rawtypes") Range r: _ranges) { @SuppressWarnings("rawtypes") Comparable o = (Comparable)object; if (r.inclusive) { if ((r.min == null || r.min.compareTo(o) <= 0) && (r.max == null || o.compareTo(r.max) <= 0)) { return; } } else { if ((r.min == null || r.min.compareTo(o) < 0) && (r.max == null || o.compareTo(r.max) < 0)) { return; } } } throw new DataValidationException("VALUES/RANGES", _name, object); } }
@param ContentInterface $content @return array
protected function extractMediasFromContentType(ContentTypeInterface $contentType) { $mediaIds = array(); $fields = $contentType->getFields(); foreach ($fields as $field) { if ($this->isMediaAttribute($field->getDefaultValue())) { $mediaIds[] = $field->getDefaultValue()['id']; } } return $mediaIds; }
Setter for **self.__splitters** attribute. :param value: Attribute value. :type value: tuple or list
def splitters(self, value): if value is not None: assert type(value) in (tuple, list), "'{0}' attribute: '{1}' type is not 'tuple' or 'list'!".format( "splitters", value) for element in value: assert type(element) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( "splitters", element) assert len(element) == 1, "'{0}' attribute: '{1}' has multiples characters!".format( "splitter", element) assert not re.search(r"\w", element), "'{0}' attribute: '{1}' is an alphanumeric character!".format( "splitter", element) self.__splitters = value
Assign float value to inputOutput SFFloat field named speed. Note that our implementation with ExoPlayer that pitch and speed will be set to the same value. @param newValue
public void setSpeed(float newValue) { if (newValue < 0) newValue = 0; this.pitch.setValue( newValue ); this.speed.setValue( newValue ); }
set loglevel based on NODE_DEBUG env variable and create exported methods
function initialize() { var flags = []; Object.keys( levels ).forEach(function( type, level ) { var method = type.toLowerCase(); exports[ method ] = log.bind( exports, type, level, false ); exports[ method ].json = log.bind( exports, type, level, true ); if ( new RegExp( '\\b' + type + '\\b', 'i' ).test( env ) ) { flags.push( level ); } }); loglevel = Math.min.apply( Math, flags ); }
Create presets of an image @param string $path
public static function createPresets($path = null, $callback = null) { $moufManager = MoufManager::getMoufManager(); $instances = $moufManager->findInstances('Mouf\\Utils\\Graphics\\MoufImagine\\Controller\\ImagePresetController'); foreach ($instances as $instanceName) { $instance = $moufManager->getInstance($instanceName); if ($path && strpos($path, $instance->originalPath) !== false && $instance->createPresetsEnabled === true) { $imagePath = substr($path, strlen($instance->originalPath) + 1); $instance->image($imagePath); if(is_callable($callback)) { $finalPath = ROOT_PATH . $instance->url . DIRECTORY_SEPARATOR . $imagePath; $callback($finalPath); } } } }