query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Add a file to a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
branch
The name of a branch.
file... | def add_file(
profile,
branch,
file_path,
file_contents,
is_executable=False,
commit_message=None):
"""Add a file to a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this... | csn |
public static function request(
$arg_endpoint,
$arg_method,
array $arg_data = array(),
array $arg_headers = array()
) {
$return = array();
$headers = array(
'Accept: application/json',
'DUE-API-KEY: '.Due::getApiKey(),
'DUE-PLATFORM... | = substr($response, $header_size);
$return['headers'] = self::headersToArray($headers);
$return['body'] = json_decode($body, true);
if(!empty($return['body']['errors'][0])){
$api_error = $return['body']['errors'][0];
$message = (empty($api_error['mess... | csn_ccr |
merge mongo group options array
@param $opt | protected function _mongo_addGroup($opt) {
if (!$this->grp_stack)
$this->grp_stack = array('keys'=>array(),'initial'=>array(),'reduce'=>'','finalize'=>'');
if (isset($opt['keys']))
$this->grp_stack['keys']+=$opt['keys'];
if (isset($opt['reduce']))
$this->grp_stack['reduce'].=$opt['reduce'];
if (isset($... | csn |
Checks if the composite AND of specifications passes.
@param ReturnType\TypeInterface $type
@return bool | public function isSatisfiedBy(ReturnType\TypeInterface $type)
{
return $this->left->isSatisfiedBy($type) && $this->right->isSatisfiedBy($type);
} | csn |
func (a *Attribute) intComparator(b *Attribute) (int, bool) {
ai := a.getInt()
bi := b.getInt()
if ai == bi {
return 0, true
} else | if ai < bi {
return -1, true
} else {
return 1, true
}
} | csn_ccr |
// Close closes the LevelDB database of the prefix queue. | func (pq *PrefixQueue) Close() error {
pq.Lock()
defer pq.Unlock()
// Check if queue is already closed.
if !pq.isOpen {
return nil
}
// Close the LevelDB database.
if err := pq.db.Close(); err != nil {
return err
}
// Reset size and set isOpen to false.
pq.size = 0
pq.isOpen = false
return nil
} | csn |
Decorate function to cache its return value.
:lifetime: How long to cache items for
:fetch_on_miss: Whether to perform a synchronous fetch when no cached
result is found
:cache_alias: The Django cache alias to store the result into.
:job_class: The class to use for running the cache... | def cacheback(lifetime=None, fetch_on_miss=None, cache_alias=None,
job_class=None, task_options=None, **job_class_kwargs):
"""
Decorate function to cache its return value.
:lifetime: How long to cache items for
:fetch_on_miss: Whether to perform a synchronous fetch when no cached
... | csn |
Method is used to parse hosts and ports
@param config
@param key
@return | public static List<HostAndPort> hostAndPorts(AbstractConfig config, String key) {
return hostAndPorts(config, key, null);
} | csn |
Extract namespace from class name
@param string $class class name
@return string $class class name | private static function _extractClassName($cls)
{
$tokens = preg_split("/\\\\/", $cls);
$size = sizeof($tokens);
if ($size < 2) {
return $cls;
}
return $tokens[$size-1];
} | csn |
// newAsyncIDTokenVerifier creates a new asynchronous token verifier. The
// verifier is available immediately, but may remain uninitialized for some time
// after creation. | func newAsyncIDTokenVerifier(ctx context.Context, c *oidc.Config, iss string) *asyncIDTokenVerifier {
t := &asyncIDTokenVerifier{}
sync := make(chan struct{})
// Polls indefinitely in an attempt to initialize the distributed claims
// verifier, or until context canceled.
initFn := func() (done bool, err error) {
... | csn |
Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2^{w}_{i} pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to ... | n = int(input())
a = [int(x) for x in input().split()]
l = [0] * (10**6 + 100)
for x in a:
l[x] += 1
cur = 0
ans = 0
for x in l:
cur += x
if cur % 2:
ans += 1
cur //= 2
print(ans)
| apps |
func RetrySelect(n int, r, w, e *FDSet, timeout time.Duration, retries int, retryDelay time.Duration) (err error) {
for i := 0; i < retries; i++ {
if err = Select(n, r, | w, e, timeout); err != syscall.EINTR {
return err
}
time.Sleep(retryDelay)
}
return err
} | csn_ccr |
func validateOptionNames(o values.Object) error {
var unexpected []string
o.Range(func(name string, _ values.Value) {
switch name {
case optName, optCron, optEvery, optOffset, optConcurrency, optRetry:
// Known option. Nothing to do.
default:
unexpected = append(unexpected, name)
}
})
if len(unexpect... | strings.Join([]string{optName, optCron, optEvery, optOffset, optConcurrency, optRetry}, ", ")
return fmt.Errorf("unknown task option(s): %s. valid options are %s", u, v)
}
return nil
} | csn_ccr |
protected void updateFromSelection() {
DBIDSelection sel = context.getSelection();
if(sel != null) { |
this.dbids = DBIDUtil.newArray(sel.getSelectedIds());
this.dbids.sort();
}
else {
this.dbids = DBIDUtil.newArray();
}
} | csn_ccr |
Set current page url. | private function setCurrentPageUrl()
{
$controller = Url::segment(1);
$method = '';
$method = (Url::segment(2) == '') ? 'index' : Url::segment(2);
$this->currentPageUrl = Url::getBase().$controller.'/'.$method;
} | csn |
func (p *Properties) SetMust(iface, property string, v interface{}) {
p.mut.Lock()
defer p.mut.Unlock() // unlock in case of panic |
if err := p.set(iface, property, v); err != nil {
panic(err)
}
} | csn_ccr |
Allow us to run gedbrowser as a standalone application with an embedded
application server.
@param args command line arguments
@throws InterruptedException if thread sleep fails at end | public static void main(final String[] args) throws InterruptedException {
SpringApplication.run(Application.class, args);
Thread.sleep(TWENTY_SECONDS);
} | csn |
func NewParams() *Params {
return &Params{
insCost: 1,
subCost: 1,
delCost: | 1,
maxCost: 0,
minScore: 0,
bonusPrefix: 4,
bonusScale: .1,
bonusThreshold: .7,
}
} | csn_ccr |
func Mounted(fsType FsMagic, mountPath string) (bool, error) {
cs := C.CString(filepath.Dir(mountPath))
defer C.free(unsafe.Pointer(cs))
buf := C.getstatfs(cs)
defer C.free(unsafe.Pointer(buf))
// on Solaris buf.f_basetype contains ['z', 'f', 's', 0 ... ]
if (buf.f_basetype[0] != 122) || (buf.f_basetype[1] != 1... | || (buf.f_basetype[2] != 115) ||
(buf.f_basetype[3] != 0) {
logrus.Debugf("[zfs] no zfs dataset found for rootdir '%s'", mountPath)
return false, ErrPrerequisites
}
return true, nil
} | csn_ccr |
def branches():
# type: () -> List[str]
""" Return a list of branches in the current repo.
Returns:
list[str]: A list of branches in the current repo.
"""
out = shell.run(
'git branch',
capture=True, |
never_pretend=True
).stdout.strip()
return [x.strip('* \t\n') for x in out.splitlines()] | csn_ccr |
public static void shutdown() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "shutdown");
}
synchronized (oneAtATime) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "have lock"); // runn... | if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "AsyncException occured while shutting down: " + ae.getMessage());
}
}
}
} // end-sync
if (TraceComponent.isAnyTracingEnabled() && tc.is... | csn_ccr |
func AccessTokenWithManager(s string, manager tokens.Manager) | Strategy {
return &accessToken{
accessToken: s,
manager: manager,
}
} | csn_ccr |
Try to read a value named ``key`` from the GET parameters. | def get_from_params(request, key):
"""Try to read a value named ``key`` from the GET parameters.
"""
data = getattr(request, 'json', None) or request.values
value = data.get(key)
return to_native(value) | csn |
Check if dtype string is valid and return ctype string. | def _check_dtype(self, dtype):
"""Check if dtype string is valid and return ctype string."""
try:
return _ffi_types[dtype]
except KeyError:
raise ValueError("dtype must be one of {0!r} and not {1!r}".format(
sorted(_ffi_types.keys()), dtype)) | csn |
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RepositoryImportStatus. | func (in *RepositoryImportStatus) DeepCopy() *RepositoryImportStatus {
if in == nil {
return nil
}
out := new(RepositoryImportStatus)
in.DeepCopyInto(out)
return out
} | csn |
register a publisher
@param [String] topic topic name of topic
@param [String] topic_type type of topic
@return [Array] URI of current subscribers
@raise RuntimeError | def register_publisher(topic, topic_type)
code, message, uris = @proxy.registerPublisher(@caller_id,
topic,
topic_type,
@slave_uri)
if code == 1
... | csn |
// LimitedLengthName returns a string subject to a maximum length | func LimitedLengthName(s string, n int) string {
// We only use the hash if we need to
if len(s) <= n {
return s
}
h := fnv.New32a()
if _, err := h.Write([]byte(s)); err != nil {
glog.Fatalf("error hashing values: %v", err)
}
hashString := base32.HexEncoding.EncodeToString(h.Sum(nil))
hashString = strings.... | csn |
private function createElement($type, $children = array(), array $attributes = array(), $text = null)
{
$element = new NodeElement();
$element->openTag($type);
if (!empty($attributes)) {
$element->addAttributes($attributes);
}
if (!empty($children)) {
... | $element->appendChildren($children);
}
if ($text !== null) {
$element->setText($text);
}
$element->closeTag();
return $element;
} | csn_ccr |
Get first dom element from iterable or selector.
@param {(string|Array|NodeList|HTMLCollection|Window|Node)} input - The iterable, selector or elements.
@return {(Window|Node|boolean)} element - The dom element from input.
@example //esnext
import { createElement, append, getElement } from 'chirashi'
const sushi = crea... | function getElement(input) {
if (typeof input === 'string') {
return _getElement(document, input);
}
if (input instanceof window.NodeList || input instanceof window.HTMLCollection) {
return input[0];
}
if (input instanceof Array) {
return getElement(input[0]);
}
return isDomElement(input) &... | csn |
@Override
public void setScaleDownInsideBorders(boolean scaleDownInsideBorders) {
if (mScaleDownInsideBorders != scaleDownInsideBorders) {
| mScaleDownInsideBorders = scaleDownInsideBorders;
mIsPathDirty = true;
invalidateSelf();
}
} | csn_ccr |
Gets the permissions for the specified share.
:param str share_name:
Name of existing share.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: A dictionary of access policies associated with the share.
:rtype: dict(str, :class:`~azure.st... | def get_share_acl(self, share_name, timeout=None):
'''
Gets the permissions for the specified share.
:param str share_name:
Name of existing share.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: A dictionary of access policies... | csn |
public function getQueryProductsAssembly()
{
$category_id = $this->getEntityManager()->getRepository('EcommerceBundle:Category')->AssemblyCategory();
return $this->createQueryBuilder('p')
| ->where('p.category = :category_id')
->setParameter('category_id', $category_id);
} | csn_ccr |
public function down()
{
$results = '';
foreach ($this->toArray() as $column => | $attributes) {
$results .= $this->createField($column, $attributes, 'remove');
}
return $results;
} | csn_ccr |
@Nonnull
public EContinue encode (@Nonnull final String sSource, @Nonnull final ByteBuffer aDestBuffer)
{
ValueEnforcer.notNull (sSource, "Source");
ValueEnforcer.notNull (aDestBuffer, "DestBuffer");
// We need to special case the empty string
if (sSource.length () == 0)
return EContinue.BREA... | a branch by always subtracting
assert m_aInChar.remaining () <= 1;
m_nReadOffset -= m_aInChar.remaining ();
assert m_nReadOffset > 0;
// If we are done, break. Otherwise, read the next chunk
if (m_nReadOffset == sSource.length ())
break;
_readInputChunk (sSour... | csn_ccr |
def create_analysisrequest(container, **data):
"""Create a minimun viable AnalysisRequest
:param container: A single folderish catalog brain or content object
:type container: ATContentType/DexterityContentType/CatalogBrain
"""
container = get_object(container)
request = req.get_request()
#... |
sample_type = data.get("SampleType", None)
if sample_type is None:
fail(400, "Please provide a SampleType")
# TODO We should handle the same values as in the DataManager for this field
# (UID, path, objects, dictionaries ...)
results = search(portal_type="SampleType", title=sample_typ... | csn_ccr |
function(repository, userCredentials){
var credentials = {
gitSshUsername : "",
gitSshPassword : "",
gitPrivateKey : "",
gitPassphrase : ""
};
if(userCredentials !== undefined){
if(userCredentials.gitSshUsername !== undefined && userCredentials.gitSshUsername !== null) { creden... | var d = new Deferred();
this._preferenceService.get(this._prefix, undefined, {scope: 2}).then(
function(pref){
var settings = pref["settings"];
if(settings === undefined){
d.reject();
return;
}
if(settings.enabled){
var data = {};
data[repository] = ... | csn_ccr |
// Post dispatches to the given handler when the pattern matches and the HTTP
// method is POST. | func (m *Mux) Post(pattern PatternType, handler HandlerType) {
m.rt.handleUntyped(pattern, mPOST, handler)
} | csn |
Bypasses a specified number of elements and then returns the remaining elements.
@param int $count The number of elements to skip before returning the remaining elements.
@return Linq A Linq object that contains the elements that occur after the specified index. | public function skip($count)
{
// If its an array iterator we must check the arrays bounds are greater than the skip count.
// This is because the LimitIterator will use the seek() method which will throw an exception if $count > array.bounds.
$innerIterator = $this->iterator;
if ($i... | csn |
Make a function that will return a greeting statement that uses an input; your program should return, `"Hello, how are you doing today?"`.
SQL: return results in a column named ```greeting```
*[Make sure you type the exact thing I wrote or the program may not execute properly]* | def greet(name):
return "Hello, {} how are you doing today?".format(name) | apps |
delete the jenkins job, if it exists | def delete(self):
""" delete the jenkins job, if it exists """
if self.jenkins_host.has_job(self.name):
LOGGER.info("deleting {0}...".format(self.name))
self.jenkins_host.delete_job(self.name) | csn |
def import_data(self, fname):
"""Import data in current namespace"""
if self.count():
nsb = self.current_widget()
nsb.refresh_table()
nsb.import_data(filenames=fname)
if self.dockwidget | and not self.ismaximized:
self.dockwidget.setVisible(True)
self.dockwidget.raise_() | csn_ccr |
Draws 1 pixel on the resource at a specific position with a determined color.
@param resource $im
@param int $x
@param int $y
@param int $color | protected function drawPixel($im, $x, $y, $color = self::COLOR_FG) {
$xR = ($x + $this->offsetX) * $this->scale + $this->pushLabel[0];
$yR = ($y + $this->offsetY) * $this->scale + $this->pushLabel[1];
// We always draw a rectangle
imagefilledrectangle($im,
$xR,
... | csn |
def list_next(next_link, custom_headers:nil)
response = list_next_async(next_link, | custom_headers:custom_headers).value!
response.body unless response.nil?
end | csn_ccr |
def add_handler(self, event, handler):
"""Adds a handler function for an event.
Note: Only one handler function is allowed per event on the module
level (different modules can provide handlers for the same event).
This is because ordering of handler functions is not guaranteed to
... | and more succint to use the
decorator form of this e.g. @Module.handle('EVENT')
"""
if event in self.event_handlers:
raise ValueError("Cannot register handler for '%s' twice." % event)
self.event_handlers[event] = handler | csn_ccr |
function sendSharedAddressToPeer(device_address, shared_address, handle){
var arrDefinition;
var assocSignersByPath={};
async.series([
function(cb){
db.query("SELECT definition FROM shared_addresses WHERE shared_address=?", [shared_address], function(rows){
if (!rows[0])
return cb("Definition not found... | rows.forEach(function(row){
assocSignersByPath[row.signing_path] = {address: row.address, member_signing_path: row.member_signing_path, device_address: row.device_address};
});
return cb(null);
});
}
],
function(err){
if (err)
return handle(err);
sendNewSharedAddress(device_address, shared_... | csn_ccr |
// UpdateUnreadCount will take the unread count for an account id and
// update the badger. | func (s *Stellar) UpdateUnreadCount(ctx context.Context, accountID stellar1.AccountID, unread int) error {
if s.badger == nil {
s.G().Log.CDebugf(ctx, "Stellar Global has no badger")
return nil
}
s.badger.SetWalletAccountUnreadCount(ctx, accountID, unread)
return nil
} | csn |
Generate the tangents and fake a circular buffer while accounting for closedness
@return [Array<Vector>] the tangents | def tangent_loop
edges.map {|e| e.direction }.tap do |tangents|
# Generating a bisector for each vertex requires an edge on both sides of each vertex.
# Obviously, the first and last vertices each have only a single adjacent edge, unless the
# Polyline happens to be closed (like a Polygon). When not closed, ... | csn |
public boolean contains(Rect r) {
// check for empty first
return this.left < this.right && this.top < this.bottom
// now check for containment
| && left <= r.left && top <= r.top && right >= r.right && bottom >= r.bottom;
} | csn_ccr |
// NewHandler creates a prometheus publisher - a http.Handler and an xstats.Sender. | func NewHandler() *sender {
return &sender{
Handler: prometheus.Handler(),
counters: make(map[string]*prometheus.CounterVec),
gauges: make(map[string]*prometheus.GaugeVec),
histograms: make(map[string]*prometheus.HistogramVec),
}
} | csn |
Performs the evaluation of the objective at x. | def evaluate(self, x):
"""
Performs the evaluation of the objective at x.
"""
if self.n_procs == 1:
f_evals, cost_evals = self._eval_func(x)
else:
try:
f_evals, cost_evals = self._syncronous_batch_evaluation(x)
except:
... | csn |
Adds a single space on the right sight.
@param \PHP_CodeSniffer\Files\File $phpcsFile
@param int $index
@return void | protected function addSpace(File $phpcsFile, int $index): void
{
if ($phpcsFile->fixer->enabled !== true) {
return;
}
$phpcsFile->fixer->addContent($index, ' ');
} | csn |
func (w *Writer) SetOffset(n int64) {
if w.cw.count != | 0 {
panic("zip: SetOffset called after data was written")
}
w.cw.count = n
} | csn_ccr |
public Object inject(Class Klass, boolean doPostConstruct) throws InjectionProviderException {
| return inject(Klass,doPostConstruct,(ExternalContext)null);
} | csn_ccr |
Once the template is successfully fetched, use its contents to proceed. Context argument is first, since it is bound for partial application reasons. | function done(context, template) {
// Store the rendered template someplace so it can be re-assignable.
var rendered;
// Trigger this once the render method has completed.
manager.callback = function(rendered) {
// Clean up asynchronous manager properties.
delete manager.isAsync... | csn |
private void initialiseMetaConcepts(TransactionOLTP tx) {
VertexElement type = tx.addTypeVertex(Schema.MetaSchema.THING.getId(), Schema.MetaSchema.THING.getLabel(), Schema.BaseType.TYPE);
VertexElement entityType = tx.addTypeVertex(Schema.MetaSchema.ENTITY.getId(), Schema.MetaSchema.ENTITY.getLabel(), S... | tx.addTypeVertex(Schema.MetaSchema.ATTRIBUTE.getId(), Schema.MetaSchema.ATTRIBUTE.getLabel(), Schema.BaseType.ATTRIBUTE_TYPE);
tx.addTypeVertex(Schema.MetaSchema.ROLE.getId(), Schema.MetaSchema.ROLE.getLabel(), Schema.BaseType.ROLE);
tx.addTypeVertex(Schema.MetaSchema.RULE.getId(), Schema.MetaSchema.RU... | csn_ccr |
Convert TTL to seconds from now
@param null|int|DateInterval $ttl
@return int|null
@throws InvalidArgumentException | protected function ttlToSeconds($ttl): ?int
{
if (!isset($ttl)) {
return $this->ttl;
}
if ($ttl instanceof DateInterval) {
$reference = new DateTimeImmutable();
$endTime = $reference->add($ttl);
$ttl = $endTime->getTimestamp() - $reference->g... | csn |
get detailed role information.
@param string $role
@return array
@throws \GuzzleHttp\Exception\BadResponseException | public function getRole($role)
{
$params = [
'role' => $role,
];
$body = $this->request(self::URI_AUTH_ROLE_GET, $params);
$body = $this->decodeBodyForFields(
$body,
'perm',
['key', 'range_end',]
);
if ($this->pretty &&... | csn |
def _build_send_args(self, **kwargs):
"""Merge optional arguments with defaults.
:param kwargs: Keyword arguments | to `Session::send`
"""
out = {}
out.update(self._default_send_args)
out.update(kwargs)
return out | csn_ccr |
Set the local name of a specific attribute.
@param index The index of the attribute (zero-based).
@param localName The attribute's local name, or the empty
string for none.
@exception java.lang.ArrayIndexOutOfBoundsException When the
supplied index does not point to an attribute
in the list. | public void setLocalName (int index, String localName)
{
if (index >= 0 && index < length) {
data[index*5+1] = localName;
} else {
badIndex(index);
}
} | csn |
def htmlSaveFileFormat(self, filename, encoding, format):
"""Dump an HTML document to a | file using a given encoding. """
ret = libxml2mod.htmlSaveFileFormat(filename, self._o, encoding, format)
return ret | csn_ccr |
def find_resources(type)
resource_collection.all_resources.select do |resource|
| resource_name(resource) == type.to_sym
end
end | csn_ccr |
Return true to cancel default action.
@param {aria.DomEvent|Number} eventOrCharCode Original event or character code directly
@param {Number} keyCode Ignored if the original event has been passed, otherwise the code of the button pressed
@return {Boolean} | function (eventOrCharCode, keyCode) {
// -------------------------------------- input arguments processing
var event;
var charCode;
if (ariaUtilsType.isObject(eventOrCharCode)) {
event = eventOrCharCode;
charCode = event.charCode;
... | csn |
Update a user
CLI Example:
.. code-block:: bash
salt '*' keystoneng.user_update name=user1 enabled=False description='new description'
salt '*' keystoneng.user_update name=user1 new_name=newuser | def user_update(auth=None, **kwargs):
'''
Update a user
CLI Example:
.. code-block:: bash
salt '*' keystoneng.user_update name=user1 enabled=False description='new description'
salt '*' keystoneng.user_update name=user1 new_name=newuser
'''
cloud = get_openstack_cloud(auth)
... | csn |
Idempotent query cache create mechanism. | public InternalQueryCache<K, V> tryCreateQueryCache(String mapName, String cacheName,
ConstructorFunction<String, InternalQueryCache<K, V>> constructor) {
ContextMutexFactory.Mutex mutex = lifecycleMutexFactory.mutexFor(mapName);
try {
... | csn |
static Class<?> getOutputType(Class<?> fieldType) {
if (!Number.class.isAssignableFrom(fieldType)) {
throw new IllegalStateException("Aggregation SUM cannot be applied to property of type " + fieldType.getName());
}
if (fieldType == Double.class || fieldType == Float.class) {
return ... | }
if (fieldType == Long.class || fieldType == Integer.class || fieldType == Byte.class || fieldType == Short.class) {
return Long.class;
}
return fieldType;
} | csn_ccr |
func (a *NavigateArgs) SetFrameID(frameID FrameID) *NavigateArgs {
| a.FrameID = &frameID
return a
} | csn_ccr |
Index all recordings.
@param string $type
@param array $parameters
@param int $page
@return \Illuminate\Support\Collection | public function index($type, array $parameters = array(), $page = null)
{
$url = 'projects/recordings.json';
$recordings = $this->client->get($url, [
'query' => array_merge([
'type' => $type,
'page' => $page,
], $parameters)
]);
... | csn |
// Run starts the brokering and should be executed in a goroutine, since it
// blocks forever, or until the session closes. | func (m *muxBroker) Run() {
for {
stream, err := m.session.AcceptStream()
if err != nil {
// Once we receive an error, just exit
break
}
// Read the stream ID from the stream
var id uint32
if err := binary.Read(stream, binary.LittleEndian, &id); err != nil {
stream.Close()
continue
}
// I... | csn |
// Convert_v1beta1_LeaseSpec_To_coordination_LeaseSpec is an autogenerated conversion function. | func Convert_v1beta1_LeaseSpec_To_coordination_LeaseSpec(in *v1beta1.LeaseSpec, out *coordination.LeaseSpec, s conversion.Scope) error {
return autoConvert_v1beta1_LeaseSpec_To_coordination_LeaseSpec(in, out, s)
} | csn |
Bind the event handler to the toolbar buttons | function(hook, context){
var hs = $('#heading-selection');
hs.on('change', function(){
var value = $(this).val();
var intValue = parseInt(value,10);
if(!_.isNaN(intValue)){
context.ace.callWithAce(function(ace){
ace.ace_doInsertHeading(intValue);
},'insertheading' , true);
hs.v... | csn |
Initializes new multipart upload for given bucket name, object name and content type. | private String initMultipartUpload(String bucketName, String objectName, Map<String, String> headerMap)
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
... | csn |
def maximum(self, vars_list: List[str]) -> 'TensorFluent':
'''Returns the TensorFluent for the maximum aggregation function.
Args:
vars_list: The list of variables to be aggregated over.
Returns:
| A TensorFluent wrapping the maximum aggregation function.
'''
return self._aggregation_op(tf.reduce_max, self, vars_list) | csn_ccr |
Returns the type of the given column based on its row values on the given RunSetResult.
@param column: the column to return the correct ColumnType for
@param column_values: the column values to consider
@return: a tuple of a type object describing the column - the concrete ColumnType is stored in the attrib... | def get_column_type(column, column_values):
"""
Returns the type of the given column based on its row values on the given RunSetResult.
@param column: the column to return the correct ColumnType for
@param column_values: the column values to consider
@return: a tuple of a type object describing the ... | csn |
function one(config, node) {
var offset = config.location.toOffset
var parser = config.parser
var doc = config.doc
var type = node.type
var start = offset(position.start(node))
var end = offset(position.end(node))
if (config.ignore.indexOf(type) === -1) {
if (config.source.indexOf(type) !== -1) {
... | return patch(config, parser.tokenize(node.alt), start + 2)
}
if (type === 'text' || type === 'escape') {
return patch(config, parser.tokenize(node.value), start)
}
if (node.type === 'break') {
return patch(config, [parser.tokenizeWhiteSpace('\n')], start)
}
}
return null
} | csn_ccr |
def commit_source_archive(file, message)
from_directory do
result_dir = File.join(packages_dir, name)
FileUtils.mkdir_p(result_dir)
result_path = File.join(result_dir, File.basename(file))
FileUtils.cp(file, result_path)
@git.commit_file(result_path, "Source archive added"... | Tetra::Tar.new
end
Dir.glob(File.join("src", "*")).each { |f| FileUtils.rm_rf(f) }
unarchiver.decompress(file, "src")
commit_sources(message, true)
end
end | csn_ccr |
// BuildOptions fills in the kubedns model | func (b *KubeDnsOptionsBuilder) BuildOptions(o interface{}) error {
clusterSpec := o.(*kops.ClusterSpec)
if clusterSpec.KubeDNS == nil {
clusterSpec.KubeDNS = &kops.KubeDNSConfig{}
}
clusterSpec.KubeDNS.Replicas = 2
if clusterSpec.KubeDNS.CacheMaxSize == 0 {
clusterSpec.KubeDNS.CacheMaxSize = 1000
}
if c... | csn |
func newPersistentVolumeLabel() *persistentVolumeLabel {
// DEPRECATED: in a future release, we will use mutating admission webhooks to apply PV labels.
// Once the mutating admission webhook is used for AWS, Azure, GCE, and OpenStack,
// this admission controller will be removed.
klog.Warning("PersistentVolumeLabe... | " +
"Please remove this controller from your configuration files and scripts.")
return &persistentVolumeLabel{
Handler: admission.NewHandler(admission.Create),
}
} | csn_ccr |
Gets new auth token to replace expired one.
@param OAuthToken $token expired auth token.
@return OAuthToken new auth token.
@throws \yii\authclient\InvalidResponseException | public function refreshAccessToken(OAuthToken $token)
{
$params = [
'grant_type' => 'refresh_token'
];
$params = array_merge($token->getParams(), $params);
$request = $this->createRequest()
->setMethod('POST')
->setUrl($this->refreshTokenUrl)
... | csn |
It's bonus time in the big city! The fatcats are rubbing their paws in anticipation... but who is going to make the most money?
Build a function that takes in two arguments (salary, bonus). Salary will be an integer, and bonus a boolean.
If bonus is true, the salary should be multiplied by 10. If bonus is false, the... | def bonus_time(salary, bonus):
return "${}".format(salary * (10 if bonus else 1)) | apps |
def logpdf(self, X):
"""
Log PDF for Inverse Wishart prior
Parameters
----------
X : float
Covariance matrix for which the prior is being formed over
Returns
| ----------
- log(p(X))
"""
return invwishart.logpdf(X, df=self.v, scale=self.Psi) | csn_ccr |
Set a URL.
@draft
@param {String|Object} url | function (url) {
!url && (url = E);
var parsedUrl = _.isString(url) ? Url.parse(url) : url,
auth = parsedUrl.auth,
protocol = parsedUrl.protocol,
port = parsedUrl.port,
path = parsedUrl.path,
hash = parsedUrl.hash,
host = parsedUrl.... | csn |
function createAndFlush(size) {
if (self._stream) {
self._stream.end();
self._stream.destroySoon();
}
self._size = size;
self.filename = target;
self._stream = fs.createWriteStream(fullname, self.options);
//
... | to make sure everything is flushed
self.flush();
self.opening = false;
self.emit('open', fullname);
});
//
// Remark: It is possible that in the time it has taken to find the
// next logfile to be written more data than `... | csn_ccr |
public static function check_browser_version($brand, $version = null) {
switch ($brand) {
case 'MSIE':
// Internet Explorer.
return self::check_ie_version($version);
case 'Edge':
// Microsoft Edge.
return self::check_edge_... | derived from it (Safari, Chrome, iOS, Android and other mobiles).
return self::check_webkit_version($version);
case 'Gecko':
// Gecko based browsers.
return self::check_gecko_version($version);
case 'WebKit Android':
// WebKit br... | csn_ccr |
python memoryview memory fragments | def read(self, start_position: int, size: int) -> memoryview:
"""
Return a view into the memory
"""
return memoryview(self._bytes)[start_position:start_position + size] | cosqa |
>>> text = '100'
>>> for base in range(2,21):
print ("String '%s' in base %i is %i in base 10"
% (text, base, int(text, base)))
String '100' in base 2 is 4 in base 10
String '100' in base 3 is 9 in base 10
String '100' in base 4 is 16 in base 10
String '100' in base 5 is 25 in base 10
String '1... | #include <iostream>
#include <sstream>
int main()
{
int num;
std::istringstream("0123459") >> num;
std::cout << num << std::endl;
std::istringstream("0123459") >> std::dec >> num;
std::cout << num << std::endl;
std::istringstream("abcf123") >> std::hex >> num;
std::cout << num << std::endl;
std:... | codetrans_contest |
Builds schema definitions for integer type values.
:param var: The integer type value
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:param property_path: [type], optional
:return: The built schema definition
:rtype: Dict[str, Any] | def _build_integer_type(var, property_path=None):
""" Builds schema definitions for integer type values.
:param var: The integer type value
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:param property_path: [type], optional
:return: The b... | csn |
Returns an input mask
@param string
@param string|null
@param string|null
@param scalar|null
@return Eden\Block\Field\Mask | public function mask($pattern, $placeholder = null, $name = null, $value = null)
{
Argument::i()
->test(1, 'string')
->test(2, 'string', 'null')
->test(3, 'string', 'null')
->test(4, 'scalar', 'null');
$field = Mask::i()->setPattern($pattern);
if(!is_null($name)) {
$field->setName($name);
... | csn |
// Handler returns an http.Handler that dispatches to functions defined in behaviors map.
// If failOnUnknown is true, a behavior that is not in the behaviors map will cause the
// handler to return an error status. Otherwise, the handler returns skipped status. | func Handler(behaviors Behaviors, failOnUnknown bool) http.Handler {
return requestHandler{behaviors: behaviors, failOnUnknown: failOnUnknown}
} | csn |
Utility method to mark the computer offline for derived classes.
@return true
if the node was actually taken offline by this act (as opposed to us deciding not to do it,
or the computer already marked offline.) | protected boolean markOffline(Computer c, OfflineCause oc) {
if(isIgnored() || c.isTemporarilyOffline()) return false; // noop
c.setTemporarilyOffline(true, oc);
// notify the admin
MonitorMarkedNodeOffline no = AdministrativeMonitor.all().get(MonitorMarkedNodeOffline.class);
i... | csn |
func (s *precheckShim) AllApplications() ([]PrecheckApplication, error) {
apps, err := s.State.AllApplications()
if err != nil | {
return nil, errors.Trace(err)
}
out := make([]PrecheckApplication, 0, len(apps))
for _, app := range apps {
out = append(out, &precheckAppShim{app})
}
return out, nil
} | csn_ccr |
Prepare to render | protected function _prepareToRender()
{
$this->addColumn(
'installment_currency', array(
'label' => Mage::helper('adyen')->__('Currency'),
'style' => 'width:100px',
)
);
$this->addColumn(
'installment_boundary', array(
... | csn |
Ignore some element from the AST
@param element
@return | private boolean isToIgnore(CtElement element) {
if (element instanceof CtStatementList && !(element instanceof CtCase)) {
if (element.getRoleInParent() == CtRole.ELSE || element.getRoleInParent() == CtRole.THEN) {
return false;
}
return true;
}
return element.isImplicit() || element instanceof CtRefe... | csn |
// validateMap validates a map of validatable elements | func validateMap(rv reflect.Value) error {
errs := Errors{}
for _, key := range rv.MapKeys() {
if mv := rv.MapIndex(key).Interface(); mv != nil {
if err := mv.(Validatable).Validate(); err != nil {
errs[fmt.Sprintf("%v", key.Interface())] = err
}
}
}
if len(errs) > 0 {
return errs
}
return nil
} | csn |
public ClassGraph overrideClasspath(final Iterable<?> overrideClasspathElements) {
final String overrideClasspath = JarUtils.pathElementsToPathStr(overrideClasspathElements);
if (overrideClasspath.isEmpty()) {
| throw new IllegalArgumentException("Can't override classpath with an empty path");
}
overrideClasspath(overrideClasspath);
return this;
} | csn_ccr |
Filter the records, keeping only sequences whose ID is contained in the
handle. | def include_from_file(records, handle):
"""
Filter the records, keeping only sequences whose ID is contained in the
handle.
"""
ids = set(i.strip() for i in handle)
for record in records:
if record.id.strip() in ids:
yield record | csn |
Set room temps by name. | async def set_room_temperatures_by_name(self, room_name, sleep_temp=None,
comfort_temp=None, away_temp=None):
"""Set room temps by name."""
if sleep_temp is None and comfort_temp is None and away_temp is None:
return
for room_id, _room in s... | csn |
public function removeSection( $section )
{
if( !$this->usesSections() )
throw new RuntimeException( 'Sections are disabled' );
if( !$this->hasSection( $section ) )
throw new InvalidArgumentException( 'Section "'.$section.'" is not existing' );
$index | = array_search( $section, $this->sections);
unset( $this->sections[$index] );
return is_int( $this->write() );
} | csn_ccr |
private RValue executeConvert(Expr.Cast expr, CallStack frame) {
RValue | operand = executeExpression(ANY_T, expr.getOperand(), frame);
return operand.convert(expr.getType());
} | csn_ccr |
def login(options, password = nil) # :yield: recvdata
login_prompt = /[Ll]ogin[: ]*\z/n
password_prompt = /[Pp]ass(?:word|phrase)[: ]*\z/n
if options.kind_of?(Hash)
username = options["Name"]
password = options["Password"]
login_prompt = options["LoginPrompt"] if options["Login... | end
if block_given?
line = waitfor(login_prompt){|c| yield c }
if password
line += cmd({"String" => username,
"Match" => password_prompt}){|c| yield c }
line += cmd(password){|c| yield c }
else
line += cmd(username){|c| yield c }
... | csn_ccr |
Checks that the given file path exists in the current working directory.
Returns a :class:`~pathlib.Path` object. If the file does not exist raises
a :class:`~click.UsageError` exception. | def changelog_file_option_validator(ctx, param, value):
"""Checks that the given file path exists in the current working directory.
Returns a :class:`~pathlib.Path` object. If the file does not exist raises
a :class:`~click.UsageError` exception.
"""
path = Path(value)
if not path.exists():
... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.