query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0
def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.table...
csn
Removes all locks from user account @throws Exception
public function unlock() { $user = UserHelper::getUser($this->getUserResource()); if ($this->getUserLocksService()->unlockUser($user)) { $this->returnJson(['success' => true, 'message' => __('User %s successfully unlocked', UserHelper::getUserLogin(UserHelper::getUser($user)))]); ...
csn
def maybe_expire(self, request_timeout_ms, retry_backoff_ms, linger_ms, is_full): """Expire batches if metadata is not available A batch whose metadata is not available should be expired if one of the following is true: * the batch is not in retry AND request timeout has elapsed afte...
error = "%d seconds have passed since last append" % (since_append,) elif not self.in_retry() and timeout < since_ready: error = "%d seconds have passed since batch creation plus linger time" % (since_ready,) elif self.in_retry() and timeout < since_backoff: error = "%d seconds ...
csn_ccr
public static final Token restore(java.io.DataInputStream dataInputStream, ObjectManagerState objectManagerState) throws ObjectManagerException { if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(cclass ...
PermanentIOException"); throw new PermanentIOException(cclass, exception); } // catch (java.io.IOException exception). Token tokenToReturn = new Token(objectManagerState.getObjectStore(objectStoreIdentifier), ...
csn_ccr
def _get_ssh_key(kwargs): ''' Construct an SshKey instance from passed arguments ''' ssh_key_name = kwargs.get('name', None) ssh_key_description =
kwargs.get('description', None) public_key = kwargs.get('public_key', None) return SshKey( name=ssh_key_name, description=ssh_key_description, public_key=public_key )
csn_ccr
Transform objects into an array of key value pairs.
function (obj) { // sanity check if (!obj || typeof obj !== 'object') { return [] } var results = [] Object.keys(obj).forEach(function (name) { // nested values in query string if (typeof obj[name] === 'object') { obj[name].forEach(function (value) { results.pus...
csn
function Hbs () { if (!(this instanceof Hbs)) { return new Hbs(); } this.handlebars
= require('handlebars').create(); this.Utils = this.handlebars.Utils; this.SafeString = this.handlebars.SafeString; }
csn_ccr
func (t *Table) SetAlign(align tableAlignment, column int) { if column < 0 { return } for i := range t.elements { row, ok := t.elements[i].(*Row) if !ok { continue
} if column >= len(row.cells) { continue } row.cells[column-1].alignment = &align } }
csn_ccr
def extract_table_names(query): """ Extract table names from an SQL query. """ # a good old fashioned regex. turns out this worked better than actually parsing the
code tables_blocks = re.findall(r'(?:FROM|JOIN)\s+(\w+(?:\s*,\s*\w+)*)', query, re.IGNORECASE) tables = [tbl for block in tables_blocks for tbl in re.findall(r'\w+', block)] return set(tables)
csn_ccr
Get the available TAN mechanisms. Note: Only checks for HITANS versions listed in IMPLEMENTED_HKTAN_VERSIONS. :return: Dictionary of security_function: TwoStepParameters objects.
def get_tan_mechanisms(self): """ Get the available TAN mechanisms. Note: Only checks for HITANS versions listed in IMPLEMENTED_HKTAN_VERSIONS. :return: Dictionary of security_function: TwoStepParameters objects. """ retval = OrderedDict() for version in sorte...
csn
public function validActivationKey($attribute, $params) { if ($this->hasErrors()) { return false; } if (($identity = $this->getIdentity()) === null) { return false; } $errorCode = $identity->verifyActivationKey($this->activationKey); switch ($...
case $identity::ERROR_AKEY_TOO_OLD: $this->addError('activationKey', Yii::t('usr', 'Activation key is too old.')); return false; case $identity::ERROR_AKEY_NONE: return true; } return true; }
csn_ccr
Create a structing element composed of the origin and another pixel x, y - x and y offsets of the other pixel returns a structuring element
def strel_pair(x, y): """Create a structing element composed of the origin and another pixel x, y - x and y offsets of the other pixel returns a structuring element """ x_center = int(np.abs(x)) y_center = int(np.abs(y)) result = np.zeros((y_center * 2 + 1, x_center * 2 + 1), bool...
csn
Add client side JAX-WS handlers. @param handlers JAX-WS handlers. @return ClientBuilder instance.
public ClientBuilder<T> handlers(Handler... handlers) { this.handlers = ImmutableList.<Handler>builder().add(handlers).build(); return this; }
csn
public static function fromURL ($url, $stripHost) { $data = parse_url ($url); $parameters = array (); if (!empty ($data['query'])) parse_str ($data['query'], $parameters); $request = new self (); if ($stripHost) { $request->setUrl ($data['path']); } else { $request->setUrl ( $data['sche...
$data['host'] . (isset ($data['port']) ? ':' . $data['port'] : '') . $data['path'] ); } $request->setParameters ($parameters); return $request; }
csn_ccr
public Revision getNearest(final int revisionCounter) { if (first != null) { ChronoStorageBlock previous = null, current = first; while (current != null && current.getRevisionCounter() <= revisionCounter) {
previous = current; current = current.getCounterNext(); } return previous.getRev(); } return null; }
csn_ccr
Solve the current model asynchronously. Args: callback: Callback to be executed when the solver is done.
def solveAsync(self, callback): """ Solve the current model asynchronously. Args: callback: Callback to be executed when the solver is done. """ def async_call(): self._lock.acquire() try: self._impl.solve() except Ex...
csn
def decode(self,data): """Decode the MAC address from a byte array. This will take the first 6 bytes from data and transform them into a MAC address string representation. This will be assigned to the attribute "val". It then returns
the data stream minus the bytes consumed :param data: The data stream containing the value to decode at its head :type data: bytes :returns: The datastream minus the bytes consumed :rtype: bytes """ self.val=':'.join("%02x" % x for x in reversed(da...
csn_ccr
python serialize datetime json
def _time_to_json(value): """Coerce 'value' to an JSON-compatible representation.""" if isinstance(value, datetime.time): value = value.isoformat() return value
cosqa
Connect to a SwarmServer and do its dirty work. :param ip: ip address of server :param port: port to connect to on server :param authkey: authorization key :param max_items: maximum number of items to process from server. Useful for say running clients on a cluster.
def run_client(ip, port, authkey, max_items=None, timeout=2): """Connect to a SwarmServer and do its dirty work. :param ip: ip address of server :param port: port to connect to on server :param authkey: authorization key :param max_items: maximum number of items to process from server. Usef...
csn
Create an output buffer for each task. @return null if there aren't enough buffers left in the pool.
private List<BBContainer> getOutputBuffers(Collection<SnapshotTableTask> tableTasks, boolean noSchedule) { final int desired = tableTasks.size(); while (true) { int available = m_availableSnapshotBuffers.get(); //Limit the number of buffers used concurrently if (...
csn
Creates the cache DB table. @param CDbConnection $db the database connection @param string $tableName the name of the table to be created
protected function createCacheTable($db,$tableName) { $driver=$db->getDriverName(); if($driver==='mysql') $blob='LONGBLOB'; elseif($driver==='pgsql') $blob='BYTEA'; else $blob='BLOB'; $sql=<<<EOD CREATE TABLE $tableName ( id CHAR(128) PRIMARY KEY, expire INTEGER, value $blob ) EOD; $db->createC...
csn
public function getCheckedOutDocs( $repositoryId, $folderId, $filter = null, $orderBy = null, $includeAllowableActions = false, IncludeRelationships $includeRelationships = null, $renditionFilter = Constants::RENDITION_NONE, $maxItems = null, $skip...
$url->getQuery()->modify([Constants::PARAM_ORDER_BY => $orderBy]); } if ($maxItems > 0) { $url->getQuery()->modify([Constants::PARAM_MAX_ITEMS => (string) $maxItems]); } if ($includeRelationships !== null) { $url->getQuery()->modify([Constants::PARAM_RELATION...
csn_ccr
private String getKeyAsString(Object id, EntityMetadata metadata, MetamodelImpl metaModel) { if (metaModel.isEmbeddable(((AbstractAttribute) metadata.getIdAttribute()).getBindableJavaType())) {
return KunderaCoreUtils.prepareCompositeKey(metadata, id); } return id.toString(); }
csn_ccr
Remove a widget from the window.
def remove(self, widget): """Remove a widget from the window.""" for i, (wid, _) in enumerate(self._widgets): if widget is wid: del self._widgets[i] return True raise ValueError('Widget not in list')
csn
Converts an rpc call into an API call governed by the settings. In typical usage, ``func`` will be a callable used to make an rpc request. This will mostly likely be a bound method from a request stub used to make an rpc call. The result is created by applying a series of function decorators defined ...
def create_api_call(func, settings): """Converts an rpc call into an API call governed by the settings. In typical usage, ``func`` will be a callable used to make an rpc request. This will mostly likely be a bound method from a request stub used to make an rpc call. The result is created by applyi...
csn
Finish the current legend. @param LegendInterface $legend Return the final legend. @return PaletteBuilder @throws DcGeneralRuntimeException When no legend is stored in the builder.
public function finishLegend(&$legend = null) { if (!$this->legend) { throw new DcGeneralRuntimeException('Legend is missing, please create a legend first'); } if ($this->property) { $this->finishProperty(); } $event = new FinishLegendEvent($this->le...
csn
public function send() { $ch = curl_init(); $url = $this->_url; $d = ''; $this->_params['format'] = 'xml'; $this->_params['key'] = self::$apiKey; // The language to retrieve results in (see http://en.wikipedia.org/wiki/ISO_639-1 for the language codes (first /...
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_ENCODING, 'gzip'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Ignore SSL warnings and questions curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $r = curl_e...
csn_ccr
Converts date and time strings into a timestamp. Recent versions of Office Scan write a log field with a Unix timestamp. Older versions may not write this field; their logs only provide a date and a time expressed in the local time zone. This functions handles the latter case. Args: date (st...
def _ConvertToTimestamp(self, date, time): """Converts date and time strings into a timestamp. Recent versions of Office Scan write a log field with a Unix timestamp. Older versions may not write this field; their logs only provide a date and a time expressed in the local time zone. This functions hand...
csn
def add_type_struct_or_union(self, name, interp, node): """Store the node with the name. When it is instantiated, the node itself will be handled. :name: name of the typedefd struct/union :node: the union/struct node
:interp: the 010 interpreter """ self.add_type_class(name, StructUnionDef(name, interp, node))
csn_ccr
func (m *Model) IsControllerModel() bool
{ return m.st.controllerModelTag.Id() == m.doc.UUID }
csn_ccr
public function getLog() { $log = []; foreach ($this->traces as $request => $traces) { $log[] = sprintf('%s: %s',
$request, implode(', ', $traces)); } return implode('; ', $log); }
csn_ccr
Load a PLY file from an open file object. Parameters --------- file_obj : an open file- like object Source data, ASCII or binary PLY resolver : trimesh.visual.resolvers.Resolver Object which can resolve assets fix_texture : bool If True, will re- index vertices and faces so ...
def load_ply(file_obj, resolver=None, fix_texture=True, *args, **kwargs): """ Load a PLY file from an open file object. Parameters --------- file_obj : an open file- like object Source data, ASCII or binary PLY resolver : trimesh.visual....
csn
public function validation($instance = true) { if ($instance instanceof Validation) { $this->validation = $instance; return $instance; } if (empty($this->validation) and $instance === true)
{ $this->validation = \Validation::forge($this); } return $this->validation; }
csn_ccr
Executes the specified prepared statement. @param name The prepared statement name. @throws DatabaseEngineException If something goes wrong while executing. @throws ConnectionResetException If the connection is down and reestablishment occurs. If this happens, the user must reset the parameters and re-execute the que...
@Override public synchronized void executePS(final String name) throws DatabaseEngineException, ConnectionResetException { final PreparedStatementCapsule ps = stmts.get(name); if (ps == null) { throw new DatabaseEngineRuntimeException(String.format("PreparedStatement named '%s' does not ...
csn
Merge the state of the given entity into the current persistence context. @param entity @return the managed instance that the state was merged to @throws IllegalArgumentException if instance is not an entity or is a removed entity @throws TransactionRequiredException if invoked on a container-managed entity manager of...
@Override public final <E> E merge(E e) { checkClosed(); checkTransactionNeeded(); try { return getPersistenceDelegator().merge(e); } catch (Exception ex) { // on Rollback doRollback(); throw new...
csn
func NewConfig() *Config { return &Config{ Collation: defaultCollation, Loc:
time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, AllowNativePasswords: true, } }
csn_ccr
func (t *Template) GetAllAWSCloudFrontCloudFrontOriginAccessIdentityResources() map[string]*resources.AWSCloudFrontCloudFrontOriginAccessIdentity { results := map[string]*resources.AWSCloudFrontCloudFrontOriginAccessIdentity{} for name, untyped := range t.Resources {
switch resource := untyped.(type) { case *resources.AWSCloudFrontCloudFrontOriginAccessIdentity: results[name] = resource } } return results }
csn_ccr
Find all link tags in a string representing a HTML document and return a list of their attributes. @todo This is quite ineffective and may fail with the default pcre.backtrack_limit of 100000 in PHP 5.2, if $html is big. It should rather use stripos (in PHP5) or strpos()+strtoupper() in PHP4 to manage this. @param st...
function parseLinkAttrs($html) { $stripped = preg_replace($this->_removed_re, "", $html); $html_begin = $this->htmlBegin($stripped); $html_end = $this->htmlEnd($stripped); if ($html_begin === false) { ret...
csn
def _serie_format(self, serie, value): """Format an independent value for the serie""" kwargs = {'chart': self, 'serie': serie,
'index': None} formatter = (serie.formatter or self.formatter or self._value_format) kwargs = filter_kwargs(formatter, kwargs) return formatter(value, **kwargs)
csn_ccr
Set the grid values for y. Create information for the grid of y values. Args: num_y (int): Number of points on axis. y_low/y_high (float): Lowest/highest value for the axis. yscale (str): Scale of the axis. Choices are 'log' or 'lin'. yval_name (str): Na...
def set_y_grid_info(self, y_low, y_high, num_y, yscale, yval_name): """Set the grid values for y. Create information for the grid of y values. Args: num_y (int): Number of points on axis. y_low/y_high (float): Lowest/highest value for the axis. yscale (str):...
csn
func Create(device Device, id string, size int64) *NBD { if shuttingDown { logrus.Warnf("Cannot create NBD device during shutdown") return nil } if size >= 0 {
globalMutex.Lock() defer globalMutex.Unlock() dev := &NBD{device: device, devicePath: "", size: size, deviceFile: nil, socket: 0, mutex: &sync.Mutex{}, } nbdDevices[id] = dev return dev } return nil }
csn_ccr
Decodes a VLQ-sequence to a block of numbers @param int[] $digits @return int[] @throws \axy\codecs\base64vlq\errors\InvalidVLQSequence
public function decode(array $digits) { $result = []; $current = 0; $cBit = $this->cBit; $bits = $this->bits; $shift = 0; foreach ($digits as $digit) { $current += (($digit % $cBit) << $shift); if ($digit < $cBit) { $result[] = ...
csn
// Check checks that this issuer public key is valid, i.e. // that all components are present and a ZK proofs verifies
func (IPk *IssuerPublicKey) Check() error { // Unmarshall the public key NumAttrs := len(IPk.GetAttributeNames()) HSk := EcpFromProto(IPk.GetHSk()) HRand := EcpFromProto(IPk.GetHRand()) HAttrs := make([]*FP256BN.ECP, len(IPk.GetHAttrs())) for i := 0; i < len(IPk.GetHAttrs()); i++ { HAttrs[i] = EcpFromProto(IPk....
csn
def get_cube(cube, init=False, pkgs=None, cube_paths=None, config=None, backends=None, **kwargs): ''' Dynamically locate and load a metrique cube :param cube: name of the cube class to import from given module :param init: flag to request initialized instance or uninitialized class :pa...
don't already exist in sys.path to sys.path [sys.path.append(path) for path in cube_paths if path not in sys.path] pkgs = pkgs + DEFAULT_PKGS err = False for pkg in pkgs: try: _cube = _load_cube_pkg(pkg, cube) except ImportError as err: _cube = None if _...
csn_ccr
def create_log2fc_bigwigs(matrix, outdir, args): # type: (pd.DataFrame, str, Namespace) -> None """Create bigwigs from matrix.""" call("mkdir -p {}".format(outdir), shell=True) genome_size_dict = args.chromosome_sizes outpaths = [] for bed_file in matrix[args.treatment]: outpath = join...
data = create_log2fc_data(matrix, args) Parallel(n_jobs=args.number_cores)(delayed(_create_bigwig)(bed_column, outpath, genome_size_dict) for outpath, bed_column in zip(outpaths, data))
csn_ccr
public static String sort( String s ) { char[] chars = s.toCharArray();
Arrays.sort( chars ); return new String( chars ); }
csn_ccr
Return our provider, creating it if needed.
@Override public CacheManagerPeerProvider createCachePeerProvider ( CacheManager cacheManager, Properties properties) { if (_instance == null) { _instance = new Provider(cacheManager); } return _instance; }
csn
func (s *SyncState) RemoveResourceIfEmpty(addr addrs.AbsResource) bool { s.lock.Lock() defer s.lock.Unlock() ms := s.state.Module(addr.Module) if ms == nil { return true // nothing to do } rs := ms.Resource(addr.Resource) if rs == nil { return true // nothing to do } if len(rs.Instances) != 0 { // We do...
any objects because it's the responsibility of the // instance-mutation methods to prune those away automatically. return false } ms.RemoveResource(addr.Resource) s.maybePruneModule(addr.Module) return true }
csn_ccr
private function replaceStyle($match) { if (!$this->isDecorated()) { return $match[2]; } if ($this->hasStyle($match[1])) {
$style = $this->getStyle($match[1]); } else { return $match[0]; } return $style->apply($match[2]); }
csn_ccr
Dynamically generate our mock configuration
def generate_mock_config(self, release): """Dynamically generate our mock configuration""" mock_tmpl = pkg_resources.resource_string(__name__, 'templates/mock.mako') mock_dir = release['mock_dir'] = os.path.join(release['tmp_dir'], 'mock') mock_cfg = os.path.join(release['mock_dir'], rel...
csn
Retrieves a job matching the given `id` Args: id (str): Job `id` to match. Returns: Job: Job matching the given `id` Raises: ValueError: No resource matches given `id` or multiple resources matching given `id`
def get_job(self, id): """Retrieves a job matching the given `id` Args: id (str): Job `id` to match. Returns: Job: Job matching the given `id` Raises: ValueError: No resource matches given `id` or multiple resources matching given `id` """ ...
csn
Executes the update and returns the affected row count Moved to its own method to reduce possibility for variable name confusion
protected int doUpdate(JdbcTemplate jdbcTemplate, TaskRequest req, TaskResponse res) { //Setup the update parameters and setter final List<Phrase> parametersInUse = update_parameters != null ? update_parameters : parameters; final PreparedStatementSetter preparedStatementSetter = new PhraseParam...
csn
public function make(Table $table, $action, array $ids = [], array $options = []) { $count = count($ids); $options = $this->_getOptions($options, $count); $redirectUrl = $options['redirect']; $messages = new JSON($options['messages']); $event = EventManager::tri...
$this->Flash->error($messages->get('no_choose')); return $this->_controller->redirect($redirectUrl); } $this->_loadBehavior($table); if ($table->process($action, $ids)) { return $this->_process($action, $messages, $redirectUrl, $ids); } $this->Fl...
csn_ccr
def diskwarp_multi_fn(src_fn_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, outdir=None, dst_ndv=None): """Helper function for diskwarp of multiple input filenames """
#Should implement proper error handling here if not iolib.fn_list_check(src_fn_list): sys.exit('Missing input file(s)') src_ds_list = [gdal.Open(fn, gdal.GA_ReadOnly) for fn in src_fn_list] return diskwarp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, outdir=outdir, dst_ndv=dst_ndv)
csn_ccr
function (excludeDisabled, caseSensitive, multiValue, sanitizeKeys) { var obj = {}, // create transformation data accumulator // gather all the switches of the list key = this._postman_listIndexKey, sanitiseKeys = this._postman_sanitizeKeys || sanitizeKeys, sensi...
case sensitivity settings, we get the property name of the item var prop = sensitive ? member[key] : String(member[key]).toLowerCase(); // now, if transformation object already has a member with same property name, we either overwrite it or // append to an array of values based on ...
csn_ccr
protected function _updateControllers($root, $controllers, $plugin = null, $prefix = null) { $pluginPath = $this->_pluginAlias($plugin); // look at each controller $controllersNames = []; foreach ($controllers as $controller) { $tmp = explode('/', $controller); ...
$path = implode('/', Hash::filter($path)); if(!in_array($path, $this->ignorePaths)) { $controllerNode = $this->_checkNode($path, $controllerName, $root->id); $this->_checkMethods($controller, $controllerName, $controllerNode, $pluginPath, $prefix); } ...
csn_ccr
// SetSettingName sets the SettingName field's value.
func (s *OptionGroupOptionSetting) SetSettingName(v string) *OptionGroupOptionSetting { s.SettingName = &v return s }
csn
func (cache *Cache) Del(key []byte) (affected bool) { hashVal := hashFunc(key) segID := hashVal
& segmentAndOpVal cache.locks[segID].Lock() affected = cache.segments[segID].del(key, hashVal) cache.locks[segID].Unlock() return }
csn_ccr
function( wcDir, options, callback ) { if ( typeof options === "function" ) { callback = options; options = null; } options = options || {}; if ( !Array.isArray( wcDir ) ) { wcDir = [wcDir]; } var args = [ '-n' ]; if ( options.lastChangeRevision ) { args.push( '-c' ); } execSvnVersion( wcDir.concat( ar...
} result.flags = match[3]; if ( result.flags.length > 0 ) { result.modified = result.flags.indexOf( 'M' ) >= 0; result.partial = result.flags.indexOf( 'P' ) >= 0; result.switched = result.flags.indexOf( 'S' ) >= 0; } } else { err = data; } } callback( err, result ); } ); }
csn_ccr
def _communicate(self): """Callback for communicate.""" if (not self._communicate_first and self._process.state()
== QProcess.NotRunning): self.communicate() elif self._fired: self._timer.stop()
csn_ccr
public function getIngestManifestAssetList() { $propertyList = $this->_getEntityList('IngestManifestAssets'); $result = []; foreach ($propertyList as $properties) { $result[] =
IngestManifestAsset::createFromOptions($properties); } return $result; }
csn_ccr
python check existance of config
def _is_already_configured(configuration_details): """Returns `True` when alias already in shell config.""" path = Path(configuration_details.path).expanduser() with path.open('r') as shell_config: return configuration_details.content in shell_config.read()
cosqa
// Tokenizer is the name of the tokenizer to use for the analysis.
func (s *IndicesAnalyzeService) Tokenizer(tokenizer string) *IndicesAnalyzeService { s.request.Tokenizer = tokenizer return s }
csn
Levko loves array a_1, a_2, ... , a_{n}, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types: Increase all elements from l_{i} to r_{i} by d_{i}. In other words, perform assignments a_{j} = a_{j...
n, m = map(int, input().split()) a = [10**9 for _ in range(n)] extra = [0 for _ in range(n)] query = list() for _ in range(m): t, l, r, x = map(int, input().split()) l -= 1 r -= 1 query.append((t, l, r, x)) if t == 1: for j in range(l, r + 1): extra[j] += x else: ...
apps
def generate_http_manifest(self): """Return http manifest. The http manifest is the resource that defines a dataset as HTTP enabled (published). """ base_path = os.path.dirname(self.translate_path(self.path)) self.dataset = dtoolcore.DataSet.from_uri(base_path) ...
with open(admin_metadata_fpath) as fh: admin_metadata = json.load(fh) http_manifest = { "admin_metadata": admin_metadata, "manifest_url": self.generate_url(".dtool/manifest.json"), "readme_url": self.generate_url("README.yml"), "overlays": se...
csn_ccr
public void concatenate(JavaMethod tail) { CodeAttribute codeAttr = getCode(); CodeAttribute tailCodeAttr = tail.getCode(); byte []code = codeAttr.getCode(); byte []tailCode = tailCodeAttr.getCode(); int codeLength = code.length; if ((code[codeLength - 1] & 0xff) == CodeVisitor.RETURN) ...
codeAttr.setMaxLocals(tailCodeAttr.getMaxLocals()); ArrayList<CodeAttribute.ExceptionItem> exns = tailCodeAttr.getExceptions(); for (int i = 0; i < exns.size(); i++) { CodeAttribute.ExceptionItem exn = exns.get(i); CodeAttribute.ExceptionItem newExn = new CodeAttribute.ExceptionItem(); ...
csn_ccr
function getCategories (posts) { var categories = posts.reduce(function (categories, post) { if (!post.category) return categories;
return categories.concat(post.category); }, []); return _.unique(categories).sort(); }
csn_ccr
func LineCount(screenWidth, w int) int { r := w / screenWidth
if w%screenWidth != 0 { r++ } return r }
csn_ccr
protected void readUUID(StreamReader stream, Map<String, Object> map) throws IOException { int unknown0Size =
stream.getMajorVersion() > 5 ? 8 : 16; map.put("UNKNOWN0", stream.readBytes(unknown0Size)); map.put("UUID", stream.readUUID()); }
csn_ccr
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the system profiler output. We get it in the form of a plist.""" _ = stderr, time_taken, args, knowledge_base # Unused self.CheckReturn(cmd, return_val) plist = biplist.readPlist(io.BytesIO(stdout)...
system_product_name = hardware_list.get("machine_model", None) bios_version = hardware_list.get("boot_rom_version", None) yield rdf_client.HardwareInfo( serial_number=serial_number, bios_version=bios_version, system_product_name=system_product_name)
csn_ccr
def url_for(endpoint_or_url_or_config_key: str, _anchor: Optional[str] = None, _cls: Optional[Union[object, type]] = None, _external: Optional[bool] = False, _external_host: Optional[str] = None, _method: Optional[str] = None, _scheme: Optional[str...
what.isupper(): what = current_app.config.get(what) if isinstance(what, LocalProxy): what = what._get_current_object() # if we already have a url (or an invalid value, eg None) if not what or '/' in what: return what flask_url_for_kwargs = dict(_anchor=_anchor, _external=_ext...
csn_ccr
List all the resource pools for this VMware environment CLI Example: .. code-block:: bash salt-cloud -f list_resourcepools my-vmware-config
def list_resourcepools(kwargs=None, call=None): ''' List all the resource pools for this VMware environment CLI Example: .. code-block:: bash salt-cloud -f list_resourcepools my-vmware-config ''' if call != 'function': raise SaltCloudSystemExit( 'The list_resourcep...
csn
Decorator that copies a method's docstring from another class. Args: source_class (type): The class that has the documented method. Returns: Callable: A decorator that will copy the docstring of the same named method in the source class to the decorated method.
def copy_docstring(source_class): """Decorator that copies a method's docstring from another class. Args: source_class (type): The class that has the documented method. Returns: Callable: A decorator that will copy the docstring of the same named method in the source class to t...
csn
protected function _createToken($identity) { $plain = $this->_createPlainToken($identity); $hash = $this->getPasswordHasher()->hash($plain);
$usernameField = $this->getConfig('fields.username'); return json_encode([$identity[$usernameField], $hash]); }
csn_ccr
@Bean public PropertiesFactoryBean casCommonMessages() { val properties = new PropertiesFactoryBean(); val resourceLoader = new DefaultResourceLoader(); val commonNames = casProperties.getMessageBundle().getCommonNames(); val resourceList = commonNames .stream() ...
.collect(Collectors.toList()); resourceList.add(resourceLoader.getResource("classpath:/cas_common_messages.properties")); properties.setLocations(resourceList.toArray(Resource[]::new)); properties.setSingleton(true); properties.setIgnoreResourceNotFound(true); return propertie...
csn_ccr
def backout_last(self, updated_singles, num_coincs): """Remove the recently added singles and coincs Parameters ---------- updated_singles: dict of numpy.ndarrays Array of indices that have been just updated in the internal buffers of single detector triggers. ...
The number of coincs that were just added to the internal buffer of coincident triggers """ for ifo in updated_singles: self.singles[ifo].discard_last(updated_singles[ifo]) self.coincs.remove(num_coincs)
csn_ccr
public function word($data, $default = '', $options = []) { //First word in a sanitized string $sentence = $this->string($data, $default,
$options, false); //@TODO validate string before breaking into words; //Requires php5.3!! return (string)strstr($sentence, ' ', true); }
csn_ccr
public Collection<Metric> metricNames(long applicationId, String name) { QueryParameterList queryParams = new QueryParameterList();
if(name != null && name.length() > 0) queryParams.add("name", name); return HTTP.GET(String.format("/v2/mobile_applications/%d/metrics.json", applicationId), null, queryParams, METRICS).get(); }
csn_ccr
func (t *Template) GetAllAWSGuardDutyMemberResources() map[string]*resources.AWSGuardDutyMember { results := map[string]*resources.AWSGuardDutyMember{} for name, untyped := range t.Resources {
switch resource := untyped.(type) { case *resources.AWSGuardDutyMember: results[name] = resource } } return results }
csn_ccr
def validate_one_format(jupytext_format): """Validate extension and options for the given format""" if not isinstance(jupytext_format, dict): raise JupytextFormatError('Jupytext format should be a dictionary') for key in jupytext_format: if key not in _VALID_FORMAT_INFO + _VALID_FORMAT_OPTI...
'extension' not in jupytext_format: raise JupytextFormatError('Missing format extension') ext = jupytext_format['extension'] if ext not in NOTEBOOK_EXTENSIONS + ['.auto']: raise JupytextFormatError("Extension '{}' is not a notebook extension. Please use one of '{}'.".format( ext, "'...
csn_ccr
public function getLinkForPage($pageNumber, $label, $htmlOptions = array()) {
return Html::get()->link($this->getURLForPage($pageNumber), $label, $htmlOptions); }
csn_ccr
func NewErrorLexer(msg string, l *buffer.Lexer) *Error { r := buffer.NewReader(l.Bytes()) offset
:= l.Offset() return NewError(msg, r, offset) }
csn_ccr
List all available instance configurations. Example: ``` $configurations = $spanner->instanceConfigurations(); ``` @codingStandardsIgnoreStart @see https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.ListInstanceConfigsRequest ListInstanceConfigsReques...
public function instanceConfigurations(array $options = []) { $resultLimit = $this->pluck('resultLimit', $options, false) ?: 0; return new ItemIterator( new PageIterator( function (array $config) { return $this->instanceConfiguration($config['name'], ...
csn
func (s *authKeyV1) Put() interface{} { var handler AuthPutHandler = func(params martini.Params, log *log.Logger, r render.Render, tokens oauth2.Tokens) { var ( err error apikey string ) log.Println("executing the put handler") username := params[UserParam] userInfo := GetUserInfo(tokens) details,...
if err = s.keyGen.Create(username, string(details[:])); err != nil { log.Println("keyGen.Create error: ", err) } if apikey, err = s.keyGen.Get(username); err != nil { log.Println("keyGen.Get error: ", err) } }). OnFailure(func() { err = ErrInvalidCallerEmail log.Println("invalid user t...
csn_ccr
On Setting display. @param AnEvent $event The event parameter
public function onSettingDisplay(AnEvent $event) { $actor = $event->actor; $tabs = $event->tabs; $this->_setSettingTabs($actor, $tabs); }
csn
Returns a logger @param string $logger Logger's name @return LoggerInterface
public function getLog(string $logger = 'default'): LoggerInterface { if (!isset($this->loggers[$logger])) { if ($logger === 'default') { if (!isset($this->implicit['logger'])) { throw new \RuntimeException('The default logger was not set'); } ...
csn
def matches(self, txt: str) -> bool: """Determine whether txt matches pattern :param txt: text to check :return: True if match """ # rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape') if r'\\u' in self.pattern_re.pattern:
txt = txt.encode('utf-8').decode('unicode-escape') match = self.pattern_re.match(txt) return match is not None and match.end() == len(txt)
csn_ccr
Loads the given class, definition or interface. @param string $class The name of the class
public function loadClass($class) { if ((true === $this->apc && ($file = $this->findFileInApc($class))) or ($file = $this->findFile($class)) ) { require_once $file; } }
csn
protected static String jacksonObjectToString(Object object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) {
logger.error("Failed to serialize JSON data: " + e.toString()); return null; } }
csn_ccr
def _join_keys_v1(left, right): """ Join two keys into a format separable by using _split_keys_v1. """ if left.endswith(':') or '::' in left: raise ValueError("Can't join a left string
ending in ':' or containing '::'") return u"{}::{}".format(_encode_v1(left), _encode_v1(right))
csn_ccr
func Convert_v1_QuobyteVolumeSource_To_core_QuobyteVolumeSource(in *v1.QuobyteVolumeSource, out
*core.QuobyteVolumeSource, s conversion.Scope) error { return autoConvert_v1_QuobyteVolumeSource_To_core_QuobyteVolumeSource(in, out, s) }
csn_ccr
Sets the alert_statuses of this IntegrationStatus. A Map from the ids of the alerts contained in this integration to their install status. The install status can take on one of three values, `VISIBLE`, `HIDDEN`, and `NOT_LOADED` # noqa: E501 :param alert_statuses: The alert_statuses of this Integrat...
def alert_statuses(self, alert_statuses): """Sets the alert_statuses of this IntegrationStatus. A Map from the ids of the alerts contained in this integration to their install status. The install status can take on one of three values, `VISIBLE`, `HIDDEN`, and `NOT_LOADED` # noqa: E501 :para...
csn
Use this API to fetch spilloverpolicy_binding resource of given name .
public static spilloverpolicy_binding get(nitro_service service, String name) throws Exception{ spilloverpolicy_binding obj = new spilloverpolicy_binding(); obj.set_name(name); spilloverpolicy_binding response = (spilloverpolicy_binding) obj.get_resource(service); return response; }
csn
public static function label($name, $value = null, array $options = []) { self::exclure($options, ['value', 'for']); self::$labels[] = $name; $value = e(self::formatLabel($name, $value));
$options = Html::attributes($options); return '<label for="'.$name.'"'.$options.'>'.$value.'</label>'; }
csn_ccr
Calculate the next fallback locale for the given locale. Note: always keep this in sync with the fallback mechanism in Java, ABAP (MIME & BSP) resource handler (Java: Peter M., MIME: Sebastian A., BSP: Silke A.) @param {string} sLocale Locale string in Java format (underscores) or null @returns {string|null} Next fall...
function nextFallbackLocale(sLocale) { // there is no fallback for the 'raw' locale or for null/undefined if ( !sLocale ) { return null; } // special (legacy) handling for zh_HK: try zh_TW (for Traditional Chinese) first before falling back to 'zh' if ( sLocale === "zh_HK" ) { return "zh_TW"; } /...
csn
private function doCallBackSingleProp($propertyName, callable $callback) { $result = $callback($this->mutations[$propertyName]); if (is_bool($result)) { if ($result) { if (is_null($this->mutations[$propertyName])) { // Delete $resul...
} if (!is_int($result)) { throw new UnexpectedValueException('A callback sent to handle() did not return an int or a bool'); } $this->result[$propertyName] = $result; if ($result >= 400) { $this->failed = true; } }
csn_ccr
def next_game_date(dt,wday) dt += 1 until wday == dt.wday &&
!self.exclude_dates.include?(dt) dt end
csn_ccr
Top level policy delete routine.
def fw_policy_delete(self, data, fw_name=None): """Top level policy delete routine. """ LOG.debug("FW Policy Debug") self._fw_policy_delete(fw_name, data)
csn
def process_file(path) code = File.read(path) sexp_node = RubyParser.new.parse(code) file = Mago::RubyFile.new(path) sexp_processor = Mago::SexpProcessor.new(file, @ignore) sexp_processor.process(sexp_node)
@report.files << file @on_file.call(file) if @on_file rescue Errno::ENOENT => err handle_error(err.message) rescue Racc::ParseError, Encoding::CompatibilityError => err msg = "#{path} has invalid ruby code. " << err.message handle_error(msg) end
csn_ccr
// DataURI parses the given data URI and returns the mediatype, data and ok.
func DataURI(dataURI []byte) ([]byte, []byte, error) { if len(dataURI) > 5 && bytes.Equal(dataURI[:5], []byte("data:")) { dataURI = dataURI[5:] inBase64 := false var mediatype []byte i := 0 for j := 0; j < len(dataURI); j++ { c := dataURI[j] if c == '=' || c == ';' || c == ',' { if c != '=' && byte...
csn