comment
stringlengths
16
255
code
stringlengths
52
3.87M
USAGE: color-lighten(@neutral, 50);
function getColorLightenFunction(less) { function rgba() { var rgbaFunc = less.functions.functionRegistry.get("rgba"); return rgbaFunc.apply(null, arguments); } return function (color, amount) { var baseRGB = [255, 255, 255]; var value = amount.value / 100; if (value < 0) { baseRGB = ...
Return a label to display for a field
def get_field_label(self, field_name, field=None): label = None if field is not None: label = getattr(field, 'verbose_name', None) if label is None: label = getattr(field, 'name', None) if label is None: label = field_name retu...
@param MockConfig $expectation @return bool
private function isExpectedScenarioState(MockConfig $expectation) { if ($expectation->getRequest()->hasScenarioState()) { $this->checkScenarioNameOrThrowException($expectation); $this->logger->debug('Checking scenario state again expectation'); $scenarioState = $this->sce...
Block Record @alias module:wallet.BlockRecord @constructor @param {Hash} hash @param {Number} height @param {Number} time
function BlockRecord(hash, height, time) { if (!(this instanceof BlockRecord)) return new BlockRecord(hash, height, time); this.hash = hash || encoding.NULL_HASH; this.height = height != null ? height : -1; this.time = time || 0; this.hashes = []; this.index = new Set(); }
Utility function for raising a werkzeug.exceptions.NotFound execption with the supplied WSGI environment and message. :param dict environ: The WSGI environment dictionary for the request :param str msg: The error message
def raise_not_found(self, environ, msg): raise NotFound(response=self.rewriterapp._error_response(environ, msg))
Parses samples, specified in either a manifest or listed with --samples :param str path_to_manifest: Path to configuration file :return: Samples and their attributes as defined in the manifest :rtype: list[list]
def parse_manifest(path_to_manifest): samples = [] with open(path_to_manifest, 'r') as f: for line in f.readlines(): if not line.isspace() and not line.startswith('#'): sample = line.strip().split('\t') require(len(sample) == 3, 'Bad manifest format! ' ...
Document height @method docHeight @return {Number} The current height of the document.
function(node) { var h = Y_DOM._getDocSize(node).height; return Math.max(h, Y_DOM._getWinSize(node).height); }
// SetKeyId sets the KeyId field's value.
func (s *StreamDescription) SetKeyId(v string) *StreamDescription { s.KeyId = &v return s }
A JSON serializable dict representation of self.
def as_dict(self): return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "operation": self.operation, "title": self.title, "xc": self.xc.as_dict(), "basis_set": self.basis_set.as_dict(), "units": self.units.as_di...
Приводит в порядок порядковые номера материалов раздела: удаляет дубликаты, дыры в нумерации. @internal @return void
public function fixMaterialTags() { $r = self::getDbConnection()->fetchAll('SELECT count(tag) as cnt from '.$this->materialsTable.' where idcat='.$this->prototype->id.' group by tag having cnt>1'); if (!count($r)) return; $i = 100; $r = self::getDbConnection()->query('SELECT id FROM '.$this->materia...
@param string|string[] $question @param string[] $choices @param string $default @param InputInterface $input @param OutputInterface $output @return string|null
private function choice($question, array $choices, $default, InputInterface $input, OutputInterface $output) { $helper = new QuestionHelper(); $result = $helper->ask($input, $output, new ChoiceQuestion( $question, $choices, $choices[$default] )); ...
/*! Returns the meta data used for storing search indeces.
function metaData( $contentObjectAttribute ) { $matrix = $contentObjectAttribute->content(); $columnsArray = $matrix->attribute( 'columns' ); $columns = $columnsArray['sequential']; $metaDataArray = array(); foreach ( $columns as $column ) { $rows = $colum...
PersistenceDelegate.initialize()
protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { // // Get the bean and associated beanInfo for the source instance // ControlBean control = (ControlBean)oldInstance; BeanInfo beanInfo; try { beanInfo ...
This preInvoke is called during init & during destroy of a Servlet class object. It will call the other preInvoke to ensure delegation occurs. {@inheritDoc}
@Override public Object preInvoke(String servletName) throws SecurityViolationException, IOException { // preInvoke will ensure delegation is done when run-as is specified return preInvoke(null, null, servletName, true); }
// ItemByID by returns the file's Item of a given ID. // If the ID is known, the returned error is ErrUnknownItem.
func (f *File) ItemByID(id uint32) (*Item, error) { meta, err := f.getMeta() if err != nil { return nil, err } it := &Item{ f: f, ID: id, } if meta.ItemLocation != nil { for _, ilbe := range meta.ItemLocation.Items { if uint32(ilbe.ItemID) == id { shallowCopy := ilbe it.Location = &shallowCopy...
Iterates through the tasks setting the correct outline level and ID values. @param id current ID value @param task current task @param outlineLevel current outline level @return next ID value
private int updateStructure(int id, Task task, Integer outlineLevel) { task.setID(Integer.valueOf(id++)); task.setOutlineLevel(outlineLevel); outlineLevel = Integer.valueOf(outlineLevel.intValue() + 1); for (Task childTask : task.getChildTasks()) { id = updateStructure(id, chil...
// Unlink removes a large object from the database.
func (o *LargeObjects) Unlink(oid pgtype.OID) error { _, err := o.fp.CallFn("lo_unlink", []fpArg{fpIntArg(int32(oid))}) return err }
What Facebook uses to define the url in a batch
@JsonProperty("relative_url") public String getRelativeURL() { StringBuilder bld = new StringBuilder(); bld.append(this.object); Param[] params = this.getParams(); if (params != null && params.length > 0) { bld.append('?'); boolean afterFirst = false; for (Param param: params) { if (afte...
// Initialize a new storage disk.
func newPosix(path string) (*posix, error) { var err error if path, err = getValidPath(path); err != nil { return nil, err } fi, err := os.Stat(path) if err != nil { return nil, err } p := &posix{ connected: true, diskPath: path, // 4MiB buffer pool for posix internal operations. pool: sync.Pool{ ...
fast counting to the lines of a given filename through only reading out a limited buffer
def countLines(filename, buf_size=1048576): f = open(filename) try: lines = 1 read_f = f.read # loop optimization buf = read_f(buf_size) # Empty file if not buf: return 0 while buf: lines += buf.count('\n') buf = read_f(bu...
Return the version before the given version. @param string $from
public function getPreviousVersion($from) { $lastTimestamp = 0; foreach (array_keys($this->versions) as $timestamp) { if ($timestamp == $from) { return $lastTimestamp; } $lastTimestamp = $timestamp; } return 0; }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
public EClass getBLN() { if (blnEClass == null) { blnEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(324); } return blnEClass; }
find files matching a shell-style pattern
def runGlob(self, path, **kwargs): def commandComplete(cmd): return cmd.updates['files'][-1] return self.runRemoteCommand('glob', {'path': path, 'logEnviron': self.logEnviron, }, evaluateCommand=comm...
Check if a directory should be considered in the walk.
def _check_open_dir(self, fs, path, info): # type: (FS, Text, Info) -> bool if self.exclude_dirs is not None and fs.match(self.exclude_dirs, info.name): return False if self.filter_dirs is not None and not fs.match(self.filter_dirs, info.name): return False ...
Sets a list of observer events that will be logged if verbose output is enabled. @param string $observerEvents List of observer events
public function setObserverEvents($observerEvents) { $this->observerEvents = []; $token = ' ,;'; $ext = strtok($observerEvents, $token); while ($ext !== false) { $this->observerEvents[] = $ext; $ext = strtok($token); } }
Check if proxy is still initialized
def homegearCheckInit(self, remote): """""" rdict = self.remotes.get(remote) if not rdict: return False if rdict.get('type') != BACKEND_HOMEGEAR: return False try: interface_id = "%s-%s" % (self._interface_id, remote) return self.pr...
// Job instantiates a Transfer job from the TransferConfig struct
func (t *TransferConfig) Job() (*storagetransfer.TransferJob, error) { if t.DestBucket == "" || t.Src == nil { return nil, ErrBadConfig } // Google returns an error if more than 20 inclusionary/exclusionary fields are included if len(t.IncludePrefixes) > MaxPrefix || len(t.ExcludePrefixes) > MaxPrefix { return...
// Run implements Command.Run.
func (c *deleteImageMetadataCommand) Run(ctx *cmd.Context) (err error) { api, err := c.newAPIFunc() if err != nil { return err } defer api.Close() err = api.Delete(c.ImageId) if err != nil { return err } return nil }
// NewAroonOscForStream creates an Aroon Oscillator (AroonOsc) for online usage with a source data stream
func NewAroonOscForStream(priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int) (indicator *AroonOsc, err error) { ind, err := NewAroonOsc(timePeriod) priceStream.AddTickSubscription(ind) return ind, err }
Retrieves additional HTML attributes as a string ready for inclusion in markup. @param array $attributes Required. @return string
protected function get_html_attributes( array $attributes ) { $html_attributes = ''; if ( ! empty( $attributes ) ) { foreach ( $attributes as $attr => $val ) { $html_attributes .= \esc_attr( $attr ) . '="' . \esc_attr( $val ) . '" '; } } return $html_attributes; }
// dataSourceIdentityUserV3Attributes populates the fields of an User resource.
func dataSourceIdentityUserV3Attributes(d *schema.ResourceData, user *users.User) error { log.Printf("[DEBUG] openstack_identity_user_v3 details: %#v", user) d.SetId(user.ID) d.Set("default_project_id", user.DefaultProjectID) d.Set("description", user.Description) d.Set("domain_id", user.DomainID) d.Set("enabled...
Compare two paths after normalization of them. @param path1 first path for comparison @param path2 second path for comparison @return whether the two paths are equivalent after normalization
public static boolean pathEquals(String path1, String path2) { return cleanPath(path1).equals(cleanPath(path2)); }
Marshall the given parameter object.
public void marshall(TriggerUpdate triggerUpdate, ProtocolMarshaller protocolMarshaller) { if (triggerUpdate == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(triggerUpdate.getName(), NAME_BINDING); ...
Execute this process, blocking until it has completed.
public void run() throws IOException { if (this.isStarted() || this.isComplete()) { throw new IllegalStateException("The process can only be used once."); } final ProcessBuilder builder = new ProcessBuilder(this.cmd); builder.directory(new File(this.workingDir)); builder.environment().putAll(...
// SelectFromStrings ...
func SelectFromStrings(messageToPrint string, options []string) (string, error) { return SelectFromStringsFromReader(messageToPrint, options, os.Stdin) }
// DefaultDescribeFormatOptions returns default options for formatting // the output.
func DefaultDescribeFormatOptions() (DescribeFormatOptions, error) { runtime.LockOSThread() defer runtime.UnlockOSThread() opts := C.git_describe_format_options{} ecode := C.git_describe_init_format_options(&opts, C.GIT_DESCRIBE_FORMAT_OPTIONS_VERSION) if ecode < 0 { return DescribeFormatOptions{}, MakeGitError...
Provide a human readable description for On instance. @param on - On @return human readable description - String
protected String describe(final On on, final boolean and) { if (and) { return nominalValue(on.getTime()); } return String.format("%s %s ", bundle.getString("at"), nominalValue(on.getTime())) + "%s"; }
Sets the Filters. @param array|sting $filters the filters @return self
public function setFilters($filters) { if (! is_array($filters)) $filters = [$filters]; $this->filters = array_unique(array_merge($this->filters, $filters)); return $this; }
Writes a short in Intel byte order.
static void writeShort(OutputStream out, int i) throws IOException { out.write((byte)i); out.write((byte)(i >> 8)); }
// CanRetry returns the current number of retries, and whether or not it exceeds // the maximum number of retries (see: retryCounter.MaxRetries).
func (r *retryCounter) CanRetry(oid string) (int, bool) { count := r.CountFor(oid) return count, count < r.MaxRetries }
Small range of hyperparameters.
def slicenet_range1(ranged_hparams): """""" rhp = ranged_hparams rhp.set_float("clip_grad_norm", 1.0, 10.0, scale=rhp.LOG_SCALE) rhp.set_float("learning_rate", 0.02, 1.0, scale=rhp.LOG_SCALE) rhp.set_float("optimizer_adam_beta2", 0.995, 0.998) rhp.set_float("weight_decay", 1.0, 5.0)
<p> Performs pixel-wise addition<br> d(x,y) = inputA(x,y) + inputB(x,y) </p> @param inputA Input image. Not modified. @param inputB Input image. Not modified. @param output Output image. Modified.
public static <T extends ImageBase<T>, O extends ImageBase> void add(T inputA, T inputB, O output) { if( inputA instanceof ImageGray) { if (GrayU8.class == inputA.getClass()) { PixelMath.add((GrayU8) inputA, (GrayU8) inputB, (GrayU16) output); } else if (GrayS8.class == inputA.getClass()) { PixelMath.a...
// Reblock is used to reinsert an existing blocked evaluation into the blocked // evaluation tracker.
func (e *Eval) Reblock(args *structs.EvalUpdateRequest, reply *structs.GenericResponse) error { if done, err := e.srv.forward("Eval.Reblock", args, args, reply); done { return err } defer metrics.MeasureSince([]string{"nomad", "eval", "reblock"}, time.Now()) // Ensure there is only a single update with token if...
Querying related methods Looks up parent instances @returns {String} current value prepended by parents' values
function () { var that = this, parentInstance = that.getParentInstance(), parentValue = parentInstance && parentInstance.extendedCurrentValue(), currentValue = $.trim(that.el.val()); return utils.compact([parentValue, currentValue]).join(' '); }
Memory efficient function for loading a table from a FITS file.
def create_table_from_fits(fitsfile, hduname, colnames=None): """""" if colnames is None: return Table.read(fitsfile, hduname) cols = [] with fits.open(fitsfile, memmap=True) as h: for k in colnames: data = h[hduname].data.field(k) cols += [Column(name=k, data=d...
// SampleRate returns the metrics sampling rate.
func (mc *MetricsConfiguration) SampleRate() float64 { if mc.SamplingRate > 0.0 && mc.SamplingRate <= 1.0 { return mc.SamplingRate } return defaultSamplingRate }
Parses the scheme-specific portion of the URI and place its parts into instance variables. @throws Exception @return void
protected function parseUri($uriString = '') { $status = @preg_match("~^((//)([^/?#]*))([^?#]*)(\?([^#]*))?(#(.*))?$~", $uriString, $matches); if($status === FALSE) { throw new Exception("URI scheme-specific decomposition failed"); } if(!$status) return; $this->path = (isset($matches[...
Return handler to open rasters (rasterio.open).
def _raster_opener(cls, filename, *args, **kwargs): """""" with rasterio.Env(**cls.get_gdal_env(filename)): try: return rasterio.open(filename, *args, **kwargs) except (rasterio.errors.RasterioIOError, rasterio._err.CPLE_BaseError) as e: raise GeoR...
Retrieves the page's content, passed through any necessary parsing eg Wiki based content @return String
public function ParsedContent() { $formatter = $this->getFormatter(); $content = $formatter->formatContent($this); // purify the output - we don't want people breaking pages if we set purify=true if (self::$purify_output) { include_once SIMPLEWIKI_DIR . '/thirdparty/htmlpurifier-4.0.0-lite/library/HTMLPurif...
Remove the property with the given key. The internal property object is not deleted itself but it's value is set to <code>null</code> and the method <code>isDeleted()</code> will return <code>true</code> . @param key Key for the property to remove.
public final void remove(final String key) { final Property prop = find(key); if (prop != null) { prop.setValue(null); } }
Matrix-vector product for real symmetric-packed matrix.
def cublasSspmv(handle, uplo, n, alpha, AP, x, incx, beta, y, incy): status = _libcublas.cublasSspmv_v2(handle, _CUBLAS_FILL_MODE[uplo], n, ctypes.byref(ctypes.c_float(alpha)), ...
Remove valores de uma tabela no banco de dados @param string $column coluna da tabela @param string $value valor na tabela @return boolean se todos os valores foram deletados com sucesso
public static function delete($column, $value) { try { self::instance(); $tableStatic = static::$table; $stmt = self::$db->prepare("delete from {$tableStatic} where {$column} = :value"); $stmt->bindValue(":value", $value); ...
Function that finds all IDs of entities that match the search criteria. @return array
protected function findIdsByGivenCriteria() { $select = $this->getSelectAs($this->idField); $subQueryBuilder = $this->createSubQueryBuilder($select); if (null != $this->limit) { $subQueryBuilder->setMaxResults($this->limit)->setFirstResult($this->limit * ($this->page - 1)); ...
Gets a single object @param type $callerClass @param type $filter @param type $cache @param type $orderby @return DataObject
public function getOne($callerClass, $filter = "", $cache = true, $orderby = "", $requiredPerm = 'View') { $items = $this->getAll($callerClass, $filter, $orderby, null, null, $requiredPerm); if ($items && count($items)) { return $items[0]; } }
Check that a string is not empty if its not null. @param value value. @param name parameter name for the exception message. @return the given value.
public static String notEmptyIfNotNull(String value, String name) { return notEmptyIfNotNull(value, name, null); }
// ReadJSON returns the decoded configuration file, or an error.
func ReadJSON(secustom string) (configger Config, err error) { naclKey := new([keySize]byte) copy(naclKey[:], pad[:keySize]) nonce := new([nonceSize]byte) in, err := ioutil.ReadFile(secustom) if err != nil { return configger, err } copy(nonce[:], in[:nonceSize]) configbytes, ok := secretbox.Open(nil, in[nonce...
// ReadB64 is a blocking read for base64 encoded msgpack rpc data. // It is called serially by the mobile run loops.
func ReadB64() (res string, err error) { defer func() { err = flattenError(err) }() if conn == nil { return "", errors.New("connection not initialized") } n, err := conn.Read(buffer) if n > 0 && err == nil { str := base64.StdEncoding.EncodeToString(buffer[0:n]) return str, nil } if err != nil { // Attem...
Párování faktur dle nezaplacenych faktur
public function invoicesMatchingByInvoices() { foreach ($this->getInvoicesToProcess() as $invoiceData) { $payments = $this->findPayments($invoiceData); if (!empty($payments) && count(current($payments))) { $typDokl = $invoiceData['typDokl'][0]; ...
This method will try to decrypt the given JWE and recipient using a JWK. @param JWE $jwe A JWE object to decrypt @param JWK $jwk The key used to decrypt the input @param int $recipient The recipient used to decrypt the token
public function decryptUsingKey(JWE &$jwe, JWK $jwk, int $recipient): bool { $jwkset = new JWKSet([$jwk]); return $this->decryptUsingKeySet($jwe, $jwkset, $recipient); }
@param string $file @return array
protected function findTables($file) { $tables = []; $xml = simplexml_load_file($file); foreach ($xml->xpath('TABLES/TABLE') as $element) { if (null !== $element['NAME']) { $tables[] = (string) $element['NAME']; } } return $tables; ...
@param string $template @param bool $clearAssignments @return string @throws DomainException
public function fetch($template, $clearAssignments = true) { extract($this->variablesForTemplate, EXTR_OVERWRITE); $template = $this->templateFolder . $template . '.template.php'; if (file_exists($template) === false) { throw new DomainException('Template not found in ' . $tem...
// SwarmUpdate updates the swarm.
func (cli *Client) SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error { query := url.Values{} query.Set("version", strconv.FormatUint(version.Index, 10)) query.Set("rotateWorkerToken", fmt.Sprintf("%v", flags.RotateWorkerToken)) query.Set("rotateManagerToken", f...
/*Line 34 - 'AtomBrowser.js'
function () { /*Line 35 - 'AtomBrowser.js' */ var nVer = navigator.appVersion; /*Line 36 - 'AtomBrowser.js' */ var nAgt = navigator.userAgent; /*Line 37 - 'AtomBrowser.js' */ this.userAgent = nAgt; /*Line 38 - 'AtomBrowser.js' */ var browserName = navigator.appName; /*Line 39 - 'AtomBrowser....
// EnableWithAIForwarding will start instrumentation and will connect to app insights forwarder // exporter making the metrics and traces available in app insights.
func EnableWithAIForwarding(agentEndpoint string) (err error) { err = Enable() if err != nil { return err } traceExporter, err := ocagent.NewExporter(ocagent.WithInsecure(), ocagent.WithAddress(agentEndpoint)) if err != nil { return err } trace.RegisterExporter(traceExporter) return }
Returns the number of shares for the given security. It gets the number from all the accounts in the book.
def get_quantity(self) -> Decimal: from pydatum import Datum # Use today's date but reset hour and lower. today = Datum() today.today() today.end_of_day() return self.get_num_shares_on(today.value)
Update an existing BuildConfiguration with new information :param id: ID of BuildConfiguration to update :param name: Name of BuildConfiguration to update :return:
def update_build_configuration(id, **kwargs): data = update_build_configuration_raw(id, **kwargs) if data: return utils.format_json(data)
Add a new TocElement to the TOC container.
def add_element(self, element): """""" try: self.toc[element.group][element.name] = element except KeyError: self.toc[element.group] = {} self.toc[element.group][element.name] = element
// GenerateHandlers ...
func GenerateHandlers() map[string]mist.HandleFunc { return map[string]mist.HandleFunc{ "register": handleRegister, "unregister": handleUnregister, "set": handleSet, "unset": handleUnset, "tags": handleTags, } }
转换最终分词结果到 finallyResult 数组 @return void
private function _sort_finally_result() { $newarr = array(); $i = 0; foreach($this->simpleResult as $k=>$v) { if( empty($v['w']) ) continue; if( isset($this->finallyResult[$k]) && count($this->finallyResult[$k]) > 0 ) { foreach($t...
// Parse implements Parser.
func (parser *SourceParser) Parse(req *http.Request, params imageserver.Params) error { ParseQueryString(imageserver_source.Param, req, params) return nil }
Returns the form element as an HTML tag @return string
public function outputElement() : string { $selected = explode(',', $this->getValue()); $disabled = $this->disabled; $hidden = $this->hidden; $return = '<div class="checkboxgroup">'; foreach ($this->options as $val=>$txt) { if (in_array($val, $hidden)) { ...
// Initialize the database from revel.Config
func InitDb(dbResult *DbGorp) error { params := DbInfo{} params.DbDriver = revel.Config.StringDefault("db.driver", "sqlite3") params.DbHost = revel.Config.StringDefault("db.host", "localhost") if params.DbDriver == "sqlite3" && params.DbHost == "localhost" { params.DbHost = "/tmp/app.db" } params.DbUser = revel...
Compute the total size of all elements in objects.
def get_size(objects): """""" res = 0 for o in objects: try: res += _getsizeof(o) except AttributeError: print("IGNORING: type=%s; o=%s" % (str(type(o)), str(o))) return res
Lists the analysis modules.
def ListAnalysisPlugins(self): """""" analysis_plugin_info = ( analysis_manager.AnalysisPluginManager.GetAllPluginInformation()) column_width = 10 for name, _, _ in analysis_plugin_info: if len(name) > column_width: column_width = len(name) table_view = views.ViewsFactory.Get...
Execute the job. @return void @throws \Throwable
protected function job(): void { CorporationDivision::where('corporation_id', $this->getCorporationId())->get() ->each(function ($division) { // retrieve last known entry for the current division and active corporation $last_known_entry = CorporationWalletJournal...
Internal method to perform the normalization. @param filename the filename @param keepSeparator true to keep the final separator @return the normalized filename
private static String doNormalizeIgnoreOtherSeparator(String filename, boolean keepSeparator) { if (filename == null) { return null; } int size = filename.length(); if (size == 0) { return filename; } int prefix = 0; // int prefix = getPrefixLength(filename); // if (prefix < 0) { // return null;...
Processes parallel bean definitions.
protected void processParallelBeans() { new Thread(() -> { final List<BeanDefinitionReference> parallelBeans = beanDefinitionsClasses.stream() .filter(bd -> bd.getAnnotationMetadata().hasDeclaredStereotype(Parallel.class) && bd.isEnabled(this)) .collect(Collec...
// Connect connects to the Client given conn. It first resets the firmata board // then continuously polls the firmata board for new information when it's // available.
func (b *Client) Connect(conn io.ReadWriteCloser) (err error) { if b.Connected() { return ErrConnected } b.connection = conn b.Reset() connected := make(chan bool, 1) connectError := make(chan error, 1) b.Once(b.Event("ProtocolVersion"), func(data interface{}) { e := b.FirmwareQuery() if e != nil { b....
Get Date from "yyyyMMddThhmmssZ" @param val String "yyyyMMddThhmmssZ" @return Date @throws BadDateException on format error
public static Date fromISODateTimeUTC(final String val) throws BadDateException { try { synchronized (isoDateTimeUTCFormat) { return isoDateTimeUTCFormat.parse(val); } } catch (Throwable t) { throw new BadDateException(); } }
daoinput keys: migration_request_id
def execute(self, conn, daoinput, transaction = False): if not conn: dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/MigrationRequests/Remove. Expects db connection from upper layer.", self.logger.exception) daoinput['create_by'] = dbsUtils()...
<code>optional .alluxio.grpc.file.UpdateUfsModePOptions options = 2;</code>
public alluxio.grpc.UpdateUfsModePOptions getOptions() { return options_ == null ? alluxio.grpc.UpdateUfsModePOptions.getDefaultInstance() : options_; }
Convenience method used to sending appropriate Kill signal to the task VM @param context @param command @throws IOException
private void finishTask(TaskControllerContext context, TaskCommands command) throws IOException{ if(context.task == null) { LOG.info("Context task null not killing the JVM"); return; } ShellCommandExecutor shExec = buildTaskControllerExecutor( command, context.env.conf.getUser(), ...
This method can be called by a payment gateway to provide automated integration. This action performs some basic setup then hands control directly to the payment handler's "callback" action. @param $request Current Request Object
public function callback($request) { // If post data exists, process. Otherwise provide error if ($this->payment_handler === null) { // Redirect to error page return $this->redirect(Controller::join_links( Director::BaseURL(), $this->config()->...
{@inheritdoc} Импорт из файла.
public function startImport(array &$form, FormStateInterface $form_state) { // Выполняет стандартную валидацию полей формы и добавляет примечания об ошибках. ConfigFormBase::validateForm($form, $form_state); if (!$form_state->getValue('validate_error')) { $config = $this->config('si...
// NewClient creates a new client for a server identified by the given dsn // A dsn is a string in the form: // {PROTOCOL}://{PUBLIC_KEY}:{SECRET_KEY}@{HOST}/{PATH}{PROJECT_ID} // eg: // http://abcd:efgh@sentry.example.com/sentry/project1
func NewClient(dsn string) (client *Client, err error) { u, err := url.Parse(dsn) if err != nil { return nil, err } basePath := path.Dir(u.Path) project := path.Base(u.Path) if u.User == nil { return nil, fmt.Errorf("the DSN must contain a public and secret key") } publicKey := u.User.Username() secretKe...
Create new Scope from the configuration string. @param \RomanPitak\Nginx\Config\Text $configString @return Scope @throws Exception
public static function fromString(Text $configString) { $scope = new Scope(); while (false === $configString->eof()) { if (true === $configString->isEmptyLine()) { $scope->addPrintable(EmptyLine::fromString($configString)); } $char = $configStrin...
performs a counter-clockwise rotation
void rotateGridCCW( Grid g ) { work.clear(); for (int i = 0; i < g.rows * g.columns; i++) { work.add(null); } for (int row = 0; row < g.rows; row++) { for (int col = 0; col < g.columns; col++) { work.set(col*g.rows + row, g.get(g.rows - row - 1,col)); } } g.ellipses.clear(); g.ellipses.add...
生成update SQL @access public @param Query $query 查询对象 @return string
public function update(Query $query) { $options = $query->getOptions(); $table = $this->parseTable($query, $options['table']); $data = $this->parseData($query, $options['data']); if (empty($data)) { return ''; } foreach ($data as $key => $val) { ...
Report to stats server of the existing domain
private static function sendInformation() { $url = CMS_SITE . 'ping.php?site=' . urlencode(Configuration::getInstance()->get('site')['name']) . '&host=' . urlencode(HOST) . '&ip=' . urlencode(IP) . '&server=' . urlencode(SERVER_IP) . '&key=' . urlencode(Configuration::getInstance()->get('cms')['unique_key']...
(non-PHPdoc) @see \Core\Html\Bootstrap\Navbar\NavbarElementAbstract::build()
public function build() { // Create brand $html = $this->content instanceof Img ? $this->page->build() : $this->content; // Brand wrapped by a link if ($this->link instanceof A) { $this->link->addCss('navbar-brand'); $this->link->setInner($html); ...
Returns the repository for an asset @param AssetInterface $asset @return RepositoryInterface @api
public function getRepository(AssetInterface $asset) { $assetRepositoryClassName = str_replace('\\Model\\', '\\Repository\\', get_class($asset)) . 'Repository'; if (class_exists($assetRepositoryClassName)) { return $this->objectManager->get($assetRepositoryClassName); } ...
create app instance and run it @param array|string $config if string it is basePath @param boolean $run if run @return static
static public function launch($config, $run = true) { if (is_string($config)) { $config = ['basePath' => $config]; } $app = new static($config); if ($run) { return $app->run(); } return $app; }
Remove a graphical shape from the canvas.
public void remove(Plot p) { shapes.remove(p); JComponent[] tb = p.getToolBar(); if (tb != null) { for (JComponent comp : tb) { toolbar.remove(comp); } } repaint(); }
Registers the built-in message types.
def register_builtin_message_types(): """""" from .plain import PlainTextMessage from .email import EmailTextMessage, EmailHtmlMessage register_message_types(PlainTextMessage, EmailTextMessage, EmailHtmlMessage)
Map natural position to machine code postion
def map_position(pos): """""" posiction_dict = dict(zip(range(1, 17), [i for i in range(30, 62) if i % 2])) return posiction_dict[pos]
Sets the primary and secondary colorization assignments.
public void setZations (byte primary, byte secondary, byte tertiary, byte quaternary) { zations = (primary | (secondary << 16) | (tertiary << 24) | (quaternary << 8)); }
// GetUsage measures the total memory provisioned for the current process // from the OS
func GetUsage() Usage { memStats := new(runtime.MemStats) runtime.ReadMemStats(memStats) return Usage{ Mem: memStats.Sys, } }
// NewFuncNode create new Function Expression Node.
func NewFuncNode(name string, f Func) *FuncNode { return &FuncNode{Name: name, F: f} }
Initialise default formats.
def _init_formats(self): theme = self._color_scheme # normal message format fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.foreground) fmt.setBackground(theme.background) self._formats[OutputFormat.NormalMessageFormat] = fmt # error message ...
Add a simple property to the map file. @param writer xml stream writer @param name property name @param propertyType property type @param readMethod read method name @param writeMethod write method name @throws XMLStreamException
private void addProperty(XMLStreamWriter writer, String name, Class<?> propertyType, String readMethod, String writeMethod) throws XMLStreamException { if (name.length() != 0) { writer.writeStartElement("property"); // convert property name to .NET style (i.e. first letter uppercase) ...