query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
Prefix the data provider properties. @param ConfigInterface $config The config. @return ConfigInterface
private function prefixDataProviderProperties(ConfigInterface $config) { $internalConfig = clone $config; $this->sortingPrefixer($internalConfig); if (null !== ($filter = $internalConfig->getFilter())) { $this->filterPrefixer($filter); $internalConfig->setFilter($fil...
csn
// AddSection adds a new section to the configuration. // // If the section is nil then uses the section by default which it's already // created. // // It returns true if the new section was inserted, and false if the section // already existed.
func (self *Config) AddSection(section string) bool { // _DEFAULT_SECTION if section == "" { return false } if _, ok := self.data[section]; ok { return false } self.data[section] = make(map[string]*tValue) // Section order self.idSection[section] = self.lastIdSection self.lastIdSection++ return true }
csn
// Run one time command in an app.
func Run(c *client.Client, appID string, command string) (api.AppRunResponse, error) { req := api.AppRunRequest{Command: command} body, err := json.Marshal(req) if err != nil { return api.AppRunResponse{}, err } u := fmt.Sprintf("/v1/apps/%s/run", appID) resBody, err := c.BasicRequest("POST", u, body) if e...
csn
python with open dynamicload file
def Load(file): """ Loads a model from specified file """ with open(file, 'rb') as file: model = dill.load(file) return model
cosqa
%matplotlib inline import math import time from mxnet import np from d2l import mxnet as d2l n = 10000 a = np.ones(n) b = np.ones(n) c = np.zeros(n) timer = Timer() for i in range(n): c[i] = a[i] + b[i] x = np.arange(-7, 7, 0.01) params = [(0, 1), (0, 2), (3, 1)] d2l.plot(x.asnumpy(), [normal(x, mu, sigma).asnumpy(...
%matplotlib inline import math import time import numpy as np import torch from d2l import torch as d2l n = 10000 a = torch.ones(n) b = torch.ones(n) c = torch.zeros(n) timer = Timer() for i in range(n): c[i] = a[i] + b[i] x = np.arange(-7, 7, 0.01) params = [(0, 1), (0, 2), (3, 1)] d2l.plot(x, [normal(x, mu, sigma...
codetrans_dl
func getUnscheduledPodsWithoutNode(runningNodesList []*v1.Node, nodeToDaemonPods map[string][]*v1.Pod) []string { var results []string isNodeRunning := make(map[string]bool) for _, node := range runningNodesList { isNodeRunning[node.Name] = true } for n, pods := range nodeToDaemonPods
{ if !isNodeRunning[n] { for _, pod := range pods { if len(pod.Spec.NodeName) == 0 { results = append(results, pod.Name) } } } } return results }
csn_ccr
Load the JSON extract tpl data into a PHP array. @param string $tpl A valid stream or file location for the tpl. @return array An array of the tpl data.
protected function loadTpl($tpl) { $this->tplBase = $this->request->args('tplBase') ? $this->request->args('tplBase') : dirname($tpl); $content = file_get_contents($tpl); $this->prepareTpl($content); return json_decode($content, true); }
csn
Get the exception details out of shared memory. @param resource $memory The shmop resource from shmop_open() @return \Throwable[]
private function unserialize($memory): array { $data = shmop_read($memory, 0, self::LIMIT); $exceptions = unserialize($data); if (!is_array($exceptions)) { $exceptions = []; } return $exceptions; }
csn
Generate a lookup index for categories that maps into the meta entry for the category. @return void.
private function createCategory() { $pattern = $this->config["category"]; $index = []; $matches = []; foreach ($this->meta as $key => $entry) { if (preg_match($pattern, $key, $matches)) { $catKey = $matches[1]; $index[$catKey] = $key; ...
csn
func (e *ControlleeExpectations) GetExpectations() (int64, int64) { return
atomic.LoadInt64(&e.add), atomic.LoadInt64(&e.del) }
csn_ccr
Set the "select" attribute. The required select attribute is an expression; this expression is evaluated and the resulting object is converted to a string as if by a call to the string function. @param v The value to set for the "select" attribute.
public void setSelect(XPath v) { if (null != v) { String s = v.getPatternString(); m_isDot = (null != s) && s.equals("."); } m_selectExpression = v; }
csn
Register a lone entry_point Will raise ImportError if the entry_point leads to an invalid import.
def register_entry_point(self, entry_point): """ Register a lone entry_point Will raise ImportError if the entry_point leads to an invalid import. """ module = _import_module(entry_point.module_name) self._register_entry_point_module(entry_point, module)
csn
def copy_sig(sig, opts, isdiff): """Deploy a sig""" info("[+] \033[92mDeploying signature:\033[0m %s" % sig) if isdiff: sourcefile = os.path.join(opts.workdir, '%s.cdiff' % sig) destfile = os.path.join(opts.mirrordir, '%s.cdiff' % sig) else: sourcefile = os.path.join(opts.workdir...
os.path.join(opts.mirrordir, '%s.cvd' % sig) deploy_signature(sourcefile, destfile, opts.user, opts.group) info("=> Deployed signature: %s" % sig)
csn_ccr
public Optional<Word<I>> findSeparatingWord(final S s1, final S s2, final Word<I> prefix) { final FastMealyState<O> n1 = this.nodeToObservationMap.get(s1); final FastMealyState<O> n2 = this.nodeToObservationMap.get(s2); final FastMealyState<O> s1Succ = this.observationTree.getSuccessor(n1, pre...
final FastMealyState<O> s2Succ = this.observationTree.getSuccessor(n2, prefix); if (s1Succ != null && s2Succ != null) { final Word<I> sepWord = NearLinearEquivalenceTest.findSeparatingWord(this.observationTree, s1Succ, s2Succ, alphabet, true); if (sepWord != n...
csn_ccr
protected function setupMongoDB($dsn, $options) { try { $this->client = new \MongoDB\Client($dsn, $options); $this->dbh = $this->client->selectDatabase($this->dbName); } catch (\MongoDB\Driver\Exception $e) {
throw new ModuleException($this, sprintf('Failed to open Mongo connection: %s', $e->getMessage())); } }
csn_ccr
Puts a new item in the cache if the current value matches oldValue. @param key the key @param value the new value @param testValue the value to test against the current @return true if the put succeeds
public boolean compareAndPut(V testValue, K key, V value) { V result = compareAndPut(testValue, key, value, true); return testValue == result; }
csn
public function download($request, $match) { // GET data $resource = Pluf_Shortcuts_GetObjectOr404('Tenant_Resource', $match['modelId']);
// Do $resource->downloads += 1; $resource->update(); return new Pluf_HTTP_Response_File($resource->getAbsloutPath(), $resource->mime_type); }
csn_ccr
function () { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index];
if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) { return true; } } return false; }
csn_ccr
Use this API to add responderpolicy.
public static base_response add(nitro_service client, responderpolicy resource) throws Exception { responderpolicy addresource = new responderpolicy(); addresource.name = resource.name; addresource.rule = resource.rule; addresource.action = resource.action; addresource.undefaction = resource.undefaction; ad...
csn
func Convert_clientauthentication_ExecCredential_To_v1beta1_ExecCredential(in *clientauthentication.ExecCredential,
out *ExecCredential, s conversion.Scope) error { return autoConvert_clientauthentication_ExecCredential_To_v1beta1_ExecCredential(in, out, s) }
csn_ccr
This resource returns a details about a single recipe. :param recipe_id: The recipe to query for. :param lang: The language to display the texts in. The response is an object with the following properties: recipe_id (number): The recipe id. type (string): The type of the produced...
def recipe_details(recipe_id, lang="en"): """This resource returns a details about a single recipe. :param recipe_id: The recipe to query for. :param lang: The language to display the texts in. The response is an object with the following properties: recipe_id (number): The recipe id. ...
csn
private function processClassAnnotation($annotation) { $class = get_class($annotation); switch ($class) { case "JPC\MongoDB\ODM\Annotations\Mapping\Document": $this->collectionInfo->setCollection($annotation->collectionName); if (null !== ($rep = $annotat...
if (null !== ($rep = $annotation->repositoryClass)) { $this->collectionInfo->setRepository($annotation->repositoryClass); } else { $this->collectionInfo->setRepository("JPC\MongoDB\ODM\GridFS\Repository"); } if (null ...
csn_ccr
returns the corresponding data source annotation if exists @param RoutingTable $annotations @param string $entityAlias @param string $method @return DataSource|null
public static function get(RoutingTable $annotations, $entityAlias, $method) { if (!self::exists($annotations, $entityAlias, $method)) return null; return $annotations->get($entityAlias)->$method(); }
csn
private List<PortletFilter> getFilters(PortletRequest request) { for (PortletSecurityFilterChain chain : filterChains)
{ if (chain.matches(request)) { return chain.getFilters(); } } return null; }
csn_ccr
Gets service request header if any. @param context the context @return the service request header if any
public static String getServiceRequestHeaderIfAny(final HttpServletRequest context) { if (context == null) { return null; } var id = context.getHeader(CasProtocolConstants.PARAMETER_SERVICE); if (StringUtils.isBlank(id)) { id = context.getHeader("X-".concat(CasPro...
csn
def crc16(data): """ Calculate an ISO13239 CRC checksum of the input buffer. """ m_crc = 0xffff for this in data: m_crc ^= ord(this) for _ in range(8):
j = m_crc & 1 m_crc >>= 1 if j: m_crc ^= 0x8408 return m_crc
csn_ccr
// newSigner is a helper used by NewSigner, split out for testability. It // allows you to inject the function that is used to determine the string to // sign for any given request.
func newSigner( sts func(*http.Request) (string, error), key *aws.AccessKey) (Signer, error) { return &signer{sts, key}, nil }
csn
public function getGateways() { $gateways = array(); foreach ($this->getGatewayNamespaces() as $namespace) { if (strpos($namespace, 'Omnipay') !== 0) { continue; }
$matches = array(); preg_match('/Omnipay\\\(.+?)\\\/', $namespace, $matches); if (isset($matches[1])) { $gateways[] = $matches[1]; } } return $gateways; }
csn_ccr
public function getScriptsHtml() { $scripts = ''; if (!isset($this->scripts)) { return $scripts; } foreach ($this->scripts as $s) { $scripts .= '<script
type="' . $s['type'] . '" src="' . $s['path'] . '"></script>' . "\n"; } return $scripts; }
csn_ccr
Read extended metadata configuration for a single mapped class @param object $meta The meta information. @param array $config The configuration. @return void @SuppressWarnings(PHPMD.Superglobals)
public function readExtendedMetadata($meta, array &$config) { $tableName = $meta->getTableName(); if (!isset($GLOBALS['TL_DCA'][$tableName])) { $this->loadDataContainer($tableName); } $dca = (array) $GLOBALS['TL_DCA'][$tableName]; $fields = (array) $dca['field...
csn
function(hcExportRequest,asyncCallback){ var makeThisExportDir = function(mkExportDirErr){ var thisExportDir = [config.processingDir, crypto.createHash('md5').update(Date().toString()+hcExportRequest.svg).digest('hex'),''].join('/'); fs.mkdir(thisExportDir, function(error){ asyncCallbac...
}; if(fs.existsSync(config.processingDir)){ makeThisExportDir(null); } else{ fs.mkdir(config.processingDir, function(error){ makeThisExportDir(error); }); } }
csn_ccr
public function logAddition($value) { if ($this->isOverridden()) { return; } if (isset($this->deleted[$value])) { unset($this->deleted[$value]); $this->replaced[$value] = $value;
return; } if (! isset($this->replaced[$value])) { $this->added[$value] = $value; } }
csn_ccr
def open_all_notifications_path_for(target, params = {}) options = params.dup options.delete(:devise_default_routes) ?
send("open_all_#{routing_scope(options)}notifications_path", options) : send("open_all_#{routing_scope(options)}#{target.to_resource_name}_notifications_path", target, options) end
csn_ccr
def transpose(self, *dims) -> 'DataArray': """Return a new DataArray object with transposed dimensions. Parameters ---------- *dims : str, optional By default, reverse the dimensions. Otherwise, reorder the dimensions to this order. Returns -----...
lazy for dask-backed DataArrays but not for numpy-backed DataArrays -- the data will be fully loaded. See Also -------- numpy.transpose Dataset.transpose """ variable = self.variable.transpose(*dims) return self._replace(variable)
csn_ccr
func (s *DocumentStore) FindDocuments(ctx context.Context, opts ...influxdb.DocumentFindOptions) ([]*influxdb.Document, error) { var ds []*influxdb.Document err := s.service.kv.View(ctx, func(tx Tx) error { if len(opts) == 0 { // TODO(desa): might be a better way to do get all. if err := s.service.findDocumen...
if dd.data { for _, doc := range docs { d, err := s.service.findDocumentContentByID(ctx, tx, s.namespace, doc.ID) if err != nil { return err } doc.Content = d } } if dd.labels { for _, doc := range docs { if err := s.decorateDocumentWithLabels(ctx, tx, doc); err != nil { re...
csn_ccr
public function getEntries($search) { $entries = ldap_get_entries($this->connect, $search); array_walk_recursive($entries, function (&$item) { if (!mb_detect_encoding($item, 'utf-8',
true)) { $item = utf8_encode($item); } }); return $entries; }
csn_ccr
Constructs an IntervalFormatter_ object which implements the Formatter_ interface. Internal object to construct and store a goog.i18n.DateTimeFormat for each part of the date interval pattern. @param {string} firstPattern First part of the date interval pattern. @param {string} secondPattern Second part of the date i...
function( firstPattern, secondPattern, dateTimeSymbols, useFirstDateOnFirstPattern) { /** * Formatter_ to format the first part of the date interval. * @private {!DateTimeFormat} */ this.firstPartFormatter_ = new DateTimeFormat(firstPattern, dateTimeSymbols); /** * Formatter_ to format the second...
csn
Renders the data items for the view. Each item is corresponding to a single data model instance. Child classes should override this method to provide the actual item rendering logic.
public function renderItems() { echo CHtml::openTag($this->itemsTagName, array('class' => $this->itemsCssClass)) . "\n"; $data = $this->dataProvider->getData(); if (!empty($data)) { echo CHtml::openTag('div', array('class' => 'row')); $owner = $this->getOwner(); $render = $owner instanceof CControll...
csn
// NewShowcaseCreatedDetails returns a new ShowcaseCreatedDetails instance
func NewShowcaseCreatedDetails(EventUuid string) *ShowcaseCreatedDetails { s := new(ShowcaseCreatedDetails) s.EventUuid = EventUuid return s }
csn
public function head($uri, $params = null, $body = null) {
return $this->performRequest("head", $uri, $params, $body); }
csn_ccr
private function _prepareGroupBy() { $sQuery = ''; if (is_array($this->_aGroupBy) && count($this->_aGroupBy) > 0) {
$sQuery .= ' GROUP BY '.implode(',', $this->_aGroupBy).' '; } return $sQuery; }
csn_ccr
Removes the composition link. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
def clear_composition(self): """Removes the composition link. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.r...
csn
public final void addMemberAndGroup(AnalyzedToken token) { if (patternToken.hasAndGroup()) { List<PatternTokenMatcher> andGroupList = andGroup; for (int i = 0; i <
andGroupList.size(); i++) { if (!andGroupCheck[i + 1]) { PatternTokenMatcher testAndGroup = andGroupList.get(i); if (testAndGroup.isMatched(token)) { andGroupCheck[i + 1] = true; } } } } }
csn_ccr
def get_user(self): """Get all information about you! Returns: dict: user information including the following fields: * assignedEthAddress (`str`) * availableNmr (`decimal.Decimal`) * availableUsd (`decimal.Decimal`) * banned ...
user { username banned assignedEthAddress availableNmr availableUsd email id mfaEnabled status country phoneNumber insertedAt apiTokens ...
csn_ccr
def eere_station(station_code): """Station information. Args: station_code (str): station code. Returns (dict): station information """ with open(env.SRC_PATH + '/eere_meta.csv') as eere_meta: stations = csv.DictReader(eere_meta)
for station in stations: if station['station_code'] == station_code: return station raise KeyError('station not found')
csn_ccr
// ListFolders returns all folders in dir `name`.
func (c *Client) ListFolders(name string) ([]os.FileInfo, error) { return c.ListFilter(name, func(info os.FileInfo) bool { return info.IsDir() }) }
csn
Load a template into the mock. python-dbusmock ships a set of standard mocks for common system services such as UPower and NetworkManager. With these the actual tests become a lot simpler, as they only have to set up the particular properties for the tests, and not the skeleton of commo...
def AddTemplate(self, template, parameters): '''Load a template into the mock. python-dbusmock ships a set of standard mocks for common system services such as UPower and NetworkManager. With these the actual tests become a lot simpler, as they only have to set up the particular ...
csn
Reads the node type of the root node of the indexing aggregate. @param config the configuration. @return the name of the node type. @throws IllegalNameException if the node type name contains illegal characters. @throws RepositoryException
private InternalQName getNodeTypeName(Node config) throws IllegalNameException, RepositoryException { String ntString = config.getAttributes().getNamedItem("primaryType").getNodeValue(); return resolver.parseJCRName(ntString).getInternalName(); }
csn
public function parseConfig(array $configs) { foreach ($configs as &$config) { $config['states'] = $this->parseStates($config['states']);
if (isset($config['callbacks'])) { $config['callbacks'] = $this->parseCallbacks($config['callbacks']); } } return $configs; }
csn_ccr
def _makeplot(self, ax, fig, data, zero_to_efermi=True, vbm_cbm_marker=False, ymin=-6., ymax=6., height=None, width=None, dos_plotter=None, dos_options=None, dos_label=None, aspect=None): """Tidy the band structure & add the density of stat...
if not dos_options: dos_options = {} dos_options.update({'xmin': ymin, 'xmax': ymax}) self._makedos(ax, dos_plotter, dos_options, dos_label=dos_label) else: # keep correct aspect ratio for axes based on canvas size x0, x1 = ax.get_xlim() ...
csn_ccr
send notification to instances
public Long sendNotification(String taskName, String data) { return tedDriverImpl.sendNotification(taskName, data); }
csn
In order to win over and get noticed by his favorite streamer Daenerys, Jon decides to donate a significant amount of money . Every donation made to Daenerys is of $at$ $least$ $1$ $beastcoin$ and is displayed on Daenerys's stream alongside any message written and is visible to every viewer. After spotting that Daenery...
# cook your dish here for _ in range(int(input(''))): n=int(input('')) x=bin(n) x=len(x)-2 if n==(2**(x-1)): print(n) else: print(2**x)
apps
protected function collectDevServiceProviders($configKey) { // Get the Config key where devProviders are located. $devProvidersConfigLocation = Config::get($configKey); // Get Providers keys. $keys = is_string($devProvidersConfigLocation) ? [$devProvidersConfigLocation] : $devProvid...
// Return Dev Providers. return collect($keys)->transform(function ($location) { // Transform each Location key to the actual array // containing the Providers. return Config::get($location); })->reject(function ($arrayOfProviders) { // Remove all ...
csn_ccr
def _bootstrap_debian(name, **kwargs): ''' Bootstrap a Debian Linux container ''' version = kwargs.get('version', False) if not version: if __grains__['os'].lower() == 'debian': version = __grains__['osrelease'] else: version = 'stable' release_blacklist ...
'Unsupported Debian version "{0}". ' 'Only "stable" or "jessie" and newer are supported'.format(version) ) dst = _make_container_root(name) cmd = 'debootstrap --arch=amd64 {0} {1}'.format(version, dst) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: ...
csn_ccr
Attempt to load a saved table state from a cookie @param {object} oSettings dataTables settings object @param {object} oInit DataTables init object so we can override settings @memberof DataTable#oApi
function _fnLoadState ( oSettings, oInit ) { if ( !oSettings.oFeatures.bStateSave ) { return; } var oData = oSettings.fnStateLoad.call( oSettings.oInstance, oSettings ); if ( !oData ) { return; } /* Allow custom and plug-in manipulation functions to alter the saved data set and ...
csn
Perform flip image manipulation. @param Image $image The source image. @return Image The manipulated image.
public function run(Image $image) { if ($flip = $this->getFlip()) { if ($flip === 'both') { return $image->flip('h')->flip('v'); } return $image->flip($flip); } return $image; }
csn
Get a new session handler. @param array $config The config from our config repository @return \SessionHandlerInterface @throws \RuntimeException When a configured handler does not exist
private function getSessionHandler(array $config) { $handler = array_get($config, 'handler', 'default'); // Build handler using a matching method "get{Type}Handler" $method = Str::camel("get_{$handler}_handler"); if (method_exists($this, $method)) { return $this->{$metho...
csn
private static boolean polygonEqualsEnvelope_(Polygon polygon_a, Envelope envelope_b, double tolerance, ProgressTracker progress_tracker) { Envelope2D env_a = new Envelope2D(), env_b = new Envelope2D(); polygon_a.queryEnvelope2D(env_a); envelope_b.queryEnvelope2D(env_b); // Quick envelope rejection test ...
tolerance, progress_tracker)) return false; Polygon polygon_b = new Polygon(); polygon_b.addEnvelope(envelope_b, false); return linearPathEqualsLinearPath_(polygon_a, polygon_b, tolerance, true); }
csn_ccr
python choose top 4
def top(self, topn=10): """ Get a list of the top ``topn`` features in this :class:`.Feature`\. Examples -------- .. code-block:: python >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)]) >>> myFeature.top(1) [('trapezoid', 5)] ...
cosqa
splits demultiplexed samples into separate entries in the global sample datadict
def split_demultiplexed_sampledata(data, demultiplexed): """ splits demultiplexed samples into separate entries in the global sample datadict """ datadicts = [] samplename = dd.get_sample_name(data) for fastq in demultiplexed: barcode = os.path.basename(fastq).split(".")[0] d...
csn
Fill the builder with information from the data provider. UTIL method. @param builder @param templateBuilderDataProvider provides data for the builder @return
public void copyProviderDataToBuilder(TemplateBuilder builder, TemplateBuilderDataProvider templateBuilderDataProvider) { PageSize size = templateBuilderDataProvider.getPageSize(); if (templateBuilderDataProvider.isLandscape()) { builder.setPageHeight(size.getWidth()); builder.setPageWidth(size.ge...
csn
function _removeEmbed(state, id) { // get existing embed var embeds = state.embeds; var embed = embeds[id]; var parent = embed.parent; var property = embed.property; // create reference to replace embed var subject = {'@id': id}; // remove existing embed if(_isArray(parent)) { // replace subject...
else { // replace subject with reference var useArray = _isArray(parent[property]); jsonld.removeValue(parent, property, subject, {propertyIsArray: useArray}); jsonld.addValue(parent, property, subject, {propertyIsArray: useArray}); } // recursively remove dependent dangling embeds var removeDe...
csn_ccr
Helper method to map columns to new columns. This takes into account column groups and will generate a new column group if its columns change. @param {?object|array} children Children of a table. @param {function} callback Function to excecute for each column. It is passed the column and should return a result column.
function mapColumns(children, callback) { var newChildren = []; React.Children.forEach(children, function(originalChild) { var newChild = originalChild; // The child is either a column group or a column. If it is a column group // we need to iterate over its columns and then potentially generate a ...
csn
@Override @Beta public <T> T Stub(Class<T> type) {
invalidMockCreation(); return null; }
csn_ccr
swig c++ map to python dict
def get_python_dict(scala_map): """Return a dict from entries in a scala.collection.immutable.Map""" python_dict = {} keys = get_python_list(scala_map.keys().toList()) for key in keys: python_dict[key] = scala_map.apply(key) return python_dict
cosqa
@Override public java.util.concurrent.Future<SetTopicAttributesResult> setTopicAttributesAsync(String topicArn, String attributeName, String attributeValue, com.amazonaws.handlers.AsyncHandler<SetTopicAttributesRequest, SetTopicAttributesResult> asyncHandler) { return setTopicAttributesAsync( ...
new SetTopicAttributesRequest().withTopicArn(topicArn).withAttributeName(attributeName).withAttributeValue(attributeValue), asyncHandler); }
csn_ccr
Clean up the text according to the textBling rules @param string $str The text to clean @param boolean $media Determines if media is parsed into html @return string The cleaned text
public static function clean($str, $allow_email=false) { $str = self::typoFix($str); $str = \sb\String\HTML::escape($str); $str = self::convertQuotes($str); $str = self::listsToHtml($str); $str = self::tablesToHtml($str); $str = self::linksToHtml($str, $allow_em...
csn
def dispatch(self, test=False): # pylint: disable=too-many-branches """ Send configuration to satellites :return: None """ if not self.new_to_dispatch: raise DispatcherError("Dispatcher cannot dispatch, " "because no configuration i...
I exclude the daemons that are not active continue if not link.reachable: logger.debug("Scheduler %s is not reachable to receive its configuration", link.name) continue logger.info("Sending configuration to the sched...
csn_ccr
Get the display preference for the help window. @return
public int getHelpPageOptions(int iOptions) { String strPreference = this.getProperty(ThinMenuConstants.USER_HELP_DISPLAY); if ((strPreference == null) || (strPreference.length() == 0)) strPreference = this.getProperty(ThinMenuConstants.HELP_DISPLAY); if (this.getHelpView() == null) if (T...
csn
private function parseEnumNotation($notation) { if (is_string($notation)) { $notation = json_decode(trim($notation, '<>')); if (json_last_error())
{ return; } } return $notation; }
csn_ccr
Use this API to fetch all the systemcollectionparam resources that are configured on netscaler.
public static systemcollectionparam get(nitro_service service) throws Exception{ systemcollectionparam obj = new systemcollectionparam(); systemcollectionparam[] response = (systemcollectionparam[])obj.get_resources(service); return response[0]; }
csn
protected function getClassNameForType($type) { if (!empty($this->rootNamespace) && strstr($type, $this->rootNamespace)) { $type = $this->stripNamespace($this->rootNamespace, $type); }
if (!empty($this->rootNamespace)) { return sprintf('%s\\%s', $this->rootNamespace, $type); } return $type; }
csn_ccr
func Convert_eventratelimit_Limit_To_v1alpha1_Limit(in *eventratelimit.Limit,
out *Limit, s conversion.Scope) error { return autoConvert_eventratelimit_Limit_To_v1alpha1_Limit(in, out, s) }
csn_ccr
Renders slow test report body.
protected function renderBody() { $slowTests = $this->slow; $length = $this->getReportLength($slowTests); for ($i = 1; $i <= $length; ++$i) { $label = key($slowTests); $time = array_shift($slowTests); echo sprintf(" %s. %sms to run %s\n", $i, $time, $lab...
csn
def get_access_token_from_cli(): '''Get an Azure authentication token from CLI's cache. Will only work if CLI local cache has an unexpired auth token (i.e. you ran 'az login' recently), or if you are running in Azure Cloud Shell (aka cloud console) Returns: An Azure authentication token st...
access_keys_path) return None if 'tokenType' not in keys[0]: print('Error from get_access_token_from_cli(): tokenType not found in ' + \ access_keys_path) return None if 'expiresOn' not in keys[0]: ...
csn_ccr
Initializes ScrollingDataTable TBODY element for data @method _initTbodyEl @param elTable {HTMLElement} TABLE element into which to create TBODY . @private
function(elTable) { SDT.superclass._initTbodyEl.call(this, elTable); // Bug 2105534 - Safari 3 gap // Bug 2492591 - IE8 offsetTop elTable.style.marginTop = (this._elTbody.offsetTop > 0) ? "-"+this._elTbody.offsetTop+"px" : 0; }
csn
The client-side tab indices will differ from the WTabSet's indices when one or more tabs are invisible. @param clientIndex the client-side index @return the WTabSet index corresponding to the given client index
private int clientIndexToTabIndex(final int clientIndex) { int childCount = getTotalTabs(); int serverIndex = clientIndex; for (int i = 0; i <= serverIndex && i < childCount; i++) { if (!isTabVisible(i)) { serverIndex++; } } return serverIndex; }
csn
Example of a single image download using this class. @param args @throws Exception
public static void main(String args[]) throws Exception { String urlStr = "http://upload.wikimedia.org/wikipedia/commons/5/58/Sunset_2007-1.jpg"; String id = "Sunset_2007-1"; String downloadFolder = "images/"; boolean saveThumb = true; boolean saveOriginal = true; boolean followRedirects = false; I...
csn
public function setCorePhpthumbNooffsitelinkValidDomains($value) { $this->setFieldName('phpthumb_nooffsitelink_valid_domains');
$this->loadObject(true); $this->setFieldValue($value); return $this; }
csn_ccr
public function canWrite(string $uri): bool { // /book => all if (in_array(Acl::RULE_ALL, (array) $this->getPermissionsOf($this->getUriRoot($uri)))) { return true; } // /book/detail => all or write $permission = array_filter((array)
$this->getPermissionsOf($uri), function($rule) { return ($rule == Acl::RULE_ALL || $rule == Acl::RULE_WRITE); }); return !empty($permission); }
csn_ccr
Simply grabs the ticker using the steem_instance method and adds it to a class variable.
def dex_ticker(self): ''' Simply grabs the ticker using the steem_instance method and adds it to a class variable. ''' self.dex = Dex(self.steem_instance()) self.ticker = self.dex.get_ticker(); return self.ticker
csn
// Use built in rolling function
func (h *CompositeMultiHandler) SetJsonFile(filePath string, options *LogOptions) { writer := &lumberjack.Logger{ Filename: filePath, MaxSize: options.GetIntDefault("maxSizeMB", 1024), // megabytes MaxAge: options.GetIntDefault("maxAgeDays", 7), //days MaxBackups: options.GetIntDefault("maxBackups",...
csn
Encode subroutine used by toEncodedForm
private void encode(byte[] frame, int[] limits) { JSType.setCount(frame, limits, indices.length); for (int i = 0; i < indices.length; i++) JSType.setCount(frame, limits, indices[i]); JSType.setCount(frame, limits, varBias); JSType.setCount(frame, limits, setCases.length); for (int i = 0; i < s...
csn
python type assertion int
def is_int_type(val): """Return True if `val` is of integer type.""" try: # Python 2 return isinstance(val, (int, long)) except NameError: # Python 3 return isinstance(val, int)
cosqa
Encode the DAT packet. This method populates self.buffer, and returns self for easy method chaining.
def encode(self): """Encode the DAT packet. This method populates self.buffer, and returns self for easy method chaining.""" if len(self.data) == 0: log.debug("Encoding an empty DAT packet") data = self.data if not isinstance(self.data, bytes): data = self...
csn
def distance2_to_line(pt, l0, l1): '''The perpendicular distance squared from a point to a line pt - point in question l0 - one point on the line l1 - another point on the line ''' pt = np.atleast_1d(pt) l0 = np.atleast_1d(l0) l1 = np.atleast_1d(l1) reshape = pt.ndim == 1 if...
(1, pt.shape[0]) result = (((l0[:,0] - l1[:,0]) * (l0[:,1] - pt[:,1]) - (l0[:,0] - pt[:,0]) * (l0[:,1] - l1[:,1]))**2 / np.sum((l1-l0)**2, 1)) if reshape: result = result[0] return result
csn_ccr
def fetch_request_ids(item_ids, cls, attr_name, verification_list=None): """Return a list of cls instances for all the ids provided in item_ids. :param item_ids: The list of ids to fetch objects for :param cls: The class to fetch the ids from :param attr_name: The name of the attribute for exception pu...
of acceptable instances Raise InvalidId exception using attr_name if any do not exist, or are not present in the verification_list. """ if not item_ids: return [] items = [] for item_id in item_ids: item = cls.fetch_by_id(item_id) if not item or (verification_list ...
csn_ccr
Format the locale. @param null|string $locale The locale @return string
public static function formatLocale($locale) { if (\is_string($locale)) { $locale = strtolower($locale); $locale = str_replace('-', '_', $locale); } return $locale; }
csn
// Returns an initialized Profiler.
func NewProfiler() (prof *Profiler) { prof = &Profiler{} prof.SysFSSystemPath(joefriday.SysFSSystem) return prof }
csn
Add optional inputs and outputs to the model spec. Parameters ---------- optionals_in: [str] List of inputs that are optionals. optionals_out: [str] List of outputs that are optionals. See Also -------- set_input, set_output
def add_optionals(self, optionals_in, optionals_out): """ Add optional inputs and outputs to the model spec. Parameters ---------- optionals_in: [str] List of inputs that are optionals. optionals_out: [str] List of outputs that are optionals. ...
csn
Given a keyword, try to get the name of it. .. versionadded:: 4.2 Definition dicts are defined in keywords.py. We try to return the name if present, otherwise we return none. keyword = 'layer_purpose' kio = safe.utilities.keyword_io.Keyword_IO() name = kio.get_name(keyword) print name ...
def get_name(key): """Given a keyword, try to get the name of it. .. versionadded:: 4.2 Definition dicts are defined in keywords.py. We try to return the name if present, otherwise we return none. keyword = 'layer_purpose' kio = safe.utilities.keyword_io.Keyword_IO() name = kio.get_name(k...
csn
python pass pointer of array to ctypes
def cfloat64_array_to_numpy(cptr, length): """Convert a ctypes double pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_double)): return np.fromiter(cptr, dtype=np.float64, count=length) else: raise RuntimeError('Expected double pointer')
cosqa
Create a resource instance.
def create(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, allow_redirects=False): """ Create a resource instance. """ response = self.request( method, uri, params=params, data=data, ...
csn
public static function gravatarHasher(string $string) { $string = strtolower($string);
$string = md5($string); return $string; }
csn_ccr
Jem is famous for his laziness at school. He always leaves things to last minute. Now Jem has N problems in the assignment of "Advanced topics in algorithm" class to solved. The assignment is due tomorrow and as you may guess he hasn't touch any of the problems. Fortunately he got a plan as always. The first step will...
for t in range(int(input())): n,b,m = list(map(int,input().split())) ans = 0 while n>0: ans+=b half = (n+1)/2 if n%2 else n/2 ans+=m*half m*=2 n=n-half print(ans-b)
apps
func AddUsHolidays(cal *Calendar) { cal.AddHoliday( USNewYear, USMLK, USPresidents, USMemorial, USIndependence, USLabor,
USColumbus, USVeterans, USThanksgiving, USChristmas, ) }
csn_ccr
Monocarp had a tree which consisted of $n$ vertices and was rooted at vertex $1$. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processed q = Queue() q.put(1) # place the roo...
from sys import stdin tt = int(stdin.readline()) for loop in range(tt): n = int(stdin.readline()) a = list(map(int,stdin.readline().split())) lis = [ [1] ] now = [] tmp = 0 for i in range(1,n): if len(now) == 0: now.append(a[i]) tmp = 1 elif now[-1] ...
apps
Return the fingerprint of the given devices announced identityKey. If we have no local copy of the identityKey of the contact, build a fresh session in order to get the key. @param managerGuard authenticated OmemoManager @param contactsDevice OmemoDevice we want to get the fingerprint from @return fingerprint @throws...
public OmemoFingerprint getFingerprintAndMaybeBuildSession(OmemoManager.LoggedInOmemoManager managerGuard, OmemoDevice contactsDevice) throws CannotEstablishOmemoSessionException, CorruptedOmemoKeyException, SmackException.NotConnectedException, InterruptedException, SmackException.NoResponseExc...
csn
Ensures that a new line has been started.
protected void ensureNewLine() { try { if ((lastElementType == Element.PHRASE) || (lastElementType == Element.CHUNK)) { newLine(); flushLines(); } } catch (DocumentException ex) { throw new ExceptionConverter(ex); } }
csn
func (c *Configurator) RegisterPeerList(s PeerListSpec) error { if s.Name == "" { return errors.New("name is required") } spec, err := compilePeerListSpec(&s) if err != nil { return fmt.Errorf("invalid
PeerListSpec for %q: %v", s.Name, err) } c.knownPeerLists[s.Name] = spec return nil }
csn_ccr