query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
Returns list of hosts unreachable via ssh.
def GetUnreachableHosts(hostnames, ssh_key): """ Returns list of hosts unreachable via ssh. """ ssh_status = AreHostsReachable(hostnames, ssh_key) assert(len(hostnames) == len(ssh_status)) nonresponsive_hostnames = [host for (host, ssh_ok) in zip(hostnames, ssh_status) if not ssh_ok...
csn
Normalize a sequence of char values. The sequence will be normalized according to the specified normalization from. @param src The sequence of char values to normalize. @param form The normalization form; one of {@link java.text.Normalizer.Form#NFC}, {@link java.text.Normalizer.Form#NFD}, {@link java.text.Normalizer.F...
public static String normalize(final CharSequence src, final Form form) { return normalize(src.toString(), form); }
csn
Returns an array of block content objects that exist in a region @param string $region a block region that exists on this page. @return array of block block_contents objects for all the blocks in a region.
public function get_content_for_region($region, $output) { $this->check_is_loaded(); $this->ensure_content_created($region, $output); return $this->visibleblockcontent[$region]; }
csn
Check if the given collection is an subset of the given collection. @param CollectionInterface $collection The collection to check. @return boolean
public function isSubsetOf($collection) { /** @var ModelInterface $localModel */ foreach ($this as $localModel) { /** @var ModelInterface $otherModel */ foreach ($collection as $otherModel) { if (($localModel->getProviderName() === $otherModel->getProviderName...
csn
Copy a file to a directory if it is not already there. Returns the target filepath. Args: source_filepath: a string target_directory: a string Returns: a string
def maybe_copy_file_to_directory(source_filepath, target_directory): """Copy a file to a directory if it is not already there. Returns the target filepath. Args: source_filepath: a string target_directory: a string Returns: a string """ if not tf.gfile.Exists(target_directory): tf.logging...
csn
Gets all code objects defined in the specified module. There are two BFS traversals involved. One in this function and the other in _FindCodeObjectsReferents. Only the BFS in _FindCodeObjectsReferents has a depth limit. This function does not. The motivation is that this function explores code object of the mo...
def _GetModuleCodeObjects(module): """Gets all code objects defined in the specified module. There are two BFS traversals involved. One in this function and the other in _FindCodeObjectsReferents. Only the BFS in _FindCodeObjectsReferents has a depth limit. This function does not. The motivation is that this f...
csn
Runs the unit test framework. Can be overridden to run anything. Returns True on passing and False on failure.
def run(self): """ Runs the unit test framework. Can be overridden to run anything. Returns True on passing and False on failure. """ try: import nose arguments = [sys.argv[0]] + list(self.test_args) return nose.run(argv=arguments) exce...
csn
Fuzzy searches the Anime Database for the query. :param str query: The text to fuzzy search. :returns: List of Anime Objects. This list can be empty.
def search_anime(self, query): """Fuzzy searches the Anime Database for the query. :param str query: The text to fuzzy search. :returns: List of Anime Objects. This list can be empty. """ r = self._query_('/search/anime', 'GET', params={'query': query})...
csn
Rename an Entry. This can also mean to move the entry from one point to another in the tree @param {string} newName the new name/path for the renamed entry
function rename(newName) { newName = newName.replace(/[\.\/]/g, ''); if (this.isRoot()) { this._name = newName; } else { var newPath = [this.parent.path(), newName].filter(function (e) { return e !== ''; }).join('.'); this.moveTo(newPath); } }
csn
Sum of the durations of the tests in this list. :return: integer
def total_duration(self): """ Sum of the durations of the tests in this list. :return: integer """ durations = [result.duration for result in self.data] return sum(durations)
csn
Analyzes characters, raising the index. Stops after encountering first non-whitespace character.
protected void burnWhitespaces() { while (reader.hasNextCharacter()) { final char character = reader.peekCharacter(); if (Strings.isWhitespace(character) || character == commentMarker && reader.hasNextCharacter(1) && reader.peekCharacter(1) == commentSecondary) { ...
csn
// label returns a string containing the label with indentation and padding.
func label(l string, indent, width int) string { pad := width - indent - len(l) if pad < 0 { pad = 0 } return fmt.Sprintf("%s%s%s", strings.Repeat(" ", indent), l, strings.Repeat(" ", pad)) }
csn
Adds attachment to current running test or step. @param name the name of attachment @param type the content type of attachment @param fileExtension the attachment file extension @param stream attachment content
public void addAttachment(final String name, final String type, final String fileExtension, final InputStream stream) { writeAttachment(prepareAttachment(name, type, fileExtension), stream); }
csn
Return a novaclient from the given args.
def _constructClient(client_version, username, user_domain, password, project_name, project_domain, auth_url): """Return a novaclient from the given args.""" loader = loading.get_plugin_loader('password') # These only work with v3 if user_domain is not None or p...
csn
Make a request to retrieve Wharton GSR listings.
def get_wharton_gsrs(self, sessionid, date=None): """ Make a request to retrieve Wharton GSR listings. """ if date: date += " {}".format(self.get_dst_gmt_timezone()) else: date = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%S") resp = requests.get('https://ap...
csn
Determines wether an array is index or key based @param array $array @return int
protected function getArrayType(array $array) { $indices = count(array_filter(array_keys($array), 'is_string')); if ($indices == 0) { $type = self::ARRAY_TYPE_LIST; } elseif ($indices == count($array)) { $type = self::ARRAY_TYPE_DICT; } else { $type = self::ARRAY_TYPE_MIXED; } return $type; }
csn
Closes the connection and any associated listeners and dispatchers
void close() { final String methodName = "close"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); } close(false); if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit...
csn
Export datas to array @param array $ignore ignore @param bool $recursive @param int $deep @return array
public function toArray($ignore = array('_type'), $recursive = false, $deep = 3) { if (!empty($ignore)) { $ignores = array(); foreach ($ignore as $val) { $ignores[$val] = 1; } $ignore = $ignores; } if ($recursive === true && $de...
csn
Calculate the most reasonable divisor for a total. Useful for repeating headers in a table with many rows. $options: - int "min" The minimum number of rows to allow before breaking (default: 5) - int "max" The maximum number of rows to allow before breaking (default: 10) @param int $rows The total number to calculate...
public static function getBestDivisor($rows, $options = null) { $options = static::getOptions($options, [ "min" => 5, "max" => 10, ]); if ($rows <= $options["max"]) { return $rows; } $divisor = false; $divisorDiff = false; ...
csn
Performs a basic set of input checks on the data
def input_checks(catalogue, config, completeness): """ Performs a basic set of input checks on the data """ if isinstance(completeness, np.ndarray): # completeness table is a numpy array (i.e. [year, magnitude]) if np.shape(completeness)[1] != 2: raise ValueError('Completeness T...
csn
// List takes label and field selectors, and returns the list of CiliumEndpoints that match those selectors.
func (c *FakeCiliumEndpoints) List(opts v1.ListOptions) (result *v2.CiliumEndpointList, err error) { obj, err := c.Fake. Invokes(testing.NewListAction(ciliumendpointsResource, ciliumendpointsKind, c.ns, opts), &v2.CiliumEndpointList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOp...
csn
Converts a list of integers into a comma-separated string.
public static String intListAsString(List<Integer> ls) { return String.join(", ", ls.stream().map(i -> i.toString()).collect(Collectors.toList())); }
csn
Determines whether the specified date1 is the same day with the specified date2. @param date1 the specified date1 @param date2 the specified date2 @return {@code true} if it is the same day, returns {@code false} otherwise
public static boolean isSameDay(final Date date1, final Date date2) { final Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); final Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calenda...
csn
// BeginExecute combines Begin and Execute.
func (tsv *TabletServer) BeginExecute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]*querypb.BindVariable, options *querypb.ExecuteOptions) (*sqltypes.Result, int64, error) { if tsv.enableHotRowProtection { txDone, err := tsv.beginWaitForSameRangeTransactions(ctx, target, options,...
csn
Return the host and port together if the port isn't standard. @return string @since 2.1
public function HostAndPort() { $Host = $this->Host(); $Port = $this->Port(); if (!in_array($Port, array(80, 443))) return $Host.':'.$Port; else return $Host; }
csn
Get default locale for this domain @return Locale
public function DefaultLocale() { // Return explicit default locale if ($this->DefaultLocaleID) { $locale = Locale::getCached()->byID($this->DefaultLocaleID); if ($locale) { return $locale; } } // Use IsGlobalDefault if this is a m...
csn
// Closes all Stmts prepared for this transaction.
func (tx *Tx) closePrepared() { tx.stmts.Lock() for _, stmt := range tx.stmts.v { stmt.Close() } tx.stmts.Unlock() }
csn
POST call to a Nexpose controller that uses a form-post model. This is here to support legacy use of POST in old controllers. @param [Connection] nsc API connection to a Nexpose console. @param [String] uri Controller address relative to https://host:port @param [Hash] parameters Hash of attributes that need to be...
def form_post(nsc, uri, parameters, content_type = CONTENT_TYPE::FORM) post = Net::HTTP::Post.new(uri) post.set_content_type(content_type) post.set_form_data(parameters) request(nsc, post) end
csn
Returns this bar code's pattern, converted into a set of corresponding codewords. Useful for bar codes that encode their content as a pattern. @param size the number of digits in each codeword @return this bar code's pattern, converted into a set of corresponding codewords
protected int[] getPatternAsCodewords(int size) { if (size >= 10) { throw new IllegalArgumentException("Pattern groups of 10 or more digits are likely to be too large to parse as integers."); } if (pattern == null || pattern.length == 0) { return new int[0]; } els...
csn
Deletes the given key-value pairs associated with the given resource. Will attempt to delete all key-value pairs even if some fail. Args: resource (intern.resource.boss.BossResource) keys (list) Raises: HTTPErrorList on failure.
def delete_metadata(self, resource, keys): """ Deletes the given key-value pairs associated with the given resource. Will attempt to delete all key-value pairs even if some fail. Args: resource (intern.resource.boss.BossResource) keys (list) Raises: ...
csn
Build descriptor for Enum class. Args: enum_definition: Enum class to provide descriptor for. Returns: Initialized EnumDescriptor instance describing the Enum class.
def describe_enum(enum_definition): """Build descriptor for Enum class. Args: enum_definition: Enum class to provide descriptor for. Returns: Initialized EnumDescriptor instance describing the Enum class. """ enum_descriptor = EnumDescriptor() enum_descriptor.name = enum_definition...
csn
Counts the number of running processes in the pool @return int The number of currently running processes
protected function runningProcesses() { $count = 0; foreach ($this->processes as $process) { if ($process->isRunning()) { $count++; } } return $count; }
csn
This method is used to process an incoming itip message. Examples: 1. A user is an attendee to an event. The organizer sends an updated meeting using a new iTip message with METHOD:REQUEST. This function will process the message and update the attendee's event accordingly. 2. The organizer cancelled the event using ...
public function processMessage(Message $itipMessage, VCalendar $existingObject = null) { // We only support events at the moment. if ('VEVENT' !== $itipMessage->component) { return false; } switch ($itipMessage->method) { case 'REQUEST': retur...
csn
// MarshalText lets Level implements the TextMarshaler interface used by encoding packages
func (l Level) MarshalText() ([]byte, error) { var t []byte switch l { case LevelDebug: t = levelBytesDebug case LevelInfo: t = levelBytesInfo case LevelWarn: t = levelBytesWarn case LevelError: t = levelBytesError case LevelFatal: t = levelBytesFatal default: t = []byte(strconv.FormatInt(int64(l), ...
csn
Resolve a revision to a new RevOptions object with the SHA1 of the branch, tag, or ref if found. Args: rev_options: a RevOptions object.
def resolve_revision(self, dest, url, rev_options): """ Resolve a revision to a new RevOptions object with the SHA1 of the branch, tag, or ref if found. Args: rev_options: a RevOptions object. """ rev = rev_options.arg_rev sha, is_branch = self.get_revi...
csn
Return the contents of this `List` as a programmer-readable `String`. If all the items in the list are serializable as Ruby literal strings, the returned string can be passed to `eval` to reconstitute an equivalent `List`. @return [::String]
def inspect if improper? result = 'Erlang::List[' list = to_proper_list list.each_with_index { |obj, i| result << ', ' if i > 0; result << obj.inspect } result << ']' result << " + #{last(true).inspect}" return result else result = '[' list = s...
csn
License action. @param string $repository repository @Route("/{repository}/license", name="pugx_badge_license", requirements={"repository" = "[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+?"} ) @Method({"GET"}) @Cache(maxage="3600", smaxage="3600", public=true) @return Response
public function licenseAction(Request $request, $repository, $format='svg') { $this->useCase = $this->container->get('use_case_badge_license'); $this->imageFactory = $this->container->get('image_factory'); if (in_array($request->query->get('format'), $this->container->get('poser')->validFor...
csn
Builds the summary for any prefixed arguments @param Argument $argument @return string
protected function prefixedArguments(Argument $argument) { $prefixes = [$argument->prefix(), $argument->longPrefix()]; $summary = []; foreach ($prefixes as $key => $prefix) { if (!$prefix) { continue; } $sub = str_repeat('-', $key + 1) ....
csn
Returns a copy of the list item with the given index. It is an error if an item with teh given index does not exist. :type source: string :param source: A list of strings. :type index: string :param index: A list of strings. :rtype: string :return: The cleaned up list of strings.
def get(scope, source, index): """ Returns a copy of the list item with the given index. It is an error if an item with teh given index does not exist. :type source: string :param source: A list of strings. :type index: string :param index: A list of strings. :rtype: string :retu...
csn
Get the explicit keys from an attribute flattened with dot notation. E.g. 'foo.1.bar.spark.baz' -> [1, 'spark'] for 'foo.*.bar.*.baz' @param string $attribute @return array
protected function getExplicitKeys($attribute) { $pattern = str_replace('\*', '([^\.]+)', preg_quote($this->getPrimaryAttribute($attribute), '/')); if (preg_match('/^'.$pattern.'/', $attribute, $keys)) { array_shift($keys); return $keys; } return []; }
csn
Sets the bean id associated with this WBeanComponent. This bean id will be used to obtain the bean from the associated {@link BeanProvider} whenever the bean data is required. @see BeanProviderBound @param beanId the bean id to associate
@Override public void setBeanId(final Object beanId) { BeanAndProviderBoundComponentModel model = getOrCreateComponentModel(); model.setBeanId(beanId); // Remove values in scratch map removeBeanFromScratchMap(); }
csn
Builds a ContentTypeGroup domain object from value object returned by persistence.
public function buildContentTypeGroupDomainObject(SPIContentTypeGroup $spiGroup, array $prioritizedLanguages = []): APIContentTypeGroup { return new ContentTypeGroup( array( 'id' => $spiGroup->id, 'identifier' => $spiGroup->identifier, 'creationDat...
csn
Setup for this controller @return void
public function onConstruct() { $this->userLinkedSourcesModel = new UserLinkedSources(); $this->userModel = new Users(); if (!isset($this->config->jwt)) { throw new Exception('You need to configure your app JWT'); } }
csn
Convert internal representation of attributes to an array of properties that can hydrate the actual object. @return array
protected function propertiesFromAttributes(): array { // Get all managed properties $propertyNames = $this->entityMap->getProperties(); $propertyAttributes = array_only($this->attributes, $propertyNames); $attributesArray = array_except($this->attributes, $propertyNames); ...
csn
Get snippet for text @param string $text Text to process @param string $index Search index @param string $terms Words for highlight @param array $options Generate snippet option @return string|false
public function getSnippet($text, $index, $terms, $options = array()) { $results = $this->getSnippets(array($text), $index, $terms, $options); if ($results) { return $results[0]; } return false; }
csn
// run is a long running goroutine that scans for new hosts periodically
func (m *AgentMDNS) run() { hosts := make(chan *mdns.ServiceEntry, 32) poll := time.After(0) var quiet <-chan time.Time var join []string for { select { case h := <-hosts: // Format the host address addr := net.TCPAddr{IP: h.Addr, Port: h.Port} addrS := addr.String() // Skip if we've handled this...
csn
Get the GL type for a typedArray type @param {ArrayBufferView} typedArrayType a typedArray constructor @return {number} the GL type for type. For example pass in `Int8Array` and `gl.BYTE` will be returned. Pass in `Uint32Array` and `gl.UNSIGNED_INT` will be returned @memberOf module:twgl/typedArray
function getGLTypeForTypedArrayType(typedArrayType) { if (typedArrayType === Int8Array) { return BYTE; } // eslint-disable-line if (typedArrayType === Uint8Array) { return UNSIGNED_BYTE; } // eslint-disable-line if (typedArrayType === Uint8ClampedArray) { return UNSIGNED_BYTE; } // esli...
csn
Get columns for selected table. @return array
protected function getTableColumns() { if (0 === count(self::$tableColumns)) { $table = $this->getTable(); $connect = $this->getConnection(); $builder = $connect->getSchemaBuilder(); $columns = $builder->getColumnListing($table); self::$tableColum...
csn
Loads a top hat filter given wavelength min and max values Parameters ---------- wave_min: astropy.units.quantity (optional) The minimum wavelength to use wave_max: astropy.units.quantity (optional) The maximum wavelength to use n_pixels: int ...
def load_TopHat(self, wave_min, wave_max, pixels_per_bin=100): """ Loads a top hat filter given wavelength min and max values Parameters ---------- wave_min: astropy.units.quantity (optional) The minimum wavelength to use wave_max: astropy.units.quantity (opt...
csn
Find subclasses of `Object` and `ObjectSet` in the given modules. :param modules: The full *names* of modules to include. These modules MUST have been imported in advance.
def find_objects(modules): """Find subclasses of `Object` and `ObjectSet` in the given modules. :param modules: The full *names* of modules to include. These modules MUST have been imported in advance. """ return { subclass.__name__: subclass for subclass in chain( g...
csn
add a relevant concept to the topic page @param conceptUri: uri of the concept to be added @param weight: importance of the provided concept (typically in range 1 - 50)
def addConcept(self, conceptUri, weight, label = None, conceptType = None): """ add a relevant concept to the topic page @param conceptUri: uri of the concept to be added @param weight: importance of the provided concept (typically in range 1 - 50) """ assert isinstance(w...
csn
Insert into an array. If no offset is given then the values are inserted at the end of the list. Returns the new array with value inserted into. @param array $array The orignal array @param array $values An array of values to be inserted @return array
public static function insert($array, $values, $index = null) { $values = (array) AnConfig::unbox($values); $array = (array) AnConfig::unbox($array); if ($index === null) { foreach ($values as $value) { array_push($array, $value); } } else { ...
csn
Add filters to already existing filters without overwriting them. @param array $filters @return \Fuzz\MagicBox\Contracts\Repository
public function addFilters(array $filters): Repository { foreach ($filters as $key => $value) { $this->addFilter($key, $value); } return $this; }
csn
Get make, only on the select request If the first selection mode is not active @param array $columns @return array|stdClass @throws
public function get(array $columns = []) { if (count($columns) > 0) { $this->select($columns); } // Execution of request. $sql = $this->toSql(); $stmt = $this->connection->prepare($sql); $this->bind($stmt, $this->where_data_binding); $this->whe...
csn
Register a callback for resource creation but where the resource already exists in Iotic Space. In this case the existing reference is passed to you. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an Ord...
def register_callback_duplicate(self, func, serialised=True): """ Register a callback for resource creation but where the resource already exists in Iotic Space. In this case the existing reference is passed to you. If `serialised` is not set, the callbacks might arrive in a different or...
csn
Drop a database table. Keyword arguments: dbo : database object DB-API 2.0 connection, callable returning a DB-API 2.0 cursor, or SQLAlchemy connection, engine or session tablename : text Name of the table schema : text Name of the database schema the table is in co...
def drop_table(dbo, tablename, schema=None, commit=True): """ Drop a database table. Keyword arguments: dbo : database object DB-API 2.0 connection, callable returning a DB-API 2.0 cursor, or SQLAlchemy connection, engine or session tablename : text Name of the table sc...
csn
Add dir path into loader only if it not already exists. @param array $templateDir
private function addDirPathIntoLoaderIfNotExists(array $templateDir) { $paths = $this->loader->getPaths(); if ((count($paths) !== count($templateDir)) || (0 < count(array_diff($paths, $templateDir)))) { $this->loader->removeAllPaths(); try { $this->loader->set...
csn
Produce an iterator rolling windows rows over our data. Each emitted window will have `window_length` rows. Parameters ---------- window_length : int The number of rows in each emitted window. offset : int, optional Number of rows to skip before the first...
def traverse(self, window_length, offset=0, perspective_offset=0): """ Produce an iterator rolling windows rows over our data. Each emitted window will have `window_length` rows. Parameters ---------- window_length : int...
csn
Create a new Blog or Page. Route is defined in inherited controllers. @param Request $request @return array|Response
protected function newPostAction(Request $request) { $entityManager = $this->get('doctrine.orm.entity_manager'); $page = $this->getNewPage(); $form = $this->get('form.factory')->create($this->getNewPageType(), $page); $form->handleRequest($request); if ($form->isValid()) { ...
csn
Stores an css array in the file @param \core_kernel_classes_resource $item @param string $lang @param string $styleSheetPath @param array $cssArr @return boolean true on success
public static function saveCssFile(\core_kernel_classes_resource $item, $lang, $styleSheetPath, $cssArr) { $directory = \taoItems_models_classes_ItemsService::singleton()->getItemDirectory($item, $lang); $file = $directory->getFile($styleSheetPath); // make sure that 'no custom css' means ...
csn
Assign %token% values if available
function assignTokens () { var sourceBranch = shelljs.exec('git rev-parse --abbrev-ref HEAD', {silent: true}); var sourceCommit = shelljs.exec('git rev-parse --short HEAD', {silent: true}); if (sourceBranch.code === 0) { tokens.branch = sourceBranch.output.replace(/\n/g, ''); } if...
csn
private static int pidc=0;
private int getPid() { PageContext pc = ThreadLocalPageContext.get(); if (pc == null) { pc = CFMLEngineFactory.getInstance().getThreadPageContext(); if (pc == null) throw new RuntimeException("cannot get pid for current thread"); } return pc.getId(); }
csn
Add the c5 specific debug stuff.
protected function addDetails() { /* * General */ $this->addDataTable( 'Concrete5', [ 'Version' => Config::get('concrete.version'), 'Installed Version' => Config::get('concrete.version_installed'), ] ); ...
csn
Reset the state of the environment and returns an initial observation. Returns: state (np.ndarray): next frame as a result of the given action
def reset(self): """ Reset the state of the environment and returns an initial observation. Returns: state (np.ndarray): next frame as a result of the given action """ # call the before reset callback self._will_reset() # reset the emulator i...
csn
Insert a new item. If equal keys are found, add to the right
def insert_right(self, item): 'Insert a new item. If equal keys are found, add to the right' k = self._key(item) i = bisect_right(self._keys, k) self._keys.insert(i, k) self._items.insert(i, item)
csn
Create a new VM CLI Example: .. code-block:: bash salt 'hypervisor' vboxmanage.create <name>
def create(name, groups=None, ostype=None, register=True, basefolder=None, new_uuid=None, **kwargs): ''' Create a new VM CLI Example: .. code-block:: bash salt 'hypervisor' vboxmanage.create <name> ''' nodes = list_node...
csn
return a list of events from the root associations @param \RGU\Dvoconnector\Service\ApiServiceFilterContext $apiServiceFilterContext @return \SimpleXMLElement XML data
public function getEventsFromRootAssociations($apiServiceFilterContext = null) { $result = []; foreach ($this->getRootAssociationIDs() as $key => $rootAssociationID) { try { $result[] = $this->getChildAssociationsFromAssociation($rootAssociationID, $apiServiceFilterConte...
csn
Remove duplicate points in the polygon. @method removeDuplicatePoints @param {Number} [precision] The threshold to use when determining whether two points are the same. Use zero for best precision.
function polygonRemoveDuplicatePoints(polygon, precision){ for(var i=polygon.length-1; i>=1; --i){ var pi = polygon[i]; for(var j=i-1; j>=0; --j){ if(points_eq(pi, polygon[j], precision)){ polygon.splice(i,1); continue; } } } }
csn
Finds a related model instance by the given field name and the id value. Use it in a 1 to N relation, with an object instance of the N side to the get 1 related model. @param $modelName : The related model name. @param $field : The field that must be used to relate. @param $id : Optional, the ID the related model, if...
public function findRelatedModel($modelName, $field, $id = NULL) { $relatedModel = $this->getInstance($modelName); if ($this->isNew() && $id === NULL) { throw new \Exception('No id for related'); } if ($id === NULL) { $id = $this->getField($field); } $result = $relatedModel->findB...
csn
By default, the CoffeeScriptFilter converts inputs with the extension +.coffee+ to +.js+. @param [Hash] options options to pass to the CoffeeScript compiler. @param [Proc] block the output name generator block The body of the filter. Compile each input file into a CoffeeScript compiled output file. @param [A...
def generate_output(inputs, output) inputs.each do |input| begin output.write CoffeeScript.compile(input, options) rescue ExecJS::Error => error raise error, "Error compiling #{input.path}. #{error.message}" end end end
csn
Parse URLs especially for Google Drive links. file_id: ID of file on Google Drive. is_download_link: Flag if it is download link of Google Drive.
def parse_url(url, warning=True): """Parse URLs especially for Google Drive links. file_id: ID of file on Google Drive. is_download_link: Flag if it is download link of Google Drive. """ parsed = urllib_parse.urlparse(url) query = urllib_parse.parse_qs(parsed.query) is_gdrive = parsed.hostn...
csn
Examines unreserved sequences to see if they are prone to mutation. This currently ignores solely-power-of-2 guides with b > 3
def filter_seq(seq): '''Examines unreserved sequences to see if they are prone to mutation. This currently ignores solely-power-of-2 guides with b > 3''' if seq.res: return None n = nt.Factors(seq.factors) guide, s, t = aq.canonical_form(n) seq.guide = guide # The target_tau...
csn
Replaces old hashes for new hashes in chunk files. This function iterates through file contents and replaces all the ocurrences of old hashes for new ones. We assume hashes are unique enough, so that we don't accidentally hit a collision and replace existing data.
function replaceOldHashForNewInChunkFiles(chunk, assets, oldHashToNewHashMap) { chunk.files.forEach(file => { Object.keys(oldHashToNewHashMap).forEach(oldHash => { const newHash = oldHashToNewHashMap[oldHash]; replaceStringInAsset(assets[file], oldHash, newHash); }); }); ...
csn
Initialize the Lago environment Args: config(str): Path to LagoInitFile workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago" **kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init` logfile(str): A path to setup a log file. loglevel(int): :mod:`logging` l...
def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs): """ Initialize the Lago environment Args: config(str): Path to LagoInitFile workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago" **kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init...
csn
// fetchMissingNodes tries to retrieve the last entries of the latest trusted bloom trie from the // ODR backend in order to be able to add new entries and calculate subsequent root hashes
func (b *BloomTrieIndexerBackend) fetchMissingNodes(ctx context.Context, section uint64, root common.Hash) error { indexCh := make(chan uint, types.BloomBitLength) type res struct { nodes *NodeSet err error } resCh := make(chan res, types.BloomBitLength) for i := 0; i < 20; i++ { go func() { for bitInde...
csn
Calculate the climatological CRPS.
def crps_climo(self): """ Calculate the climatological CRPS. """ o_bar = self.errors["O"].values / float(self.num_forecasts) crps_c = np.sum(self.num_forecasts * (o_bar ** 2) - o_bar * self.errors["O"].values * 2.0 + self.errors["O_2"].values) / float(self...
csn
Heapify takes the sketch image in Memory and instantiates an on-heap Sketch using the given seed. The resulting sketch will not retain any link to the source Memory. @param srcMem an image of a Sketch where the image seed hash matches the given seed hash. <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a...
public static Sketch heapify(final Memory srcMem, final long seed) { final int serVer = srcMem.getByte(SER_VER_BYTE); if (serVer == 3) { final byte famID = srcMem.getByte(FAMILY_BYTE); final boolean ordered = (srcMem.getByte(FLAGS_BYTE) & ORDERED_FLAG_MASK) != 0; return constructHeapSketch(fam...
csn
Makes a OCS API request :param method: HTTP method :param service: service name :param action: action path :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns :class:`requests.Response` instance
def _make_ocs_request(self, method, service, action, **kwargs): """Makes a OCS API request :param method: HTTP method :param service: service name :param action: action path :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns :class:`...
csn
// GetEndosByHeight returns all of the endorsements between start and // stop where anything stored at the stop height is excluded
func (db *PublicRecord) GetEndosByHeight(startH, stopH int32) ([]*ombjson.Endorsement, error) { rows, err := db.selectEndosByHeight.Query(startH, stopH) defer rows.Close() if err != nil { return []*ombjson.Endorsement{}, err } endos, err := scanEndos(rows) if err != nil { return []*ombjson.Endorsement{}, err ...
csn
Collect the available wlan interfaces.
def interfaces(self): """Collect the available wlan interfaces.""" self._ifaces = [] wifi_ctrl = wifiutil.WifiUtil() for interface in wifi_ctrl.interfaces(): iface = Interface(interface) self._ifaces.append(iface) self._logger.info("Get interface: %s...
csn
Send a GET request to the specified URL. Method directly wraps around `Session.get` and updates browser attributes. <http://docs.python-requests.org/en/master/api/#requests.get> Args: url: URL for the new `Request` object. **kwargs: Optional arguments that `Requ...
def get(self, url, **kwargs): """Send a GET request to the specified URL. Method directly wraps around `Session.get` and updates browser attributes. <http://docs.python-requests.org/en/master/api/#requests.get> Args: url: URL for the new `Request` object. ...
csn
Get the value of the first header matching "headerName". @param headerName @param httpResponse @return value of the first header or null if it doesn't exist.
public static String getFirstHeader(String headerName, HttpResponse httpResponse) { Header header = httpResponse.getFirstHeader(headerName); if (header != null) { return header.getValue(); } return null; }
csn
replace all cells in current grid with updated grid
def replace_grid(self, updated_grid): """ replace all cells in current grid with updated grid """ for col in range(self.get_grid_width()): for row in range(self.get_grid_height()): if updated_grid[row][col] == EMPTY: self.set_empty(row, col...
csn
Finds a file using PSR0 while resetting composer PSR4 prefix this patch was loaded by. @throws \LogicException
public static function findClassFileUsingPsr(string $class): string { $classLoader = self::classLoader(); $originalClassMap = $classLoader->getClassMap(); $classMap = &Objects::getPropertyValue($classLoader, 'classMap', ClassLoader::class); $classMap = []; if (!$file = self:...
csn
// lexText scans until an opening action delimiter, "{{".
func lexText(l *lexer) stateFn { for { if strings.HasPrefix(l.input[l.pos:], l.leftDelim) { if l.pos > l.start { l.emit(itemText) } return lexLeftDelim } if l.next() == eof { break } } // Correctly reached EOF. if l.pos > l.start { l.emit(itemText) } l.emit(itemEOF) return nil }
csn
Updates a deployment by creating a new status update. @link https://developer.github.com/v3/repos/deployments/#create-a-deployment-status @param string $username the username @param string $repository the repository @param int $id the deployment number @param array $params The information about the ...
public function updateStatus($username, $repository, $id, array $params) { if (!isset($params['state'])) { throw new MissingArgumentException(['state']); } return $this->post('/repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/deployments/'.rawurlencode($id).'/stat...
csn
Apply filter on query @param \Globalis\PuppetSkilled\Database\Query\Builder|\Globalis\PuppetSkilled\Database\Magic\Builder $query @return \Globalis\PuppetSkilled\Database\Query\Builder
public function run($query) { $options = $this->options; if ($this->hasActiveFilters()) { foreach ($options['params'] as $param => $value) { $query->where( function ($query) use ($options, $param, $value) { $options['filters'][$...
csn
Set the scale for an IChemModel. It calculates the average bond length of the model and calculates the multiplication factor to transform this to the bond length that is set in the RendererModel. @param chemModel
@Override public void setScale(IChemModel chemModel) { double bondLength = AverageBondLengthCalculator.calculateAverageBondLength(chemModel); double scale = this.calculateScaleForBondLength(bondLength); // store the scale so that other components can access it this.rendererModel.get...
csn
Strip datetime and other parts so that there is no redundancy.
def _strip_datetime(self, sub_line): """Strip datetime and other parts so that there is no redundancy.""" try: begin = sub_line.index(']') except ValueError: return sub_line else: # create a "" in place character for the beginnings.. # need...
csn
This function creates a new dialog template. The name must be unique, the file can be in any accepted format, and be either a text file or a binary buffer.
function performCreate(node,dialog,msg) { var params = {} node.status({fill:'blue', shape:'dot', text:'requesting create of new dialog template'}); //if ('file' in msg.dialog_params && 'dialog_name' in msg.dialog_params) { if ('dialog_name' in msg.dialog_params) { // extension supported : only...
csn
returns true if array is not empty and there is a non-int key @param array $array array to test @return boolean
public static function isHash($array) { // is_array($data) && ( empty($data) || array_keys($data) === range(0, count($data)-1) ); $hash = false; if (\is_array($array) && !empty($array)) { $keys = \array_keys($array); foreach ($keys as $k) { if (!\is_in...
csn
// DecryptFavorites implements KeybaseService for KeybaseDaemonLocal
func (k *KeybaseDaemonLocal) DecryptFavorites(ctx context.Context, dataToDecrypt []byte) ([]byte, error) { return nil, checkContext(ctx) }
csn
Add allowed mime types @param array $mimes Mime types @return array Modified mime types
public function mimeTypes($mimes) { // Archives $mimes['zip'] = 'application/zip'; $mimes['gz'] = 'application/x-gzip'; // Images $mimes['ico'] = 'image/x-icon'; // Video $mimes['webm'] = 'video/webm'; $mimes['mp4'] = 'video/mp4'; $mimes['ogg...
csn
Stringify JS, replacing duplicates with variable references.
function printJSCode(isDupedVar, depth, value) { if (value == null || typeof value !== 'object') { return JSON.stringify(value); } // Only use variable references at depth beyond the top level. if (depth !== '') { const metadata = metadataForVal.get(value); if (metadata && metadata.isD...
csn
Generate the vertices for straight lines between nodes. If it is a directed graph, it also generates the vertices which can be passed to an :class:`ArrowVisual`. Parameters ---------- adjacency_mat : array The adjacency matrix of the graph node_coords : array The current coordi...
def _straight_line_vertices(adjacency_mat, node_coords, directed=False): """ Generate the vertices for straight lines between nodes. If it is a directed graph, it also generates the vertices which can be passed to an :class:`ArrowVisual`. Parameters ---------- adjacency_mat : array ...
csn
Add a single constraint violation to a partially-built array of errors in the format described in `groupViolationsByField` @param array $errors Array of errors @param ConstraintViolationInterface $violation Violation to add
protected function addViolationToOutput(array $errors, ConstraintViolationInterface $violation) { $path = $this->getPropertyPathAsArray($violation); // Drill into errors and find where the error message should be added, building nonexistent portions of the path $currentPointer = &$errors; ...
csn
Returns error if compiled blacklist is empty. @param Config $config The config instance. @return Error|null
protected function errorIfCompiledBlacklistIsEmpty(Config $config): ?Error { $blacklist = $config->compileBlacklist(); return empty($blacklist) ? ResultFactory::makeError($this, 'Blacklist is empty.') : null; }
csn
grape all payment details @param $param @param null $apiContext @return \PayPal\Api\Payment
public static function getAll($param, $apiContext = null) { if (isset($apiContext)) { return Payment::all($param, $apiContext); } return Payment::all($param); }
csn
Serve Nikola assets. This is meant to be used ONLY by the internal dev server. Please configure your web server to handle requests to this URL:: /assets/ => output/assets
def serve_assets(path): """Serve Nikola assets. This is meant to be used ONLY by the internal dev server. Please configure your web server to handle requests to this URL:: /assets/ => output/assets """ res = os.path.join(app.config['NIKOLA_ROOT'], _site.config["OUTPU...
csn
injects a block at the top of the plugin stack without calling its preProcessing method used by {else} blocks to re-add themselves after having closed everything up to their parent @param string $type block type (name) @param array $params parameters array
public function injectBlock($type, array $params) { $class = 'Dwoo_Plugin_'.$type; if (class_exists($class, false) === false) { $this->dwoo->getLoader()->loadPlugin($type); } $this->stack[] = array('type' => $type, 'params' => $params, 'custom' => false, 'class' => $class, 'buffer' => null); $this->curBlo...
csn