query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Devicemapper mount backend. | def _mount_devicemapper(self, identifier):
"""
Devicemapper mount backend.
"""
info = self.client.info()
# cid is the contaienr_id of the temp container
cid = self._identifier_as_cid(identifier)
cinfo = self.client.inspect_container(cid)
dm_dev_name, d... | csn |
function waitForCancel() {
/* jshint validthis: true */
var self = this;
var cancel_batch = {};
cancel_batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true;
self.call.startBatch(cancel_batch, function(err, result) {
if (err) {
| self.emit('error', err);
}
if (result.cancelled) {
self.cancelled = true;
self.emit('cancelled');
}
});
} | csn_ccr |
static public function findCurrentPage($key='page') {
$f3 = \Base::instance();
return $f3->exists('PARAMS.'.$key) ?
| preg_replace("/[^0-9]/", "", $f3->get('PARAMS.'.$key)) : 1;
} | csn_ccr |
func (w *SegmentWAL) Reader() WALReader {
return &repairingWALReader{
wal: w,
r: | newWALReader(w.files, w.logger),
}
} | csn_ccr |
Keep parsed val in memory per lang
@return mixed Parsed property value. | public function parsedVal()
{
if (!isset($this->parsedVal[$this->lang()])) {
$val = $this->propertyVal();
if ($val === null) {
return null;
}
$val = $this->p()->parseVal($val);
// Could be Translation instance
// Could... | csn |
def expand_x_1(n):
c =1
for i in range(n//2+1):
c = c*(n-i)//(i+1)
yield c
def aks(p):
if p==2:
return True
for i in expand_x_1(p):
if i % p:
return False
return True
| #include <iomanip>
#include <iostream>
using namespace std;
const int pasTriMax = 61;
uint64_t pasTri[pasTriMax + 1];
void pascalTriangle(unsigned long n)
{
unsigned long j, k;
pasTri[0] = 1;
j = 1;
while (j <= n)
{
j++;
k = j / 2;
pasTri[k] = pasTri[k - 1];
for ... | codetrans_contest |
Checks that current url matches action
``` php
<?php
$I->seeCurrentActionIs('PostsController@index');
?>
```
@param $action | public function seeCurrentActionIs($action)
{
$this->getRouteByAction($action); // Fails if route does not exists
$currentRoute = $this->app->request->route();
$currentAction = $currentRoute ? $currentRoute->getActionName() : '';
$currentAction = ltrim(str_replace($this->getRootContr... | csn |
def inc(self):
"""Get index for new entry."""
self.lock.acquire()
cur = self.counter
| self.counter += 1
self.lock.release()
return cur | csn_ccr |
function getReference( referenceFile ) {
var text = '';
// Read references file.
var referencePath = path.join( process.cwd(), referenceFile );
var stats = fs.statSync( referencePath );
if (stats && stats.isFile()) {
text = fs.readFileSync( referencePath, { encoding: 'utf8' } );
// Find common root... | var result = re.exec( line );
if (result)
// Save common root value.
tildes[ result[ 1 ] ] = line.substring( line.indexOf( ':' ) + 1 ).trim();
else if (line[ 0 ] === '[')
// Store reference link.
target.push( line );
}
text = target.join( '\n' );
// Replace tilde+nu... | csn_ccr |
// ResourceLocation returns a URL to which one can send traffic for the specified node. | func (r *REST) ResourceLocation(ctx context.Context, id string) (*url.URL, http.RoundTripper, error) {
return node.ResourceLocation(r, r.connection, r.proxyTransport, ctx, id)
} | csn |
protected static function filterEncoding(string $encoding): string
{
static $encoding_list;
if (null === $encoding_list) {
$list = mb_list_encodings();
$encoding_list = array_combine(array_map('strtolower', $list), $list);
}
$key = strtolower($encoding);
... | return $encoding_list[$key];
}
throw new OutOfRangeException(sprintf('The submitted charset %s is not supported by the mbstring extension', $encoding));
} | csn_ccr |
Initiate database maintenance tasks to improve database performance and
consistency.
A restart will be initiated in order to put the product into maintenance
mode while the tasks are run. It will then restart automatically.
@param [Boolean] clean_up Removes any unnecessary data from the database.
@param [Boolean]... | def db_maintenance(clean_up = false, compress = false, reindex = false)
return unless compress || clean_up || reindex
parameters = { 'cmd' => 'startMaintenance', 'targetTask' => 'dbMaintenance' }
parameters['cleanup'] = 1 if clean_up
parameters['compress'] = 1 if compress
parameters['rein... | csn |
Convert a string representation of a binary operator to an enum.
These enums come from the protobuf message definition
``StructuredQuery.FieldFilter.Operator``.
Args:
op_string (str): A comparison operation in the form of a string.
Acceptable values are ``<``, ``<=``, ``==``, ``>=``
... | def _enum_from_op_string(op_string):
"""Convert a string representation of a binary operator to an enum.
These enums come from the protobuf message definition
``StructuredQuery.FieldFilter.Operator``.
Args:
op_string (str): A comparison operation in the form of a string.
Acceptable... | csn |
public function slice($offset, $length = null, $preserveKeys = false, $asArray = false)
{
if (!is_int($offset)) {
throw new InvalidArgumentException('integer', 0);
}
if (!is_null($length) && !is_int($length)) {
throw new InvalidArgumentException('integer', 1);
... | $preserveKeys = !!$preserveKeys;
$array = $this->getArrayCopy();
$newArray = array_slice($array, $offset, $length, $preserveKeys);
return (!!$asArray) ? $newArray : new self($newArray);
} | csn_ccr |
Extend the generatePoints method by adding total and percentage properties to each point | function () {
var i,
total = 0,
points,
len,
point,
ignoreHiddenPoint = this.options.ignoreHiddenPoint;
Series.prototype.generatePoints.call(this);
// Populate local vars
points = this.points;
len = points.length;
// Get the total sum
for (i = 0; i < len; i++) {
point = points[i];
... | csn |
// RegisterMessage is called from generated code to register message. | func RegisterMessage(x Message, name string) {
name = x.GetMessageName() + "_" + x.GetCrcString()
/*if _, ok := registeredMessages[name]; ok {
panic(fmt.Errorf("govpp: duplicate message registered: %s (%s)", name, x.GetCrcString()))
}*/
registeredMessages[name] = x
} | csn |
def set_range(self, start=None, end=None, occurrences=None):
""" Set the range of recurrence
:param date start: Start date of repetition
:param date end: End date of repetition
:param int occurrences: no of occurrences
"""
if start is None:
if self.__start_da... | self.start_date = start
if end:
self.end_date = end
elif occurrences:
self.__occurrences = occurrences
self._track_changes() | csn_ccr |
return array as iterable python | def _npiter(arr):
"""Wrapper for iterating numpy array"""
for a in np.nditer(arr, flags=["refs_ok"]):
c = a.item()
if c is not None:
yield c | cosqa |
Gets the locale currently set within either the session or cookie.
@param HTTPRequest $request
@return null|string The locale, if available | protected function getPersistLocale(HTTPRequest $request)
{
$key = $this->getPersistKey();
// Skip persist if key is unset
if (empty($key)) {
return null;
}
// check session then cookies
$session = $request->getSession();
if ($session->isStarted(... | csn |
function check(CacheKey $key) {
if (isset ( $this->elements [$key->getModule()] [$key->getProperty()] )) {
| return true;
} else {
return false;
}
} | csn_ccr |
Gets the date at which the current session will expire or null if no session
has been created.
@return the date at which the current session will expire | protected final Date getExpirationDate() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
return (currentSession != null) ? currentSession.getExpirationDate() : null;
}
return null;
} | csn |
function (a, b) {
if (!b.pos || !a.pos) {
return (a.pos ? -Infinity : Infinity); |
}
var result = b.pos.z - a.pos.z;
return (result ? result : (b.pos.x - a.pos.x));
} | csn_ccr |
// SetClientTimeout sets the client request timeout | func (c *Client) SetClientTimeout(timeout time.Duration) {
c.modifyLock.RLock()
c.config.modifyLock.Lock()
defer c.config.modifyLock.Unlock()
c.modifyLock.RUnlock()
c.config.Timeout = timeout
} | csn |
def basic_query(returns):
"""decorator factory for NS queries"""
return compose(
reusable,
map_send(parse_request),
map_yield(prepare_params, | snug.prefix_adder(API_PREFIX)),
map_return(loads(returns)),
oneyield,
) | csn_ccr |
Write a DirectedPair in the current binary stream.
@param \qtism\common\datatypes\DirectedPair $directedPair A DirectedPair object.
@throws \qtism\runtime\storage\binary\QtiBinaryStreamAccessException | public function writeDirectedPair(QtiDirectedPair $directedPair)
{
try {
$this->writeString($directedPair->getFirst());
$this->writeString($directedPair->getSecond());
} catch (BinaryStreamAccessException $e) {
$msg = "An error occured while writing a directedPair... | csn |
def xrun(command, options, log=None, _log_container_as_started=False, logfile=None, timeout=-1, kill_callback=None):
"""
Run something on command line.
Example: _run("ls", ["-lrt", "../"])
"""
cmd = " ".join([command] + list(map(str, options)) )
def _print_info(msg):
if ms... | time.sleep(INTERRUPT_TIME)
Thread(target=clock_killer, args=tuple([p])).start()
while (process.poll() is None):
currenttime = time.time()
DEBUG and _print_info(u"God mode on: has been running for {0:f}".format(currenttime - starttime))
time.sle... | csn_ccr |
// Adds a format function to the formatFunc list. | func (fp *formatParser) addFormatFunc(
f func(*LineData, *bytes.Buffer) error, size int,
) {
fp.commitStatic()
fp.formatFuncs = append(fp.formatFuncs, f)
fp.initialSize += size
} | csn |
def remove(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
thread = args.first
options.merge!(:thread => thread) | if ([:ident, :link] & options.keys).empty?
response = post('threads/remove', options)
end | csn_ccr |
Adds a Participant Object representing a URI
@param documentRetrieveUri The URI of the Participant Object
@param documentUniqueId The Document Entry Unique ID | public void addDocumentUriParticipantObject(String documentRetrieveUri, String documentUniqueId)
{
List<TypeValuePairType> tvp = new LinkedList<>();
if (documentUniqueId != null) {
tvp.add(getTypeValuePair("XDSDocumentEntry.uniqueId", documentUniqueId.getBytes()));
}
addParticipantObjectIdentification(
... | csn |
Called when this action has been completed within the workflow | public function actionComplete(WorkflowTransition $transition)
{
$this->MemberID = Member::currentUserID();
$this->write();
$this->extend('onActionComplete', $transition);
} | csn |
Check that all the instances have the same types. | def _check_types(self) -> None:
"""
Check that all the instances have the same types.
"""
all_instance_fields_and_types: List[Dict[str, str]] = [{k: v.__class__.__name__
for k, v in x.fields.items()}
... | csn |
Parse the given `str` of JSON builder and return a function body.
@param {String} str
@param {Object} options
@return {String}
@api private | function parse(str, options) {
var obj = options.object || 'obj'
, space = options.pretty ? 2 : 0
, space = options.spaces ? options.spaces : space
, js = str;
return ''
+ 'var ' + obj + ' = factory();\n'
+ (options.self
? 'var self = locals || {};\n' + js
: 'with (locals || {}) {... | csn |
def ensure_vm_running(self, vm_location):
""" Gets or creates a Vagrantfile in ``vm_location`` and calls ``vagrant up`` if the VM is not running.
"""
import vagrant
if self.vagrant is None:
vagrant_file = vm_location / "Vagrantfile"
if not vagrant_file.exists():
... | err_cm=self.log_cm)
status = [x for x in self.vagrant.status() if x.name == "default"][0]
if status.state != "running":
try:
self.vagrant.up()
except subprocess.CalledProcessError:
raise BuildError("Vagrant VM couldn... | csn_ccr |
Set EEP based on FUNC and TYPE | def select_eep(self, rorg_func, rorg_type, direction=None, command=None):
''' Set EEP based on FUNC and TYPE '''
# set EEP profile
self.rorg_func = rorg_func
self.rorg_type = rorg_type
self._profile = self.eep.find_profile(self._bit_data, self.rorg, rorg_func, rorg_type, directio... | csn |
public function setValue($var)
{
GPBUtil::checkEnum($var, \Google\Cloud\Debugger\V2\Breakpoint_Action::class); |
$this->value = $var;
return $this;
} | csn_ccr |
Terminate and close the multiprocessing pool if necessary. | def terminate_pool(self):
"""Terminate and close the multiprocessing pool if necessary."""
if self.pool is not None:
self.pool.terminate()
self.pool.join()
del(self.pool)
self.pool = None | csn |
Returns the mask string for a given connection.
@param \Phergie\Irc\ConnectionInterface $connection
@return string | protected function getConnectionMask(ConnectionInterface $connection)
{
return strtolower(sprintf(
'%s!%s@%s',
$connection->getNickname(),
$connection->getUsername(),
$connection->getServerHostname()
));
} | csn |
public function setHolders($holders)
{
if(is_array($holders)) {
$this->holders = | $holders;
}
$args = func_get_args();
$this->holders[$args[0]] = $args[1];
return $this;
} | csn_ccr |
Write p2sh to the given buffer.
@param {String} scripthash For example multisig address
@param {Buffer} buffer
@param {Number} offset
@returns {Number} new offset | function writeScriptPayToScriptHash(scripthash, buffer, offset) {
offset = buffer.writeUInt8(23, offset); //Script length
offset = buffer.writeUInt8(OPS.OP_HASH160, offset);
//Write previous output address
offset = buffer.writeUInt8(20, offset); //Address length
offset += Buffer.from(base58check.dec... | csn |
async function post(url, body) {
try {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(body),
});
| wappalyzer.log(`POST ${url}: ${response.status}`, 'driver');
} catch (error) {
wappalyzer.log(`POST ${url}: ${error}`, 'driver', 'error');
}
} | csn_ccr |
Alphabetically sorts a range of menu items.
@param parent Parent whose children are to be sorted alphabetically.
@param startIndex Index of first child to be sorted.
@param endIndex Index of last child to be sorted. | public static void sortMenu(BaseComponent parent, int startIndex, int endIndex) {
List<BaseComponent> items = parent.getChildren();
int bottom = startIndex + 1;
for (int i = startIndex; i < endIndex;) {
BaseComponent item1 = items.get(i++);
BaseComponent item2 = items.ge... | csn |
def run(cookbook, options = {})
log.info("Running validations for `#{klass.id}.#{id}'")
inside(cookbook) do
instance = klass.new(cookbook, options)
unless result = instance.instance_eval(&block)
log.debug("Validation failed, result: #{result.inspect}")
# Convert the cla... | Error.const_get("#{Util.camelize(klass.id)}#{Util.camelize(id)}ValidationFailed")
raise error.new(path: Dir.pwd, result: result)
end
end
log.debug("Validation #{id} passed!")
end | csn_ccr |
Chef loves to play with arrays by himself. Today, he has an array A consisting of N distinct integers. He wants to perform the following operation on his array A.
- Select a pair of adjacent integers and remove the larger one of these two. This decreases the array size by 1. Cost of this operation will be equal to the... | from math import *
for t in range(int(input())):
n = int(input())
numberlist = list(map(int,input().split()))
numberlist.sort()
print(numberlist[0]* ( len(numberlist) -1)) | apps |
public User getUser() {
ClientResource resource = new ClientResource(Route.ME.url());
resource.setChallengeResponse(this.auth.toChallenge());
try {
| Representation repr = resource.get();
return mapper.readValue(repr.getText(), User.class);
} catch (IOException ex) {
LEX4JLogger.log(Level.WARNING, "Could not retrieve user (me) correctly!");
return null;
}
} | csn_ccr |
public boolean validation() throws ParallelTaskInvalidException {
ParallelTask task = new ParallelTask();
targetHostMeta = new TargetHostMeta(targetHosts);
task = new ParallelTask(requestProtocol, concurrency, httpMeta,
targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null,... | replacementVarMap, requestReplacementType, config);
boolean valid = false;
try {
valid = task.validateWithFillDefault();
} catch (ParallelTaskInvalidException e) {
logger.info("task is invalid " + e);
}
return valid;
} | csn_ccr |
sets path for local saving of information
if create is true we will create the folder even if it doesnt exist | def set_local_path(directory, create_dir=False):
"""
sets path for local saving of information
if create is true we will create the folder even if it doesnt exist
"""
if not os.path.exists(directory) and create_dir is True:
os.makedirs(directory)
if not os.path.exists(directory)... | csn |
function setFontFamily(fontFamily) {
var editor = EditorManager.getCurrentFullEditor();
if (currFontFamily === fontFamily) {
return;
}
_removeDynamicFontFamily();
if (fontFamily) {
_addDynamicFontFamily(fontFamily);
}
| exports.trigger("fontFamilyChange", fontFamily, currFontFamily);
currFontFamily = fontFamily;
prefs.set("fontFamily", fontFamily);
if (editor) {
editor.refreshAll();
}
} | csn_ccr |
%matplotlib inline
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from d2l import tensorflow as d2l
fair_probs = tf.ones(6) / 6
tfp.distributions.Multinomial(1, fair_probs).sample()
tfp.distributions.Multinomial(10, fair_probs).sample()
counts = tfp.distributions.Multinomial(1000, fair_... | %matplotlib inline
import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import random
import numpy as np
import paddle
fair_probs = [1.0 / 6] * 6
paddle.distribution.Multinomial(1, paddle.to_tensor(fair_probs)).sample()
counts = paddle.distribution.Multinomial(1000, paddle.to_tensor(fair_prob... | codetrans_dl |
public function set_identity($name) {
$sentence = new SentenceUtil();
$sentence->addCommand("/system/identity/set");
$sentence->setAttribute("name", | $name);
$this->talker->send($sentence);
return "Sucsess";
} | csn_ccr |
Applies and processes the pre-tsd command line
@param cap The main configuration wrapper
@param argp The preped command line argument handler | protected static void applyCommandLine(ConfigArgP cap, ArgP argp) {
// --config, --include-config, --help
if(argp.has("--help")) {
if(cap.hasNonOption("extended")) {
System.out.println(cap.getExtendedUsage("tsd extended usage:"));
} else {
System.out.println(cap.getDefaultUsage("tsd ... | csn |
def transcode(text, input=PREFERRED_ENCODING, output=PREFERRED_ENCODING):
"""Transcode a text string"""
try:
return text.decode("cp437").encode("cp1252")
except UnicodeError:
try:
| return text.decode("cp437").encode(output)
except UnicodeError:
return text | csn_ccr |
check if a number is complex in python | def is_complex(dtype):
"""Returns whether this is a complex floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_complex'):
return dtype.is_complex
return np.issubdtype(np.dtype(dtype), np.complex) | cosqa |
Focus at the end of the document
@param {Slate.Change} change
@return {Slate.Change} | function focusAtEnd(change) {
const { value } = change;
const document = value.document;
return change.collapseToEndOf(document);
} | csn |
public static final KeyPressHandler getRegExKeyPressHandler(final String pregEx) {
if (StringUtils.isEmpty(pregEx)) {
return null;
}
| RegExKeyPressHandler result = HandlerFactory.REG_EX_KEY_PRESS_HANDLER_MAP.get(pregEx);
if (result == null) {
result = new RegExKeyPressHandler(pregEx);
}
return result;
} | csn_ccr |
def reboot_instances(self, instance_ids=None):
"""
Reboot the specified instances.
:type instance_ids: list
:param instance_ids: The instances to terminate and reboot
"""
params = {}
if instance_ids: |
self.build_list_params(params, instance_ids, 'InstanceId')
return self.get_status('RebootInstances', params) | csn_ccr |
function readMultiPolygonGeometry(object, arcs) {
const coordinates = [];
for (let i = 0, ii = object['arcs'].length; i < ii; ++i) {
// for each polygon
const polyArray = object['arcs'][i];
const ringCoords = [];
for (let j = 0, jj = polyArray.length; j < jj; ++j) {
// for each ring |
ringCoords[j] = concatenateArcs(polyArray[j], arcs);
}
coordinates[i] = ringCoords;
}
return new MultiPolygon(coordinates);
} | csn_ccr |
Removes the specified featureSet from this repository. | def removeFeatureSet(self, featureSet):
"""
Removes the specified featureSet from this repository.
"""
q = models.Featureset.delete().where(
models.Featureset.id == featureSet.getId())
q.execute() | csn |
func (uvm *UtilityVM) findVPMEMDevice(findThisHostPath string) (uint32, string, error) {
for deviceNumber, vi := range uvm.vpmemDevices {
if vi.hostPath == findThisHostPath {
logrus.WithFields(logrus.Fields{
logfields.UVMID: uvm.id,
"host-path": findThisHostPath,
"uvm-path": vi.uvmPath,
"... | "deviceNumber": uint32(deviceNumber),
}).Debug("uvm::findVPMEMDevice")
return uint32(deviceNumber), vi.uvmPath, nil
}
}
return 0, "", fmt.Errorf("%s is not attached to VPMEM", findThisHostPath)
} | csn_ccr |
protected function exportItem($locations, $exportFormat, $labelFormat)
{
$form = $this->dataConversionForm($locations, $exportFormat, $labelFormat);
$item = null;
if ($form) {
$item | = $this->doc->createElement('li');
$item->appendChild($form);
}
return $item;
} | csn_ccr |
Accept an object or class name that implements StripperInterface
@param string|StripperInterface $stripper | public function addStripper($stripper)
{
if (is_string($stripper)) {
if (!class_exists($stripper)) {
$stripper = '\\' . __NAMESPACE__ . '\\Stripper\\' . $stripper;
if (!class_exists($stripper)) {
throw new \InvalidArgumentException('Class ' . $... | csn |
If the managed bean is of the desired type, remove it from the registry. | @SuppressWarnings("unchecked")
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
if (clazz.isInstance(bean)) {
unregister((V) bean);
}
} | csn |
Creates a new column item using the columns of the information_schema.columns.
@param array $record Associative array with TABLE_NAME, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH,
NUMERIC_PRECISION, COLUMN_DEFAULT, IS_NULLABLE
@return MW_Setup_DBSchema_Column_Interface Column item | protected function _createColumnItem( array $record = array() )
{
$length = ( isset( $record['CHARACTER_MAXIMUM_LENGTH'] ) ? $record['CHARACTER_MAXIMUM_LENGTH'] : $record['NUMERIC_PRECISION'] );
return new MW_Setup_DBSchema_Column_Item( $record['TABLE_NAME'], $record['COLUMN_NAME'], $record['DATA_TYPE'], $length,
... | csn |
public function useLineageRelatedByAncestorIdQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
{
return $this
->joinLineageRelatedByAncestorId($relationAlias, $joinType)
| ->useQuery($relationAlias ? $relationAlias : 'LineageRelatedByAncestorId', '\gossi\trixionary\model\LineageQuery');
} | csn_ccr |
def bindToEndPoint(self,bindingEndpoint):
"""
2-way binds the target endpoint to all other registered endpoints.
"""
| self.bindings[bindingEndpoint.instanceId] = bindingEndpoint
bindingEndpoint.valueChangedSignal.connect(self._updateEndpoints) | csn_ccr |
perform a better initial guess of lambda
no improvement | def pressision_try(orbitals, U, beta, step):
"""perform a better initial guess of lambda
no improvement"""
mu, lam = main(orbitals, U, beta, step)
mu2, lam2 = linspace(0, U*orbitals, step), zeros(step)
for i in range(99):
lam2[i+1] = fsolve(restriction, lam2[i], (mu2[i+1], orbitals, U, be... | csn |
// Amount order item's amount | func (item OrderItem) Amount() float32 {
amount := item.SellingPrice() * float32(item.Quantity)
if item.DiscountRate > 0 && item.DiscountRate <= 100 {
amount = amount * float32(100-item.DiscountRate) / 100
}
return amount
} | csn |
function ( uri ) {
var item = cache.items[uri];
return item !== undefined && | item.expires !== undefined && item.expires < new Date();
} | csn_ccr |
// StreamExecute is the RPC version of vtgateservice.VTGateService method | func (vtg *VTGate) StreamExecute(request *vtgatepb.StreamExecuteRequest, stream vtgateservicepb.Vitess_StreamExecuteServer) (err error) {
defer vtg.server.HandlePanic(&err)
ctx := withCallerIDContext(stream.Context(), request.CallerId)
// Handle backward compatibility.
session := request.Session
if session == nil... | csn |
// if path was removed, notify already removed the watch and returns EINVAL error | func removeInotifyWatch(fd int32, iwd int32) (err error) {
if _, err = unix.InotifyRmWatch(int(fd), uint32(iwd)); err != nil && err != unix.EINVAL {
return
}
return nil
} | csn |
Applies the provided conditions to the query. | private function applyConditions(QueryBuilder $query, array $conditions): void
{
foreach ($conditions as $identifier => $value) {
$query->andWhere(
$query->expr()->eq($identifier, ':' . $identifier)
);
$query->setParameter($identifier, $value, is_int($val... | csn |
Attaches a set of request headers to a stub.
@param stub to bind the headers to.
@param extraHeaders the headers to be passed by each call on the returned stub.
@return an implementation of the stub with {@code extraHeaders} bound to each call. | @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1789")
public static <T extends AbstractStub<T>> T attachHeaders(T stub, Metadata extraHeaders) {
return stub.withInterceptors(newAttachHeadersInterceptor(extraHeaders));
} | csn |
python suspend until response | def _wait_for_response(self):
"""
Wait until the user accepted or rejected the request
"""
while not self.server.response_code:
time.sleep(2)
time.sleep(5)
self.server.shutdown() | cosqa |
Private helper to init values from a dictionary, wraps children into
AttributeFilter objects
:param from_dictionary: dictionary to get attribute names and visibility from
:type from_dictionary: dict
:param template_model:
:type template_model: DataCollection | def _init_from_dictionary(self, from_dictionary, template_model=None):
"""
Private helper to init values from a dictionary, wraps children into
AttributeFilter objects
:param from_dictionary: dictionary to get attribute names and visibility from
:type from_dictionary: dict
... | csn |
// Confirm sends the confirm message | func (c *Client) Confirm() bool {
if err := c.Set("confirm", ""); err == nil {
return true
}
return false
} | csn |
python dialog choose directory | def browse_dialog_dir():
"""
Open up a GUI browse dialog window and let to user pick a target directory.
:return str: Target directory path
"""
_go_to_package()
logger_directory.info("enter browse_dialog")
_path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False)
... | cosqa |
This method will extract read the given stream and return the response from Lambda function separated out
from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function
wrote directly to stdout using System.out.println or equivalents.
Parameters
... | def get_lambda_output(stdout_stream):
"""
This method will extract read the given stream and return the response from Lambda function separated out
from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function
wrote directly to stdout using Syst... | csn |
Parses single abbreviation
@param {String} key Abbreviation name
@param {String} value Abbreviation value
@return {Object} | function parseAbbreviation(key, value) {
key = utils.trim(key);
var m;
if ((m = reTag.exec(value))) {
return elements.create('element', m[1], m[2], m[4] == '/');
} else {
// assume it's reference to another abbreviation
return elements.create('reference', value);
}
} | csn |
def private_messenger():
"""
Thread which runs in parallel and constantly checks for new messages
in the private pipe and sends them to the specific client.
If client is not connected the message is discarded.
"""
while __websocket_server_running__:
pipein = open(PRIVATE_PIPE, 'r')
... | message=message)
print line
remaining_lines = pipein.read()
pipein.close()
pipeout = open(PRIVATE_PIPE, 'w')
pipeout.write(remaining_lines)
pipeout.close()
else:
pipein.close()
t... | csn_ccr |
format a number to m or k if large python | def reportMemory(k, options, field=None, isBytes=False):
""" Given k kilobytes, report back the correct format as string.
"""
if options.pretty:
return prettyMemory(int(k), field=field, isBytes=isBytes)
else:
if isBytes:
k /= 1024.
if field is not None:
re... | cosqa |
On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed).
Examples:
Input: N = 1, K = 1
Output: 0
... | class Solution:
def maxChunksToSorted(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
res = 0
temp = sorted(arr)
sum1, sum2 = 0, 0
for i in range(0,len(arr)):
sum1 += arr[i]
sum2 += temp[i]
if(sum1 =... | apps |
Starts a "HAVING" condition
Only call this method once per query because it will overwrite any previously-set "HAVING" expressions
@param array $conditions,... A variable list of conditions to be met
@return self For method chaining | public function having(...$conditions) : self
{
// We want to wipe out anything already in the condition list
$this->havingConditions = [];
$this->havingConditions = $this->conditionalQueryBuilder->addConditionToClause(
$this->havingConditions, 'AND', ...$this->createConditionExp... | csn |
func (ns nsRefcounts_) CreateOrIncRefOp(coll mongo.Collection, key string, n int) (txn.Op, error) {
if exists, err := ns.exists(coll, key); err != nil {
return txn.Op{}, errors.Trace(err)
} else if !exists {
| return ns.JustCreateOp(coll.Name(), key, n), nil
}
return ns.JustIncRefOp(coll.Name(), key, n), nil
} | csn_ccr |
func (as *Step) AddURLLink(label, alias, url string) {
link := as.getOrCreateLinkForLabel(label)
| link.AliasLabel = alias
link.Value = &milo.Link_Url{url}
} | csn_ccr |
// debugGCS is a dirty hack for debugging for Linux Utility VMs. It simply
// runs a bunch of commands inside the UVM, but seriously aides in advanced debugging. | func (c *container) debugGCS() {
if c == nil || c.isWindows || c.hcsContainer == nil {
return
}
cfg := opengcs.Config{
Uvm: c.hcsContainer,
UvmTimeoutSeconds: 600,
}
cfg.DebugGCS()
} | csn |
function CreateSchemedProperty(object, scheme, schema_name, index) {
if (object[schema_name])
return;
Object.defineProperty(object, schema_name, {
configurable: false,
enumerable: true,
get: function() {
return this.getHook(schema_name, this.prop_array[index]);
... |
if (result.valid && this.prop_array[index] != val) {
this.prop_array[index] = this.setHook(schema_name, val);
this.scheduleUpdate(schema_name);
this._changed_ = true;
}
}
});
} | csn_ccr |
func decodeShortChanIDs(r io.Reader) (ShortChanIDEncoding, []ShortChannelID, error) {
// First, we'll attempt to read the number of bytes in the body of the
// set of encoded short channel ID's.
var numBytesResp uint16
err := ReadElements(r, &numBytesResp)
if err != nil {
return 0, nil, err
}
if numBytesResp ... |
if err := ReadElements(bodyReader, &shortChanIDs[i]); err != nil {
return 0, nil, fmt.Errorf("unable to parse "+
"short chan ID: %v", err)
}
}
return encodingType, shortChanIDs, nil
// In this encoding, we'll use zlib to decode the compressed payload.
// However, we'll pay attention to ensure th... | csn_ccr |
def _setup_arm_arch(self, arch_mode=None):
"""Set up ARM architecture.
"""
if arch_mode is None:
arch_mode = ARCH_ARM_MODE_THUMB
| self.name = "ARM"
self.arch_info = ArmArchitectureInformation(arch_mode)
self.disassembler = ArmDisassembler(architecture_mode=arch_mode)
self.ir_translator = ArmTranslator(architecture_mode=arch_mode) | csn_ccr |
func (pm *ProtocolManager) handle(p *peer) error {
// Ignore maxPeers if this is a trusted peer
// In server mode we try to check into the client pool after handshake
if pm.lightSync && pm.peers.Len() >= pm.maxPeers && !p.Peer.Info().Network.Trusted {
return p2p.DiscTooManyPeers
}
p.Log().Debug("Light Ethereum ... | }
defer func() {
pm.removePeer(p.id)
}()
// Register the peer in the downloader. If the downloader considers it banned, we disconnect
if pm.lightSync {
p.lock.Lock()
head := p.headInfo
p.lock.Unlock()
if pm.fetcher != nil {
pm.fetcher.announce(p, head)
}
if p.poolEntry != nil {
pm.serverPool.... | csn_ccr |
This static function is used to perform the actual upload and resizing using the Multup class
@return array | public function doUpload()
{
$mimes = $this->getOption('mimes') ? '|mimes:' . $this->getOption('mimes') : '';
//use the multup library to perform the upload
$result = Multup::open('file', 'max:' . $this->getOption('size_limit') * 1000 . $mimes, $this->getOption('location'),
$this->getOption('naming') =... | csn |
private function loadPaginated(array $options, $limit, $page, $pageSize)
{
$pageSize = intval($pageSize);
$offset = ($page - 1) * $pageSize;
$position = $pageSize * $page;
if (null !== $limit && $position >= $limit) {
$pageSize = $limit - $offset;
$loadLimit ... | $options['webspaceKey'],
[$options['locale']],
$this->contentQueryBuilder,
true,
-1,
$loadLimit,
$offset
);
} | csn_ccr |
category property setter.
@param string|array $category
@return self | public function setCategory($category)
{
$properties = $this->getProperty();
$properties['category'] = (array) $category;
$this->getConfig()->setSection('bundle', $properties, true);
return $this;
} | csn |
func (s *Scanner) recentPosition() (pos token.Pos) {
pos.Offset = s.srcPos.Offset - s.lastCharLen
switch {
case s.srcPos.Column > 0:
// common case: last character was not a '\n'
pos.Line = s.srcPos.Line
pos.Column = s.srcPos.Column |
case s.lastLineLen > 0:
// last character was a '\n'
// (we cannot be at the beginning of the source
// since we have called next() at least once)
pos.Line = s.srcPos.Line - 1
pos.Column = s.lastLineLen
default:
// at the beginning of the source
pos.Line = 1
pos.Column = 1
}
return
} | csn_ccr |
Render Columns object
@param SQL\Columns $item
@return string | public static function renderItem(SQL\Columns $item)
{
return Compiler::braced(
Arr::join(', ', Arr::map(__NAMESPACE__.'\Compiler::name', $item->all()))
);
} | csn |
func (s *PhasedStopper) StopInbounds() error {
if s.inboundsStopInitiated.Swap(true) {
return errors.New("already began stopping inbounds")
}
defer s.inboundsStopped.Store(true)
| s.log.Debug("stopping inbounds")
wait := errorsync.ErrorWaiter{}
for _, ib := range s.dispatcher.inbounds {
wait.Submit(ib.Stop)
}
if errs := wait.Wait(); len(errs) > 0 {
return multierr.Combine(errs...)
}
s.log.Debug("stopped inbounds")
return nil
} | csn_ccr |
def set_step_name
case self.job.type
when 'Elasticrawl::ParseJob'
if self.crawl_segment.present?
max_files = self.job.max_files || 'all'
"#{self.crawl_segment.segment_desc} Parsing: #{max_files}"
end
| when 'Elasticrawl::CombineJob'
paths = self.input_paths.split(',')
"Combining #{paths.count} jobs"
end
end | csn_ccr |
returns true if time is aligned to the recurrence pattern and matches all the filters | def match?(time, base)
aligned?(time, base) && @filters.all? { |f| f.match?(time) }
end | csn |
Creates new instance of \Google\Protobuf\FileDescriptorSet
@throws \InvalidArgumentException
@return FileDescriptorSet | public static function create()
{
switch (func_num_args()) {
case 0:
return new FileDescriptorSet();
case 1:
return new FileDescriptorSet(func_get_arg(0));
case 2:
return new FileDescriptorSet(func_get_arg(0), func_get_arg(1));
case 3:
return new FileDescriptorSet(func_get_arg(0), func_ge... | csn |
python invalid type typecast | def is_timestamp(obj):
"""
Yaml either have automatically converted it to a datetime object
or it is a string that will be validated later.
"""
return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj) | cosqa |
Handles `GUILD_MEMBERS_CHUNK` packets.
@param object $data Packet data. | protected function handleGuildMembersChunk($data)
{
$guild = $this->guilds->get('id', $data->d->guild_id);
$members = $data->d->members;
$this->logger->debug('received guild member chunk', ['guild_id' => $guild->id, 'guild_name' => $guild->name, 'member_count' => count($members)]);
... | csn |
Create new Config object, either ephemerally or from a file | def write
new = get
new[@note] = @token
File.open(@file, 'w', 0o0600) { |fh| fh.write new.to_yaml }
end | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.