query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
def handle_deletions(self):
"""
Manages handling deletions of objects that were previously managed by the initial data process but no longer
managed. It does so by mantaining a list of receipts for model objects that are registered for deletion on
each round of initial data processing. A... |
registered_for_deletion_receipts, ['model_obj_type_id', 'model_obj_id'], update_fields=['register_time'])
# Delete all receipts and their associated model objects that weren't updated
for receipt in RegisteredForDeletionReceipt.objects.exclude(register_time=now):
try:
... | csn_ccr |
func AddMultiple(cookies []*http.Cookie) p.Plugin {
return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {
for _, cookie | := range cookies {
ctx.Request.AddCookie(cookie)
}
h.Next(ctx)
})
} | csn_ccr |
def get_off_ang(src, rec, nsrc, nrec, verb):
r"""Get depths, offsets, angles, hence spatial input parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
-----... | Angles
"""
global _min_off
# Pre-allocate off and angle
off = np.empty((nrec*nsrc,))
angle = np.empty((nrec*nsrc,))
# Coordinates
# Loop over sources, append them one after another.
for i in range(nsrc):
xco = rec[0] - src[0][i] # X-coordinates [m]
yco = rec[1] -... | csn_ccr |
func (sys *PolicySys) refresh(objAPI ObjectLayer) error {
buckets, err := objAPI.ListBuckets(context.Background())
if err != nil {
logger.LogIf(context.Background(), err)
return err
}
sys.removeDeletedBuckets(buckets)
for _, bucket := range buckets {
config, err := objAPI.GetBucketPolicy(context.Background()... |
}
// This part is specifically written to handle migration
// when the Version string is empty, this was allowed
// in all previous minio releases but we need to migrate
// those policies by properly setting the Version string
// from now on.
if config.Version == "" {
logger.Info("Found in-consistent ... | csn_ccr |
def find_plugins():
"""Locate and initialize all available plugins.
"""
plugin_dir = os.path.dirname(os.path.realpath(__file__))
plugin_dir = | os.path.join(plugin_dir, "plugins")
plugin_files = [x[:-3] for x in os.listdir(plugin_dir) if x.endswith(".py")]
sys.path.insert(0, plugin_dir)
for plugin in plugin_files:
__import__(plugin) | csn_ccr |
Url encode a value.
@param value the value to encode
@param encoding the encoding
@return the encoded value | @SneakyThrows
public static String urlEncode(final String value, final String encoding) {
return URLEncoder.encode(value, encoding);
} | csn |
Determine whether the text nodes contain similar values
@param control
@param test
@return true if text nodes are similar, false otherwise | protected boolean similar(Text control, Text test) {
if (control == null) {
return test == null;
} else if (test == null) {
return false;
}
return control.getNodeValue().equals(test.getNodeValue());
} | csn |
protected function shouldBeDelayed(): bool
{
if ($this->job && \is_null($this->model)) {
$this->release(10);
| return true;
}
return false;
} | csn_ccr |
private function convertToExtendedFieldQuery()
{
$this->fieldModel = $this->dispatcher->getContainer()->get('mautic.lead.model.field');
$this->selectParts = $this->query->getQueryPart('select');
$this->orderByParts = $this->query->getQueryPart('orderBy');
$this->groupByParts = $th... | // }
$this->extendedFields = $this->fieldModel->getExtendedFields();
}
$this->alterSelect();
if (method_exists($this->event, 'getQuery')) { // identify ReportQueryEvent instance in backwards compatible way
$this->alterOrderBy();
}
$this->alterGr... | csn_ccr |
// newUnsucessDest returns a new UnsucessDest constructed from a UnSme struct | func newUnsucessDest(p pdufield.UnSme) UnsucessDest {
unDest := UnsucessDest{}
unDest.AddrTON, _ = p.Ton.Raw().(uint8) // if there is an error default value will be set
unDest.AddrNPI, _ = p.Npi.Raw().(uint8)
unDest.Address = string(p.DestAddr.Bytes())
unDest.Error = pdu.Status(binary.BigEndian.Uint32(p.ErrCode.By... | csn |
protected function getDefaultConfigurationLibrary($magentoEdition, $entityTypeCode)
{
// query whether or not, a default configuration file for the passed entity type is available
if (isset($this->defaultConfigurations[$edition = strtolower($magentoEdition)])) {
if (isset($this->default... | // throw an exception, if the passed entity type is not supported
throw new \Exception(
sprintf(
'Entity Type Code \'%s\' not supported by entity type code \'%s\' (MUST be one of catalog_product, catalog_category or eav_attribute)',
$edition,
... | csn_ccr |
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the re... | """
Codeforces Contest 260 Div 1 Problem B
Author : chaotic_iak
Language: Python 3.3.4
"""
def main():
n,k = read()
s = set()
for i in range(n): s.add(read(0))
s = list(s)
s.sort()
s = treeify(s)
res = solve(s)
if res == 0: # neither: second player win
print("Second")
if r... | apps |
Gets the passwordCredentials associated with a service principal.
@param object_id [String] The object ID of the service principal.
@param custom_headers [Hash{String => String}] A hash of custom headers that
will be added to the HTTP request.
@return [PasswordCredentialListResult] operation results. | def list_password_credentials(object_id, custom_headers:nil)
response = list_password_credentials_async(object_id, custom_headers:custom_headers).value!
response.body unless response.nil?
end | csn |
// Retrieve The item price that an account is restricted to. | func (r Account) GetPriceRestrictions() (resp []datatypes.Product_Item_Price_Account_Restriction, err error) {
err = r.Session.DoRequest("SoftLayer_Account", "getPriceRestrictions", nil, &r.Options, &resp)
return
} | csn |
// buildInformers creates all the informer factories. | func (sdn *OpenShiftSDN) buildInformers() error {
kubeConfig, err := configapi.GetKubeConfigOrInClusterConfig(sdn.NodeConfig.MasterKubeConfig, sdn.NodeConfig.MasterClientConnectionOverrides)
if err != nil {
return err
}
kubeClient, err := kubernetes.NewForConfig(kubeConfig)
if err != nil {
return err
}
netwo... | csn |
The built-in print function for Python class instances is not very entertaining.
In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (a... | def show_me(instname):
attrs = sorted(instname.__dict__.keys())
if len(attrs) == 1:
attrs = attrs[0]
else:
attrs = '{} and {}'.format(', '.join(attrs[:-1]), attrs[-1])
return 'Hi, I\'m one of those {}s! Have a look at my {}.'\
.format(instname.__class__.__name__, attrs)
| apps |
func (db *BytesConnectionRedis) Close() error {
if db.closed {
db.Debug("Close() called on a closed connection")
return nil
}
db.Debug("Close()")
| db.closed = true
safeclose.Close(db.closeCh)
if db.client != nil {
err := safeclose.Close(db.client)
if err != nil {
return fmt.Errorf("Close() encountered error: %s", err)
}
}
return nil
} | csn_ccr |
Remove the current notebook from the list of paired notebooks | def drop_paired_notebook(self, path):
"""Remove the current notebook from the list of paired notebooks"""
if path not in self.paired_notebooks:
return
fmt, formats = self.paired_notebooks.pop(path)
prev_paired_paths = paired_paths(path, fmt, formats)
for alt_path, _ ... | csn |
public TrmClientAttachRequest createNewTrmClientAttachRequest() throws MessageCreateFailedException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createNewTrmClientAttachRequest");
TrmClientAttachRequest msg = null;
try {
msg = new TrmClientAttachRequestImpl();
... | as JsMsgObject will already have done so */
// No FFDC code needed
throw new MessageCreateFailedException(e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createNewTrmClientAttachRequest");
return msg;
} | csn_ccr |
Returns the MD5 hash of the input string
@param input Input string
@return String The md5 hash of the input string
@throws HibiscusException | public static String getMD5Hash(final String input) throws HibiscusException {
String hashValue = null;
try {
final MessageDigest messageDigest = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM_MD5);
byte[] md5Hash = new byte[BYTE_LENGTH_MD5];
messageDigest.up... | csn |
Parse arguments of script. | def parse_arguments(args=sys.argv[1:]):
"""Parse arguments of script."""
cmd_description = "Download tracklistings for BBC radio shows.\n\n" \
"Saves to a text file, tags audio file or does both.\n" \
"To select output file, filename " \
"must bo... | csn |
Returns an array of Collection instances which use the given storage
@param StorageInterface $storage
@return array<CollectionInterface> | public function getCollectionsByStorage(StorageInterface $storage)
{
$this->initialize();
$collections = [];
foreach ($this->collections as $collectionName => $collection) {
/** @var CollectionInterface $collection */
if ($collection->getStorage() === $storage) {
... | csn |
Assignment submission is processed before grading.
@param moodleform|null $mform If validation failed when submitting this form - this is the moodleform.
It can be null.
@return bool Return false if the validation fails. This affects which page is displayed next. | protected function process_submit_for_grading($mform, $notices) {
global $CFG;
require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
require_sesskey();
if (!$this->submissions_open()) {
$notices[] = get_string('submissionsclosed', 'assign');
ret... | csn |
function compact(array) {
const aResult = [];
for (let idx = 0, len = array.length; idx < len; idx++) {
| if (array[idx]) { aResult.push(array[idx]); }
}
return aResult;
} | csn_ccr |
Function used internally to generate functions to format complex
valued data. | def mk_complex_format_func(fmt):
"""
Function used internally to generate functions to format complex
valued data.
"""
fmt = fmt + u"+i" + fmt
def complex_format_func(z):
return fmt % (z.real, z.imag)
return complex_format_func | csn |
public static URI buildURI(String urlTemplate, Map<String, String> keys, Map<String, String> queryParams) {
// Compute base url
String url = urlTemplate;
if (keys != null && keys.size() != 0) {
url = StrSubstitutor.replace(urlTemplate, keys);
}
try {
URIBuilder uriBuilder = new URIBuild... | for (Map.Entry<String, String> entry : queryParams.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
}
}
return uriBuilder.build();
} catch (URISyntaxException e) {
throw new RuntimeException("Fail to build uri", e);
}
} | csn_ccr |
// SetBackgroundColor sets the box's background color. | func (b *Box) SetBackgroundColor(color tcell.Color) *Box {
b.backgroundColor = color
return b
} | csn |
The alphabetized kata
---------------------
Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed!
The input is restricted to contain no numerals and only words containing ... | def alphabetized(s):
return "".join(sorted(filter(str.isalpha, s),key=str.lower))
| apps |
public function deleteNode($node)
{
$target_pos = $node->getPosition();
$this->rewind();
$pos = 0;
// Omit target node and adjust pos of remainder
$done = false;
try {
while ($n = $this->current()) {
if ($pos == $target_pos && !$done) {
... | $done = true;
$this->next();
$this->offsetUnset($pos);
} elseif ($pos >= $target_pos) {
$n->setPosition($pos);
$pos++;
$this->next();
} else {
$pos++;
... | csn_ccr |
Convert input data for storing in the database | private function convert_save_data($save_data, $record = array())
{
$out = array();
$words = '';
// copy values into vcard object
$vcard = new rcube_vcard($record['vcard'] ?: $save_data['vcard'], RCUBE_CHARSET, false, $this->vcard_fieldmap);
$vcard->reset();
// don'... | csn |
def script():
"""Run the command-line script."""
parser = argparse.ArgumentParser(description="Print all textual tags of one or more audio files.")
parser.add_argument("-b", "--batch", help="disable user interaction", action="store_true")
parser.add_argument("file", nargs="+", help="file(s) to print tag... | if len(audioFile.unsupported) > 0:
print('Unsupported tag elements: ' + "; ".join(audioFile.unsupported))
if sys.version_info[0] == 2:
inputFunction = raw_input
else:
inputFunction = input
if not args.batch and inputFunction("remove unsup... | csn_ccr |
how to detect mouse click in the graphic window in python | def on_mouse_motion(self, x, y, dx, dy):
"""
Pyglet specific mouse motion callback.
Forwards and traslates the event to the example
"""
# Screen coordinates relative to the lower-left corner
# so we have to flip the y axis to make this consistent with
# other wind... | cosqa |
def is_valid_email(self):
"""A bool value that indicates whether the address is a valid
email address.
Note that the check is done be matching to the regular expression
| at Email.re_email which is very basic and far from covering end-cases...
"""
return bool(self.address and Email.re_email.match(self.address)) | csn_ccr |
public static function saveData(Registry $syncdata)
{
$db = Factory::getDBO();
$data = new stdClass;
$data->syncdata = $syncdata->toString();
$data->syncid = $syncdata->get('syncid');
$data->time_start = | time();
$data->action = $syncdata->get('action');
$db->insertObject('#__jfusion_sync', $data);
} | csn_ccr |
method to save the tags of an attachment
@param Attachments\Model\Entity\Attachment $attachment the attachment entity
@param array $tags array of tags
@return bool | public function saveTags($attachment, $tags)
{
$newTags = [];
foreach ($tags as $tag) {
if (isset($this->config('tags')[$tag])) {
$newTags[] = $tag;
if ($this->config('tags')[$tag]['exclusive'] === true) {
$this->_clearTag($attachment, ... | csn |
detect the date created on a file with python | def get_creation_datetime(filepath):
"""
Get the date that a file was created.
Parameters
----------
filepath : str
Returns
-------
creation_datetime : datetime.datetime or None
"""
if platform.system() == 'Windows':
return datetime.fromtimestamp(os.path.getctime(filepa... | cosqa |
private FilesystemIteratorRule getBestRule(final String filename) {
String longestPrefix = null;
FilesystemIteratorRule rule = null;
// First search the path and all of its parents for the first regular rule
String path = filename;
while(true) {
// Check the current path for an exact match
//System.out.... | length of this filename, it will at some threshold
// be faster to do a map lookup for each possible length of the string.
// Would also only need to look down to longestPrefix
for(Map.Entry<String,FilesystemIteratorRule> entry : prefixRules.entrySet()) {
String prefix = entry.getKey();
if... | csn_ccr |
Start MongoDB on demand before running your tests.
@example
describe('my app', function(){
before(require('mongodb-runner/mocha/before');
it('should connect', function(done){
require('mongodb').connect('mongodb://localhost:27017/', done);
});
});
@param {Object|Function} [opts] - options or the `done` callback.
@retur... | function mongodb_runner_mocha_before(opts) {
if (typeof opts === 'function') {
// So you can just do `before(require('mongodb-runner/mocha/before'));`
return mongodb_runner_mocha_before({}).apply(this, arguments);
}
opts = opts || {};
defaults(opts, {
port: 27017,
timeout: 10000,
slow: 10000... | csn |
public String[] plan(String aam, String uniqueOfferingsTosca) throws ParsingException, IOException {
log.info("Planning for aam: \n" + aam);
//Get offerings
log.info("Getting Offeing Step: Start");
Map<String, Pair<NodeTemplate, String>> offerings = parseOfferings(uniqueOfferingsTosca)... | Matchmaker mm = new Matchmaker();
Map<String, HashSet<String>> matchingOfferings = mm.match(ToscaSerializer.fromTOSCA(aam), offerings);
log.info("Matchmaking Step: Complete");
//Optimize
String mmOutput = "";
try {
mmOutput = generateMMOutput2(matchingOfferings, of... | csn_ccr |
public boolean truncate(long zxid) throws IOException {
FileTxnIterator itr = new FileTxnIterator(this.logDir, zxid);
PositionInputStream input = itr.inputStream;
long pos = input.getPosition();
// now, truncate at the current position
RandomAccessFile raf=new RandomAccessFile(it... | while(itr.goToNextLog()) {
if (!itr.logFile.delete()) {
LOG.warn("Unable to truncate " + itr.logFile);
}
}
return true;
} | csn_ccr |
public Collection<RepositoryResource> getMatchingResources(final FilterPredicate... predicates) throws RepositoryBackendException {
Collection<RepositoryResource> resources = cycleThroughRepositories(new RepositoryInvoker<RepositoryResource>() {
@Override
| public Collection<RepositoryResource> performActionOnRepository(RepositoryConnection connection) throws RepositoryBackendException {
return connection.getMatchingResources(predicates);
}
});
return resources;
} | csn_ccr |
public function getArgInfoName(ClassDefinition $classDefinition = null)
{
if (null != $classDefinition) {
return sprintf(
'arginfo_%s_%s_%s',
strtolower($classDefinition->getCNamespace()),
strtolower($classDefinition->getName()),
| strtolower($this->getName())
);
}
return sprintf('arginfo_%s', strtolower($this->getInternalName()));
} | csn_ccr |
Extend a query with a list of two-tuples. | def add_params_to_qs(query, params):
"""Extend a query with a list of two-tuples."""
if isinstance(params, dict):
params = params.items()
queryparams = urlparse.parse_qsl(query, keep_blank_values=True)
queryparams.extend(params)
return urlencode(queryparams) | csn |
func ToQuicError(err error) *QuicError {
switch e := err.(type) {
case *QuicError:
return e
case ErrorCode:
| return Error(e, "")
}
return Error(InternalError, err.Error())
} | csn_ccr |
public function setTableName($tableName) {
$this->query = str_replace($this->tableName, $tableName, $this->query);
$this->dummyQuery | = str_replace($this->tableName, $tableName, $this->dummyQuery);
$this->tableName = $tableName;
return $this;
} | csn_ccr |
public function createJsTranslation($content, $langcode = null)
{
$extracted = $this->parseJs($content);
if (empty($extracted)) {
return false;
}
$file = $this->getContextJsFile($langcode);
| $translations = $this->loadTranslation($this->getCommonFile($langcode));
foreach ($extracted as $string) {
$this->addTranslation($string, $translations, $file);
}
return true;
} | csn_ccr |
python instance into list | def as_list(self):
"""Return all child objects in nested lists of strings."""
return [self.name, self.value, [x.as_list for x in self.children]] | cosqa |
public function getOffensivenessOfWeaponlike(WeaponlikeCode $weaponlikeCode): int
{
| return $this->tables->getWeaponlikeTableByWeaponlikeCode($weaponlikeCode)->getOffensivenessOf($weaponlikeCode);
} | csn_ccr |
function(e) {
var DOM = YAHOO.util.Dom;
this.logger.log(this.id + " endDrag");
var lel = this.getEl();
var del = this.getDragEl();
// Show the drag frame briefly so we can get its position
// del.style.visibility = "";
DOM.setStyle(del, "visibility", "");
| // Hide the linked element before the move to get around a Safari
// rendering bug.
//lel.style.visibility = "hidden";
DOM.setStyle(lel, "visibility", "hidden");
YAHOO.util.DDM.moveToEl(lel, del);
//del.style.visibility = "hidden";
DOM.setStyle(del, "visibility"... | csn_ccr |
// update brings the VersionList up to date with file. It returns the updated
// VersionList, a potentially removed old FileVersion and its index, as well as
// the index where the new FileVersion was inserted. | func (vl VersionList) update(folder, device []byte, file protocol.FileInfo, t readOnlyTransaction) (_ VersionList, removedFV FileVersion, removedAt int, insertedAt int) {
vl, removedFV, removedAt = vl.pop(device)
nv := FileVersion{
Device: device,
Version: file.Version,
Invalid: file.IsInvalid(),
}
i := 0
... | csn |
public static Hashtable<String, Object> getCustomCredentials(Subject callSubject, String cacheKey) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "getCustomCredentials", cacheKey);
}
if (callSubject == null || cacheKey == null) {
if (Tra... |
Hashtable<String, Object> cred = (Hashtable<String, Object>) AccessController.doPrivileged(action);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "getCustomCredentials", objectId(cred));
}
return cred;
} | csn_ccr |
public static List<NetFlowV9BaseRecord> parseRecords(ByteBuf bb, Map<Integer, NetFlowV9Template> cache, NetFlowV9OptionTemplate optionTemplate) {
List<NetFlowV9BaseRecord> records = new ArrayList<>();
int flowSetId = bb.readUnsignedShort();
int length = bb.readUnsignedShort();
int end = ... | final ImmutableMap.Builder<Integer, Object> scopes = ImmutableMap.builder();
for (NetFlowV9ScopeDef def : optionTemplate.scopeDefs()) {
int t = def.type();
int len = def.length();
long l = 0;
for (int i = 0;... | csn_ccr |
how to evaluate if strings are equal python | def indexes_equal(a: Index, b: Index) -> bool:
"""
Are two indexes equal? Checks by comparing ``str()`` versions of them.
(AM UNSURE IF THIS IS ENOUGH.)
"""
return str(a) == str(b) | cosqa |
func (s *serverConfig) SetCacheConfig(drives, exclude []string, expiry int, maxuse int) {
s.Cache.Drives = drives
s.Cache.Exclude = | exclude
s.Cache.Expiry = expiry
s.Cache.MaxUse = maxuse
} | csn_ccr |
Check that a signature is valid against a public key.
@param string $signature
@param string $data
@param string $publicKey
@return bool
@throws ApiException
@api | public function checkSignature(string $signature, string $data, string $publicKey): bool
{
return $this->getJson([
'q' => 'checkSignature',
'signature' => $signature,
'data' => $data,
'public_key' => $publicKey,
]);
} | csn |
Make a cursor from the specific row.
@param Query $query
@param mixed $row
@return int[]|string[] | protected function makeCursor(Query $query, $row)
{
$fields = [];
foreach ($query->orders() as $order) {
$fields[$order->column()] = $this->field($row, $order->column());
}
return $fields;
} | csn |
protected String getWebSocketURL(ChannelHandlerContext ctx, HttpRequest req) {
boolean isSecure = ctx.pipeline().get(SslHandler.class) != null;
| return (isSecure ? SCHEME_SECURE_WEBSOCKET : SCHEME_WEBSOCKET) + req.getHeaders().get(HttpHeaderNames.HOST) + req.getUri() ;
} | csn_ccr |
public final int getUint8(final int pos) {
if (pos >= limit || pos < 0) throw new IllegalArgumentException("limit excceed: | " + pos);
return 0xff & buffer[origin + pos];
} | csn_ccr |
public function declinePayment($orderId)
{
/**
* Loads order to validate.
*/
$this
->paymentBridge
->findOrder($orderId);
/**
* Order Not found Exception must be thrown just here.
*/
if (!$this->paymentBridge->getOrder()) {... |
*/
$this
->paymentEventDispatcher
->notifyPaymentOrderFail(
$this->paymentBridge,
$this
->methodFactory
->create()
);
return $this;
} | csn_ccr |
public function getLogger() {
if ($this->logger) {
return $this->logger;
}
| $this->setLogger(CoreLib\getLogger());
return $this->logger;
} | csn_ccr |
func New(rootLogger *logrus.Logger, cfg *config.Gateway, r *Router) *Gateway {
logger := rootLogger.WithFields(logrus.Fields{"prefix": "gateway"})
cache, _ := lru.New(5000)
gw := &Gateway{
Channels: make(map[string]*config.ChannelInfo),
Message: r.Message,
Router: r,
Bridges: make(map[string]*bridge.Bri... | Config: r.Config,
Messages: cache,
logger: logger,
}
if err := gw.AddConfig(cfg); err != nil {
logger.Errorf("Failed to add configuration to gateway: %#v", err)
}
return gw
} | csn_ccr |
Finds a document by its identifier
@param string|object $id The identifier
@param int $lockMode
@param int $lockVersion
@param array $options
@throws Mapping\MappingException
@throws LockException
@throws UserDeactivatedException
@return null | UserInterface | public function find($id, $lockMode = \Doctrine\ODM\MongoDB\LockMode::NONE, $lockVersion = null, array $options = [])
{
return $this->assertEntity(parent::find($id, $lockMode, $lockVersion), $options);
} | csn |
public function set($index, $newValue) {
if (!$this->offsetSet($index, $newValue)) {
| $this->append($newValue);
}
return $this;
} | csn_ccr |
func IsSubpath(path, root string) bool {
path, err := filepath.Abs(filepath.Clean(path))
if err != nil {
return false
}
root, err = filepath.Abs(filepath.Clean(root))
if err != nil {
return false
}
if root == path { |
return true
}
if root[len(root)-1] != filepath.Separator {
root += string(filepath.Separator)
}
return strings.HasPrefix(path, root)
} | csn_ccr |
public function appendTokens(Tokenizer $new_tokens)
{
$this->tokens = array_merge($this->tokens, | $new_tokens->asArray());
$this->rewind();
return $this;
} | csn_ccr |
// SetUserIdentity sets the UserIdentity field's value. | func (s *Record) SetUserIdentity(v *Identity) *Record {
s.UserIdentity = v
return s
} | csn |
Remove a Revoked Certificate Extension
@param string $serial
@param string $id
@access public
@return bool | function removeRevokedCertificateExtension($serial, $id)
{
if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates'))) {
if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) {
return $this->_removeExtension($id, "tbsCertList/rev... | csn |
Unsubscribe object from all events
@param object $obj Subscriber
@return boolean Success | public function unsubFromAll($obj)
{
foreach ($this->events as $event) {
$event->unsub($obj);
}
return true;
} | csn |
Adjust a feature's location when flipping DNA.
:param feature: The feature to flip.
:type feature: coral.Feature
:param parent_len: The length of the sequence to which the feature belongs.
:type parent_len: int | def _flip_feature(self, feature, parent_len):
'''Adjust a feature's location when flipping DNA.
:param feature: The feature to flip.
:type feature: coral.Feature
:param parent_len: The length of the sequence to which the feature belongs.
:type parent_len: int
'''
copy = feature.copy()
... | csn |
public function liftEmbargo()
{
$query = $this->getEntityManager()
->createQuery('SELECT e.id, e.embargoed FROM '.$this->getEntityName().' e WHERE e.status = \'Embargoed\' AND DATE_DIFF(CURRENT_DATE(), e.embargoed) >= 0');
$embargoed = $query->getResult();
if (empty($embargoed))... | return $entry['id'];
}, $updated);
if (empty($ids)) {
return;
}
$query = $this->getEntityManager()
->createQuery('UPDATE '.$this->getEntityName().' e SET e.status = \'usable\' WHERE e.id IN (' . implode(',', $ids) . ')');
$query->getResult();
} | csn_ccr |
func loadModulesHcl(list *ast.ObjectList) ([]*Module, error) {
if err := assertAllBlocksHaveNames("module", list); err != nil {
return nil, err
}
list = list.Children()
if len(list.Items) == 0 {
return nil, nil
}
// Where all the results will go
var result []*Module
// Now go over all the types and their... | if o := listVal.Filter("version"); len(o.Items) > 0 {
err = hcl.DecodeObject(&version, o.Items[0].Val)
if err != nil {
return nil, fmt.Errorf(
"Error parsing version for %s: %s",
k,
err)
}
}
var providers map[string]string
if o := listVal.Filter("providers"); len(o.Items) > 0 {
e... | csn_ccr |
function () {
if (this.showing && this.hasNode() && this.activator) {
this.resetPositioning();
this.activatorOffset = this.getPageOffset(this.activator);
var innerWidth = this.getViewWidth();
var innerHeight = this.getViewHeight();
//These are the view "flush boundaries"
var topFlushPt = this.vertF... | never
//position a popup where there isn't enough room for it.
//Rule 3 - Popup Size based positioning
var clientRect = this.getBoundingRect(this.node);
//if the popup is wide then use vertical positioning
if (clientRect.width > this.widePopup) {
if (this.applyVerticalPositioning()){
return;
... | csn_ccr |
python prettyxml remove carrige returns | def pp_xml(body):
"""Pretty print format some XML so it's readable."""
pretty = xml.dom.minidom.parseString(body)
return pretty.toprettyxml(indent=" ") | cosqa |
Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
Example 1:
Input: s = "eleetminicoworoep"
Output: 13
Explanation: The longest substring is "leetminicowor" which contains two each of th... | class Solution:
def findTheLongestSubstring(self, s: str) -> int:
s = s + 'a'
bits, dp = {'a':0,'e':1,'i':2,'o':3,'u':4}, {0:-1}
res = 0
key = 0
for i, char in enumerate(s):
if char in bits:
if key in dp:
res = m... | apps |
public function removeUnwantedModuleMetaboxes($postType)
{
$publicPostTypes = array_keys(\Municipio\Helper\PostType::getPublic());
$publicPostTypes[] = 'page';
if | (!in_array($postType, $publicPostTypes)) {
// Navigation settings
remove_meta_box('acf-group_56d83cff12bb3', $postType, 'side');
// Display settings
remove_meta_box('acf-group_56c33cf1470dc', $postType, 'side');
}
} | csn_ccr |
Constructs a surface polyline.
@alias SurfacePolyline
@constructor
@augments SurfaceShape
@classdesc Represents a polyline draped over the terrain surface.
<p>
SurfacePolyline uses the following attributes from its associated shape attributes bundle:
<ul>
<li>Draw outline</li>
<li>Outline color</li>
<li>Outline width</... | function (locations, attributes) {
if (!locations) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "SurfacePolyline", "constructor",
"The specified locations array is null or undefined."));
}
SurfaceShape.... | csn |
// Returns identation spaces for end of block character | func (rule *Rule) indentEndBlock() string {
result := ""
for i := 0; i < (rule.EmbedLevel * indentSpace); i++ {
result += " "
}
return result
} | csn |
def check_datasource_perms(self, datasource_type=None, datasource_id=None):
"""
Check if user can access a cached response from explore_json.
This function takes `self` since it must have the same signature as the
the decorated method.
"""
form_data = get_form_data()[0]
datasource_id, data... | viz_obj = get_viz(
datasource_type=datasource_type,
datasource_id=datasource_id,
form_data=form_data,
force=False,
)
security_manager.assert_datasource_permission(viz_obj.datasource) | csn_ccr |
func (m *HTTPResponseProperties) Validate() error {
if m == nil {
return nil
}
{
tmp := m.GetResponseCode()
if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return HTTPResponsePropertiesValidationError{
field: "ResponseCode",
reason: "... | }
}
// no validation rules for ResponseHeadersBytes
// no validation rules for ResponseBodyBytes
// no validation rules for ResponseHeaders
// no validation rules for ResponseTrailers
// no validation rules for ResponseCodeDetails
return nil
} | csn_ccr |
this format preprocessor is far from being full markdown, it is built to be usable for tipograph readme in the future, this may grow into full markdown support | function dummyMarkdown() {
var codeBlock = /^```/;
var quoteBlock = /^>/;
var listBlock = /^\* /;
var commentInline = '<!--.*-->';
var codeInline = '`.+`';
function split(content) {
var pattern = new RegExp([commentInline, codeInline].join('|'), 'g');
var result = null;
... | csn |
private void closeQuietly(Closeable c) {
if (c != null) {
try {
| c.close();
} catch (Throwable t) {
logger.warn("Error closing, ignoring", t);
}
}
} | csn_ccr |
Copies a file to a target directory | def copy_file_if_missing(file, to_directory)
unless File.exists? File.join(to_directory, File.basename(file))
FileUtils.cp(file, to_directory)
end
end | csn |
public static function loadFromPlainList($num, array $positions)
{
$rPositions = [];
foreach ($positions as $pos) {
| $rPositions[$pos->generated->column] = $pos;
}
return new self($num, $rPositions);
} | csn_ccr |
func NewCiliumEndpointInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { |
return NewFilteredCiliumEndpointInformer(client, namespace, resyncPeriod, indexers, nil)
} | csn_ccr |
how to set axis range on graphs in python | def ylim(self, low, high, index=1):
"""Set yaxis limits.
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart
"""
self.layout['yaxis' + str(index)]['range'] = [low, high]
return sel... | cosqa |
def _check_unused_kwargs(self, kwargs):
""" Call this at the end of call module to check if all the kwargs have
been used. Assumes kwargs were extracted using pop.
"""
if len(kwargs.keys()) | != 0:
unused = ""
for k in kwargs.keys():
unused += "'%s', "%k
if unused[-2:] == ", ": # get rid of trailing comma
unused = unused[:-2]
raise Exception('Unused keys in kwargs: %s'%unused) | csn_ccr |
Iterate internal Routes array
Provides a unified method for iterating the Routes array with PHP
functions, 'next', 'prev', 'current', and 'end'. Returns the Route on the
position that is desired, if no Route is found, false is returned.
@param string $function Function name for array iteration
@return \SlaxWeb\Router... | protected function iterateRoutes(string $function)
{
if (($route = $function($this->routes)) !== false) {
$this->currentRoute = $route;
return $this->currentRoute;
}
return false;
} | csn |
Creates a local ssh key, if it doesn't exist already, and uploads it to Github. | def _github_create_ssh_key(cls):
"""Creates a local ssh key, if it doesn't exist already, and uploads it to Github."""
try:
login = cls._user.login
pkey_path = '{home}/.ssh/{keyname}'.format(
home=os.path.expanduser('~'),
keyname=settings.GITHUB_SS... | csn |
Sets the metric name and tags of this batch. This method only need be
called if there is a desire to reuse the data structure after the data has
been flushed. This will reset all cached information in this data structure.
@throws IllegalArgumentException if the metric name is empty or contains
illegal characters or if ... | @Override
public void setSeries(final String metric, final Map<String, String> tags) {
IncomingDataPoints.checkMetricAndTags(metric, tags);
try {
row_key = IncomingDataPoints.rowKeyTemplate(tsdb, metric, tags);
RowKey.prefixKeyWithSalt(row_key);
reset();
}
catch (RuntimeException e) ... | csn |
Process the event onGetGroupList and sets a formatted array of groups the user belongs to.
@param string $phone The phone number (jid ) of the user
@param array $groupArray Array with details of all groups user eitehr belongs to or owns.
@return array|bool | public function processGroupArray($phone, $groupArray)
{
$formattedGroups = [];
if (!empty($groupArray)) {
foreach ($groupArray as $group) {
$formattedGroups[] = ['name' => 'GROUP: '.$group['subject'], 'id' => $group['id']];
}
$this->waGroupList ... | csn |
Returns the hue with the smallest difference. | function getHueDifference(value) {
return hues.reduce(function (min, hue) {
var diff = Math.abs(hue - value);
if (diff < min) {
return diff;
}
return min;
}, Infinity);
} | csn |
public function totalCount()
{
if (!isset($this->parameters['conditions'])) {
return count($this->value);
}
if (!$this->totalCount) {
if (is_callable($this->totalCountCalculation)) {
$this->totalCount = ($this->totalCountCalculation)();
} ... | $mongo = Entity::getInstance()->getDatabase();
$entity = $this->entityClass;
$this->totalCount = $mongo->count($entity::getCollection(), $this->parameters['conditions']);
}
}
return $this->totalCount;
} | csn_ccr |
configure the worker | function (services, callback) {
var http = require('http');
var app = require('express')();
var server = http.createServer(app);
// get remote services
//var fakedb1 = services[0];
//var fakedb2 = services[1];
// all express-related stuff goes here... | csn |
func NewSubjectChecker(spec *authorizationapi.RoleBindingRestrictionSpec) (SubjectChecker, error) {
switch {
case spec.UserRestriction != nil:
return NewUserSubjectChecker(spec.UserRestriction), nil
case spec.GroupRestriction != nil:
return NewGroupSubjectChecker(spec.GroupRestriction), nil
case spec.ServiceA... | return NewServiceAccountSubjectChecker(spec.ServiceAccountRestriction), nil
}
return nil, fmt.Errorf("invalid RoleBindingRestrictionSpec: %v", spec)
} | csn_ccr |
Finalize the block in FSDataset.
@param dstNamespaceId
the namespace id for dstBlock
@param dstBlock
the block that needs to be finalized
@param dstBlockFile
the block file for the block that has to be finalized
@throws IOException | private void copyBlockLocalFinalize(int dstNamespaceId,
Block dstBlock, File dstBlockFile)
throws IOException {
boolean inlineChecksum = Block.isInlineChecksumBlockFilename(dstBlockFile
.getName());
long blkSize = 0;
long fileSize = dstBlockFile.length();
lock.writeLock().lock();
t... | csn |
def latch_config_variables(self):
"""Latch the current value of all config variables as python objects.
This function will capture the current value of all config variables
at the time that this method is called. It must be called after
start() has been called so that any default value... | back.
Returns:
dict: A dict of str -> object with the config variable values.
The keys in the dict will be the name passed to
`declare_config_variable`.
The values will be the python objects that result from calling
latch() on each config variable.... | csn_ccr |
func NewProcessor(gamma float64, highQuality bool) *Processor {
prc := new(Processor)
gammaInv := 1 / gamma
for i := range prc.vals {
prc.vals[i] = uint16(math.Pow(float64(i)/65535, gammaInv)*65535 + 0.5)
}
if highQuality {
prc.newDrawable = func(p image.Image) draw.Image {
| return image.NewNRGBA64(p.Bounds())
}
} else {
prc.newDrawable = imageserver_image_internal.NewDrawable
}
return prc
} | csn_ccr |
def _ip_unnumbered_name(self, **kwargs):
"""Return the `ip unnumbered` donor name XML.
You should not use this method.
You probably want `Interface.ip_unnumbered`.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
... |
method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\
'interface_name' % kwargs['int_type']
ip_unnumbered_name = getattr(self._interface, method_name)
config = ip_unnumbered_name(**kwargs)
if kwargs['delete']:
tag = 'ip-donor-interface-name'
... | csn_ccr |
Information about current PHP reporting
@return JBDump | public static function errors()
{
$result = array();
$result['error_reporting'] = error_reporting();
$errTypes = self::_getErrorTypes();
foreach ($errTypes as $errTypeKey => $errTypeName) {
if ($result['error_reporting'] & $errT... | csn |
func (c *CheckSuite) GetBeforeSHA() string {
if c == nil || c.BeforeSHA == nil {
| return ""
}
return *c.BeforeSHA
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.