Dataset Viewer
Auto-converted to Parquet Duplicate
query
stringlengths
4
15k
positive
stringlengths
5
373k
source
stringclasses
7 values
hard_negatives
listlengths
1
1
Start the asyncio event loop and runs the application.
def main(): """Start the asyncio event loop and runs the application.""" # Helper method so that the coroutine exits cleanly if an exception # happens (which would leave resources dangling) async def _run_application(loop): try: return await cli_handler(loop) except KeyboardInterrupt: pass # User pressed Ctrl+C, just ignore it except SystemExit: pass # sys.exit() was used - do nothing except: # pylint: disable=bare-except # noqa import traceback traceback.print_exc(file=sys.stderr) sys.stderr.writelines( '\n>>> An error occurred, full stack trace above\n') return 1 try: loop = asyncio.get_event_loop() return loop.run_until_complete(_run_application(loop)) except KeyboardInterrupt: pass return 1
csn
[ "def run(self):\n \"\"\"Run the event loop.\"\"\"\n self.signal_init()\n self.listen_init()\n self.logger.info('starting')\n self.loop.start()" ]
Start the asyncio event loop and runs the application.
def main(): """Start the asyncio event loop and runs the application.""" # Helper method so that the coroutine exits cleanly if an exception # happens (which would leave resources dangling) async def _run_application(loop): try: return await cli_handler(loop) except KeyboardInterrupt: pass # User pressed Ctrl+C, just ignore it except SystemExit: pass # sys.exit() was used - do nothing except: # pylint: disable=bare-except # noqa import traceback traceback.print_exc(file=sys.stderr) sys.stderr.writelines( '\n>>> An error occurred, full stack trace above\n') return 1 try: loop = asyncio.get_event_loop() return loop.run_until_complete(_run_application(loop)) except KeyboardInterrupt: pass return 1
csn
[ "def _open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None,\n closefd=True, opener=None, *, loop=None, executor=None):\n \"\"\"Open an asyncio file.\"\"\"\n if loop is None:\n loop = asyncio.get_event_loop()\n cb = partial(sync_open, file, mode=mode, buffering=bufferi...
Start the asyncio event loop and runs the application.
def main(): """Start the asyncio event loop and runs the application.""" # Helper method so that the coroutine exits cleanly if an exception # happens (which would leave resources dangling) async def _run_application(loop): try: return await cli_handler(loop) except KeyboardInterrupt: pass # User pressed Ctrl+C, just ignore it except SystemExit: pass # sys.exit() was used - do nothing except: # pylint: disable=bare-except # noqa import traceback traceback.print_exc(file=sys.stderr) sys.stderr.writelines( '\n>>> An error occurred, full stack trace above\n') return 1 try: loop = asyncio.get_event_loop() return loop.run_until_complete(_run_application(loop)) except KeyboardInterrupt: pass return 1
csn
[ "async function start() {\n if (child) {\n await stop();\n }\n\n return new Promise((resolve) => {\n const serverPath = path.resolve(process.cwd(), 'packages/node_modules/@webex/test-helper-server');\n\n child = spawn(process.argv[0], [serverPath], {\n env: process.env,\n stdio: ['ignore', 'pi...
Initialize the pool manager with the number of pools, the entry sizes for each pool, and the maximum depth of the free pool. @param bufferEntrySizes the memory sizes of each entry in the pools @param bufferEntryDepths the maximum number of entries in the free pool
public void initialize(int[] bufferEntrySizes, int[] bufferEntryDepths) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "initialize"); } // order both lists from smallest to largest, based only on Entry Sizes int len = bufferEntrySizes.length; int[] bSizes = new int[len]; int[] bDepths = new int[len]; int sizeCompare; int depth; int sizeSort; int j; for (int i = 0; i < len; i++) { sizeCompare = bufferEntrySizes[i]; depth = bufferEntryDepths[i]; // go backwards, for speed, since first Array List is // probably already ordered small to large for (j = i - 1; j >= 0; j--) { sizeSort = bSizes[j]; if (sizeCompare > sizeSort) { // add the bigger one after the smaller one bSizes[j + 1] = sizeCompare; bDepths[j + 1] = depth; break; } // move current one down, since it is bigger bSizes[j + 1] = sizeSort; bDepths[j + 1] = bDepths[j]; } if (j < 0) { // smallest so far, add it at the front of the list bSizes[0] = sizeCompare; bDepths[0] = depth; } } boolean tracking = trackingBuffers(); this.pools = new WsByteBufferPool[len]; this.poolsDirect = new WsByteBufferPool[len]; this.poolSizes = new int[len]; for (int i = 0; i < len; i++) { // make backing pool 10 times larger than local pools this.pools[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, false); this.poolsDirect[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, true); this.poolSizes[i] = bSizes[i]; } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Number of pools created: " + this.poolSizes.length); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "initialize"); } }
csn
[ "private void redistributeBuffers() throws IOException {\n\t\tassert Thread.holdsLock(factoryLock);\n\n\t\t// All buffers, which are not among the required ones\n\t\tfinal int numAvailableMemorySegment = totalNumberOfMemorySegments - numTotalRequiredBuffers;\n\n\t\tif (numAvailableMemorySegment == 0) {\n\t\t\t// in...
Initialize the pool manager with the number of pools, the entry sizes for each pool, and the maximum depth of the free pool. @param bufferEntrySizes the memory sizes of each entry in the pools @param bufferEntryDepths the maximum number of entries in the free pool
public void initialize(int[] bufferEntrySizes, int[] bufferEntryDepths) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "initialize"); } // order both lists from smallest to largest, based only on Entry Sizes int len = bufferEntrySizes.length; int[] bSizes = new int[len]; int[] bDepths = new int[len]; int sizeCompare; int depth; int sizeSort; int j; for (int i = 0; i < len; i++) { sizeCompare = bufferEntrySizes[i]; depth = bufferEntryDepths[i]; // go backwards, for speed, since first Array List is // probably already ordered small to large for (j = i - 1; j >= 0; j--) { sizeSort = bSizes[j]; if (sizeCompare > sizeSort) { // add the bigger one after the smaller one bSizes[j + 1] = sizeCompare; bDepths[j + 1] = depth; break; } // move current one down, since it is bigger bSizes[j + 1] = sizeSort; bDepths[j + 1] = bDepths[j]; } if (j < 0) { // smallest so far, add it at the front of the list bSizes[0] = sizeCompare; bDepths[0] = depth; } } boolean tracking = trackingBuffers(); this.pools = new WsByteBufferPool[len]; this.poolsDirect = new WsByteBufferPool[len]; this.poolSizes = new int[len]; for (int i = 0; i < len; i++) { // make backing pool 10 times larger than local pools this.pools[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, false); this.poolsDirect[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, true); this.poolSizes[i] = bSizes[i]; } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Number of pools created: " + this.poolSizes.length); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "initialize"); } }
csn
[ "public void registerBufferPool(BufferPool bufferPool) {\n\t\tcheckArgument(bufferPool.getNumberOfRequiredMemorySegments() >= getNumberOfSubpartitions(),\n\t\t\t\t\"Bug in result partition setup logic: Buffer pool has not enough guaranteed buffers for this result partition.\");\n\n\t\tcheckState(this.bufferPool == ...
Initialize the pool manager with the number of pools, the entry sizes for each pool, and the maximum depth of the free pool. @param bufferEntrySizes the memory sizes of each entry in the pools @param bufferEntryDepths the maximum number of entries in the free pool
public void initialize(int[] bufferEntrySizes, int[] bufferEntryDepths) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "initialize"); } // order both lists from smallest to largest, based only on Entry Sizes int len = bufferEntrySizes.length; int[] bSizes = new int[len]; int[] bDepths = new int[len]; int sizeCompare; int depth; int sizeSort; int j; for (int i = 0; i < len; i++) { sizeCompare = bufferEntrySizes[i]; depth = bufferEntryDepths[i]; // go backwards, for speed, since first Array List is // probably already ordered small to large for (j = i - 1; j >= 0; j--) { sizeSort = bSizes[j]; if (sizeCompare > sizeSort) { // add the bigger one after the smaller one bSizes[j + 1] = sizeCompare; bDepths[j + 1] = depth; break; } // move current one down, since it is bigger bSizes[j + 1] = sizeSort; bDepths[j + 1] = bDepths[j]; } if (j < 0) { // smallest so far, add it at the front of the list bSizes[0] = sizeCompare; bDepths[0] = depth; } } boolean tracking = trackingBuffers(); this.pools = new WsByteBufferPool[len]; this.poolsDirect = new WsByteBufferPool[len]; this.poolSizes = new int[len]; for (int i = 0; i < len; i++) { // make backing pool 10 times larger than local pools this.pools[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, false); this.poolsDirect[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, true); this.poolSizes[i] = bSizes[i]; } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Number of pools created: " + this.poolSizes.length); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "initialize"); } }
csn
[ "public void ensureCapacity(int size) {\n if (size > elements.length) {\n reallocate(Math.max(size, 2 * elements.length));\n }\n }" ]
Initialize the pool manager with the number of pools, the entry sizes for each pool, and the maximum depth of the free pool. @param bufferEntrySizes the memory sizes of each entry in the pools @param bufferEntryDepths the maximum number of entries in the free pool
public void initialize(int[] bufferEntrySizes, int[] bufferEntryDepths) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "initialize"); } // order both lists from smallest to largest, based only on Entry Sizes int len = bufferEntrySizes.length; int[] bSizes = new int[len]; int[] bDepths = new int[len]; int sizeCompare; int depth; int sizeSort; int j; for (int i = 0; i < len; i++) { sizeCompare = bufferEntrySizes[i]; depth = bufferEntryDepths[i]; // go backwards, for speed, since first Array List is // probably already ordered small to large for (j = i - 1; j >= 0; j--) { sizeSort = bSizes[j]; if (sizeCompare > sizeSort) { // add the bigger one after the smaller one bSizes[j + 1] = sizeCompare; bDepths[j + 1] = depth; break; } // move current one down, since it is bigger bSizes[j + 1] = sizeSort; bDepths[j + 1] = bDepths[j]; } if (j < 0) { // smallest so far, add it at the front of the list bSizes[0] = sizeCompare; bDepths[0] = depth; } } boolean tracking = trackingBuffers(); this.pools = new WsByteBufferPool[len]; this.poolsDirect = new WsByteBufferPool[len]; this.poolSizes = new int[len]; for (int i = 0; i < len; i++) { // make backing pool 10 times larger than local pools this.pools[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, false); this.poolsDirect[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, true); this.poolSizes[i] = bSizes[i]; } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Number of pools created: " + this.poolSizes.length); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "initialize"); } }
csn
[ "private void circularByteBufferInitializer(int bufferCapacity, int bufferSize, int readPosition, int writePosition) {\n if (bufferCapacity < 2) {\n throw new IllegalArgumentException(\"Buffer capacity must be greater than 2 !\");\n }\n if ((bufferSize < 0) || (bufferSize > bufferCap...
Initialize the pool manager with the number of pools, the entry sizes for each pool, and the maximum depth of the free pool. @param bufferEntrySizes the memory sizes of each entry in the pools @param bufferEntryDepths the maximum number of entries in the free pool
public void initialize(int[] bufferEntrySizes, int[] bufferEntryDepths) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "initialize"); } // order both lists from smallest to largest, based only on Entry Sizes int len = bufferEntrySizes.length; int[] bSizes = new int[len]; int[] bDepths = new int[len]; int sizeCompare; int depth; int sizeSort; int j; for (int i = 0; i < len; i++) { sizeCompare = bufferEntrySizes[i]; depth = bufferEntryDepths[i]; // go backwards, for speed, since first Array List is // probably already ordered small to large for (j = i - 1; j >= 0; j--) { sizeSort = bSizes[j]; if (sizeCompare > sizeSort) { // add the bigger one after the smaller one bSizes[j + 1] = sizeCompare; bDepths[j + 1] = depth; break; } // move current one down, since it is bigger bSizes[j + 1] = sizeSort; bDepths[j + 1] = bDepths[j]; } if (j < 0) { // smallest so far, add it at the front of the list bSizes[0] = sizeCompare; bDepths[0] = depth; } } boolean tracking = trackingBuffers(); this.pools = new WsByteBufferPool[len]; this.poolsDirect = new WsByteBufferPool[len]; this.poolSizes = new int[len]; for (int i = 0; i < len; i++) { // make backing pool 10 times larger than local pools this.pools[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, false); this.poolsDirect[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, true); this.poolSizes[i] = bSizes[i]; } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Number of pools created: " + this.poolSizes.length); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "initialize"); } }
csn
[ "public static ByteBuffer allocate(int capacity) {\n ByteBuffer buf = ByteBuffer.allocate(capacity);\n buf.limit(0);\n return buf;\n }" ]
// List lists all of the documents in an index. The documents are returned in // increasing ID order.
func (x *Index) List(c context.Context, opts *ListOptions) *Iterator { t := &Iterator{ c: c, index: x, count: -1, listInclusive: true, more: moreList, limit: -1, } if opts != nil { t.listStartID = opts.StartID if opts.Limit > 0 { t.limit = opts.Limit } t.idsOnly = opts.IDsOnly } return t }
csn
[ "func (tx *Tx) Indexes() ([]string, error) {\n\tif tx.db == nil {\n\t\treturn nil, ErrTxClosed\n\t}\n\tnames := make([]string, 0, len(tx.db.idxs))\n\tfor name := range tx.db.idxs {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\treturn names, nil\n}" ]
// List lists all of the documents in an index. The documents are returned in // increasing ID order.
func (x *Index) List(c context.Context, opts *ListOptions) *Iterator { t := &Iterator{ c: c, index: x, count: -1, listInclusive: true, more: moreList, limit: -1, } if opts != nil { t.listStartID = opts.StartID if opts.Limit > 0 { t.limit = opts.Limit } t.idsOnly = opts.IDsOnly } return t }
csn
[ "func (o *SortOption) Indexes() []int {\n\tvar ret []int\n\tfor _, x := range o.orderByList {\n\t\tret = append(ret, x.Index)\n\t}\n\treturn ret\n}" ]
// List lists all of the documents in an index. The documents are returned in // increasing ID order.
func (x *Index) List(c context.Context, opts *ListOptions) *Iterator { t := &Iterator{ c: c, index: x, count: -1, listInclusive: true, more: moreList, limit: -1, } if opts != nil { t.listStartID = opts.StartID if opts.Limit > 0 { t.limit = opts.Limit } t.idsOnly = opts.IDsOnly } return t }
csn
[ "func (list *TargetList) List() []TargetID {\n\tlist.RLock()\n\tdefer list.RUnlock()\n\n\tkeys := []TargetID{}\n\tfor k := range list.targets {\n\t\tkeys = append(keys, k)\n\t}\n\n\treturn keys\n}" ]
// List lists all of the documents in an index. The documents are returned in // increasing ID order.
func (x *Index) List(c context.Context, opts *ListOptions) *Iterator { t := &Iterator{ c: c, index: x, count: -1, listInclusive: true, more: moreList, limit: -1, } if opts != nil { t.listStartID = opts.StartID if opts.Limit > 0 { t.limit = opts.Limit } t.idsOnly = opts.IDsOnly } return t }
csn
[ "func (db *NodeSet) NodeList() NodeList {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tvar values NodeList\n\tfor _, key := range db.order {\n\t\tvalues = append(values, db.nodes[key])\n\t}\n\treturn values\n}" ]
Loads the entity that holds the item type data when an Item is loaded. @param Item $item @param LifecycleEventArgs $event
public function postLoad(Item $item, LifecycleEventArgs $event) { $type = $this->itemDefinitions->getConvertedType($item->getMimeType()); $definition = $this->itemDefinitions->get($type); $repository = $event ->getEntityManager() ->getRepository($definition->getEntityClass()); /** @var \UJM\ExoBundle\Entity\ItemType\AbstractItem $typeEntity */ $typeEntity = $repository->findOneBy([ 'question' => $item, ]); if (!empty($typeEntity)) { $item->setInteraction($typeEntity); } }
csn
[ "public function prePersist(Item $item, LifecycleEventArgs $event)\n {\n $interaction = $item->getInteraction();\n if (null !== $interaction) {\n $event->getEntityManager()->persist($interaction);\n }\n }" ]
Loads the entity that holds the item type data when an Item is loaded. @param Item $item @param LifecycleEventArgs $event
public function postLoad(Item $item, LifecycleEventArgs $event) { $type = $this->itemDefinitions->getConvertedType($item->getMimeType()); $definition = $this->itemDefinitions->get($type); $repository = $event ->getEntityManager() ->getRepository($definition->getEntityClass()); /** @var \UJM\ExoBundle\Entity\ItemType\AbstractItem $typeEntity */ $typeEntity = $repository->findOneBy([ 'question' => $item, ]); if (!empty($typeEntity)) { $item->setInteraction($typeEntity); } }
csn
[ "protected function dispatchClassMetadataLoadedEvent(ClassMetadataInterface $classMetadata): void\n {\n if (null === $this->eventDispatcher) {\n return;\n }\n\n $this->eventDispatcher->dispatch(\n ClassMetadataLoadedEvent::LOADED_EVENT,\n new ClassMetadataLoa...
Loads the entity that holds the item type data when an Item is loaded. @param Item $item @param LifecycleEventArgs $event
public function postLoad(Item $item, LifecycleEventArgs $event) { $type = $this->itemDefinitions->getConvertedType($item->getMimeType()); $definition = $this->itemDefinitions->get($type); $repository = $event ->getEntityManager() ->getRepository($definition->getEntityClass()); /** @var \UJM\ExoBundle\Entity\ItemType\AbstractItem $typeEntity */ $typeEntity = $repository->findOneBy([ 'question' => $item, ]); if (!empty($typeEntity)) { $item->setInteraction($typeEntity); } }
csn
[ "public function onLoaded(ResourceInterface $resource)\n {\n if (!$this->isDebugging() || $this->current === $resource) {\n return;\n }\n\n $this->ensureCollector($this->current);\n $this->meta[$this->current]->addResource($resource);\n }" ]
Loads the entity that holds the item type data when an Item is loaded. @param Item $item @param LifecycleEventArgs $event
public function postLoad(Item $item, LifecycleEventArgs $event) { $type = $this->itemDefinitions->getConvertedType($item->getMimeType()); $definition = $this->itemDefinitions->get($type); $repository = $event ->getEntityManager() ->getRepository($definition->getEntityClass()); /** @var \UJM\ExoBundle\Entity\ItemType\AbstractItem $typeEntity */ $typeEntity = $repository->findOneBy([ 'question' => $item, ]); if (!empty($typeEntity)) { $item->setInteraction($typeEntity); } }
csn
[ "protected function _prepareEvent($eventName, array $data = [])\n {\n if (is_array($eventName)) {\n list($eventName, $subject) = $eventName;\n } else {\n $subject = new EventDispatcher();\n }\n\n return new Event($eventName, $subject, $data);\n }" ]
Loads the entity that holds the item type data when an Item is loaded. @param Item $item @param LifecycleEventArgs $event
public function postLoad(Item $item, LifecycleEventArgs $event) { $type = $this->itemDefinitions->getConvertedType($item->getMimeType()); $definition = $this->itemDefinitions->get($type); $repository = $event ->getEntityManager() ->getRepository($definition->getEntityClass()); /** @var \UJM\ExoBundle\Entity\ItemType\AbstractItem $typeEntity */ $typeEntity = $repository->findOneBy([ 'question' => $item, ]); if (!empty($typeEntity)) { $item->setInteraction($typeEntity); } }
csn
[ "public Resource getStoreResource(final Instance _instance,\n final Resource.StoreEvent _event)\n throws EFapsException\n {\n Resource storeRsrc = null;\n final Store store = Store.get(_instance.getType().getStoreId());\n storeRsrc = store.getResour...
Extract the normalized text from within an element @param fromElement @return extracted Text node (could be null)
protected Text extractText(Element fromElement) { fromElement.normalize(); NodeList fromNodeList = fromElement.getChildNodes(); Node currentNode; for (int i=0; i < fromNodeList.getLength(); ++i) { currentNode = fromNodeList.item(i); if (currentNode.getNodeType() == Node.TEXT_NODE) { return (Text) currentNode; } } return null; }
csn
[ "private static String getText(Element element) {\n if (element.getFirstChild() == null) {\n return \"\";\n }\n return ((Text) element.getFirstChild()).getData().trim();\n }" ]
Extract the normalized text from within an element @param fromElement @return extracted Text node (could be null)
protected Text extractText(Element fromElement) { fromElement.normalize(); NodeList fromNodeList = fromElement.getChildNodes(); Node currentNode; for (int i=0; i < fromNodeList.getLength(); ++i) { currentNode = fromNodeList.item(i); if (currentNode.getNodeType() == Node.TEXT_NODE) { return (Text) currentNode; } } return null; }
csn
[ "private String parseXmlElement(Element element) {\n if(element.getFirstChild() instanceof Text) {\n Text text = (Text) element.getFirstChild();\n return text.getData();\n }\n \n return toXml(element);\n }" ]
Extract the normalized text from within an element @param fromElement @return extracted Text node (could be null)
protected Text extractText(Element fromElement) { fromElement.normalize(); NodeList fromNodeList = fromElement.getChildNodes(); Node currentNode; for (int i=0; i < fromNodeList.getLength(); ++i) { currentNode = fromNodeList.item(i); if (currentNode.getNodeType() == Node.TEXT_NODE) { return (Text) currentNode; } } return null; }
csn
[ "public @Nonnull String text() {\n return new NodeListSpliterator(node.getChildNodes()).stream()\n .filter(it -> it instanceof Text)\n .map(it -> ((Text) it).getNodeValue())\n .collect(joining());\n }" ]
Extract the normalized text from within an element @param fromElement @return extracted Text node (could be null)
protected Text extractText(Element fromElement) { fromElement.normalize(); NodeList fromNodeList = fromElement.getChildNodes(); Node currentNode; for (int i=0; i < fromNodeList.getLength(); ++i) { currentNode = fromNodeList.item(i); if (currentNode.getNodeType() == Node.TEXT_NODE) { return (Text) currentNode; } } return null; }
csn
[ "@Override\n public XMLObject unmarshall(Element domElement) throws UnmarshallingException {\n\n Document newDocument = null;\n\n Node childNode = domElement.getFirstChild();\n while (childNode != null) {\n if (childNode.getNodeType() != Node.TEXT_NODE) {\n // We skip everything except for a t...
// handle processes a request from a Multiwatcher to the storeManager.
func (sm *storeManager) handle(req *request) { if req.w.stopped { // The watcher has previously been stopped. if req.reply != nil { select { case req.reply <- false: case <-sm.tomb.Dying(): } } return } if req.reply == nil { // This is a request to stop the watcher. for req := sm.waiting[req.w]; req != nil; req = req.next { select { case req.reply <- false: case <-sm.tomb.Dying(): } } delete(sm.waiting, req.w) req.w.stopped = true sm.leave(req.w) return } // Add request to head of list. req.next = sm.waiting[req.w] sm.waiting[req.w] = req }
csn
[ "func NewAckingResourceMutatorWrapper(mutator ResourceMutator, nodeToID NodeToIDFunc) *AckingResourceMutatorWrapper {\n\treturn &AckingResourceMutatorWrapper{\n\t\tmutator: mutator,\n\t\tnodeToID: nodeToID,\n\t\tpendingCompletions: make(map[*completion.Completion]*pendingCompletion),\n\t}\n}" ]
// handle processes a request from a Multiwatcher to the storeManager.
func (sm *storeManager) handle(req *request) { if req.w.stopped { // The watcher has previously been stopped. if req.reply != nil { select { case req.reply <- false: case <-sm.tomb.Dying(): } } return } if req.reply == nil { // This is a request to stop the watcher. for req := sm.waiting[req.w]; req != nil; req = req.next { select { case req.reply <- false: case <-sm.tomb.Dying(): } } delete(sm.waiting, req.w) req.w.stopped = true sm.leave(req.w) return } // Add request to head of list. req.next = sm.waiting[req.w] sm.waiting[req.w] = req }
csn
[ "func newStore() *multiwatcherStore {\n\treturn &multiwatcherStore{\n\t\tentities: make(map[interface{}]*list.Element),\n\t\tlist: list.New(),\n\t}\n}" ]
// handle processes a request from a Multiwatcher to the storeManager.
func (sm *storeManager) handle(req *request) { if req.w.stopped { // The watcher has previously been stopped. if req.reply != nil { select { case req.reply <- false: case <-sm.tomb.Dying(): } } return } if req.reply == nil { // This is a request to stop the watcher. for req := sm.waiting[req.w]; req != nil; req = req.next { select { case req.reply <- false: case <-sm.tomb.Dying(): } } delete(sm.waiting, req.w) req.w.stopped = true sm.leave(req.w) return } // Add request to head of list. req.next = sm.waiting[req.w] sm.waiting[req.w] = req }
csn
[ "func New(s store.Store, ctx context.Context) (watcher.Watcher, error) {\n\treturn watcher.New(s, ctx, KEY, convert, invertKey)\n}" ]
// handle processes a request from a Multiwatcher to the storeManager.
func (sm *storeManager) handle(req *request) { if req.w.stopped { // The watcher has previously been stopped. if req.reply != nil { select { case req.reply <- false: case <-sm.tomb.Dying(): } } return } if req.reply == nil { // This is a request to stop the watcher. for req := sm.waiting[req.w]; req != nil; req = req.next { select { case req.reply <- false: case <-sm.tomb.Dying(): } } delete(sm.waiting, req.w) req.w.stopped = true sm.leave(req.w) return } // Add request to head of list. req.next = sm.waiting[req.w] sm.waiting[req.w] = req }
csn
[ "func (c *Cacher) Watch(ctx context.Context, key string, resourceVersion string, pred storage.SelectionPredicate) (watch.Interface, error) {\n\twatchRV, err := c.versioner.ParseResourceVersion(resourceVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.ready.wait()\n\n\ttriggerValue, triggerSupported := \"...
// handle processes a request from a Multiwatcher to the storeManager.
func (sm *storeManager) handle(req *request) { if req.w.stopped { // The watcher has previously been stopped. if req.reply != nil { select { case req.reply <- false: case <-sm.tomb.Dying(): } } return } if req.reply == nil { // This is a request to stop the watcher. for req := sm.waiting[req.w]; req != nil; req = req.next { select { case req.reply <- false: case <-sm.tomb.Dying(): } } delete(sm.waiting, req.w) req.w.stopped = true sm.leave(req.w) return } // Add request to head of list. req.next = sm.waiting[req.w] sm.waiting[req.w] = req }
csn
[ "func (mux *ServeMux) Handler(r *Request) Handler {\n\tvar matcher Matcher\n\tvar entry *muxEntry\n\n\t// Acquire a read lock to ensure that list would not\n\t// be modified during the search of registered handler.\n\tmux.mu.RLock()\n\tvar matched bool\n\n\t// Try to match the processing request to any of the regis...
// Limit returns true if rate was exceeded
func (rl *RateLimiter) Limit() bool { // Calculate the number of ns that have passed since our last call now := unixNano() passed := now - atomic.SwapUint64(&rl.lastCheck, now) // Add them to our allowance rate := atomic.LoadUint64(&rl.rate) current := atomic.AddUint64(&rl.allowance, passed*rate) // Ensure our allowance is not over maximum if max := atomic.LoadUint64(&rl.max); current > max { atomic.AddUint64(&rl.allowance, max-current) current = max } // If our allowance is less than one unit, rate-limit! if current < rl.unit { return true } // Not limited, subtract a unit atomic.AddUint64(&rl.allowance, -rl.unit) return false }
csn
[ "func LimitFuncHandler(lmt *limiter.Limiter, nextFunc func(http.ResponseWriter, *http.Request)) http.Handler {\n\treturn LimitHandler(lmt, http.HandlerFunc(nextFunc))\n}" ]
// Limit returns true if rate was exceeded
func (rl *RateLimiter) Limit() bool { // Calculate the number of ns that have passed since our last call now := unixNano() passed := now - atomic.SwapUint64(&rl.lastCheck, now) // Add them to our allowance rate := atomic.LoadUint64(&rl.rate) current := atomic.AddUint64(&rl.allowance, passed*rate) // Ensure our allowance is not over maximum if max := atomic.LoadUint64(&rl.max); current > max { atomic.AddUint64(&rl.allowance, max-current) current = max } // If our allowance is less than one unit, rate-limit! if current < rl.unit { return true } // Not limited, subtract a unit atomic.AddUint64(&rl.allowance, -rl.unit) return false }
csn
[ "func UsingRateLimit(rps float64) Option {\n\treturn func(api *API) error {\n\t\t// because ratelimiter doesnt do any windowing\n\t\t// setting burst makes it difficult to enforce a fixed rate\n\t\t// so setting it equal to 1 this effectively disables bursting\n\t\t// this doesn't check for sensible values, ultimat...
// Limit returns true if rate was exceeded
func (rl *RateLimiter) Limit() bool { // Calculate the number of ns that have passed since our last call now := unixNano() passed := now - atomic.SwapUint64(&rl.lastCheck, now) // Add them to our allowance rate := atomic.LoadUint64(&rl.rate) current := atomic.AddUint64(&rl.allowance, passed*rate) // Ensure our allowance is not over maximum if max := atomic.LoadUint64(&rl.max); current > max { atomic.AddUint64(&rl.allowance, max-current) current = max } // If our allowance is less than one unit, rate-limit! if current < rl.unit { return true } // Not limited, subtract a unit atomic.AddUint64(&rl.allowance, -rl.unit) return false }
csn
[ "func isResourceGuaranteed(container *api.Container, resource api.ResourceName) bool {\n\t// A container resource is guaranteed if its request == limit.\n\t// If request == limit, the user is very confident of resource consumption.\n\treq, hasReq := container.Resources.Requests[resource]\n\tlimit, hasLimit := conta...
// Limit returns true if rate was exceeded
func (rl *RateLimiter) Limit() bool { // Calculate the number of ns that have passed since our last call now := unixNano() passed := now - atomic.SwapUint64(&rl.lastCheck, now) // Add them to our allowance rate := atomic.LoadUint64(&rl.rate) current := atomic.AddUint64(&rl.allowance, passed*rate) // Ensure our allowance is not over maximum if max := atomic.LoadUint64(&rl.max); current > max { atomic.AddUint64(&rl.allowance, max-current) current = max } // If our allowance is less than one unit, rate-limit! if current < rl.unit { return true } // Not limited, subtract a unit atomic.AddUint64(&rl.allowance, -rl.unit) return false }
csn
[ "func admitImage(size int64, limit corev1.LimitRangeItem) error {\n\tif limit.Type != imagev1.LimitTypeImage {\n\t\treturn nil\n\t}\n\n\tlimitQuantity, ok := limit.Max[corev1.ResourceStorage]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\timageQuantity := resource.NewQuantity(size, resource.BinarySI)\n\tif limitQuantity.Cmp...
Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime
def _last_of_quarter(self, day_of_week=None): """ Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime """ return self.on(self.year, self.quarter * 3, 1).last_of("month", day_of_week)
csn
[ "def previous(self, day_of_week=None):\n \"\"\"\n Modify to the previous occurrence of a given day of the week.\n If no day_of_week is provided, modify to the previous occurrence\n of the current day of the week. Use the supplied consts\n to indicate the desired day_of_week, ex. ...
Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime
def _last_of_quarter(self, day_of_week=None): """ Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime """ return self.on(self.year, self.quarter * 3, 1).last_of("month", day_of_week)
csn
[ "def next(self, day_of_week=None, keep_time=False):\n \"\"\"\n Modify to the next occurrence of a given day of the week.\n If no day_of_week is provided, modify to the next occurrence\n of the current day of the week. Use the supplied consts\n to indicate the desired day_of_week,...
Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime
def _last_of_quarter(self, day_of_week=None): """ Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime """ return self.on(self.year, self.quarter * 3, 1).last_of("month", day_of_week)
csn
[ "def day(self, num):\n \"\"\"Return the given day of week as a date object. Day 0 is the Monday.\"\"\"\n d = date(self.year, 1, 4) # The Jan 4th must be in week 1 according to ISO\n return d + timedelta(weeks=self.week-1, days=-d.weekday() + num)" ]
Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime
def _last_of_quarter(self, day_of_week=None): """ Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime """ return self.on(self.year, self.quarter * 3, 1).last_of("month", day_of_week)
csn
[ "def get_period_last_3_months() -> str:\n \"\"\" Returns the last week as a period string \"\"\"\n today = Datum()\n today.today()\n\n # start_date = today - timedelta(weeks=13)\n start_date = today.clone()\n start_date.subtract_months(3)\n\n period = get_period(start_date.date, today.date)\n ...
Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime
def _last_of_quarter(self, day_of_week=None): """ Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime """ return self.on(self.year, self.quarter * 3, 1).last_of("month", day_of_week)
csn
[ "def get_last_weekday_in_month(year, month, weekday):\n \"\"\"Get the last weekday in a given month. e.g:\n\n >>> # the last monday in Jan 2013\n >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n datetime.date(2013, 1, 28)\n \"\"\"\n day = date(year, month, monthrange(...
Compile Sass content using Leafo's ScssPhp compiler. @link https://github.com/leafo/scssphp @param string $content Content to compile. @param array $directories The import directories to make available when compiling. @return string Compiled Sass content.
private static function compileSassContentWithLeafoScss(string $content, array $directories) { if (empty($content)) { return ''; } if (self::$sassCompilerInstance == null) { self::$sassCompilerInstance = self::getLeafoScssInstance(); } self::updateLeafoScssInstance(self::$sassCompilerInstance, $directories); return self::$sassCompilerInstance->compile($content); }
csn
[ "def compile_sass(self, sass_filename, sass_fileurl):\n \"\"\"\n Compile the given SASS file into CSS\n \"\"\"\n compile_kwargs = {\n 'filename': sass_filename,\n 'include_paths': SassProcessor.include_paths + APPS_INCLUDE_DIRS,\n 'custom_functions': get_...
Compile Sass content using Leafo's ScssPhp compiler. @link https://github.com/leafo/scssphp @param string $content Content to compile. @param array $directories The import directories to make available when compiling. @return string Compiled Sass content.
private static function compileSassContentWithLeafoScss(string $content, array $directories) { if (empty($content)) { return ''; } if (self::$sassCompilerInstance == null) { self::$sassCompilerInstance = self::getLeafoScssInstance(); } self::updateLeafoScssInstance(self::$sassCompilerInstance, $directories); return self::$sassCompilerInstance->compile($content); }
csn
[ "def compile_scss_normal\n Dir[\"#{@path}.scss\"].select { |f| File.file? f }.each do |file|\n next if File.basename(file).chr == '_'\n scss_file = File.open(file, 'rb') { |f| f.read }\n\n output_file = File.open( file.split('.').reverse.drop(1).reverse.join('.'), \"w\" )\n ...
Compile Sass content using Leafo's ScssPhp compiler. @link https://github.com/leafo/scssphp @param string $content Content to compile. @param array $directories The import directories to make available when compiling. @return string Compiled Sass content.
private static function compileSassContentWithLeafoScss(string $content, array $directories) { if (empty($content)) { return ''; } if (self::$sassCompilerInstance == null) { self::$sassCompilerInstance = self::getLeafoScssInstance(); } self::updateLeafoScssInstance(self::$sassCompilerInstance, $directories); return self::$sassCompilerInstance->compile($content); }
csn
[ "public static function css_files(array $files) {\n if (empty($files)) {\n return '';\n }\n\n $compressed = array();\n foreach ($files as $file) {\n $content = file_get_contents($file);\n if ($content === false) {\n $compressed[] = \"\\n\\n...
Compile Sass content using Leafo's ScssPhp compiler. @link https://github.com/leafo/scssphp @param string $content Content to compile. @param array $directories The import directories to make available when compiling. @return string Compiled Sass content.
private static function compileSassContentWithLeafoScss(string $content, array $directories) { if (empty($content)) { return ''; } if (self::$sassCompilerInstance == null) { self::$sassCompilerInstance = self::getLeafoScssInstance(); } self::updateLeafoScssInstance(self::$sassCompilerInstance, $directories); return self::$sassCompilerInstance->compile($content); }
csn
[ "public function process($source, $force = true)\n {\n list ($webRoot, $source) = $this->_findWebRoot($source);\n $lessFile = FS::clean($webRoot . Configure::read('App.lessBaseUrl') . $source, '/');\n\n $this->_setForce($force);\n $less = new Less($this->_config);\n\n if (!FS::...
Compile Sass content using Leafo's ScssPhp compiler. @link https://github.com/leafo/scssphp @param string $content Content to compile. @param array $directories The import directories to make available when compiling. @return string Compiled Sass content.
private static function compileSassContentWithLeafoScss(string $content, array $directories) { if (empty($content)) { return ''; } if (self::$sassCompilerInstance == null) { self::$sassCompilerInstance = self::getLeafoScssInstance(); } self::updateLeafoScssInstance(self::$sassCompilerInstance, $directories); return self::$sassCompilerInstance->compile($content); }
csn
[ "def render_css(self, fn=None, text=None, margin='', indent='\\t'):\n \"\"\"output css using the Sass processor\"\"\"\n fn = fn or os.path.splitext(self.fn)[0]+'.css'\n if not os.path.exists(os.path.dirname(fn)):\n os.makedirs(os.path.dirname(fn))\n curdir = os.path.abspath(os...
Reset the date to the last day of the decade. :rtype: Date
def _end_of_decade(self): """ Reset the date to the last day of the decade. :rtype: Date """ year = self.year - self.year % YEARS_PER_DECADE + YEARS_PER_DECADE - 1 return self.set(year, 12, 31)
csn
[ "private Date[] getBeforeDays(int year, int month) {\n Calendar cal = Calendar.getInstance();\n cal.set(year, month, 1);\n int dayNum = getDayIndex(year, month, 1) - 1;\n Date[] date = new Date[dayNum];\n if (dayNum > 0)\n for (int i = 0; i < dayNum; i++) {\n ...
Reset the date to the last day of the decade. :rtype: Date
def _end_of_decade(self): """ Reset the date to the last day of the decade. :rtype: Date """ year = self.year - self.year % YEARS_PER_DECADE + YEARS_PER_DECADE - 1 return self.set(year, 12, 31)
csn
[ "def yesterday(date=None):\n \"\"\"yesterday once more\"\"\"\n if not date:\n return _date - datetime.timedelta(days=1)\n else:\n current_date = parse(date)\n return current_date - datetime.timedelta(days=1)" ]
Reset the date to the last day of the decade. :rtype: Date
def _end_of_decade(self): """ Reset the date to the last day of the decade. :rtype: Date """ year = self.year - self.year % YEARS_PER_DECADE + YEARS_PER_DECADE - 1 return self.set(year, 12, 31)
csn
[ "def rollforward(self, date):\n \"\"\"Roll date forward to nearest start of year\"\"\"\n if self.onOffset(date):\n return date\n else:\n return date + YearBegin(month=self.month)" ]
Reset the date to the last day of the decade. :rtype: Date
def _end_of_decade(self): """ Reset the date to the last day of the decade. :rtype: Date """ year = self.year - self.year % YEARS_PER_DECADE + YEARS_PER_DECADE - 1 return self.set(year, 12, 31)
csn
[ "def today(year=None):\n \"\"\"this day, last year\"\"\"\n return datetime.date(int(year), _date.month, _date.day) if year else _date" ]
Reset the date to the last day of the decade. :rtype: Date
def _end_of_decade(self): """ Reset the date to the last day of the decade. :rtype: Date """ year = self.year - self.year % YEARS_PER_DECADE + YEARS_PER_DECADE - 1 return self.set(year, 12, 31)
csn
[ "def gday_of_year(self):\n \"\"\"Return the number of days since January 1 of the given year.\"\"\"\n return (self.date - dt.date(self.date.year, 1, 1)).days" ]
Puts an archive data row in an index.
private function putRowInIndex(&$index, $metadataNamesToIndexBy, $row, $idSite, $period) { $currentLevel = & $index; foreach ($metadataNamesToIndexBy as $metadataName) { if ($metadataName == DataTableFactory::TABLE_METADATA_SITE_INDEX) { $key = $idSite; } elseif ($metadataName == DataTableFactory::TABLE_METADATA_PERIOD_INDEX) { $key = $period; } else { $key = $row[self::METADATA_CONTAINER_ROW_KEY][$metadataName]; } if (!isset($currentLevel[$key])) { $currentLevel[$key] = array(); } $currentLevel = & $currentLevel[$key]; } $currentLevel = $row; }
csn
[ "def _insert_row(self, i, index):\n \"\"\"\n Insert a new row in the Series.\n\n :param i: index location to insert\n :param index: index value to insert into the index list\n :return: nothing\n \"\"\"\n if i == len(self._index):\n self._add_row(index)\n ...
Puts an archive data row in an index.
private function putRowInIndex(&$index, $metadataNamesToIndexBy, $row, $idSite, $period) { $currentLevel = & $index; foreach ($metadataNamesToIndexBy as $metadataName) { if ($metadataName == DataTableFactory::TABLE_METADATA_SITE_INDEX) { $key = $idSite; } elseif ($metadataName == DataTableFactory::TABLE_METADATA_PERIOD_INDEX) { $key = $period; } else { $key = $row[self::METADATA_CONTAINER_ROW_KEY][$metadataName]; } if (!isset($currentLevel[$key])) { $currentLevel[$key] = array(); } $currentLevel = & $currentLevel[$key]; } $currentLevel = $row; }
csn
[ "def _index(self, row):\n \"\"\"Add a row to the internal list of rows without writing it to disk.\n\n This function should keep the data structure consistent so it's usable\n for both adding new rows, and loading pre-existing histories.\n \"\"\"\n self.rows.append(row)\n s...
Puts an archive data row in an index.
private function putRowInIndex(&$index, $metadataNamesToIndexBy, $row, $idSite, $period) { $currentLevel = & $index; foreach ($metadataNamesToIndexBy as $metadataName) { if ($metadataName == DataTableFactory::TABLE_METADATA_SITE_INDEX) { $key = $idSite; } elseif ($metadataName == DataTableFactory::TABLE_METADATA_PERIOD_INDEX) { $key = $period; } else { $key = $row[self::METADATA_CONTAINER_ROW_KEY][$metadataName]; } if (!isset($currentLevel[$key])) { $currentLevel[$key] = array(); } $currentLevel = & $currentLevel[$key]; } $currentLevel = $row; }
csn
[ "func (dt *DbfTable) InsertRecord() int {\n\tif row := dt.findSpot(); row > -1 {\n\t\t// undelete selected row\n\t\tdt.dataStore[dt.getRowOffset(row)] = 0x20\n\t\treturn row\n\t}\n\treturn dt.AddRecord()\n}" ]
Puts an archive data row in an index.
private function putRowInIndex(&$index, $metadataNamesToIndexBy, $row, $idSite, $period) { $currentLevel = & $index; foreach ($metadataNamesToIndexBy as $metadataName) { if ($metadataName == DataTableFactory::TABLE_METADATA_SITE_INDEX) { $key = $idSite; } elseif ($metadataName == DataTableFactory::TABLE_METADATA_PERIOD_INDEX) { $key = $period; } else { $key = $row[self::METADATA_CONTAINER_ROW_KEY][$metadataName]; } if (!isset($currentLevel[$key])) { $currentLevel[$key] = array(); } $currentLevel = & $currentLevel[$key]; } $currentLevel = $row; }
csn
[ "private static void writeLineToMasterIndex(FSDataOutputStream stream, long startHash,\n long endHash, long indexStartPos, long indexEndPos) throws IOException {\n String toWrite = startHash + \" \" + endHash + \" \" + indexStartPos + \" \" + indexEndPos + \"\\n\";\n stream.write(toWrite.getBytes());\n ...
Puts an archive data row in an index.
private function putRowInIndex(&$index, $metadataNamesToIndexBy, $row, $idSite, $period) { $currentLevel = & $index; foreach ($metadataNamesToIndexBy as $metadataName) { if ($metadataName == DataTableFactory::TABLE_METADATA_SITE_INDEX) { $key = $idSite; } elseif ($metadataName == DataTableFactory::TABLE_METADATA_PERIOD_INDEX) { $key = $period; } else { $key = $row[self::METADATA_CONTAINER_ROW_KEY][$metadataName]; } if (!isset($currentLevel[$key])) { $currentLevel[$key] = array(); } $currentLevel = & $currentLevel[$key]; } $currentLevel = $row; }
csn
[ "public void writeIndexes(JobKey jobKey) throws IOException {\n // Defensive coding\n if (jobKey != null) {\n Table historyByJobIdTable = null;\n\n try {\n historyByJobIdTable = hbaseConnection\n .getTable(TableName.valueOf(Constants.HISTORY_BY_JOBID_TABLE));\n byte[] jobKey...
Is the point near any points in the multi lat lng @param point point @param multiLatLng multi lat lng @param tolerance distance tolerance @return true if near
public static boolean isPointNearMultiLatLng(LatLng point, MultiLatLng multiLatLng, double tolerance) { boolean near = false; for (LatLng multiPoint : multiLatLng.getLatLngs()) { near = isPointNearPoint(point, multiPoint, tolerance); if (near) { break; } } return near; }
csn
[ "public boolean isCloseTo(GeoPoint point, double tolerance, MapView mapView) {\n return getCloseTo(point, tolerance, mapView) != null;\n }" ]
Is the point near any points in the multi lat lng @param point point @param multiLatLng multi lat lng @param tolerance distance tolerance @return true if near
public static boolean isPointNearMultiLatLng(LatLng point, MultiLatLng multiLatLng, double tolerance) { boolean near = false; for (LatLng multiPoint : multiLatLng.getLatLngs()) { near = isPointNearPoint(point, multiPoint, tolerance); if (near) { break; } } return near; }
csn
[ "public static boolean isPointOnPolyline(LatLng point, PolylineOptions polyline, boolean geodesic, double tolerance) {\n return PolyUtil.isLocationOnPath(point, polyline.getPoints(), geodesic, tolerance);\n }" ]
Is the point near any points in the multi lat lng @param point point @param multiLatLng multi lat lng @param tolerance distance tolerance @return true if near
public static boolean isPointNearMultiLatLng(LatLng point, MultiLatLng multiLatLng, double tolerance) { boolean near = false; for (LatLng multiPoint : multiLatLng.getLatLngs()) { near = isPointNearPoint(point, multiPoint, tolerance); if (near) { break; } } return near; }
csn
[ "int subSimplify(PointList points, int fromIndex, int lastIndex) {\n if (lastIndex - fromIndex < 2) {\n return 0;\n }\n int indexWithMaxDist = -1;\n double maxDist = -1;\n double firstLat = points.getLatitude(fromIndex);\n double firstLon = points.getLongitude(fr...
Is the point near any points in the multi lat lng @param point point @param multiLatLng multi lat lng @param tolerance distance tolerance @return true if near
public static boolean isPointNearMultiLatLng(LatLng point, MultiLatLng multiLatLng, double tolerance) { boolean near = false; for (LatLng multiPoint : multiLatLng.getLatLngs()) { near = isPointNearPoint(point, multiPoint, tolerance); if (near) { break; } } return near; }
csn
[ "public static double getLatitudeDistance(double minLatitude,\n double maxLatitude) {\n LatLng lowerMiddle = new LatLng(minLatitude, 0);\n LatLng upperMiddle = new LatLng(maxLatitude, 0);\n double latDistance = SphericalUtil.computeDistanceBetween(low...
Gives support for Rails date_select, datetime_select, time_select helpers.
def process_attributes(attributes = nil) return attributes if attributes.blank? multi_parameter_attributes = {} new_attributes = {} attributes.each_pair do |key, value| if key.match(DATE_KEY_REGEX) match = key.to_s.match(DATE_KEY_REGEX) found_key = match[1] index = match[2].to_i (multi_parameter_attributes[found_key] ||= {})[index] = value.empty? ? nil : value.send("to_#{$3}") else new_attributes[key] = value end end multi_parameter_attributes.empty? ? new_attributes : process_multiparameter_attributes(multi_parameter_attributes, new_attributes) end
csn
[ "def select_simple_date(date_input, value, format = nil)\n value = value.strftime format unless format.nil?\n\n date_input.set \"#{value}\\e\"\n end" ]
Gives support for Rails date_select, datetime_select, time_select helpers.
def process_attributes(attributes = nil) return attributes if attributes.blank? multi_parameter_attributes = {} new_attributes = {} attributes.each_pair do |key, value| if key.match(DATE_KEY_REGEX) match = key.to_s.match(DATE_KEY_REGEX) found_key = match[1] index = match[2].to_i (multi_parameter_attributes[found_key] ||= {})[index] = value.empty? ? nil : value.send("to_#{$3}") else new_attributes[key] = value end end multi_parameter_attributes.empty? ? new_attributes : process_multiparameter_attributes(multi_parameter_attributes, new_attributes) end
csn
[ "def draw_datetime(f, col_or_sym, options={})\n col_name = get_column_name(col_or_sym)\n f.text_field(col_name,\n value: datetime_fmt(f.object.send(col_name)))\n end" ]
Gives support for Rails date_select, datetime_select, time_select helpers.
def process_attributes(attributes = nil) return attributes if attributes.blank? multi_parameter_attributes = {} new_attributes = {} attributes.each_pair do |key, value| if key.match(DATE_KEY_REGEX) match = key.to_s.match(DATE_KEY_REGEX) found_key = match[1] index = match[2].to_i (multi_parameter_attributes[found_key] ||= {})[index] = value.empty? ? nil : value.send("to_#{$3}") else new_attributes[key] = value end end multi_parameter_attributes.empty? ? new_attributes : process_multiparameter_attributes(multi_parameter_attributes, new_attributes) end
csn
[ "def parse_timestamps\n super\n @next_capture_at = Time.at(next_capture_at) if next_capture_at\n @canceled_at = Time.at(canceled_at) if canceled_at\n @trial_start = Time.at(trial_start) if trial_start\n @trial_end = Time.at(trial_end) if trial_end\n end" ]
Gives support for Rails date_select, datetime_select, time_select helpers.
def process_attributes(attributes = nil) return attributes if attributes.blank? multi_parameter_attributes = {} new_attributes = {} attributes.each_pair do |key, value| if key.match(DATE_KEY_REGEX) match = key.to_s.match(DATE_KEY_REGEX) found_key = match[1] index = match[2].to_i (multi_parameter_attributes[found_key] ||= {})[index] = value.empty? ? nil : value.send("to_#{$3}") else new_attributes[key] = value end end multi_parameter_attributes.empty? ? new_attributes : process_multiparameter_attributes(multi_parameter_attributes, new_attributes) end
csn
[ "public static function date_field_types() {\n\n\t\tstatic $field_types = null;\n\n\t\tif ( null === $field_types ) {\n\t\t\t$field_types = array( 'date', 'datetime', 'time' );\n\n\t\t\t$field_types = apply_filters( 'pods_tableless_field_types', $field_types );\n\t\t}\n\n\t\treturn $field_types;\n\t}" ]
read-only @language=en Set text CSS font style. @param {String} font Text CSS font style to set. @returns {Text} the Text object, chained call supported.
function(font){ var me = this; if(me.font !== font){ me.font = font; me._fontHeight = Text.measureFontHeight(font); } return me; }
csn
[ "function setFontFamily(fontFamily) {\n var editor = EditorManager.getCurrentFullEditor();\n\n if (currFontFamily === fontFamily) {\n return;\n }\n\n _removeDynamicFontFamily();\n if (fontFamily) {\n _addDynamicFontFamily(fontFamily);\n }\n\n ex...
read-only @language=en Set text CSS font style. @param {String} font Text CSS font style to set. @returns {Text} the Text object, chained call supported.
function(font){ var me = this; if(me.font !== font){ me.font = font; me._fontHeight = Text.measureFontHeight(font); } return me; }
csn
[ "function fontSet(alias, className) {\n config.fontSets.push({\n alias: alias,\n fontSet: className || alias\n });\n return this;\n }" ]
read-only @language=en Set text CSS font style. @param {String} font Text CSS font style to set. @returns {Text} the Text object, chained call supported.
function(font){ var me = this; if(me.font !== font){ me.font = font; me._fontHeight = Text.measureFontHeight(font); } return me; }
csn
[ "function font() {\n return src([`${svgDir}/*.svg`])\n .pipe(\n iconfontCss({\n fontName: config.name,\n path: template,\n targetPath: '../src/index.less',\n normalize: true,\n firstGlyph: 0xf000,\n cssClass: fontName // this is a trick to pass fontName to template...
read-only @language=en Set text CSS font style. @param {String} font Text CSS font style to set. @returns {Text} the Text object, chained call supported.
function(font){ var me = this; if(me.font !== font){ me.font = font; me._fontHeight = Text.measureFontHeight(font); } return me; }
csn
[ "def _update_fontcolor(self, fontcolor):\n \"\"\"Updates text font color button\n\n Parameters\n ----------\n\n fontcolor: Integer\n \\tText color in integer RGB format\n\n \"\"\"\n\n textcolor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n textcolo...
read-only @language=en Set text CSS font style. @param {String} font Text CSS font style to set. @returns {Text} the Text object, chained call supported.
function(font){ var me = this; if(me.font !== font){ me.font = font; me._fontHeight = Text.measureFontHeight(font); } return me; }
csn
[ "def OnTextFont(self, event):\n \"\"\"Text font choice event handler\"\"\"\n\n fontchoice_combobox = event.GetEventObject()\n idx = event.GetInt()\n\n try:\n font_string = fontchoice_combobox.GetString(idx)\n except AttributeError:\n font_string = event.GetSt...
Generate a new Key in the NFVO. @param name the name of the new Key @return the private Key @throws SDKException if the request fails
@Help(help = "Generate a new Key in the NFVO") public String generateKey(String name) throws SDKException { return (String) requestPost("generate", name); }
csn
[ "@Help(help = \"Import a Key into the NFVO by providing name and public key\")\n public Key importKey(String name, String publicKey) throws SDKException {\n Key key = new Key();\n key.setName(name);\n key.setPublicKey(publicKey);\n return (Key) requestPost(key);\n }" ]
Generate a new Key in the NFVO. @param name the name of the new Key @return the private Key @throws SDKException if the request fails
@Help(help = "Generate a new Key in the NFVO") public String generateKey(String name) throws SDKException { return (String) requestPost("generate", name); }
csn
[ "private NameGenerator getNameGenerator(String namePrefix)\n {\n synchronized(this)\n {\n if (_nameGenerators == null)\n _nameGenerators = new HashMap<String,NameGenerator>();\n\n NameGenerator nameGenerator = _nameGenerators.get(namePrefix);\n if (na...
Generate a new Key in the NFVO. @param name the name of the new Key @return the private Key @throws SDKException if the request fails
@Help(help = "Generate a new Key in the NFVO") public String generateKey(String name) throws SDKException { return (String) requestPost("generate", name); }
csn
[ "public static void generateSecretKey(KeyConfig config)\n\t\t\tthrows NoSuchAlgorithmException, KeyStoreException,\n\t\t\tCertificateException, IOException {\n\n\t\tif (config == null || config.getKeyStoreFile() == null\n\t\t\t\t|| StringUtils.isEmpty(config.getKeyEntryName())\n\t\t\t\t|| config.getAlgorithm() == n...
Generate a new Key in the NFVO. @param name the name of the new Key @return the private Key @throws SDKException if the request fails
@Help(help = "Generate a new Key in the NFVO") public String generateKey(String name) throws SDKException { return (String) requestPost("generate", name); }
csn
[ "public PBKey getPBKey()\r\n {\r\n if (pbKey == null)\r\n {\r\n this.pbKey = new PBKey(this.getJcdAlias(), this.getUserName(), this.getPassWord());\r\n }\r\n return pbKey;\r\n }" ]
Generate a new Key in the NFVO. @param name the name of the new Key @return the private Key @throws SDKException if the request fails
@Help(help = "Generate a new Key in the NFVO") public String generateKey(String name) throws SDKException { return (String) requestPost("generate", name); }
csn
[ "def generate_semantic_data_key(used_semantic_keys):\n \"\"\" Create a new and unique semantic data key\n\n :param list used_semantic_keys: Handed list of keys already in use\n :rtype: str\n :return: semantic_data_id\n \"\"\"\n semantic_data_id_counter = -1\n while True:\n semantic_data_...
hack for NS62 bug
function jsUnitFixTop() { var tempTop = top; if (!tempTop) { tempTop = window; while (tempTop.parent) { tempTop = tempTop.parent; if (tempTop.top && tempTop.top.jsUnitTestSuite) { tempTop = tempTop.top; break; } } } try { window.top = tempTop; } catch (e) { } }
csn
[ "@Fix(io.sarl.lang.validation.IssueCodes.INVALID_IMPLEMENTED_TYPE)\n\tpublic void fixInvalidImplementedType(final Issue issue, IssueResolutionAcceptor acceptor) {\n\t\tImplementedTypeRemoveModification.accept(this, issue, acceptor, RemovalType.OTHER);\n\t}" ]
hack for NS62 bug
function jsUnitFixTop() { var tempTop = top; if (!tempTop) { tempTop = window; while (tempTop.parent) { tempTop = tempTop.parent; if (tempTop.top && tempTop.top.jsUnitTestSuite) { tempTop = tempTop.top; break; } } } try { window.top = tempTop; } catch (e) { } }
csn
[ "public boolean shouldInvalidate (Object id, int sourceOfInvalidation, int causeOfInvalidation) {\n \tboolean retVal = true;\n if (preInvalidationListenerCount > 0) {\n \t// In external implementation, catch any exceptions and process\n \ttry {\n \t\tretVal = currentPreInvalidationLis...
hack for NS62 bug
function jsUnitFixTop() { var tempTop = top; if (!tempTop) { tempTop = window; while (tempTop.parent) { tempTop = tempTop.parent; if (tempTop.top && tempTop.top.jsUnitTestSuite) { tempTop = tempTop.top; break; } } } try { window.top = tempTop; } catch (e) { } }
csn
[ "def remove(spy)\n if @constant_spies[spy.constant_name] == spy\n @constant_spies.delete(spy.constant_name)\n else\n raise NoSpyError, \"#{spy.constant_name} was not stubbed on #{base_module.name}\"\n end\n self\n end" ]
hack for NS62 bug
function jsUnitFixTop() { var tempTop = top; if (!tempTop) { tempTop = window; while (tempTop.parent) { tempTop = tempTop.parent; if (tempTop.top && tempTop.top.jsUnitTestSuite) { tempTop = tempTop.top; break; } } } try { window.top = tempTop; } catch (e) { } }
csn
[ "def test():\n \"\"\"Test for ReverseDNS class\"\"\"\n dns = ReverseDNS()\n\n print(dns.lookup('192.168.0.1'))\n print(dns.lookup('8.8.8.8'))\n\n # Test cache\n print(dns.lookup('8.8.8.8'))" ]
hack for NS62 bug
function jsUnitFixTop() { var tempTop = top; if (!tempTop) { tempTop = window; while (tempTop.parent) { tempTop = tempTop.parent; if (tempTop.top && tempTop.top.jsUnitTestSuite) { tempTop = tempTop.top; break; } } } try { window.top = tempTop; } catch (e) { } }
csn
[ "import re\n\ndef debug(s):\n return re.sub(r'bug(?!s)', '', s)" ]
Convert a file into a raid file format
public void raidFile(INode sourceINodes[], String source, RaidCodec codec, short expectedSourceRepl, Block[] parityBlocks) throws IOException { waitForReady(); long now = FSNamesystem.now(); unprotectedRaidFile(sourceINodes, source, codec, expectedSourceRepl, parityBlocks, now); fsImage.getEditLog().logRaidFile(source, codec.id, expectedSourceRepl, now); }
csn
[ "boolean reconstructFile(Path srcPath, Context context)\n throws IOException, InterruptedException {\n Progressable progress = context;\n if (progress == null) {\n progress = RaidUtils.NULL_PROGRESSABLE;\n }\n \n FileSystem fs = srcPath.getFileSystem(getConf());\n FileStatus srcStat = nu...
Convert a file into a raid file format
public void raidFile(INode sourceINodes[], String source, RaidCodec codec, short expectedSourceRepl, Block[] parityBlocks) throws IOException { waitForReady(); long now = FSNamesystem.now(); unprotectedRaidFile(sourceINodes, source, codec, expectedSourceRepl, parityBlocks, now); fsImage.getEditLog().logRaidFile(source, codec.id, expectedSourceRepl, now); }
csn
[ "def getpart(self, ix):\r\n \"\"\"\r\n Returns a fileobject for the specified section.\r\n\r\n This method optionally decompresses the data found in the .idb file,\r\n and returns a file-like object, with seek, read, tell.\r\n \"\"\"\r\n if self.offsets[ix] == 0:\r\n ...
Convert a file into a raid file format
public void raidFile(INode sourceINodes[], String source, RaidCodec codec, short expectedSourceRepl, Block[] parityBlocks) throws IOException { waitForReady(); long now = FSNamesystem.now(); unprotectedRaidFile(sourceINodes, source, codec, expectedSourceRepl, parityBlocks, now); fsImage.getEditLog().logRaidFile(source, codec.id, expectedSourceRepl, now); }
csn
[ "def read_raid(self, controller=None):\n \"\"\"Get the current RAID configuration from the system.\n\n :param controller: If controller model its post-create read else\n post-delete\n :returns: current raid config.\n \"\"\"\n if controller:\n i...
Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object
def manage_conflict(self, item, name): """ Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object """ if item.is_tpl(): existing = self.name_to_template[name] else: existing = self.name_to_item[name] if existing == item: return item existing_prio = getattr( existing, "definition_order", existing.properties["definition_order"].default) item_prio = getattr( item, "definition_order", item.properties["definition_order"].default) if existing_prio < item_prio: # Existing item has lower priority, so it has precedence. return existing if existing_prio > item_prio: # New item has lower priority, so it has precedence. # Existing item will be deleted below pass else: # Don't know which one to keep, lastly defined has precedence objcls = getattr(self.inner_class, "my_type", "[unknown]") mesg = "duplicate %s '%s', from: '%s' and '%s', using lastly defined. " \ "You may manually set the definition_order parameter to avoid this message." \ % (objcls, name, item.imported_from, existing.imported_from) item.configuration_warnings.append(mesg) if item.is_tpl(): self.remove_template(existing) else: self.remove_item(existing) return item
csn
[ "def cmpname(name1, name2):\n \"\"\"\n Compare two CIM names for equality and ordering.\n\n The comparison is performed case-insensitively.\n\n One or both of the items may be `None`, and `None` is considered the lowest\n possible value.\n\n The implementation delegates to the '==' and '<' operato...
Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object
def manage_conflict(self, item, name): """ Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object """ if item.is_tpl(): existing = self.name_to_template[name] else: existing = self.name_to_item[name] if existing == item: return item existing_prio = getattr( existing, "definition_order", existing.properties["definition_order"].default) item_prio = getattr( item, "definition_order", item.properties["definition_order"].default) if existing_prio < item_prio: # Existing item has lower priority, so it has precedence. return existing if existing_prio > item_prio: # New item has lower priority, so it has precedence. # Existing item will be deleted below pass else: # Don't know which one to keep, lastly defined has precedence objcls = getattr(self.inner_class, "my_type", "[unknown]") mesg = "duplicate %s '%s', from: '%s' and '%s', using lastly defined. " \ "You may manually set the definition_order parameter to avoid this message." \ % (objcls, name, item.imported_from, existing.imported_from) item.configuration_warnings.append(mesg) if item.is_tpl(): self.remove_template(existing) else: self.remove_item(existing) return item
csn
[ "def is_fullfilled_by(self, other):\n \"\"\"\n Checks if the other index already fulfills\n all the indexing and constraint needs of the current one.\n\n :param other: The other index\n :type other: Index\n\n :rtype: bool\n \"\"\"\n # allow the other index to ...
Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object
def manage_conflict(self, item, name): """ Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object """ if item.is_tpl(): existing = self.name_to_template[name] else: existing = self.name_to_item[name] if existing == item: return item existing_prio = getattr( existing, "definition_order", existing.properties["definition_order"].default) item_prio = getattr( item, "definition_order", item.properties["definition_order"].default) if existing_prio < item_prio: # Existing item has lower priority, so it has precedence. return existing if existing_prio > item_prio: # New item has lower priority, so it has precedence. # Existing item will be deleted below pass else: # Don't know which one to keep, lastly defined has precedence objcls = getattr(self.inner_class, "my_type", "[unknown]") mesg = "duplicate %s '%s', from: '%s' and '%s', using lastly defined. " \ "You may manually set the definition_order parameter to avoid this message." \ % (objcls, name, item.imported_from, existing.imported_from) item.configuration_warnings.append(mesg) if item.is_tpl(): self.remove_template(existing) else: self.remove_item(existing) return item
csn
[ "def insert_right(self, item):\n 'Insert a new item. If equal keys are found, add to the right'\n k = self._key(item)\n i = bisect_right(self._keys, k)\n self._keys.insert(i, k)\n self._items.insert(i, item)" ]
Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object
def manage_conflict(self, item, name): """ Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object """ if item.is_tpl(): existing = self.name_to_template[name] else: existing = self.name_to_item[name] if existing == item: return item existing_prio = getattr( existing, "definition_order", existing.properties["definition_order"].default) item_prio = getattr( item, "definition_order", item.properties["definition_order"].default) if existing_prio < item_prio: # Existing item has lower priority, so it has precedence. return existing if existing_prio > item_prio: # New item has lower priority, so it has precedence. # Existing item will be deleted below pass else: # Don't know which one to keep, lastly defined has precedence objcls = getattr(self.inner_class, "my_type", "[unknown]") mesg = "duplicate %s '%s', from: '%s' and '%s', using lastly defined. " \ "You may manually set the definition_order parameter to avoid this message." \ % (objcls, name, item.imported_from, existing.imported_from) item.configuration_warnings.append(mesg) if item.is_tpl(): self.remove_template(existing) else: self.remove_item(existing) return item
csn
[ "def has_key(cls, *args):\n \"\"\"\n Check whether flyweight object with specified key has already been created.\n\n Returns:\n bool: True if already created, False if not\n \"\"\"\n key = args if len(args) > 1 else args[0]\n return key in cls._instances" ]
Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object
def manage_conflict(self, item, name): """ Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object """ if item.is_tpl(): existing = self.name_to_template[name] else: existing = self.name_to_item[name] if existing == item: return item existing_prio = getattr( existing, "definition_order", existing.properties["definition_order"].default) item_prio = getattr( item, "definition_order", item.properties["definition_order"].default) if existing_prio < item_prio: # Existing item has lower priority, so it has precedence. return existing if existing_prio > item_prio: # New item has lower priority, so it has precedence. # Existing item will be deleted below pass else: # Don't know which one to keep, lastly defined has precedence objcls = getattr(self.inner_class, "my_type", "[unknown]") mesg = "duplicate %s '%s', from: '%s' and '%s', using lastly defined. " \ "You may manually set the definition_order parameter to avoid this message." \ % (objcls, name, item.imported_from, existing.imported_from) item.configuration_warnings.append(mesg) if item.is_tpl(): self.remove_template(existing) else: self.remove_item(existing) return item
csn
[ "public KType indexReplace(int index, KType equivalentKey) {\n assert index >= 0 : \"The index must point at an existing key.\";\n assert index <= mask ||\n (index == mask + 1 && hasEmptyKey);\n assert Intrinsics.equals(this, keys[index], equivalentKey);\n\n KType previousValue = Intrinsics.<K...
Convert the alias. @param string @return LibBaseTemplateFilterAlias
public function write(&$text) { $matches = array(); if (strpos($text, '<html')) { //add language $text = str_replace('<html', '<html lang="'.$this->getService('anahita:language')->getTag().'"', $text); //render the styles $text = str_replace('</head>', $this->_renderHead().$this->_renderStyles().'</head>', $text); //render the scripts $text = str_replace('</body>', $this->_renderScripts().'</body>', $text); } }
csn
[ "public function getConvertedValue($alias = null)\n {\n if ($alias && isset($this->convertedAliasValue[$alias])) {\n return $this->convertedAliasValue[$alias];\n } else {\n return $this->convertedValue;\n }\n }" ]
Convert the alias. @param string @return LibBaseTemplateFilterAlias
public function write(&$text) { $matches = array(); if (strpos($text, '<html')) { //add language $text = str_replace('<html', '<html lang="'.$this->getService('anahita:language')->getTag().'"', $text); //render the styles $text = str_replace('</head>', $this->_renderHead().$this->_renderStyles().'</head>', $text); //render the scripts $text = str_replace('</body>', $this->_renderScripts().'</body>', $text); } }
csn
[ "private static String aliasAsUrlPattern(final String alias) {\n\t\tString urlPattern = alias;\n\t\tif (urlPattern != null && !urlPattern.equals(\"/\")\n\t\t\t\t&& !urlPattern.contains(\"*\")) {\n\t\t\tif (urlPattern.endsWith(\"/\")) {\n\t\t\t\turlPattern = urlPattern + \"*\";\n\t\t\t} else {\n\t\t\t\turlPattern = ...
Create an object URL. Given a base URL and an object name, create an object URL. This is useful because object names can contain certain characters (namely slashes (`/`)) that are normally URLencoded when they appear inside of path sequences. @note Swift does not distinguish between @c %2F and a slash character, so this is not strictly necessary. @param string $base The base URL. This is not altered; it is just prepended to the returned string. @param string $oname The name of the object. @retval string @return string The URL to the object. Characters that need escaping will be escaped, while slash characters are not. Thus, the URL will look pathy.
public static function objectUrl($base, $oname) { if (strpos($oname, '/') === FALSE) { return $base . '/' . rawurlencode($oname); } $oParts = explode('/', $oname); $buffer = array(); foreach ($oParts as $part) { $buffer[] = rawurlencode($part); } $newname = implode('/', $buffer); return $base . '/' . $newname; }
csn
[ "public function getAddUrlFor(array $params = array())\n {\n $params = array_merge($params, $this->getExtraParameters());\n\n $friendlyName = explode('\\\\', $this->getEntityName());\n $friendlyName = array_pop($friendlyName);\n $re = '/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/';\...
Create an object URL. Given a base URL and an object name, create an object URL. This is useful because object names can contain certain characters (namely slashes (`/`)) that are normally URLencoded when they appear inside of path sequences. @note Swift does not distinguish between @c %2F and a slash character, so this is not strictly necessary. @param string $base The base URL. This is not altered; it is just prepended to the returned string. @param string $oname The name of the object. @retval string @return string The URL to the object. Characters that need escaping will be escaped, while slash characters are not. Thus, the URL will look pathy.
public static function objectUrl($base, $oname) { if (strpos($oname, '/') === FALSE) { return $base . '/' . rawurlencode($oname); } $oParts = explode('/', $oname); $buffer = array(); foreach ($oParts as $part) { $buffer[] = rawurlencode($part); } $newname = implode('/', $buffer); return $base . '/' . $newname; }
csn
[ "public function standardizeUri(string $uri): string {\n if ($uri == '') {\n throw new BadMethodCallException('URI is empty');\n }\n if (substr($uri, 0, 1) === '/') {\n $uri = substr($uri, 1);\n }\n $uri = preg_replace('|^https?://[^/]+/rest/(tx:[-0-9a-zA-Z]+...
Create an object URL. Given a base URL and an object name, create an object URL. This is useful because object names can contain certain characters (namely slashes (`/`)) that are normally URLencoded when they appear inside of path sequences. @note Swift does not distinguish between @c %2F and a slash character, so this is not strictly necessary. @param string $base The base URL. This is not altered; it is just prepended to the returned string. @param string $oname The name of the object. @retval string @return string The URL to the object. Characters that need escaping will be escaped, while slash characters are not. Thus, the URL will look pathy.
public static function objectUrl($base, $oname) { if (strpos($oname, '/') === FALSE) { return $base . '/' . rawurlencode($oname); } $oParts = explode('/', $oname); $buffer = array(); foreach ($oParts as $part) { $buffer[] = rawurlencode($part); } $newname = implode('/', $buffer); return $base . '/' . $newname; }
csn
[ "public function baseUrl($targetPath = null)\n {\n if (!isset($this->baseUrl)) {\n throw new RuntimeException(sprintf(\n 'The base URI is not defined for [%s]',\n get_class($this)\n ));\n }\n\n if ($targetPath !== null) {\n retur...
Create an object URL. Given a base URL and an object name, create an object URL. This is useful because object names can contain certain characters (namely slashes (`/`)) that are normally URLencoded when they appear inside of path sequences. @note Swift does not distinguish between @c %2F and a slash character, so this is not strictly necessary. @param string $base The base URL. This is not altered; it is just prepended to the returned string. @param string $oname The name of the object. @retval string @return string The URL to the object. Characters that need escaping will be escaped, while slash characters are not. Thus, the URL will look pathy.
public static function objectUrl($base, $oname) { if (strpos($oname, '/') === FALSE) { return $base . '/' . rawurlencode($oname); } $oParts = explode('/', $oname); $buffer = array(); foreach ($oParts as $part) { $buffer[] = rawurlencode($part); } $newname = implode('/', $buffer); return $base . '/' . $newname; }
csn
[ "public static function alias( $alias, $params = array(), $retain = false )\n\t{\n\t\t$route_params = array();\n\t\t\n\t\t// to handle the suffix after a slash in an alias define\n\t\t$suffix = '';\n\t\t\n\t\tif ( strpos( $alias, '/' ) !== false && $alias !== '/' )\n\t\t{\n\t\t\t// slashes in aliases get appended a...
Create an object URL. Given a base URL and an object name, create an object URL. This is useful because object names can contain certain characters (namely slashes (`/`)) that are normally URLencoded when they appear inside of path sequences. @note Swift does not distinguish between @c %2F and a slash character, so this is not strictly necessary. @param string $base The base URL. This is not altered; it is just prepended to the returned string. @param string $oname The name of the object. @retval string @return string The URL to the object. Characters that need escaping will be escaped, while slash characters are not. Thus, the URL will look pathy.
public static function objectUrl($base, $oname) { if (strpos($oname, '/') === FALSE) { return $base . '/' . rawurlencode($oname); } $oParts = explode('/', $oname); $buffer = array(); foreach ($oParts as $part) { $buffer[] = rawurlencode($part); } $newname = implode('/', $buffer); return $base . '/' . $newname; }
csn
[ "public function qualify($url, $base)\n {\n if(!parse_url($url, PHP_URL_SCHEME))\n {\n if ($url[0] != '/')\n {\n //Relative path\n $url = dirname($base) . '/' . $url;\n }\n else\n {\n //Absolute path...
get the current input instance @param CCIn_Instance $set if set the current instance gets updated @return CCIn_Instance
public static function instance( $set = null ) { if ( is_null( $set ) ) { return static::$_instance; } if ( !$set instanceof CCIn_Instance ) { throw new \InvalidArgumentException('CCIn::set() - only CCIn_Instance object can be passed.'); } static::$_instance = $set; }
csn
[ "public function getInstanceValue()\n {\n $value = $this->getValue();\n if (\n is_array($value) &&\n array_key_exists($this->instances, $this->value)\n ) {\n $value = $value[$this->instances];\n }\n return $value;\n }" ]
get the current input instance @param CCIn_Instance $set if set the current instance gets updated @return CCIn_Instance
public static function instance( $set = null ) { if ( is_null( $set ) ) { return static::$_instance; } if ( !$set instanceof CCIn_Instance ) { throw new \InvalidArgumentException('CCIn::set() - only CCIn_Instance object can be passed.'); } static::$_instance = $set; }
csn
[ "public function setConfig( array $config )\n\t{\n\t\tif ( $config == $this->getConfig() ) { return; }\n\n\t\t$this->_values['config'] = $config;\n\t\t$this->setModified();\n\t}" ]
get the current input instance @param CCIn_Instance $set if set the current instance gets updated @return CCIn_Instance
public static function instance( $set = null ) { if ( is_null( $set ) ) { return static::$_instance; } if ( !$set instanceof CCIn_Instance ) { throw new \InvalidArgumentException('CCIn::set() - only CCIn_Instance object can be passed.'); } static::$_instance = $set; }
csn
[ "public function setInstance($instance = 'default')\n {\n $this->get($instance);\n\n $this->session->put($this->prefix.'.instance', $instance);\n\n if (!in_array($instance, $this->getInstances())) {\n $this->session->push($this->prefix.'.instances', $instance);\n }\n ...
get the current input instance @param CCIn_Instance $set if set the current instance gets updated @return CCIn_Instance
public static function instance( $set = null ) { if ( is_null( $set ) ) { return static::$_instance; } if ( !$set instanceof CCIn_Instance ) { throw new \InvalidArgumentException('CCIn::set() - only CCIn_Instance object can be passed.'); } static::$_instance = $set; }
csn
[ "protected function fill_instance_data(\\cm_info $cm) {\n global $DB;\n\n if (!isset($this->instancedata[$cm->instance])) {\n $this->instancedata[$cm->instance] = $DB->get_record($this->get_activity_type(), array('id' => $cm->instance),\n '*', MUST_EXIST);\n }\n }" ...
get the current input instance @param CCIn_Instance $set if set the current instance gets updated @return CCIn_Instance
public static function instance( $set = null ) { if ( is_null( $set ) ) { return static::$_instance; } if ( !$set instanceof CCIn_Instance ) { throw new \InvalidArgumentException('CCIn::set() - only CCIn_Instance object can be passed.'); } static::$_instance = $set; }
csn
[ "public static function getInstance(): ConnectionManager\n\t{\n\t\tif (self::$instance === NULL)\n\t\t{\n\t\t\tself::$instance = new self();\n\t\t}\n\n\t\treturn self::$instance;\n\t}" ]
Print the default values of all cls's Parameters.
def print_param_defaults(self_): """Print the default values of all cls's Parameters.""" cls = self_.cls for key,val in cls.__dict__.items(): if isinstance(val,Parameter): print(cls.__name__+'.'+key+ '='+ repr(val.default))
csn
[ "function(name, options) {\n name = defaultValue(name, \"Conditions\");\n\n options = defaultValue(options, defaultValue.EMPTY_OBJECT);\n DisplayVariablesConcept.call(this, name, options);\n}" ]
Print the default values of all cls's Parameters.
def print_param_defaults(self_): """Print the default values of all cls's Parameters.""" cls = self_.cls for key,val in cls.__dict__.items(): if isinstance(val,Parameter): print(cls.__name__+'.'+key+ '='+ repr(val.default))
csn
[ "def print_param_values(self_):\n \"\"\"Print the values of all this object's Parameters.\"\"\"\n self = self_.self\n for name,val in self.param.get_param_values():\n print('%s.%s = %s' % (self.name,name,val))" ]
Print the default values of all cls's Parameters.
def print_param_defaults(self_): """Print the default values of all cls's Parameters.""" cls = self_.cls for key,val in cls.__dict__.items(): if isinstance(val,Parameter): print(cls.__name__+'.'+key+ '='+ repr(val.default))
csn
[ "def print_parameters(self):\n \"\"\"\n Print the list of parameters and exit.\n \"\"\"\n self.print_info(u\"Available parameters:\")\n self.print_generic(u\"\\n\" + u\"\\n\".join(self.PARAMETERS) + u\"\\n\")\n return self.HELP_EXIT_CODE" ]
Print the default values of all cls's Parameters.
def print_param_defaults(self_): """Print the default values of all cls's Parameters.""" cls = self_.cls for key,val in cls.__dict__.items(): if isinstance(val,Parameter): print(cls.__name__+'.'+key+ '='+ repr(val.default))
csn
[ "def all_options\n env_variable_options = UserOptions.new\n global_configuration_options = UserOptions.new(Departure.configuration.global_percona_args)\n options = env_variable_options.merge(global_configuration_options).merge(DEFAULT_OPTIONS)\n options.to_a.join(' ')\n end" ]
Print the default values of all cls's Parameters.
def print_param_defaults(self_): """Print the default values of all cls's Parameters.""" cls = self_.cls for key,val in cls.__dict__.items(): if isinstance(val,Parameter): print(cls.__name__+'.'+key+ '='+ repr(val.default))
csn
[ "protected function getDefaultInputDefinition()\n {\n return new InputDefinition(array(\n new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'),\n new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message.'),\n ne...
Perform an ajax request to get comments for a node and insert the comments into the comments tree.
function getComments(id) { $.ajax({ type: 'GET', url: opts.getCommentsURL, data: {node: id}, success: function(data, textStatus, request) { var ul = $('#cl' + id); var speed = 100; $('#cf' + id) .find('textarea[name="proposal"]') .data('source', data.source); if (data.comments.length === 0) { ul.html('<li>No comments yet.</li>'); ul.data('empty', true); } else { // If there are comments, sort them and put them in the list. var comments = sortComments(data.comments); speed = data.comments.length * 100; appendComments(comments, ul); ul.data('empty', false); } $('#cn' + id).slideUp(speed + 200); ul.slideDown(speed); }, error: function(request, textStatus, error) { showError('Oops, there was a problem retrieving the comments.'); }, dataType: 'json' }); }
csn
[ "public function create(Comment &$comment)\n {\n $data = $comment->exportData();\n $endpoint = '/admin/comments.json';\n $respoinse = $this->request(\n $endpoint, 'POST', array(\n 'comment' => $data\n )\n );\n $comment->setData($response['commen...
Perform an ajax request to get comments for a node and insert the comments into the comments tree.
function getComments(id) { $.ajax({ type: 'GET', url: opts.getCommentsURL, data: {node: id}, success: function(data, textStatus, request) { var ul = $('#cl' + id); var speed = 100; $('#cf' + id) .find('textarea[name="proposal"]') .data('source', data.source); if (data.comments.length === 0) { ul.html('<li>No comments yet.</li>'); ul.data('empty', true); } else { // If there are comments, sort them and put them in the list. var comments = sortComments(data.comments); speed = data.comments.length * 100; appendComments(comments, ul); ul.data('empty', false); } $('#cn' + id).slideUp(speed + 200); ul.slideDown(speed); }, error: function(request, textStatus, error) { showError('Oops, there was a problem retrieving the comments.'); }, dataType: 'json' }); }
csn
[ "public static void appendQueryPageComments(RequestContext requestContext, QueryPage queryPage) {\n QueryQuestionCommentDAO queryQuestionCommentDAO = new QueryQuestionCommentDAO();\n PanelStamp activeStamp = RequestUtils.getActiveStamp(requestContext);\n List<QueryQuestionComment> rootComments = queryQuest...
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
35

Models trained or fine-tuned on benjamintli/code-retrieval-combined-v2-llm-negatives