query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
Connects to the websocket. Returns a listening task.
async def enable_events(self) -> asyncio.Task: """Connects to the websocket. Returns a listening task.""" return await self._connection.ws_connect( on_message=self._ws_on_message, on_error=self._ws_on_error )
csn
Get size and unit. :param size: size in bytes :type size: int :param binary: whether use binary or standard units, defaults to True :type binary: bool :return: size and unit :rtype: tuple of int and unit as str
def fmt_size(size, binary=True): ''' Get size and unit. :param size: size in bytes :type size: int :param binary: whether use binary or standard units, defaults to True :type binary: bool :return: size and unit :rtype: tuple of int and unit as str ''' if binary: fmt_size...
csn
Extracts requires of given types from metadata file, filter windows specific requires.
def get_requires(self, requires_types): """Extracts requires of given types from metadata file, filter windows specific requires. """ if not isinstance(requires_types, list): requires_types = list(requires_types) extracted_requires = [] for requires_name in re...
csn
Determine if the given pattern filters applies to a given method. @param array $filter @param array $method @return bool
protected function filterSupportsMethod($filter, $method) { $methods = $filter['methods']; return is_null($methods) || in_array($method, $methods); }
csn
Sets the localized terms of use content of this cp definition virtual setting in the language, and sets the default locale. @param termsOfUseContent the localized terms of use content of this cp definition virtual setting @param locale the locale of the language @param defaultLocale the default locale
@Override public void setTermsOfUseContent(String termsOfUseContent, java.util.Locale locale, java.util.Locale defaultLocale) { _cpDefinitionVirtualSetting.setTermsOfUseContent(termsOfUseContent, locale, defaultLocale); }
csn
// SetDestinationSchemaUpdate sets the DestinationSchemaUpdate field's value.
func (s *OutputUpdate) SetDestinationSchemaUpdate(v *DestinationSchema) *OutputUpdate { s.DestinationSchemaUpdate = v return s }
csn
Test if the model has properties A model may also be valid if it has at least one m:1 relationships which will add inferred foreign key properties. @return [undefined] @raise [IncompleteModelError] raised if the model has no properties @api private
def assert_valid_properties repository_name = self.repository_name if properties(repository_name).empty? && !relationships(repository_name).any? { |relationship| relationship.kind_of?(Associations::ManyToOne::Relationship) } raise IncompleteModelError, "#{name} must have at least one propert...
csn
Init singleton instance with context @param context Application context @return The singleton instance
public static synchronized MCAAuthorizationManager createInstance(Context context) { if (instance == null) { instance = new MCAAuthorizationManager(context.getApplicationContext()); instance.bluemixRegionSuffix = BMSClient.getInstance().getBluemixRegionSuffix(); instance.ten...
csn
// parsePackageDir parses the package residing in the directory.
func (g *GoParser) parsePackageDir(directory string) { pkg, err := build.Default.ImportDir(directory, 0) if err != nil { log.Fatalf("cannot process directory %s: %s", directory, err) } var names []string names = append(names, pkg.GoFiles...) //names = append(names, pkg.CgoFiles...) //names = append(names, pkg....
csn
Export user data in course contexts related to course settings. @param int $userid The user ID. @param array $courseids The course IDs. @param array $path The root path to export at. @return void
protected static function export_user_data_in_course_contexts_settings($userid, $courseids, $path) { global $DB; // Fetch all the courses with associations we created or modified. $ccsfields = course_competency_settings::get_sql_fields('ccs', 'ccs_'); list($insql, $inparams) = $DB->get_...
csn
Obtains a signature for an operation in a `AllocateQuotaRequest` Args: op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an operation used in a `AllocateQuotaRequest` Returns: string: a secure hash generated from the operation
def sign(allocate_quota_request): """Obtains a signature for an operation in a `AllocateQuotaRequest` Args: op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an operation used in a `AllocateQuotaRequest` Returns: string: a secure hash generated from the op...
csn
Gets or Sets the path. @param string $value @param boolean $overwrite @return string|Tarsana\Filesystem\AbstractFile @throws Tarsana\Filesystem\Exceptions\FilesystemException if could not rename the file.
public function path($value = false, $overwrite = false) { if ($value === false) { return $this->path; } $oldPath = $this->path; if (!$overwrite && $this->adapter->fileExists($value)) { throw new FilesystemException("Cannot rename the file '{$this->path}' to...
csn
Strip HTTP transport implementation details so they don't leak via metadata into the application layer.
private static void stripTransportDetails(Metadata metadata) { metadata.discardAll(HTTP2_STATUS); metadata.discardAll(InternalStatus.CODE_KEY); metadata.discardAll(InternalStatus.MESSAGE_KEY); }
csn
Redirects to path with or without querystring @param RedirectContainer $container
public function performRedirect(RedirectContainer $container) { $path = $container->getRedirectpath(); $request = $container->getRequest(); $request->flash(); if ($container->shouldIncludeQuery()) { $path .= $this->getQueryStringFromRequest($request); } if...
csn
Validates that the contract being used for the request is valid against the api information included in the request. Basically the request includes information indicating which specific api is being invoked. This method ensures that the api information in the contract matches the requested api. @param request the req...
protected void validateRequest(ApiRequest request) throws InvalidContractException { ApiContract contract = request.getContract(); boolean matches = true; if (!contract.getApi().getOrganizationId().equals(request.getApiOrgId())) { matches = false; } if (!contract.get...
csn
Checks the similarity of two strings and returns the number of matching chars in both strings. @param txt1 @param txt2 @return
public static int similarityChars(String txt1, String txt2) { int sim = similar_char(txt1, txt1.length(), txt2, txt2.length()); return sim; }
csn
retrieve the database connection @return \PDO @throws ParseException @throws \PDOException
protected function getDatabasePDO() { $configPath = THELIA_CONF_DIR . "database.yml"; if (!file_exists($configPath)) { throw new UpdateException("Thelia is not installed yet"); } $definePropel = new DatabaseConfigurationSource( Yaml::parse(file_get_contents(...
csn
Get all of the invoie items by a given type. @param string $type @return array
public function invoiceItemsByType($type) { $lineItems = []; if (isset($this->lines->data)) { foreach ($this->lines->data as $line) { if ($line->type == $type) { $lineItems[] = new InvoiceItem($this->user, $line); } } ...
csn
Processes the compressed version of a document where each integer indicates that token's index and identifies all the contexts for the target word, adding them as new rows to the context matrix. @param termIndex the term whose contexts should be extracted @param document the document to be processed where each {@code ...
private int processIntDocument(int termIndex, int[] document, Matrix contextMatrix, int rowStart, BitSet featuresForTerm) { int contexts = 0; for (int i = 0; i < document.length; ++i) { ...
csn
Controller Service API to delete scope. @param scope Name of scope to be deleted. @return Status of delete scope.
public CompletableFuture<DeleteScopeStatus> deleteScope(final String scope) { Exceptions.checkNotNullOrEmpty(scope, "scope"); return streamStore.deleteScope(scope); }
csn
Return JSON column.
def _json_column(**kwargs): """Return JSON column.""" return db.Column( JSONType().with_variant( postgresql.JSON(none_as_null=True), 'postgresql', ), nullable=True, **kwargs )
csn
Gets the current injector instance associated to the injector class literal. This method is called internally by the framework to determine which injector instance should be used when injecting views. @param injectorClass The class literal of the injector. @return The injector instance previously set on {@link #setInj...
@SuppressWarnings("unchecked") public static <T> T getInjectorInstance(Class<T> injectorClass) { return (T) injectorsMap.get(injectorClass); }
csn
Resolves Member object. @param Member|int|null $member @return Member|null
protected function getMember($member = null) { if (!$member) { $member = Member::currentUser(); } if (is_numeric($member)) { $member = DataObject::get_by_id(Member::class, $member, true); } return $member; }
csn
Represents a BIP70 payment. @alias module:bip70.Payment @constructor @param {Object?} options @property {Buffer} merchantData @property {TX[]} transactions @property {Output[]} refundTo @property {String|null} memo
function Payment(options) { if (!(this instanceof Payment)) return new Payment(options); this.merchantData = null; this.transactions = []; this.refundTo = []; this.memo = null; if (options) this.fromOptions(options); }
csn
Convert RA hours, minutes, seconds into an angle in degrees.
def hmsToDeg(h, m, s): """Convert RA hours, minutes, seconds into an angle in degrees.""" return h * degPerHMSHour + m * degPerHMSMin + s * degPerHMSSec
csn
Append new elements to the list. @param array|Iterator $items Items to be appended. Existing keys will be overridden with the new values. @return $this
public function append($items) { if ($items instanceof static) { $items = $items->toArray(); } $this->items = array_merge($this->items, (array)$items); return $this; }
csn
Handles command line session related arguments, synchronously. @param control the {@code Control} singleton @return {@code true} if the arguments were handled successfully, {@code false} otherwise.
protected boolean handleCmdLineSessionArgsSynchronously(Control control) { if (getArgs().isEnabled(CommandLine.SESSION) && getArgs().isEnabled(CommandLine.NEW_SESSION)) { System.err.println( "Error: Invalid command line options: option '" + CommandLine.SESSION + "' not allowed wi...
csn
Get a transport handler by identifier @param mixed $transport An object that implements ObjectInterface, ObjectIdentifier object or valid identifier string @param array $config An optional associative array of configuration settings @throws \UnexpectedValueException @return DispatcherResponseAbstract
public function getTransport($transport, $config = array()) { //Create the complete identifier if a partial identifier was passed if (is_string($transport) && strpos($transport, '.') === false) { $identifier = $this->getIdentifier()->toArray(); if($identifier['packag...
csn
Get shell to use, either plugin shell or application shell All paths in the loaded shell paths are searched, handles alias dereferencing @param string $shell Optionally the name of a plugin @return \Cake\Console\Shell A shell instance. @throws \Cake\Console\Exception\MissingShellException when errors are encountered.
public function findShell($shell) { $className = $this->_shellExists($shell); if (!$className) { $shell = $this->_handleAlias($shell); $className = $this->_shellExists($shell); } if (!$className) { throw new MissingShellException([ ...
csn
Show log overview for the current user
public function overviewAction() { if ($this->overviewSnippets) { $params = $this->_processParameters($this->overviewParameters); $this->addSnippets($this->overviewSnippets, $params); } }
csn
Get a default blade value, if any is available @return BladeCompiler|null A default blade value or Null if no default value is available
public function getDefaultBlade(): ?BladeCompiler { // The blade compiler is usually only available, once // Laravel's view service provider has been initialised. // Thus, before just returning the Blade Facade's root // instance, we must make sure that the view facade // act...
csn
Loads a shader. @param {WebGLRenderingContext} gl The WebGLRenderingContext to use. @param {string} shaderSource The shader source. @param {number} shaderType The type of shader. @param {module:twgl.ErrorCallback} opt_errorCallback callback for errors. @return {WebGLShader} The created shader. @private
function loadShader(gl, shaderSource, shaderType, opt_errorCallback) { const errFn = opt_errorCallback || error; // Create the shader object const shader = gl.createShader(shaderType); // Remove the first end of line because WebGL 2.0 requires // #version 300 es // as the first line. No whitespace allowed ...
csn
Convert expression specified in different formats to canonical form @param Expression|callable $expression @return array
public static function normalize($expression) { if (is_callable($expression)) { $expressionConfigurator = $expression; $expression = new Expression; call_user_func($expressionConfigurator, $expression); } if ($expression instanceof Expression) { ...
csn
Gets access token. @param ticketId the ticket id @return the access token
@ReadOperation public Ticket getToken(@Selector final String ticketId) { var ticket = (Ticket) ticketRegistry.getTicket(ticketId, AccessToken.class); if (ticket == null) { ticket = ticketRegistry.getTicket(ticketId, RefreshToken.class); } if (ticket == null) { ...
csn
Execute registered startup routines.
public void execute() { List<ICareWebStartup> temp = new ArrayList<>(startupRoutines); for (ICareWebStartup startupRoutine : temp) { try { if (startupRoutine.execute()) { unregisterObject(startupRoutine); } } catch (Thr...
csn
Given a code and list of locations, convert to snippet lines. return will include line number, a separator (``sep``), then line contents. At most ``context`` lines are shown before each location line. After each location line, the column is marked using ``colmark``. The first ...
def snippet(code, locations, sep=' | ', colmark=('-', '^'), context=5): '''Given a code and list of locations, convert to snippet lines. return will include line number, a separator (``sep``), then line contents. At most ``context`` lines are shown before each location line. A...
csn
Get the git hash retriever command. @param string|null $mode @return \Illuminate\Config\Repository|mixed
public function getGitHashRetrieverCommand($mode = null) { $mode = is_null($mode) ? $this->config->get('build.mode') : $mode; return $this->config->get('git.'.$mode); }
csn
Sets the placeholder text. @param text
public final void setPlaceholder(String text) { if (!text.equalsIgnoreCase(mText)) { setPlaceholderTextInternal(text, mTextColor, mTextSize, true); } }
csn
Find an existing model by slug. @param string $slug @param string[] $columns @return \Illuminate\Database\Eloquent\Model
public function find($slug, array $columns = ['*']) { $model = $this->model; return $model::where('slug', '=', $slug)->first($columns); }
csn
List NAS account credentials.
def cli(env, identifier): """List NAS account credentials.""" nw_mgr = SoftLayer.NetworkManager(env.client) result = nw_mgr.get_nas_credentials(identifier) table = formatting.Table(['username', 'password']) table.add_row([result.get('username', 'None'), result.get('password', 'No...
csn
Split data into train, valid and test groups
def make_data_splits(self, max_samples, valid_story=None, test_story=None): """Split data into train, valid and test groups""" # TODO Make this also work with wordlists. if valid_story or test_story: if not (valid_story and test_story): raise PersephoneException( ...
csn
// computePatternStr computes the pattern string required for generating the route's regex. // It also adds the URI parameter key to the route's `keys` field
func (r *Route) computePatternStr(patternString string, hasWildcard bool, key string) (string, error) { regexPattern := "" patternKey := "" if hasWildcard { patternKey = fmt.Sprintf(":%s*", key) regexPattern = urlwildcard } else { patternKey = fmt.Sprintf(":%s", key) regexPattern = urlchars } patternStri...
csn
Permet de formater @param $str @param array $values @return string
private static function format($str, array $values = []) { foreach ($values as $key => $value) { $str = preg_replace('/{\s*'.$key.'\s*\}/', $value, $str); } return $str; }
csn
Build a range of numeric pagination links. For the current page, an HTML span element will be generated instead of a link. @param int $start @param int $end @return string
protected function range($start, $end) { $pages = array(); // To generate the range of page links, we will iterate through each page // and, if the current page matches the page, we will generate a span, // otherwise we will generate a link for the page. The span...
csn
// Context returns the run's context. It is always non-nil.
func (rc *RunContext) Context() context.Context { if rc.ctx != nil { return rc.ctx } return context.Background() }
csn
Generate username by template. Supported template placeholders: (U, l, d) Supported separators: (-, ., _) Template must contain at least one "U" or "l" placeholder. If template is None one of the following templates is used: ('U_d', 'U.d', 'U-d', 'UU-d', 'UU.d', 'UU_d', ...
def username(self, template: Optional[str] = None) -> str: """Generate username by template. Supported template placeholders: (U, l, d) Supported separators: (-, ., _) Template must contain at least one "U" or "l" placeholder. If template is None one of the following template...
csn
// marshalPlanModules iterates over a list of modules to recursively describe // the full module tree.
func marshalPlanModules( changes *plans.Changes, schemas *terraform.Schemas, childModules []addrs.ModuleInstance, moduleMap map[string][]addrs.ModuleInstance, moduleResourceMap map[string][]addrs.AbsResourceInstance, ) ([]module, error) { var ret []module for _, child := range childModules { moduleResources ...
csn
General action GET | POST Edit general settings. @return void
public function general() { $keys = [ 'instance_name', 'instance_short_name', 'html_title_suffix', 'Login__Message__show', 'Login__Message__text', 'Login__Message__class', 'Login__HeartBeat__max_login_time', 'Ema...
csn
Read and parse a pseudopotential file. Main entry point for client code. Returns: pseudopotential object or None if filename is not a valid pseudopotential file.
def parse(self, filename): """ Read and parse a pseudopotential file. Main entry point for client code. Returns: pseudopotential object or None if filename is not a valid pseudopotential file. """ path = os.path.abspath(filename) # Only PAW supports XML at p...
csn
Get only one cookie, using the cookie name.
@Override public Optional<WSCookie> getCookie(String name) { for (Cookie ahcCookie : ahcResponse.getCookies()) { // safe -- cookie.getName() will never return null if (ahcCookie.name().equals(name)) { return Optional.of(asCookie(ahcCookie)); } } ...
csn
The intializeMimetic function. @param {object} config - The API parameters.
function initalizeMimeticFinal(config) { // Destructured API parameters. const { scaleDelay, } = config; // Store the scaleDelay for kill and revive. resize.scaleDelay = scaleDelay; // The intial root font size. const rootFontSize = getRootREMValue...
csn
Create a set with contents. @param contents The contents of the set. @return A set containing contents.
public static <T> Set<T> newSet(T...contents) { Set<T> set; if(contents == null || contents.length==0) return newSet(); set = newSet(contents.length); Collections.addAll(set, contents); return set; }
csn
Pop the record number from the front of the list, and parse it to ensure that it is a valid integer. @param list MPX record
private void setRecordNumber(LinkedList<String> list) { try { String number = list.remove(0); m_recordNumber = Integer.valueOf(number); } catch (NumberFormatException ex) { // Malformed MPX file: the record number isn't a valid integer // Catch the ex...
csn
Prints usage information to the provided output stream. @param os Non-null output stream
public void printUsage(final OutputStream os) { final StringBuilder bldr = new StringBuilder(); bldr.append("Usage: "); bldr.append(getUsage()); bldr.append("\n"); bldr.append("Try '--help' for more information.\n"); PrintWriter pw = new PrintWriter(os); pw.write(...
csn
Create a copy of the provided `object` and delete all properties listed in `excludedProperties` @param {Object} object @param {string[]} excludedProperties @return {Object}
function exclude (object, excludedProperties) { const strippedObject = Object.assign({}, object) excludedProperties.forEach(excludedProperty => { delete strippedObject[excludedProperty] }) return strippedObject }
csn
Returns a list of all components installed on the server @return array (string)legacyname => (string)frankenstylename
public static function list_components() { $list['moodle'] = 'core'; $coresubsystems = core_component::get_core_subsystems(); ksort($coresubsystems); // should be but just in case foreach ($coresubsystems as $name => $location) { $list[$name] = 'core_'.$name; } ...
csn
// PrintAndReturnErrors prints the "err" to the given "printer", // printer will be called multiple times if the "err" is a StackError, where it contains more than one error.
func PrintAndReturnErrors(err error, printer func(string, ...interface{})) error { if err == nil || err.Error() == "" { return nil } if stackErr, ok := err.(StackError); ok { if len(stackErr.Stack()) == 0 { return nil } stack := stackErr.Stack() for _, e := range stack { if e.HasStack() { for ...
csn
Create a new Cloudformation stack. Args: fqn (str): The fully qualified name of the Cloudformation stack. template (:class:`stacker.providers.base.Template`): A Template object to use when creating the stack. parameters (list): A list of dictionaries that def...
def create_stack(self, fqn, template, parameters, tags, force_change_set=False, stack_policy=None, **kwargs): """Create a new Cloudformation stack. Args: fqn (str): The fully qualified name of the Cloudformation stack. template (:class:`...
csn
Returns the alpha value of a shadow by interpolating between a minimum and maximum alpha value, depending on a specific elevation. @param elevation The elevation, which should be emulated, in dp as an {@link Integer} value. The elevation must be at least 0 and at maximum the value of the constant <code>MAX_ELEVATION</...
private static int getShadowAlpha(final int elevation, final int minTransparency, final int maxTransparency) { float ratio = (float) elevation / (float) MAX_ELEVATION; int range = maxTransparency - minTransparency; return Math.round(minTransparency + ratio *...
csn
Exception handler function. Can register as PHP's exception handling function and use Fannie's output format
static public function exceptionHandler($exception) { $msg = $exception->getMessage() . " Line " . $exception->getLine() . ", " . $exception->getFile(); self::$logger->debug($msg); }
csn
Allocate new ID to return the ID of an existring string from file string lookup table.
function(string) { var index = this.stringLookupQuick[string]; // If missing, allocate now if (index === undefined) { index = this.stringLookup.length; this.stringLookup.push( string ); this.stringLookupQuick[string]= index; } return index; }
csn
Creates the doManifest-Request via SOAP @param Object|array $data - Manifest-Data @return Object - DHL-Response
private function sendDoManifestRequest($data) { switch($this->getMayor()) { case 1: return $this->getSoapClient()->DoManifestTD($data); case 2: default: return $this->getSoapClient()->doManifest($data); } }
csn
l.color = l._colors.Dim+l._colors.FgRed;
function _normaliseExt(ext) { // we don't use '.' in our extension info... but some might leak in here and there ext = (ext||'').trim(); if (ext.length && ext[0]=='.') return ext.substr(1); return ext; }
csn
Check whether an option with a given name exists and has been set. :param name: the name of the option to check; can be short or long name. :return: true if an option matching the given name exists and it has had it's value set by the user
def optionIsSet(self, name): """ Check whether an option with a given name exists and has been set. :param name: the name of the option to check; can be short or long name. :return: true if an option matching the given name exists and it has had it's value set by the user """ name ...
csn
Set the default currency @param CurrencyUpdateEvent $event @param $eventName @param EventDispatcherInterface $dispatcher
public function setDefault(CurrencyUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $currency = CurrencyQuery::create()->findPk($event->getCurrencyId())) { // Reset default status CurrencyQuery::create()->filterByByDefault(true)->update(array('ByDe...
csn
// Network creates a NetworkController instance.
func Network() (c *NetworkController) { return &NetworkController{ List: networkList, New: networkNew, Create: networkCreate, Delete: networkDelete, Disconnect: networkDisconnect, Detail: networkDetail, Raw: networkRaw, } }
csn
Apply the action by removing the virtual machine from the model. @param m the model to alter @return {@code true}
@Override public boolean applyAction(Model m) { Mapping map = m.getMapping(); if (map.isOnline(node) && map.isRunning(vm) && map.getVMLocation(vm).equals(node)) { map.addReadyVM(vm); return true; } return false; }
csn
// Message returns the reason the parameter was invalid, and its context.
func (e *errInvalidParam) Message() string { return fmt.Sprintf("%s, %s.", e.msg, e.Field()) }
csn
Return a parser state, a move-ahead amount, and an append range. If this parser state should terminate and return back to the TEXT state, then return that state and also any corresponding chunk that would have been yielded as a result.
def get_transition(self, # suppress(too-many-arguments) line, line_index, column, is_escaped, comment_system_transitions, eof=False): """Return a parser state, a move-ahead ...
csn
Bind panner slider @see http://stackoverflow.com/a/14412601/352796
function() { var xDeg = parseInt(slider.value); var x = Math.sin(xDeg * (Math.PI / 180)); wavesurfer.panner.setPosition(x, 0, 0); }
csn
Translate a limited subset of imagemagick convert commands to rio color operations Parameters ---------- convert_opts: String, imagemagick convert options Returns ------- operations string, ordered rio color operations
def magick_to_rio(convert_opts): """Translate a limited subset of imagemagick convert commands to rio color operations Parameters ---------- convert_opts: String, imagemagick convert options Returns ------- operations string, ordered rio color operations """ ops = [] bands ...
csn
Perform cleanup of reponse. @param Response $response
protected function cleanupHeadersForProd(Response $response) { // remove headers that identify the content or internal digest info $response->headers->remove('xkey'); $response->headers->remove('x-content-digest'); // remove vary by X-User-Hash header $varyValues = []; ...
csn
Delete system property. @param propertyName the property name @return the response
public Response deleteSystemProperty(String propertyName) { return restClient.delete("system/properties/" + propertyName, new HashMap<String, String>()); }
csn
Gets the total number of seconds from a DateInterval @link https://stackoverflow.com/a/14277647/570787 @param \DateInterval $i @return int
public static function dateIntervalToSeconds(\DateInterval $i){ return $i->days * 86400 + $i->h * 3600 + $i->i * 60 + $i->s; }
csn
Obtains a single `Operation` representing this instances contents. Returns: :class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`
def as_operation(self): """Obtains a single `Operation` representing this instances contents. Returns: :class:`endpoints_management.gen.servicecontrol_v1_messages.Operation` """ result = encoding.CopyProtoMessage(self._op) names = sorted(self._metric_values_by_name_th...
csn
Make sure provided mode is converted to a valid integer value. @return int
private static function convertMode($mode) { if (is_string($mode)) { $mode = defined('\Tideways\Profiler::MODE_' . strtoupper($mode)) ? constant('\Tideways\Profiler::MODE_' . strtoupper($mode)) : self::MODE_DISABLED; } else if (!is_int($mode)) { ...
csn
Replies all the registered document drawers. @return the drawers.
@SuppressWarnings("unchecked") @Pure public static Iterator<Drawer<?>> getAllDrawers() { if (services == null) { services = ServiceLoader.load(Drawer.class); } return services.iterator(); }
csn
Check for browser support for various codecs and cache the results. @return {Howler}
function() { var self = this || Howler; var audioTest = null; // Must wrap in a try/catch because IE11 in server mode throws an error. try { audioTest = (typeof Audio !== 'undefined') ? new Audio() : null; } catch (err) { return self; } if (!audioTest || typeo...
csn
// checks if a function returns either the specified type or the specified type // and an error.
func checkReturnType(fnType, tptType reflect.Type) error { switch fnType.NumOut() { case 2: if fnType.Out(1) != errorType { return fmt.Errorf("expected (optional) second return value from transport constructor to be an error") } fallthrough case 1: if !fnType.Out(0).Implements(tptType) { return fmt.Er...
csn
// PasswordFieldFromInstance creates and initializes a password field based on its name, the reference object instance and field number.
func PasswordFieldFromInstance(val reflect.Value, t reflect.Type, fieldNo int, name string) *Field { ret := PasswordField(name) ret.SetValue(fmt.Sprintf("%s", val.Field(fieldNo).String())) return ret }
csn
create feature index
private FeatureIndex[] createFeatureIndex(int subspaceCount) // throws // Exception { logger.info("create feature index"); FeatureIndex[] index = new FeatureIndex[subspaceCount]; for (int i = 0; i < subspaceCount; i++) ...
csn
Returns the uuid of the current selected terminal
def get_selected_uuidtab(self): # TODO DBUS ONLY """Returns the uuid of the current selected terminal """ page_num = self.get_notebook().get_current_page() terminals = self.get_notebook().get_terminals_for_page(page_num) return str(terminals[0].get_uuid())
csn
! extract app scripts and reset app.js script tag.
function prepareAppScriptsInfo(docDom) { // read index file, and getting target ts files. var appScripts = []; var $appScripts = $(docDom).find('script[type="lazy"]'); var findAppJs = false; $appScripts.each(function () { var $scripts = getScriptElements($(this)); ...
csn
Pretty string representation of the results :param stat: bool :param verbose: bool :return: str
def get_pretty_string(self, stat, verbose): """ Pretty string representation of the results :param stat: bool :param verbose: bool :return: str """ pretty_output = _PrettyOutputToStr() self.generate_pretty_output(stat=stat, ...
csn
// HasKey returns true if section contains a key with given name.
func (s *Section) HasKey(name string) bool { key, _ := s.GetKey(name) return key != nil }
csn
Transform call site to have normal function call. Examples -------- For methods: >> a = [1, 2, 3] >> a.append(1) Becomes >> __list__.append(a, 1) For functions: >> __builtin__.dict.fromkeys([1, 2, 3]) Becomes >> __builtin__....
def visit_Call(self, node): """ Transform call site to have normal function call. Examples -------- For methods: >> a = [1, 2, 3] >> a.append(1) Becomes >> __list__.append(a, 1) For functions: >> __builtin__.dict.fromkeys([1, ...
csn
// Env returns metadata about the current CI environment, falling back to LocalEnv // if not running on CI.
func Env() Environment { switch { case os.Getenv("CI") == "true" && os.Getenv("TRAVIS") == "true": return Environment{ Name: "travis", Repo: os.Getenv("TRAVIS_REPO_SLUG"), Commit: os.Getenv("TRAVIS_COMMIT"), Branch: os.Getenv("TRAVIS_BRANCH"), Tag: os.Getenv(...
csn
Teach remark about inline tags, so that it neither wraps block level tags in paragraphs nor processes the text within the tag.
function inlineTagDefs() { const Parser = this.Parser; const inlineTokenizers = Parser.prototype.inlineTokenizers; const inlineMethods = Parser.prototype.inlineMethods; const blockTokenizers = Parser.prototype.blockTokenizers; const blockMethods = Parser.prototype.blockMethods; blockTokenizers....
csn
Close out the current span and set the parent as the current span @param kvs [Hash] list of key values to be reported in the span
def end_span(kvs = {}, end_time = ::Instana::Util.now_in_ms) return unless @current_span @current_span.close(end_time) add_info(kvs) if kvs && !kvs.empty? @current_span = @current_span.parent unless @current_span.is_root? end
csn
Set the fields for the attachment. @param array $fields @return $this
public function setFields(array $fields) { $this->clearFields(); foreach ($fields as $field) { $this->addField($field); } return $this; }
csn
Unserialize saved note data. Args: state (dict): Serialized state to load.
def restore(self, state): """Unserialize saved note data. Args: state (dict): Serialized state to load. """ self._clear() self._parseUserInfo({'labels': state['labels']}) self._parseNodes(state['nodes']) self._keep_version = state['keep_version']
csn
Remove task format text for rendering @param {object} token Token object @ignore
function removeMarkdownTaskFormatText(token) { // '[X] ' length is 4 // FIXED: we don't need first space token.content = token.content.slice(4); token.children[0].content = token.children[0].content.slice(4); }
csn
Get transformer implementation with output properties set. @return the transformer instance. @throws TransformerConfigurationException
private Transformer createIndentingTransformer() throws TransformerConfigurationException { Transformer transformer = createTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); return transformer; ...
csn
A set of monitored resources in the group. Generated from protobuf field <code>repeated .google.api.MonitoredResource members = 1;</code> @param \Google\Api\MonitoredResource[]|\Google\Protobuf\Internal\RepeatedField $var @return $this
public function setMembers($var) { $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Api\MonitoredResource::class); $this->members = $arr; return $this; }
csn
Register callback function to be called on certain events @param string $name Name of event @param function $methodName A anonymous function to be called @param bool $prepend Whether the event should be prepended. @return KoolReport the report object
public function registerEvent($name, $methodName, $prepend = false) { if (!isset($this->events[$name])) { $this->events[$name] = array(); } if (!in_array($methodName, $this->events[$name])) { if ($prepend) { array_unshift($this->events[$name], $methodN...
csn
This function convert WSG84 GPS coordinate to France Lambert I coordinate. @param lambda in degrees. @param phi in degrees. @return the France Lambert I coordinates.
@Pure public static Point2d WSG84_L1(double lambda, double phi) { final Point2d ntfLambdaPhi = WSG84_NTFLamdaPhi(lambda, phi); return NTFLambdaPhi_NTFLambert( ntfLambdaPhi.getX(), ntfLambdaPhi.getY(), LAMBERT_1_N, LAMBERT_1_C, LAMBERT_1_XS, LAMBERT_1_YS); }
csn
execute particular command @return @throws IOException
public static int execute(String[] commandArray, String[] alternativeEnvVars, File workingDir, Receiver outputReceiver) throws IOException { Runtime rt = Runtime.getRuntime(); //command + arguments, environment parameters, workingdir Process proc = null; try { proc = rt.exec(commandArray, alte...
csn
// NewDrain returns a pointer to an appropriate implementation of the LogDrain interface, as // determined by the drainURL it is passed.
func NewDrain(drainURL string) (LogDrain, error) { if drainURL == "" { // nil means no drain-- which is valid return nil, nil } // Any of these three can use the same drain implementation if strings.HasPrefix(drainURL, "udp://") || strings.HasPrefix(drainURL, "syslog://") || strings.HasPrefix(drainURL, "tcp://"...
csn
Serialize the HTK model into a file. :param model: Model to be serialized
def serialize_model(model): """Serialize the HTK model into a file. :param model: Model to be serialized """ result = '' # First serialize the macros for macro in model['macros']: if macro.get('options', None): result += '~o ' for option in macro['options']['de...
csn
Overwrite the standard Home path. @param string Path title. @param string Optional URL.
public function setHome($title, $url=NULL) { $path = new \stdClass(); $path->title = $title; $path->url = $url; $path->active = count($this->paths) > 1 ? FALSE : TRUE; $this->paths[0] = $path; }
csn