query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
Add a response which can be referenced. :param str component_id: ref_id to use as reference :param dict component: response fields :param dict kwargs: plugin-specific arguments
def response(self, component_id, component=None, **kwargs): """Add a response which can be referenced. :param str component_id: ref_id to use as reference :param dict component: response fields :param dict kwargs: plugin-specific arguments """ if component_id in self._responses: raise DuplicateComponentNameError( 'Another response with name "{}" is already registered.'.format( component_id ) ) component = component or {} ret = component.copy() # Execute all helpers from plugins for plugin in self._plugins: try: ret.update(plugin.response_helper(component, **kwargs) or {}) except PluginMethodNotImplementedError: continue self._responses[component_id] = ret return self
csn
Ends measuring a cache request. @param string $type Request type, either a miss or a hit @param string $hash The hash of the cache request @param array $tags The cache request tags @param string $sql The underlying SQL query string @param array $parameters The SQL query parameters
public function endMeasuring($type, $hash, $tags, $sql, $parameters) { $name = '[' . ucfirst($type) . '] ' . $sql; $endTime = microtime(true); $params = [ 'hash' => $hash, 'tags' => $tags, 'parameters' => $parameters, ]; $this->addMeasure($name, $this->startTime, $endTime, $params); }
csn
def apply(self, func, keep_attrs=None, args=(), **kwargs): """Apply a function over the data variables in this dataset. Parameters ---------- func : function Function which can be called in the form `func(x, *args, **kwargs)` to transform each DataArray `x` in this dataset into another DataArray. keep_attrs : bool, optional If True, the dataset's attributes (`attrs`) will be copied from the original object to the new one. If False, the new object will be returned without attributes. args : tuple, optional Positional arguments passed on to `func`. **kwargs : dict Keyword arguments passed on to `func`. Returns ------- applied : Dataset Resulting dataset from applying ``func`` over each data variable. Examples -------- >>> da = xr.DataArray(np.random.randn(2, 3)) >>> ds = xr.Dataset({'foo': da, 'bar': ('x', [-1, 2])}) >>> ds <xarray.Dataset> Dimensions: (dim_0: 2, dim_1: 3, x: 2) Dimensions without coordinates: dim_0, dim_1, x Data variables:
foo (dim_0, dim_1) float64 -0.3751 -1.951 -1.945 0.2948 0.711 -0.3948 bar (x) int64 -1 2 >>> ds.apply(np.fabs) <xarray.Dataset> Dimensions: (dim_0: 2, dim_1: 3, x: 2) Dimensions without coordinates: dim_0, dim_1, x Data variables: foo (dim_0, dim_1) float64 0.3751 1.951 1.945 0.2948 0.711 0.3948 bar (x) float64 1.0 2.0 """ # noqa variables = OrderedDict( (k, maybe_wrap_array(v, func(v, *args, **kwargs))) for k, v in self.data_vars.items()) if keep_attrs is None: keep_attrs = _get_keep_attrs(default=False) attrs = self.attrs if keep_attrs else None return type(self)(variables, attrs=attrs)
csn_ccr
add two polynomials using function in python
def __add__(self, other): """Left addition.""" return chaospy.poly.collection.arithmetics.add(self, other)
cosqa
A string module that asynchronously replaces text. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'RULE': [ { 'param': {'value': <match type: 1=first, 2=last, 3=every>}, 'find': {'value': <text to find>}, 'replace': {'value': <replacement>} } ] } Returns ------- _OUTPUT : twisted.internet.defer.Deferred generator of replaced strings
def asyncPipeStrreplace(context=None, _INPUT=None, conf=None, **kwargs): """A string module that asynchronously replaces text. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'RULE': [ { 'param': {'value': <match type: 1=first, 2=last, 3=every>}, 'find': {'value': <text to find>}, 'replace': {'value': <replacement>} } ] } Returns ------- _OUTPUT : twisted.internet.defer.Deferred generator of replaced strings """ splits = yield asyncGetSplits(_INPUT, conf['RULE'], **kwargs) parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs()) _OUTPUT = yield asyncStarMap(asyncParseResult, parsed) returnValue(iter(_OUTPUT))
csn
def set_param(self, param, value): '''Set a parameter in this configuration set.''' self.data[param] = value
self._object.configuration_data = utils.dict_to_nvlist(self.data)
csn_ccr
public static function isValidError(string $name, $node = null): ?ValidationException { if (\strlen($name) > 1 && $name{0} === '_' && $name{1} === '_') { return new ValidationException( sprintf('Name "%s" must not begin with "__", which is reserved by GraphQL introspection.', $name), $node instanceof NodeInterface ? [$node] : null ); } if (preg_match("/^[_a-zA-Z][_a-zA-Z0-9]*$/", $name) === 0) {
return new ValidationException( sprintf('Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "%s" does not.', $name), $node instanceof NodeInterface ? [$node] : null ); } return null; }
csn_ccr
python c structure to dict
def struct2dict(struct): """convert a ctypes structure to a dictionary""" return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}
cosqa
public static Collection<Column> getPrimaryKeyColumns(Table catalogTable) { Collection<Column> columns = new ArrayList<>(); Index catalog_idx = null; try { catalog_idx = CatalogUtil.getPrimaryKeyIndex(catalogTable);
} catch (Exception ex) { // IGNORE return (columns); } assert(catalog_idx != null); for (ColumnRef catalog_col_ref : getSortedCatalogItems(catalog_idx.getColumns(), "index")) { columns.add(catalog_col_ref.getColumn()); } return (columns); }
csn_ccr
Create the Authentication header @return string @throws \Akamai\Open\EdgeGrid\Authentication\Exception\SignerException\InvalidSignDataException @link https://developer.akamai.com/introduction/Client_Auth.html
public function createAuthHeader() { if ($this->timestamp === null) { $this->setTimestamp(); } if (!$this->timestamp->isValid()) { throw new InvalidSignDataException('Timestamp is invalid. Too old?'); } if ($this->nonce === null) { $this->nonce = new Nonce(); } $auth_header = 'EG1-HMAC-SHA256 ' . 'client_token=' . $this->auth['client_token'] . ';' . 'access_token=' . $this->auth['access_token'] . ';' . 'timestamp=' . $this->timestamp . ';' . 'nonce=' . $this->nonce . ';'; return $auth_header . 'signature=' . $this->signRequest($auth_header); }
csn
// Update changes the passphrase of an existing account.
func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error { a, key, err := ks.getDecryptedKey(a, passphrase) if err != nil { return err } return ks.storage.StoreKey(a.URL.Path, key, newPassphrase) }
csn
Callback for the event onMouseClickClose raised by the popup. @protected
function (evt) { var domEvent = evt.domEvent; if (domEvent.target == this.getTextInputField()) { // Clicking on the input should directly give the focus to the input. // Setting this boolean to false prevents the focus from being given // to this._touchFocusSpan when the dropdown is closed (which would // be temporary anyway, but would make Edge fail on DatePickerInputTouchTest) this._focusNoKeyboard = false; } this.$DropDownTrait._dropDownMouseClickClose.call(this, evt); }
csn
private function resolveAuthenticator(TokenInterface $token) { foreach ($this->authenticators as $authenticator) { if ($authenticator->supports($token)) {
return $authenticator; } } return false; }
csn_ccr
func (p ResourcePersistence) SetCharmStoreResource(id, applicationID string, res charmresource.Resource, lastPolled time.Time) error { if err := res.Validate(); err != nil { return errors.Annotate(err, "bad resource") } csRes := charmStoreResource{ Resource: res, id: id, applicationID: applicationID, lastPolled: lastPolled, } buildTxn := func(attempt int) ([]txn.Op, error) {
// This is an "upsert". var ops []txn.Op switch attempt { case 0: ops = newInsertCharmStoreResourceOps(csRes) case 1: ops = newUpdateCharmStoreResourceOps(csRes) default: // Either insert or update will work so we should not get here. return nil, errors.New("setting the resource failed") } // No pending resources so we always do this here. ops = append(ops, p.base.ApplicationExistsOps(applicationID)...) return ops, nil } if err := p.base.Run(buildTxn); err != nil { return errors.Trace(err) } return nil }
csn_ccr
Handles a line received from the prompt. \param string $line A single line of text received from the prompt, with the end-of-line sequence stripped.
protected function handleMessage($line) { $pos = strpos($line, ' '); if ($pos === false) { return; } $pattern = preg_quote(substr($line, 0, $pos), '@'); $pattern = strtr($pattern, array('\\?' => '.?', '\\*' => '.*')); $line = substr($line, $pos + 1); if ($line === false) { return; } foreach ($this->bot->getConnections() as $connection) { if (!($connection instanceof \Erebot\Interfaces\SendingConnection) || $connection == $this) { continue; } $config = $connection->getConfig(null); $netConfig = $config->getNetworkCfg(); if (preg_match('@^'.$pattern.'$@Di', $netConfig->getName())) { $connection->getIO()->push($line); } } }
csn
Register a job for executing in batch. @param string $identifier Unique identifier of the job. @param callable $callback Callback that accepts the job $idNum and returns a JobInterface instance. @return void
public function registerJob($identifier, $callback) { if (array_key_exists($identifier, $this->identifierToId)) { $idNum = $this->identifierToId[$identifier]; } else { $idNum = count($this->identifierToId) + 1; $this->idToIdentifier[$idNum] = $identifier; } $this->jobs[$identifier] = call_user_func( $callback, $idNum ); $this->identifierToId[$identifier] = $idNum; }
csn
// newVserver returns an initialised vserver struct.
func newVserver(e *Engine) *vserver { return &vserver{ engine: e, ncc: ncclient.NewNCC(e.config.NCCSocket), fwm: make(map[seesaw.AF]uint32), active: make(map[seesaw.IP]bool), lbVservers: make(map[seesaw.IP]*seesaw.Vserver), vips: make(map[seesaw.VIP]bool), overrideChan: make(chan seesaw.Override, 5), notify: make(chan *checkNotification, 20), update: make(chan *config.Vserver, 1), quit: make(chan bool, 1), stopped: make(chan bool, 1), } }
csn
// ParseAnnotationsCPUWeight searches `s.Annotations` for the CPU annotation. If // not found searches `s` for the Windows CPU section. If neither are found // returns `def`.
func ParseAnnotationsCPUWeight(s *specs.Spec, annotation string, def int32) int32 { if m := parseAnnotationsUint64(s.Annotations, annotation, 0); m != 0 { return int32(m) } if s.Windows != nil && s.Windows.Resources != nil && s.Windows.Resources.CPU != nil && s.Windows.Resources.CPU.Shares != nil && *s.Windows.Resources.CPU.Shares > 0 { return int32(*s.Windows.Resources.CPU.Shares) } return def }
csn
protected function toRtf() { $rtf = ''; // if a word exists if ($this->word) { // if the word is ignored if ($this->isIgnored) { // prepend the ignored control symbol
$rtf = '\\*'; } // append the word and its parameter $rtf .= "\\{$this->word}{$this->parameter}"; // if the word is space-delimited, append the space if ($this->isSpaceDelimited) { $rtf .= ' '; } } return $rtf; }
csn_ccr
def merge_record_extra(record, target, reserved): """ Merges extra attributes from LogRecord object into target dictionary :param record: logging.LogRecord :param target: dict to update :param reserved: dict or list with reserved keys to skip """ for key, value in record.__dict__.items(): # this allows to have numeric
keys if (key not in reserved and not (hasattr(key, "startswith") and key.startswith('_'))): target[key] = value return target
csn_ccr
public function info($identities) { $ids = []; $names = []; if (is_array($identities)) { foreach ($identities as $identity) { if (gettype($identity) === 'integer') { // it's the id $ids[] = $identity; } else { // the summoner name $names[] = $identity; } } } else { if (gettype($identities) === 'integer') { // it's the id $ids[] = $identities; } else { // the summoner name $names[] = $identities; } } if (count($ids) > 0) {
// it's the id $ids = $this->infoByIds($ids); } if (count($names) > 0) { // the summoner name $names = $this->infoByNames($names); } $summoners = $ids + $names; if (count($summoners) == 1) { return reset($summoners); } else { return $summoners; } }
csn_ccr
Retrieve the pageId based on the pageRequest information, as well as the url map. As a default, the homePageId is returned @param {aria.pageEngine.CfgBeans:PageRequest} pageRequest @return {String} the pageId @private
function (pageRequest) { var map = this.__urlMap.urlToPageId, pageId = pageRequest.pageId, url = pageRequest.url; if (pageId) { return pageId; } if (url) { var returnUrl = map[url] || map[url + "/"] || map[url.replace(/\/$/, "")]; if (returnUrl) { return returnUrl; } } return this.__config.homePageId; }
csn
Format decimal numbers in this locale.
private static void decimal(CLDR.Locale locale, String[] numbers, DecimalFormatOptions opts) { for (String num : numbers) { BigDecimal n = new BigDecimal(num); StringBuilder buf = new StringBuilder(" "); NumberFormatter fmt = CLDR.get().getNumberFormatter(locale); fmt.formatDecimal(n, buf, opts); System.out.println(buf.toString()); } }
csn
Matches route produces configurer and Accept-header in an incoming provider @param route route configurer @param request incoming provider object @return returns {@code true} if the given route has produces Media-Type one of an Accept from an incoming provider
public static boolean matchProduces(InternalRoute route, InternalRequest<?> request) { if (nonEmpty(request.getAccept())) { List<MediaType> matchedAcceptTypes = getAcceptedMediaTypes(route.getProduces(), request.getAccept()); if (nonEmpty(matchedAcceptTypes)) { request.setMatchedAccept(matchedAcceptTypes.get(0)); return true; } } return false; }
csn
Gets the rating information for this video, if available. The rating is returned as an array containing the keys 'average' and 'numRaters'. null is returned if the rating information is not available. @return array|null The rating information for this video
public function getVideoRatingInfo() { if ($this->getRating() != null) { $returnArray = array(); $returnArray['average'] = $this->getRating()->getAverage(); $returnArray['numRaters'] = $this->getRating()->getNumRaters(); return $returnArray; } else { return null; } }
csn
def _encrypt_data_key(self, data_key, algorithm, encryption_context=None): """Encrypts a data key and returns the ciphertext. :param data_key: Unencrypted data key :type data_key: :class:`aws_encryption_sdk.structures.RawDataKey` or :class:`aws_encryption_sdk.structures.DataKey` :param algorithm: Placeholder to maintain API compatibility with parent :param dict encryption_context: Encryption context to pass to KMS :returns: Data key containing encrypted data key :rtype: aws_encryption_sdk.structures.EncryptedDataKey :raises EncryptKeyError: if Master Key is unable to encrypt data key
""" kms_params = {"KeyId": self._key_id, "Plaintext": data_key.data_key} if encryption_context: kms_params["EncryptionContext"] = encryption_context if self.config.grant_tokens: kms_params["GrantTokens"] = self.config.grant_tokens # Catch any boto3 errors and normalize to expected EncryptKeyError try: response = self.config.client.encrypt(**kms_params) ciphertext = response["CiphertextBlob"] key_id = response["KeyId"] except (ClientError, KeyError): error_message = "Master Key {key_id} unable to encrypt data key".format(key_id=self._key_id) _LOGGER.exception(error_message) raise EncryptKeyError(error_message) return EncryptedDataKey( key_provider=MasterKeyInfo(provider_id=self.provider_id, key_info=key_id), encrypted_data_key=ciphertext )
csn_ccr
converting nodeUrl to absolute Url form @param boolean $withFragment @return string
public function getAbsoluteUrl($withFragment=true) { if($this->isCrawlable() === false && empty($this->getFragment())){ $absolutePath = $this->getOriginalUrl(); }else{ if($this->parentLink !==null){ $newUri = \GuzzleHttp\Psr7\UriResolver::resolve($this->parentLink,$this); }else{ $newUri = $this; } $absolutePath = GuzzleUri::composeComponents( $newUri->getScheme(), $newUri->getAuthority(), $newUri->getPath(), $newUri->getQuery(), $withFragment===true?$this->getFragment():"" ); } return $absolutePath; }
csn
func NewDecoder(r io.Reader) *Decoder { client := xml.NewDecoder(r) return &Decoder{
TokenType: StartXML, client: client, } }
csn_ccr
private static GeometricParity geometric(Map<IAtom, Integer> elevationMap, List<IBond> bonds, int i, int[] adjacent, IAtomContainer container) { int nStereoBonds =
nStereoBonds(bonds); if (nStereoBonds > 0) return geometric2D(elevationMap, bonds, i, adjacent, container); else if (nStereoBonds == 0) return geometric3D(i, adjacent, container); return null; }
csn_ccr
public static ControlledAttribute createIceControlledAttribute( long tieBreaker)
{ ControlledAttribute attribute = new ControlledAttribute(); attribute.setTieBreaker(tieBreaker); return attribute; }
csn_ccr
Access the Notify Twilio Domain :returns: Notify Twilio Domain :rtype: twilio.rest.notify.Notify
def notify(self): """ Access the Notify Twilio Domain :returns: Notify Twilio Domain :rtype: twilio.rest.notify.Notify """ if self._notify is None: from twilio.rest.notify import Notify self._notify = Notify(self) return self._notify
csn
void addSchema(JMFSchema schema, Transaction tran) throws MessageStoreException {
addItem(new SchemaStoreItem(schema), tran); }
csn_ccr
// SetGitHub sets the GitHub field's value.
func (s *CodeDestination) SetGitHub(v *GitHubCodeDestination) *CodeDestination { s.GitHub = v return s }
csn
def calc_normal_std_glorot(inmaps, outmaps, kernel=(1, 1)): r"""Calculates the standard deviation proposed by Glorot et al. .. math:: \sigma = \sqrt{\frac{2}{NK + M}} Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :math:`M`. kernel (:obj:`tuple` of :obj:`int`): Convolution kernel spatial shape. In above definition, :math:`K` is the product of shape dimensions. In Affine, the default value should be used. Example: .. code-block:: python import nnabla as nn import nnabla.parametric_functions as PF import nnabla.initializer as I x
= nn.Variable([60,1,28,28]) s = I.calc_normal_std_glorot(x.shape[1],64) w = I.NormalInitializer(s) b = I.ConstantInitializer(0) h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv') References: * `Glorot and Bengio. Understanding the difficulty of training deep feedforward neural networks <http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf>`_ """ return np.sqrt(2. / (np.prod(kernel) * inmaps + outmaps))
csn_ccr
public List<ISubmission> getSubmissionsForSubmitter(ISubmitter submitter, String resourceUrl, String verb)
throws Exception{ return new SubmitterSubmissionsFilter().include(new NormalizingFilter(IRating.VERB).filter(getSubmissions(resourceUrl)), submitter); }
csn_ccr
def collect_garbage(): ''' Completely removed all currently 'uninstalled' packages in the nix store. Tells the user how many store paths were removed and how much space was freed. :return: How much space was freed and how many derivations were removed :rtype: str .. warning:: This is a destructive action on the nix
store. .. code-block:: bash salt '*' nix.collect_garbage ''' cmd = _nix_collect_garbage() cmd.append('--delete-old') out = _run(cmd) return out['stdout'].splitlines()
csn_ccr
Initialize the view object $options may contain the following keys: - neverRender - flag dis/enabling postDispatch() autorender (affects all subsequent calls) - noController - flag indicating whether or not to look for view scripts in subdirectories named after the controller - noRender - flag indicating whether or not to autorender postDispatch() - responseSegment - which named response segment to render a view script to - scriptAction - what action script to render - viewBasePathSpec - specification to use for determining view base path - viewScriptPathSpec - specification to use for determining view script paths - viewScriptPathNoControllerSpec - specification to use for determining view script paths when noController flag is set - viewSuffix - what view script filename suffix to use @param string $path @param string $prefix @param array $options @throws Zend_Controller_Action_Exception @return void
public function initView($path = null, $prefix = null, array $options = array()) { $this->setView($this->getServiceLocator()->get('View')); parent::initView($path, $prefix, $options); }
csn
import urllib import base64 data = urllib.urlopen('http://rosettacode.org/favicon.ico').read() print base64.b64encode(data)
#include <iostream> #include <fstream> #include <vector> typedef unsigned char byte; using namespace std; const unsigned m1 = 63 << 18, m2 = 63 << 12, m3 = 63 << 6; class base64 { public: base64() { char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; } string encode( vector<byte> v ) { string res; unsigned d, a = 0, l = static_cast<unsigned>( v.size() ); while( l > 2 ) { d = v[a++] << 16 | v[a++] << 8 | v[a++]; res.append( 1, char_set.at( ( d & m1 ) >> 18 ) ); res.append( 1, char_set.at( ( d & m2 ) >> 12 ) ); res.append( 1, char_set.at( ( d & m3 ) >> 6 ) ); res.append( 1, char_set.at( d & 63 ) ); l -= 3; } if( l == 2 ) { d = v[a++] << 16 | v[a++] << 8; res.append( 1, char_set.at( ( d & m1 ) >> 18 ) ); res.append( 1, char_set.at( ( d & m2 ) >> 12 ) ); res.append( 1, char_set.at( ( d & m3 ) >> 6 ) ); res.append( 1, '=' ); } else if( l == 1 ) { d = v[a++] << 16; res.append( 1, char_set.at( ( d & m1 ) >> 18 ) ); res.append( 1, char_set.at( ( d & m2 ) >> 12 ) ); res.append( "==", 2 ); } return res; } private: string char_set; }; int main( int argc, char* argv[] ) { base64 b; basic_ifstream<byte> f( "favicon.ico", ios::binary ); string r = b.encode( vector<byte>( ( istreambuf_iterator<byte>( f ) ), istreambuf_iterator<byte>() ) ); copy( r.begin(), r.end(), ostream_iterator<char>( cout ) ); return 0; }
codetrans_contest
Return list of 3x3-tuples.
def get_3_3_tuple_list(self,obj,default=None): """Return list of 3x3-tuples. """ if is_sequence3(obj): return [self.get_3_3_tuple(o,default) for o in obj] return [self.get_3_3_tuple(obj,default)]
csn
Add some UI to a "utility bar" type structure.
private void setUpUtilBar() { utilBar.setLayout(new ListLayout(ListLayout.Type.FLAT, ListLayout.Alignment.RIGHT, ListLayout.Separator.NONE, false)); WTextField selectOther = new WTextField(); selectOther.setToolTip("Enter text."); utilBar.add(selectOther); utilBar.add(new WButton("Go")); utilBar.add(new WButton("A")); utilBar.add(new WButton("B")); utilBar.add(new WButton("C")); utilBar.setVisible(false); }
csn
// float32 version of math.Max
func Max(x, y float32) float32 { return float32(math.Max(float64(x), float64(y))) }
csn
def auth_request_handler(self, callback): """Specifies the authentication response handler function. :param callable callback: the auth request handler function .. deprecated """ warnings.warn("This handler is deprecated. The recommended approach to have
control over " "the authentication resource is to disable the built-in resource by " "setting JWT_AUTH_URL_RULE=None and registering your own authentication " "resource directly on your application.", DeprecationWarning, stacklevel=2) self.auth_request_callback = callback return callback
csn_ccr
public static String toJsonObject(String[] arr) { if ( arr == null ) { return null; } StringBuffer sb = new StringBuffer(); sb.append('{'); for ( String
ele : arr ) { if ( sb.length() == 1 ) { sb.append('"').append(ele).append("\":true"); } else { sb.append(",\"").append(ele).append("\":true"); } } sb.append('}'); return sb.toString(); }
csn_ccr
In this Kata, you will be given a number `n` (`n > 0`) and your task will be to return the smallest square number `N` (`N > 0`) such that `n + N` is also a perfect square. If there is no answer, return `-1` (`nil` in Clojure, `Nothing` in Haskell, `None` in Rust). ```clojure solve 13 = 36 ; because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49 solve 3 = 1 ; 3 + 1 = 4, a perfect square solve 12 = 4 ; 12 + 4 = 16, a perfect square solve 9 = 16 solve 4 = nil ``` ```csharp solve(13) = 36 //because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49 solve(3) = 1 // 3 + 1 = 4, a perfect square solve(12) = 4 // 12 + 4 = 16, a perfect square solve(9) = 16 solve(4) = -1 ``` ```haskell solve 13 = Just 36 -- because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49 solve 3 = Just 1 -- 3 + 1 = 4, a perfect square solve 12 = Just 4 -- 12 + 4 = 16, a perfect square solve 9 = Just 16 solve 4 = Nothing ``` ```python solve(13) = 36 # because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49 solve(3) = 1 # 3 + 1 = 4, a perfect square solve(12) = 4 # 12 + 4 = 16, a perfect square solve(9) = 16 solve(4) = -1 ``` More examples in test cases. Good luck!
def solve(n): for i in range(int(n**0.5), 0, -1): x = n - i**2 if x > 0 and x % (2*i) == 0: return ((n - i ** 2) // (2 * i)) ** 2 return -1
apps
// MakeMagicEndpoint creates go-kit endpoint function
func MakeMagicEndpoint(magic *Magic) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(Workload) result, err := magic.DoMagic(req) return result, err } }
csn
Render a path with locs, opts and contents block. @api private @param [Middleman::SourceFile] file The file. @param [Hash] locs Template locals. @param [Hash] opts Template options. @param [Proc] block A block will be evaluated to return internal contents. @return [String] The resulting content string. Contract IsA['Middleman::SourceFile'], Hash, Hash, Maybe[Proc] => String
def render_file(file, locs, opts, &block) _render_with_all_renderers(file[:relative_path].to_s, locs, self, opts, &block) end
csn
// ChannelBalance returns the total available channel flow across all open // channels in satoshis.
func (r *rpcServer) ChannelBalance(ctx context.Context, in *lnrpc.ChannelBalanceRequest) (*lnrpc.ChannelBalanceResponse, error) { openChannels, err := r.server.chanDB.FetchAllOpenChannels() if err != nil { return nil, err } var balance btcutil.Amount for _, channel := range openChannels { balance += channel.LocalCommitment.LocalBalance.ToSatoshis() } pendingChannels, err := r.server.chanDB.FetchPendingChannels() if err != nil { return nil, err } var pendingOpenBalance btcutil.Amount for _, channel := range pendingChannels { pendingOpenBalance += channel.LocalCommitment.LocalBalance.ToSatoshis() } return &lnrpc.ChannelBalanceResponse{ Balance: int64(balance), PendingOpenBalance: int64(pendingOpenBalance), }, nil }
csn
def merge_all_cells(cells): """ Loop through list of cells and piece them together one by one Parameters ---------- cells : list of dashtable.data2rst.Cell Returns ------- grid_table : str The final grid table """ current = 0 while len(cells) > 1: count = 0 while count < len(cells): cell1 = cells[current] cell2 = cells[count] merge_direction = get_merge_direction(cell1, cell2) if not merge_direction == "NONE":
merge_cells(cell1, cell2, merge_direction) if current > count: current -= 1 cells.pop(count) else: count += 1 current += 1 if current >= len(cells): current = 0 return cells[0].text
csn_ccr
private function resolveIDsfromESI(Collection $ids, $eseye) { // Finally, grab outstanding ids and resolve their names // using Esi. try { $eseye->setVersion('v3'); $eseye->setBody($ids->flatten()->toArray()); $names = $eseye->invoke('post', '/universe/names/'); collect($names)->each(function ($name) { // Cache the name resolution for this id for a long time. cache([$this->prefix . $name->id => $name->name], carbon()->addCentury()); $this->response[$name->id] = $name->name; UniverseName::firstOrCreate([ 'entity_id' => $name->id, ], [ 'name' => $name->name, 'category' => $name->category, ]); }); } catch (\Exception $e) { // If this fails split the ids in half and try to self referential resolve the half_chunks
// until all possible resolvable ids has processed. if ($ids->count() === 1) { // return a singleton unresolvable id as 'unknown' $this->response[$ids->first()] = trans('web::seat.unknown'); } else { //split the chunk in two $half = ceil($ids->count() / 2); //keep on processing the halfs independently, //ideally one of the halfs will process just perfect $ids->chunk($half)->each(function ($half_chunk) use ($eseye) { //this is a selfrefrencial call. $this->resolveIDsfromESI($half_chunk, $eseye); }); } } }
csn_ccr
Chef has a sequence of N$N$ integers A1,A2,...,AN$A_1, A_2, ..., A_N$. Chef thinks that a triplet of integers (i,j,k)$(i,j,k)$ is good if 1≤i<j<k≤N$1 \leq i < j < k \leq N$ and P$P$ in the following expression contains an odd number of ones in its binary representation: P=[Ai<<(⌊log2(Aj)⌋+⌊log2(Ak)⌋+2)]+[Aj<<(⌊log2(Ak)⌋+1)]+Ak$P = [ A_i<< ( \lfloor \log_2(A_j) \rfloor + \lfloor \log_2(A_k) \rfloor + 2 ) ] + [A_j << ( \lfloor \log_2(A_k) \rfloor + 1) ] + A_k$ The <<$<<$ operator is called left shift, x<<y$x << y$ is defined as x⋅2y$x \cdot 2^y$. Help the Chef finding the total number of good triplets modulo 109+7$10^9 + 7$. -----Input:----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first line of each test case contains a single integer N$N$. - The second line of each test case contains N$N$ space-separated integers A1,A2,...,AN$A_1, A_2, ..., A_N$. -----Output:----- For each test case, print a single line containing one integer, the number of good triplets modulo 109+7$10^9+7$. -----Constraints:----- - 1≤T≤103$1 \leq T \leq 10^3$ - 1≤N≤105$1\leq N \leq 10^5$ - 1≤Ai≤109$1 \leq A_i \leq 10^9$ - The sum of N$N$ over all testcases is less than 106$10^6$ -----Sample Input:----- 1 4 1 1 2 3 -----Sample Output:----- 1
from math import * t = int(input()) for _ in range(t): n = int(input()) a = [int(d) for d in input().split()] odd,even = 0,0 for i in range(n): if bin(a[i]).count("1")%2 == 1: odd += 1 else: even +=1 total = 0 if odd >= 3 and even >= 2: total += (odd*(odd-1)*(odd-2))//6 total += odd*(even*(even-1))//2 elif odd >= 3 and even < 2: total += (odd*(odd-1)*(odd-2))//6 elif 0<odd < 3 and even >= 2: total += odd*(even*(even-1))//2 print(total%(10**9+7))
apps
public function consumeOne(MessageInterface $message) { $consumeEvent = new ConsumeEvent($message); try { $this->dispatcher->dispatch(BarbeQEvents::PRE_CONSUME, $consumeEvent); $message->start(); $this->messageDispatcher->dispatch($message->getQueue(), $consumeEvent); $message->complete(); $this->adapter->onSuccess($message); $this->dispatcher->dispatch(BarbeQEvents::POST_CONSUME, $consumeEvent); } catch(\Exception $e) { $message->completeWithError();
$this->adapter->onError($message); $this->dispatcher->dispatch(BarbeQEvents::POST_CONSUME, $consumeEvent); // TODO throw new ConsumerIndigestionException("Error while consuming a message", 0, $e); } }
csn_ccr
def unindent(lines): '''Convert an iterable of indented lines into a sequence of tuples. The first element of each tuple is the indent in number of characters, and the second element is the unindented string. Args: lines: A sequence of strings representing the lines of text in a docstring. Returns:
A list of tuples where each tuple corresponds to one line of the input list. Each tuple has two entries - the first is an integer giving the size of the indent in characters, the second is the unindented text. ''' unindented_lines = [] for line in lines: unindented_line = line.lstrip() indent = len(line) - len(unindented_line) unindented_lines.append((indent, unindented_line)) return unindented_lines
csn_ccr
final public function readGuid() { $C = @unpack('V1V/v2v/N2N', $this->read(16)); list($hex) = @unpack('H*0', pack('NnnNN', $C['V'], $C['v1'], $C['v2'], $C['N1'], $C['N2'])); /* Fixes a bug in PHP versions earlier than Jan 25 2006 */ if (implode('', unpack('H*', pack('H*', 'a'))) == 'a00') {
// @codeCoverageIgnoreStart $hex = substr($hex, 0, -1); } // @codeCoverageIgnoreEnd return preg_replace('/^(.{8})(.{4})(.{4})(.{4})/', "\\1-\\2-\\3-\\4-", $hex); }
csn_ccr
public function map(array $configuration) { return [ 'driver' => $this->driver($configuration['driver']), 'host' => $configuration['host'], 'dbname' => $configuration['database'],
'user' => $configuration['username'], 'password' => $configuration['password'], 'charset' => $configuration['charset'], 'prefix' => @$configuration['prefix'] ? $configuration['prefix'] : null ]; }
csn_ccr
Accept user invitation. @param Request $request @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
public function accept(Request $request) { if (! $request->has('token')) abort(404); if (! $invitation = $this->validateToken($request->input('token'))) abort(404); return $this->showAcceptUserInvitationForm($invitation); }
csn
public static function startsWithDirectorySeparator($string, $separator = '') { if (empty($separator)) { $separator = DIRECTORY_SEPARATOR;
} return self::startsWith($string, $separator); }
csn_ccr
Try to choose the view limits intelligently.
def view_limits(self, vmin, vmax): """ Try to choose the view limits intelligently. """ b = self._transform.base if vmax < vmin: vmin, vmax = vmax, vmin if not matplotlib.ticker.is_decade(abs(vmin), b): if vmin < 0: vmin = -matplotlib.ticker.decade_up(-vmin, b) else: vmin = matplotlib.ticker.decade_down(vmin, b) if not matplotlib.ticker.is_decade(abs(vmax), b): if vmax < 0: vmax = -matplotlib.ticker.decade_down(-vmax, b) else: vmax = matplotlib.ticker.decade_up(vmax, b) if vmin == vmax: if vmin < 0: vmin = -matplotlib.ticker.decade_up(-vmin, b) vmax = -matplotlib.ticker.decade_down(-vmax, b) else: vmin = matplotlib.ticker.decade_down(vmin, b) vmax = matplotlib.ticker.decade_up(vmax, b) result = matplotlib.transforms.nonsingular(vmin, vmax) return result
csn
@Override protected void preparePaintComponent(final Request request) { super.preparePaintComponent(request); // If is an internal AJAX action, set the action type. if (isCurrentAjaxTrigger()) { AjaxOperation operation = AjaxHelper.getCurrentOperation(); if (operation.isInternalAjaxRequest()) { // Want to replace children in the target (Internal defaults to REPLACE target) operation.setAction(AjaxOperation.AjaxAction.IN); } } // Check if a custom tree needs the expanded rows checked TreeItemIdNode custom
= getCustomTree(); if (custom != null) { checkExpandedCustomNodes(); } // Make sure the ID maps are up to date clearItemIdMaps(); if (getExpandMode() == ExpandMode.LAZY) { if (AjaxHelper.getCurrentOperation() == null) { clearPrevExpandedRows(); } else { addPrevExpandedCurrent(); } } }
csn_ccr
def load_fixture(fixture_file): """ Populate the database from a JSON file. Reads the JSON file FIXTURE_FILE and uses it to populate the database. Fuxture files should consist of a dictionary mapping database names to arrays of objects to store in those databases. """ utils.check_for_local_server() local_url = config["local_server"]["url"] server = Server(local_url) fixture = json.load(fixture_file) for db_name, _items in fixture.items(): db = server[db_name] with click.progressbar( _items, label=db_name, length=len(_items) ) as items:
for item in items: item_id = item["_id"] if item_id in db: old_item = db[item_id] item["_rev"] = old_item["_rev"] if item == old_item: continue db[item_id] = item
csn_ccr
func FilteredBy(pred ResourcePredicate, rls []*metav1.APIResourceList) []*metav1.APIResourceList { result := []*metav1.APIResourceList{} for _, rl := range rls { filtered := *rl filtered.APIResources = nil for i := range rl.APIResources { if pred.Match(rl.GroupVersion, &rl.APIResources[i]) {
filtered.APIResources = append(filtered.APIResources, rl.APIResources[i]) } } if filtered.APIResources != nil { result = append(result, &filtered) } } return result }
csn_ccr
Create a new file entry in the namespace. @throws IOException if file name is invalid {@link FSDirectory#isValidToCreate(String)}. @see ClientProtocol#create(String, FsPermission, String, boolean, short, long)
void startFile(String src, PermissionStatus permissions, String holder, String clientMachine, boolean overwrite, boolean createParent, short replication, long blockSize ) throws IOException { INodeFileUnderConstruction file = startFileInternal(src, permissions, holder, clientMachine, overwrite, false, createParent, replication, blockSize); getEditLog().logSync(false); if (auditLog.isInfoEnabled()) { logAuditEvent(getCurrentUGI(), Server.getRemoteIp(), "create", src, null, file); } }
csn
def _write_parameter_file(params): """ Write the parameter file in the format that elaxtix likes. """ # Get path path = os.path.join(get_tempdir(), 'params.txt') # Define helper function def valToStr(val): if val in [True, False]: return '"%s"' % str(val).lower() elif isinstance(val, int): return str(val) elif isinstance(val, float): tmp = str(val) if not '.' in tmp: tmp += '.0' return tmp elif isinstance(val, str): return '"%s"' % val # Compile text text = '' for key in params: val = params[key] # Make a string of the values if isinstance(val, (list, tuple)): vals = [valToStr(v) for
v in val] val_ = ' '.join(vals) else: val_ = valToStr(val) # Create line and add line = '(%s %s)' % (key, val_) text += line + '\n' # Write text f = open(path, 'wb') try: f.write(text.encode('utf-8')) finally: f.close() # Done return path
csn_ccr
Stops the playing thread and close
def stop(self): """ Stops the playing thread and close """ with self.lock: self.halting = True self.go.clear()
csn
// dispatchSig launches a goroutine and closes the given stop channel // when SIGTERM, SIGHUP, or SIGINT is received.
func dispatchSig(stop chan<- error) { sigChan := make(chan os.Signal) signal.Notify( sigChan, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGINT, ) go func() { diag.Println("Waiting for signal") sig := <-sigChan diag.Printf("Received signal %v\n", sig) close(stop) }() }
csn
// Get return instance by name
func (d *Provider) Get(name string) (interface{}, error) { d.Block() if d.isCalled(name) { return nil, fmt.Errorf("%s is cyclic dependency (dependency callstack: %v)", name, append(d.callstack, name)) } if instance, exist := d.instances[name]; exist { return instance, nil } if factory, exist := d.factories[name]; exist { d.callstack = append(d.callstack, name) instance, err := factory(d) if err != nil { return nil, fmt.Errorf("%v (dependency callstack: %v)", err, d.callstack) } if instance == nil { return nil, fmt.Errorf("factory for %s return nil as instance", name) } d.callstack = d.callstack[:len(d.callstack)-1] d.clean(name) d.instances[name] = instance return instance, nil } if factory, exist := d.defaultFactories[name]; exist { d.callstack = append(d.callstack, name) instance, err := factory(d) if err != nil { return nil, fmt.Errorf("%v (dependency callstack: %v)", err, d.callstack) } if instance == nil { return nil, fmt.Errorf("default factory for %s return nil as instance", name) } d.callstack = d.callstack[:len(d.callstack)-1] if d.autoclean { delete(d.defaultFactories, name) } d.instances[name] = instance return instance, nil } return nil, fmt.Errorf("goatcore/dependency/provider: dependency %s doesn't exist", name) }
csn
def each_event(cycle=0) return enum_for(__method__, cycle) unless
block_given? EventEnumerator.new(self, cycle).each { |v, s, d, i| yield v, s, d, i } end
csn_ccr
public function parseKeyword() { $token = ''; /** * Value to be returned. * * @var Token */ $ret = null; /** * The value of `$this->last` where `$token` ends in `$this->str`. * * @var int */ $iEnd = $this->last; /** * Whether last parsed character is a whitespace. * * @var bool */ $lastSpace = false; for ($j = 1; $j < Context::KEYWORD_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) { // Composed keywords shouldn't have more than one whitespace between // keywords. if (Context::isWhitespace($this->str[$this->last])) { if ($lastSpace) { --$j; // The size of the keyword didn't increase. continue; } $lastSpace = true;
} else { $lastSpace = false; } $token .= $this->str[$this->last]; if (($this->last + 1 === $this->len || Context::isSeparator($this->str[$this->last + 1])) && $flags = Context::isKeyword($token) ) { $ret = new Token($token, Token::TYPE_KEYWORD, $flags); $iEnd = $this->last; // We don't break so we find longest keyword. // For example, `OR` and `ORDER` have a common prefix `OR`. // If we stopped at `OR`, the parsing would be invalid. } } $this->last = $iEnd; return $ret; }
csn_ccr
ManagerEvent addMember(BridgeEnterEvent event) { List<BridgeEnterEvent> remaining = null; synchronized (members) { if (members.put(event.getChannel(), event) == null && members.size() == 2) { remaining = new ArrayList<>(members.values()); } } if (remaining == null) { return null; }
logger.info("Members size " + remaining.size() + " " + event); BridgeEvent bridgeEvent = buildBridgeEvent( BridgeEvent.BRIDGE_STATE_LINK, remaining); logger.info("Bridge " + bridgeEvent.getChannel1() + " " + bridgeEvent.getChannel2()); return bridgeEvent; }
csn_ccr
def scanStoVars(self, strline): """ scan input string line, replace sto parameters with calculated results. """ for wd in strline.split(): if wd in
self.stodict: strline = strline.replace(wd, str(self.stodict[wd])) return strline
csn_ccr
Given a block of ciphertext as a string, and a gpg object, try to decrypt the cipher and return the decrypted string. If the cipher cannot be decrypted, log the error, and return the ciphertext back out.
def _decrypt_ciphertext(cipher): ''' Given a block of ciphertext as a string, and a gpg object, try to decrypt the cipher and return the decrypted string. If the cipher cannot be decrypted, log the error, and return the ciphertext back out. ''' try: cipher = salt.utils.stringutils.to_unicode(cipher).replace(r'\n', '\n') except UnicodeDecodeError: # ciphertext is binary pass cipher = salt.utils.stringutils.to_bytes(cipher) cmd = [_get_gpg_exec(), '--homedir', _get_key_dir(), '--status-fd', '2', '--no-tty', '-d'] proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False) decrypted_data, decrypt_error = proc.communicate(input=cipher) if not decrypted_data: try: cipher = salt.utils.stringutils.to_unicode(cipher) except UnicodeDecodeError: # decrypted data contains undecodable binary data pass log.warning( 'Could not decrypt cipher %s, received: %s', cipher, decrypt_error ) return cipher else: try: decrypted_data = salt.utils.stringutils.to_unicode(decrypted_data) except UnicodeDecodeError: # decrypted data contains undecodable binary data pass return decrypted_data
csn
Adds permissions classes that should exist for Jwt based authentication, if needed.
def _add_missing_jwt_permission_classes(self, view_class): """ Adds permissions classes that should exist for Jwt based authentication, if needed. """ view_permissions = list(getattr(view_class, 'permission_classes', [])) # Not all permissions are classes, some will be ConditionalPermission # objects from the rest_condition library. So we have to crawl all those # and expand them to see if our target classes are inside the # conditionals somewhere. permission_classes = [] classes_to_add = [] while view_permissions: permission = view_permissions.pop() if not hasattr(permission, 'perms_or_conds'): permission_classes.append(permission) else: for child in getattr(permission, 'perms_or_conds', []): view_permissions.append(child) for perm_class in self._required_permission_classes: if not self._includes_base_class(permission_classes, perm_class): log.warning( u"The view %s allows Jwt Authentication but needs to include the %s permission class (adding it for you)", view_class.__name__, perm_class.__name__, ) classes_to_add.append(perm_class) if classes_to_add: view_class.permission_classes += tuple(classes_to_add)
csn
protected function get_release_asset_redirect( $asset, $aws = false ) { if ( ! $asset ) { return false; } // Unset release asset url if older than 5 min to account for AWS expiration. if ( $aws && ( time() - strtotime( '-12 hours', $this->response['timeout'] ) ) >= 300 ) { unset( $this->response['release_asset_redirect'] ); } $response = isset( $this->response['release_asset_redirect'] ) ? $this->response['release_asset_redirect'] : false; if ( $this->exit_no_update( $response ) ) { return false; } if ( ! $response ) { add_action( 'requests-requests.before_redirect', [ $this,
'set_redirect' ], 10, 1 ); add_filter( 'http_request_args', [ $this, 'set_aws_release_asset_header' ] ); $url = $this->add_access_token_endpoint( $this, $asset ); wp_remote_get( $url ); remove_filter( 'http_request_args', [ $this, 'set_aws_release_asset_header' ] ); } if ( ! empty( $this->redirect ) ) { $this->set_repo_cache( 'release_asset_redirect', $this->redirect ); return $this->redirect; } return $response; }
csn_ccr
func (l *Lexer) emit(kind TokenKind)
{ l.produce(kind, l.input[l.start:l.pos]) }
csn_ccr
function BlankField(type, options) { Field.call(this, type, options); this.element = util.createElement(this.document, 'div');
this.onFieldChange = util.createEvent('BlankField.onFieldChange'); }
csn_ccr
// MessageReceived must be called by the protocol upon receiving a message
func (b *Bot) MessageReceived(channel *ChannelData, message *Message, sender *User) { command, err := parse(message.Text, channel, sender) if err != nil { b.SendMessage(channel.Channel, err.Error(), sender) return } if command == nil { b.executePassiveCommands(&PassiveCmd{ Raw: message.Text, MessageData: message, Channel: channel.Channel, ChannelData: channel, User: sender, }) return } if b.isDisabled(command.Command) { return } switch command.Command { case helpCommand: b.help(command) default: b.handleCmd(command) } }
csn
Get instance for current collection. @return \Search\Model\Filter\FilterCollectionInterface
protected function _collection() { if (!isset($this->_collections[$this->_collection])) { $this->_collections[$this->_collection] = new $this->_collectionClass($this); } return $this->_collections[$this->_collection]; }
csn
Checks And Shows Review Message
protected function maybe_prompt() { if ( ! $this->is_time() ) { return; } \add_action( 'admin_footer', array( $this, 'script' ) ); if ( false !== $this->op['notice_callback'] ) { call_user_func_array( $this->op['notice_callback'], array( &$this ) ); } else { \add_action( 'admin_notices', array( $this, 'add_notice' ) ); } }
csn
private void probe(ImmutableMember member) { LOGGER.trace("{} - Probing {}", localMember.id(), member); bootstrapService.getMessagingService().sendAndReceive( member.address(), MEMBERSHIP_PROBE, SERIALIZER.encode(Pair.of(localMember.copy(), member)), false, config.getProbeTimeout()) .whenCompleteAsync((response, error) -> { if (error == null) { updateState(SERIALIZER.decode(response)); } else { LOGGER.debug("{} - Failed to probe {}", this.localMember.id(), member, error); // Verify that the local member term has not changed and
request probes from peers. SwimMember swimMember = members.get(member.id()); if (swimMember != null && swimMember.getIncarnationNumber() == member.incarnationNumber()) { requestProbes(swimMember.copy()); } } }, swimScheduler); }
csn_ccr
func (h *httpForwarder) Accept() (net.Conn, error) { conn
:= <-h.connChan return conn, nil }
csn_ccr
private function getAdditionalTableFields() { $type = $this->eavConfig->getEntityType(\Magento\Catalog\Model\Product::ENTITY); $table = $type->getAdditionalAttributeTable(); $fullTableName = $this->getResource()->getTable($table);
$tableDesc = $this->getConnection()->describeTable($fullTableName); $tableFields = array_keys($tableDesc); return array_diff($tableFields, $this->overridenColumns); }
csn_ccr
Applying genotype calls to multi-way alignment incidence matrix :param alnfile: alignment incidence file (h5), :param gtypefile: genotype calls by GBRS (tsv), :param grpfile: gene ID to isoform ID mapping info (tsv) :return: genotyped version of alignment incidence file (h5)
def stencil(**kwargs): """ Applying genotype calls to multi-way alignment incidence matrix :param alnfile: alignment incidence file (h5), :param gtypefile: genotype calls by GBRS (tsv), :param grpfile: gene ID to isoform ID mapping info (tsv) :return: genotyped version of alignment incidence file (h5) """ alnfile = kwargs.get('alnfile') gtypefile = kwargs.get('gtypefile') grpfile = kwargs.get('grpfile') if grpfile is None: grpfile2chk = os.path.join(DATA_DIR, 'ref.gene2transcripts.tsv') if os.path.exists(grpfile2chk): grpfile = grpfile2chk else: print >> sys.stderr, '[gbrs::stencil] A group file is *not* given. Genotype will be stenciled as is.' # Load alignment incidence matrix ('alnfile' is assumed to be in multiway transcriptome) alnmat = emase.AlignmentPropertyMatrix(h5file=alnfile, grpfile=grpfile) # Load genotype calls hid = dict(zip(alnmat.hname, np.arange(alnmat.num_haplotypes))) gid = dict(zip(alnmat.gname, np.arange(len(alnmat.gname)))) gtmask = np.zeros((alnmat.num_haplotypes, alnmat.num_loci)) gtcall_g = dict.fromkeys(alnmat.gname) with open(gtypefile) as fh: if grpfile is not None: gtcall_t = dict.fromkeys(alnmat.lname) for curline in dropwhile(is_comment, fh): item = curline.rstrip().split("\t") g, gt = item[:2] gtcall_g[g] = gt hid2set = np.array([hid[c] for c in gt]) tid2set = np.array(alnmat.groups[gid[g]]) gtmask[np.meshgrid(hid2set, tid2set)] = 1.0 for t in tid2set: gtcall_t[alnmat.lname[t]] = gt else: for curline in dropwhile(is_comment, fh): item = curline.rstrip().split("\t") g, gt = item[:2] gtcall_g[g] = gt hid2set = np.array([hid[c] for c in gt]) gtmask[np.meshgrid(hid2set, gid[g])] = 1.0 alnmat.multiply(gtmask, axis=2) for h in xrange(alnmat.num_haplotypes): alnmat.data[h].eliminate_zeros() outfile = kwargs.get('outfile') if outfile is None: outfile = 'gbrs.stenciled.' + os.path.basename(alnfile) alnmat.save(h5file=outfile)
csn
selects locale based on availability of translations @param string $errorId @param string $requestedLocale @return string
private function selectLocale(string $errorId, string $requestedLocale = null): string { $properties = $this->properties(); if (null !== $requestedLocale) { if ($properties->containValue($errorId, $requestedLocale)) { return $requestedLocale; } $baseLocale = substr($requestedLocale, 0, strpos($requestedLocale, '_')) . '_*'; if ($properties->containValue($errorId, $baseLocale)) { return $baseLocale; } } if ($properties->containValue($errorId, $this->defaultLocale)) { return $this->defaultLocale; } return 'default'; }
csn
func (w *Worker) Report() map[string]interface{} { w.mu.Lock() result := map[string]interface{}{ "api-port": w.config.APIPort, "status": w.status, "ports": w.holdable.report(), } if w.config.ControllerAPIPort != 0 { result["api-port-open-delay"]
= w.config.APIPortOpenDelay result["controller-api-port"] = w.config.ControllerAPIPort } w.mu.Unlock() return result }
csn_ccr
A function that calculates the total difference between demand for an event and the slot capacity it is scheduled in.
def efficiency_capacity_demand_difference(slots, events, X, **kwargs): """ A function that calculates the total difference between demand for an event and the slot capacity it is scheduled in. """ overflow = 0 for row, event in enumerate(events): for col, slot in enumerate(slots): overflow += (event.demand - slot.capacity) * X[row, col] return overflow
csn
func (ctx *CertContext) initServerCert(host string) (err error) { if ctx.PK, err = keyman.LoadPKFromFile(ctx.PKFile); err != nil { if os.IsNotExist(err) { fmt.Printf("Creating new PK at: %s\n", ctx.PKFile) if ctx.PK, err = keyman.GeneratePK(2048); err != nil { return } if err = ctx.PK.WriteToFile(ctx.PKFile); err != nil { return fmt.Errorf("Unable to save private key: %s\n", err) } } else { return fmt.Errorf("Unable to read private key, even though
it exists: %s\n", err) } } fmt.Printf("Creating new server cert at: %s\n", ctx.ServerCertFile) ctx.ServerCert, err = ctx.PK.TLSCertificateFor(tenYearsFromToday, true, nil, "Lantern", host) if err != nil { return } err = ctx.ServerCert.WriteToFile(ctx.ServerCertFile) if err != nil { return } return nil }
csn_ccr
Pick a random location for the star making sure it does not overwrite an existing piece of text.
def _respawn(self): """ Pick a random location for the star making sure it does not overwrite an existing piece of text. """ self._cycle = randint(0, len(self._star_chars)) (height, width) = self._screen.dimensions while True: self._x = randint(0, width - 1) self._y = self._screen.start_line + randint(0, height - 1) if self._screen.get_from(self._x, self._y)[0] == 32: break self._old_char = " "
csn
python rest cookie session managment
def _get_data(self): """ Extracts the session data from cookie. """ cookie = self.adapter.cookies.get(self.name) return self._deserialize(cookie) if cookie else {}
cosqa
Add a property to be injected in the new object @param mixed $value
public function withProperty(string $property, $value): self { return new self( $this->class, $this->properties->put($property, $value), $this->injectionStrategy, $this->instanciator ); }
csn
func (s *ContainerDefinition) SetDockerLabels(v map[string]*string)
*ContainerDefinition { s.DockerLabels = v return s }
csn_ccr
function min(array) { var length = array.length; if (length === 0) { return 0; } var index = -1; var result = array[++index]; while (++index < length) {
if (array[index] < result) { result = array[index]; } } return result; }
csn_ccr
Create a new collaboration object. @param api the API connection used to make the request. @param accessibleBy the JSON object describing who should be collaborated. @param item the JSON object describing which item to collaborate. @param role the role to give the collaborators. @param notify the user/group should receive email notification of the collaboration or not. @param canViewPath the view path collaboration feature is enabled or not. @return info about the new collaboration.
protected static BoxCollaboration.Info create(BoxAPIConnection api, JsonObject accessibleBy, JsonObject item, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath) { String queryString = ""; if (notify != null) { queryString = new QueryStringBuilder().appendParam("notify", notify.toString()).toString(); } URL url; if (queryString.length() > 0) { url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString); } else { url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL()); } JsonObject requestJSON = new JsonObject(); requestJSON.add("item", item); requestJSON.add("accessible_by", accessibleBy); requestJSON.add("role", role.toJSONString()); if (canViewPath != null) { requestJSON.add("can_view_path", canViewPath.booleanValue()); } BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); request.setBody(requestJSON.toString()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); BoxCollaboration newCollaboration = new BoxCollaboration(api, responseJSON.get("id").asString()); return newCollaboration.new Info(responseJSON); }
csn
Add a new SSH public key resource to the account :param str name: the name to give the new SSH key resource :param str public_key: the text of the public key to register, in the form used by :file:`authorized_keys` files :param kwargs: additional fields to include in the API request :return: the new SSH key resource :rtype: SSHKey :raises DOAPIError: if the API endpoint replies with an error
def create_ssh_key(self, name, public_key, **kwargs): """ Add a new SSH public key resource to the account :param str name: the name to give the new SSH key resource :param str public_key: the text of the public key to register, in the form used by :file:`authorized_keys` files :param kwargs: additional fields to include in the API request :return: the new SSH key resource :rtype: SSHKey :raises DOAPIError: if the API endpoint replies with an error """ data = {"name": name, "public_key": public_key} data.update(kwargs) return self._ssh_key(self.request('/v2/account/keys', method='POST', data=data)["ssh_key"])
csn
defined depending on which selector was used
def rvm_task(name,&block) if fetch(:rvm_require_role,nil).nil? task name, &block else task name, :roles => fetch(:rvm_require_role), &block end end
csn
Open a session. @param string $path @param string $name @return bool
public function open($path, $name) { $rand = $this->psl['crypt/rand']; /* Set some variables we need later. */ $this->savePath = $path; $this->name = $name; $this->keyCookie = $name.'_secret'; /* Set current and new ID. */ if(isset($_COOKIE[$name])) { $this->currID = $_COOKIE[$name]; } else { $this->currID = null; } if($this->sessIdRegen === true || $this->currID === null) { $this->newID = $rand->str(128, 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ-_.!*#=%'); } else { $this->newID = $this->currID; } /* Set cookie with new session ID. */ $cookieParam = session_get_cookie_params(); setcookie( $name, $this->newID, $cookieParam['lifetime'], $cookieParam['path'], $cookieParam['domain'], $cookieParam['secure'], $cookieParam['httponly'] ); /* If we don't have a encryption key, create one. */ if(!isset($_COOKIE[$this->keyCookie])) { /* Create a secret used for encryption of session. */ $this->setSecret(); } else { $this->secret = base64_decode($_COOKIE[$this->keyCookie]); } return true; }
csn
func (conn *Conn) Signal(ch chan<- *Signal) {
conn.defaultSignalAction((*defaultSignalHandler).addSignal, ch) }
csn_ccr
private function instantiateGroup($group) { if ( !isset($group['instantiate'])) { return;
} foreach ($group['instantiate'] as $nickname => $className) { $this->objectRegistry->register($nickname, new $className()); } }
csn_ccr
HTTP POST required for security.
@RequestMapping( headers = {"org.apereo.portal.url.UrlType=ACTION"}, method = RequestMethod.POST) public void actionRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { final IPortalRequestInfo portalRequestInfo = this.urlSyntaxProvider.getPortalRequestInfo(request); final IPortletRequestInfo portletRequestInfo = portalRequestInfo.getTargetedPortletRequestInfo(); final IPortalUrlBuilder actionRedirectUrl; if (portletRequestInfo != null) { final IPortletWindowId targetWindowId = portletRequestInfo.getPortletWindowId(); actionRedirectUrl = this.portalUrlProvider.getPortalUrlBuilderByPortletWindow( request, targetWindowId, UrlType.RENDER); } else { final String targetedLayoutNodeId = portalRequestInfo.getTargetedLayoutNodeId(); if (targetedLayoutNodeId != null) { actionRedirectUrl = this.portalUrlProvider.getPortalUrlBuilderByLayoutNode( request, targetedLayoutNodeId, UrlType.RENDER); } else { actionRedirectUrl = this.portalUrlProvider.getDefaultUrl(request); } } // Stuff the action-redirect URL builder into the request so other code can use it during // request processing this.portalUrlProvider.convertToPortalActionUrlBuilder(request, actionRedirectUrl); if (portletRequestInfo != null) { final IPortletWindowId targetWindowId = portletRequestInfo.getPortletWindowId(); try { this.portletExecutionManager.doPortletAction(targetWindowId, request, response); } catch (RuntimeException e) { this.logger.error( "Exception thrown while executing portlet action for: " + portletRequestInfo, e); // TODO this should be a constant right? actionRedirectUrl.setParameter("portletActionError", targetWindowId.toString()); } } sendRedirect(actionRedirectUrl, response); }
csn
Recurse through the provided json object, looking for strings that are encrypted @param obj @returns {*}
function containsEncryptedData(obj) { var foundEncrypted = false; if (_.isString(obj)) { foundEncrypted = isEncrypted(obj); } else if (_.isArray(obj)) { for (var i = 0; i < obj.length; i++) { foundEncrypted = foundEncrypted || containsEncryptedData(obj[i]); } } else if (_.isObject(obj)) { for (var key in obj) { foundEncrypted = foundEncrypted || containsEncryptedData(obj[key]); } } return foundEncrypted; }
csn
Deploy a WampServer @return IoServer
private function startWampServer() { if (! $this->serverInstance instanceof RatchetWampServer) { throw new \Exception("{$this->class} must be an instance of ".RatchetWampServer::class." to create a Wamp server"); } // Decorate the server instance with a WampServer $this->serverInstance = new WampServer($this->serverInstance); return $this->bootWebSocketServer(true); }
csn
public function get_activities() { $modinfo = get_fast_modinfo($this->course); $result = array(); foreach ($modinfo->get_cms() as $cm) { if ($cm->completion !=
COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) { $result[$cm->id] = $cm; } } return $result; }
csn_ccr