query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
public function depth(string $symbol, int $limit = 100)
{
if (is_int($limit) === false) {
$limit = 100;
}
if (isset($symbol) === false || is_string($symbol) === false) {
// WPCS: XSS OK.
echo "asset: expected bool false, " . gettype($symbol) . " given" . ... | if (isset($this->info[$symbol]) === false) {
$this->info[$symbol] = [];
}
$this->info[$symbol]['firstUpdate'] = $json['lastUpdateId'];
return $this->depthData($symbol, $json);
} | csn_ccr |
public Set<Weighted<DirectedEdge>> directedEdges(Map<NodeId, Node> nodes) {
| return Collections.emptySet();
} | csn_ccr |
This function identifies whether the engine is running on the master
or the minion and sends the data to the master event bus accordingly.
:param result: It's a dictionary which has the final data and topic. | def send_event_to_salt(self, result):
'''
This function identifies whether the engine is running on the master
or the minion and sends the data to the master event bus accordingly.
:param result: It's a dictionary which has the final data and topic.
'''
if result['send'... | csn |
Start a vote.
@param Player $player
@param string $typeCode
@param array $params | public function startVote(Player $player, $typeCode, $params)
{
if ($this->getCurrentVote() !== null) {
$this->chatNotification->sendMessage("expansion_votemanager.error.in_progress");
return;
}
if (isset($this->voteMapping[$typeCode])) {
$typeCode = $thi... | csn |
Check for invalid columns in the given ProtoFeed DataFrame.
Parameters
----------
problems : list
A four-tuple containing
1. A problem type (string) equal to ``'error'`` or
``'warning'``;
``'error'`` means the ProtoFeed is violated;
``'warning'`` means ther... | def check_for_invalid_columns(problems, table, df):
"""
Check for invalid columns in the given ProtoFeed DataFrame.
Parameters
----------
problems : list
A four-tuple containing
1. A problem type (string) equal to ``'error'`` or
``'warning'``;
``'error'`` mean... | csn |
function(err, req, res, next) {
err.message = err.message || 'Internal Server Error';
err.code = err.code || res.code || 500;
if (!_.isNumber(err.code)) {
err.code = 500;
}
try {
err.line = err.stack.split('\n')[1].match(/\(.+\)/)[0];
} catch (e) {
err.line = null;
}
... | message: err.message,
line: err.line
}
},
data: err.message
};
// Set code and data
res.code = err.code;
res.data = envelope;
return next();
} | csn_ccr |
protected function replaceParam($line, array $param)
{
if (! empty($param) and is_array($param)) {
foreach ($param as $key => $value) {
$line | = str_replace(':'.$key, $value, $line);
}
}
return $line;
} | csn_ccr |
how to get index from parent as a child python | def parent(self, index):
"""Return the index of the parent for a given index of the
child. Unfortunately, the name of the method has to be parent,
even though a more verbose name like parentIndex, would avoid
confusion about what parent actually is - an index or an item.
"""
... | cosqa |
def dumptree(self, pn):
"""
Walks entire tree, dumping all records on each page
in sequential order
"""
page = self.readpage(pn)
print("%06x: preceeding = %06x, reccount = %04x" % (pn, page.preceeding, page.count))
for ent in page.index:
print(... | %s" % ent)
if page.preceeding:
self.dumptree(page.preceeding)
for ent in page.index:
self.dumptree(ent.page) | csn_ccr |
def _interval(dates):
"""Return the distance between all dates and 0 if they are different"""
interval = (dates[1] - dates[0]).days
last = dates[0]
for dat in dates[1:]:
| if (dat - last).days != interval:
return 0
last = dat
return interval | csn_ccr |
Inform the watchdog of activity. | async def _inform_watchdog(self):
"""Inform the watchdog of activity."""
async with self._wd_lock:
if self._watchdog_task is None:
# Check within the Lock to deal with external cancel_watchdog
# calls with queued _inform_watchdog tasks.
return
... | csn |
Executes the request and returns the HTTP response code.
@return int HTTP response code
@throws HelloSignException thrown if no request has been performed | public int asHttpCode() throws HelloSignException {
Integer code = getLastResponseCode();
if (code == null) {
throw new HelloSignException("No request performed");
}
if (code >= 200 && code < 300) {
reset();
return code;
}
throw new Hel... | csn |
Quotes value if needed for sql. | public function quoteOrNot($val)
{
return ((is_string($val) || is_numeric($val)) and !$this->isNotQuotable($val)) ? sprintf("'%s'", $val) : $val;
} | csn |
func (c *Client) SetWriteTimeout(d time.Duration) error {
if c == nil {
return fmt.Errorf("Client is | nil")
}
return c.writer.SetWriteTimeout(d)
} | csn_ccr |
private WebSocketInputStream openInputStream(Socket socket) throws WebSocketException
{
try
{
// Get the input stream of the raw socket through which
// this client receives data from the server.
return new WebSocketInputStream(
new BufferedInputSt... | throw new WebSocketException(
WebSocketError.SOCKET_INPUT_STREAM_FAILURE,
"Failed to get the input stream of the raw socket: " + e.getMessage(), e);
}
} | csn_ccr |
def status_message(self):
"""Return friendly response from API based on response code. """
msg = None
if self.last_ddns_response in response_messages.keys():
return response_messages.get(self.last_ddns_response)
if 'good' in self.last_ddns_response:
ip = re.sear... |
ip = re.search(r'(\d{1,3}\.?){4}', self.last_ddns_response).group()
msg = "SUCCESS: IP address (%s) is up to date, nothing was changed. " \
"Additional 'nochg' updates may be considered abusive." % ip
else:
msg = "ERROR: Ooops! Something went wrong !!!"
... | csn_ccr |
Save an HTML file with the data for the current document.
Will fall back to the default output state (or an explicitly provided
:class:`State` object) for ``filename``, ``resources``, or ``title`` if they
are not provided. If the filename is not given and not provided via output state,
it is derived fr... | def save(obj, filename=None, resources=None, title=None, template=None, state=None, **kwargs):
''' Save an HTML file with the data for the current document.
Will fall back to the default output state (or an explicitly provided
:class:`State` object) for ``filename``, ``resources``, or ``title`` if they
... | csn |
protected function prettifyArray($array, $indexed = true)
{
$content = ($indexed)
? var_export($array, true)
: preg_replace("/[0-9]+ \=\>/i", '', var_export($array, true));
$lines = explode("\n", $content);
$inString = false;
$tabCount = 3;
for ($i =... | if ($lines[$i][$j] == '\\') {
$j++;
}
//check string open/end
else if ($lines[$i][$j] == '\'') {
$inString = !$inString;
}
}
//check for openning bracket
if (strpo... | csn_ccr |
// SetLastUpdateVersion sets the last update version. | func (h *Handle) SetLastUpdateVersion(version uint64) {
h.mu.Lock()
defer h.mu.Unlock()
h.mu.lastVersion = version
} | csn |
method to check if any of the rna polymers have a modified nucleotide
@param polymers list of {@link PolymerNotation}
@return true if at least one rna polymer has a modified nucleotide
@throws NotationException if notation is not valid | public static boolean hasNucleotideModification(List<PolymerNotation> polymers) throws NotationException {
for (PolymerNotation polymer : getRNAPolymers(polymers)) {
if (RNAUtils.hasNucleotideModification(polymer)) {
return true;
}
}
return false;
} | csn |
public static function view_submission($submissionid) {
global $DB;
$params = self::validate_parameters(self::view_submission_parameters(), array('submissionid' => $submissionid));
$warnings = array();
// Get and validate the submission and workshop.
$submission = $DB->get_reco... | $context) = self::validate_workshop($submission->workshopid);
self::validate_submission($submission, $workshop);
$workshop->set_submission_viewed($submission);
$result = array(
'status' => true,
'warnings' => $warnings,
);
return $result;
} | csn_ccr |
// Get returns the resolver builder registered with the given name.
// Note that the compare is done in a case-insensitive fashion.
// If no builder is register with the name, nil will be returned. | func Get(name string) Builder {
if b, ok := m[strings.ToLower(name)]; ok {
return b
}
return nil
} | csn |
// Calls scsi_id on the given devicePath to get the serial number reported by that device. | func getScsiSerial(devicePath, diskName string) (string, error) {
exists, err := utilpath.Exists(utilpath.CheckFollowSymlink, "/lib/udev/scsi_id")
if err != nil {
return "", fmt.Errorf("failed to check scsi_id existence: %v", err)
}
if !exists {
klog.V(6).Infof("scsi_id doesn't exist; skipping check for %v", d... | csn |
public static function can_request_review_user($planuserid) {
global $USER;
$capabilities = array('moodle/competency:planrequestreview');
if ($USER->id == $planuserid) {
| $capabilities[] = 'moodle/competency:planrequestreviewown';
}
return has_any_capability($capabilities, context_user::instance($planuserid));
} | csn_ccr |
Generates from a list of rows a PrettyTable object. | def generate_table(self, rows):
"""
Generates from a list of rows a PrettyTable object.
"""
table = PrettyTable(**self.kwargs)
for row in self.rows:
if len(row[0]) < self.max_row_width:
appends = self.max_row_width - len(row[0])
for i i... | csn |
check type in list python | def _valid_other_type(x, types):
"""
Do all elements of x have a type from types?
"""
return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) | cosqa |
Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of `numbers` and the second is the `divisor`.
## Example
```python
divisible_by([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6]
``` | def divisible_by(numbers, divisor):
return [x for x in numbers if x%divisor == 0] | apps |
Returns the install path of a resource in the target location.
This is a path relative to the root of the target location.
@param Resource $resource The resource.
@return string The web path. | public function getWebPathForResource(Resource $resource)
{
$relPath = Path::makeRelative($resource->getRepositoryPath(), $this->basePath);
return '/'.trim($this->mapping->getWebPath().'/'.$relPath, '/');
} | csn |
func supervisor(paths chan string, bundler chan *x509.Certificate, numWorkers int) {
var workerPool sync.WaitGroup |
for i := 0; i < numWorkers; i++ {
workerPool.Add(1)
go worker(paths, bundler, &workerPool)
}
workerPool.Wait()
close(bundler)
} | csn_ccr |
Setter for session lifetime | public function set_lifetime($lifetime)
{
$this->lifetime = max(120, $lifetime);
// valid time range is now - 1/2 lifetime to now + 1/2 lifetime
$now = time();
$this->now = $now - ($now % ($this->lifetime / 2));
} | csn |
protected <T> T roundtrip(T object, ClassLoader classLoader) {
A data = serialize(object);
@SuppressWarnings("unchecked")
| T copy = (T) deserialize(data, classLoader);
return copy;
} | csn_ccr |
python queue element stackoverflow | def full(self):
"""Return ``True`` if the queue is full, ``False``
otherwise (not reliable!).
Only applicable if :attr:`maxsize` is set.
"""
return self.maxsize and len(self.list) >= self.maxsize or False | cosqa |
// killConnection issues a MySQL KILL command for the given connection ID. | func (mysqld *Mysqld) killConnection(connID int64) error {
// There's no other interface that both types of connection implement.
// We only care about one method anyway.
var killConn interface {
ExecuteFetch(query string, maxrows int, wantfields bool) (*sqltypes.Result, error)
}
// Get another connection with ... | csn |
Renames the projected variables | private DistinctVariableOnlyDataAtom transformProjectionAtom(DistinctVariableOnlyDataAtom atom) {
ImmutableList<Variable> newArguments = atom.getArguments().stream()
.map(renamingSubstitution::applyToVariable)
.collect(ImmutableCollectors.toList());
return atomFactory.ge... | csn |
def check_with_pep8(source_code, filename=None):
"""Check source code with pycodestyle"""
try:
args = get_checker_executable('pycodestyle')
results = check(args, source_code, filename=filename, options=['-r'])
|
except Exception:
# Never return None to avoid lock in spyder/widgets/editor.py
# See Issue 1547
results = []
if DEBUG_EDITOR:
traceback.print_exc() # Print exception in internal console
return results | csn_ccr |
Returns multiple model instances by given table and id or alias.
@param string $table
@param mixed $idOrAlias
@param array $options
@return mixed | public function findModelInstanceByIdOrAlias(string $table, $idOrAlias, array $options = [])
{
if (!($modelClass = $this->framework->getAdapter(Model::class)->getClassFromTable($table))) {
return null;
}
/* @var Model $adapter */
if (null === ($adapter = $this->framework... | csn |
func WithDefaultAttributes(attrs ...trace.Attribute) Option {
return | func(t *Transport) {
t.defaultAttributes = attrs
}
} | csn_ccr |
Parse a build part string
A build part can look like build.11.e0f985a
@param string $string
@return BuildVersion | public static function parse($string)
{
// Explode over '.'
$parts = explode('.', $string);
// Instantiate
$buildVersion = new BuildVersion;
// No parts is no build?
if (count($parts) === 0) {
return $buildVersion;
}
// Discard "build" s... | csn |
def get_ip(host):
'''
Return the ip associated with the named host
CLI Example:
.. code-block:: bash
salt '*' hosts.get_ip <hostname>
'''
hosts = _list_hosts()
if not hosts:
return ''
# Look | for the op
for addr in hosts:
if host in hosts[addr]:
return addr
# ip not found
return '' | csn_ccr |
Provides a JSON decoder that converts dictionaries to Python objects if
suitable methods are found in our ``TYPE_MAP``. | def json_class_decoder_hook(d: Dict) -> Any:
"""
Provides a JSON decoder that converts dictionaries to Python objects if
suitable methods are found in our ``TYPE_MAP``.
"""
if TYPE_LABEL in d:
typename = d.get(TYPE_LABEL)
if typename in TYPE_MAP:
if DEBUG:
... | csn |
Increment the score if the given text contains any of the supply keywords.
@param text the text to evaluate; may be null
@param factor the factor to use for each increment
@param keywords the keywords to be found in the text | public void scoreText( String text,
int factor,
String... keywords ) {
if (text != null && keywords != null) {
// Increment the score once for each keyword that is found within the text ...
String lowercaseText = text.toLowerCase();
... | csn |
Make a TensorProto with specified arguments. If raw is False, this
function will choose the corresponding proto field to store the
values based on data_type. If raw is True, use "raw_data" proto
field to store the values, and values should be of type bytes in
this case. | def _make_tensor_fixed(name, data_type, dims, vals, raw=False):
'''
Make a TensorProto with specified arguments. If raw is False, this
function will choose the corresponding proto field to store the
values based on data_type. If raw is True, use "raw_data" proto
field to store the values, and value... | csn |
public function getPlans($page = '')
{
$planObjects = [];
$plans = $this->getPlanResource()->getAll($page);
if ($plans instanceof \Exception) {
throw $plans;
}
foreach ($plans as | $plan) {
$planObject = new Plan($this->getPlanResource());
$planObjects[] = $planObject->_setAttributes($plan);
}
return $planObjects;
} | csn_ccr |
python format compute length | def __len__(self):
""" This will equal 124 for the V1 database. """
length = 0
for typ, siz, _ in self.format:
length += siz
return length | cosqa |
Clear attributes value.
@method clear
@param string $key
@return \Norm\Model | public function clear($key = null)
{
if (func_num_args() === 0) {
$this->attributes = array();
} elseif ($key === '$id') {
throw new Exception('[Norm/Model] Restricting clear for $id.');
} else {
unset($this->attributes[$key]);
}
return $t... | csn |
// regularPoints generates a slice of points shaped as a regular polygon with
// the numVertices vertices, all located on a circle of the specified angular radius
// around the center. The radius is the actual distance from center to each vertex. | func regularPoints(center Point, radius s1.Angle, numVertices int) []Point {
return regularPointsForFrame(getFrame(center), radius, numVertices)
} | csn |
Enable high availability for a YARN ResourceManager.
@param new_rm_host_id: id of the host where the second ResourceManager
will be added.
@param zk_service_name: Name of the ZooKeeper service to use for auto-failover.
If YARN service depends on a ZooKeeper service then th... | def enable_rm_ha(self, new_rm_host_id, zk_service_name=None):
"""
Enable high availability for a YARN ResourceManager.
@param new_rm_host_id: id of the host where the second ResourceManager
will be added.
@param zk_service_name: Name of the ZooKeeper service to use for auto-f... | csn |
Poll to check if the auth session or current stage has been
completed out-of-band. If so, the attemptAuth promise will
be resolved. | function() {
if (!this._data.session) return;
let authDict = {};
if (this._currentStage == EMAIL_STAGE_TYPE) {
// The email can be validated out-of-band, but we need to provide the
// creds so the HS can go & check it.
if (this._emailSid) {
co... | csn |
def is_gtk_desktop():
"""Detect if we are running in a Gtk-based desktop"""
if sys.platform.startswith('linux'):
xdg_desktop = os.environ.get('XDG_CURRENT_DESKTOP', '')
if xdg_desktop:
gtk_desktops = ['Unity', 'GNOME', 'XFCE']
if any([xdg_desktop.startswith(d) for d | in gtk_desktops]):
return True
else:
return False
else:
return False
else:
return False | csn_ccr |
Create archive of directory and write to ``path``.
:param path: Path to archive
Ignored::
* build/* - This is used for packing the charm itself and any
similar tasks.
* */.* - Hidden files are all ignored for now. This will most
... | def make_archive(self, path):
"""Create archive of directory and write to ``path``.
:param path: Path to archive
Ignored::
* build/* - This is used for packing the charm itself and any
similar tasks.
* */.* - Hidden files are all ignored fo... | csn |
Retrieve page uuid from legacy moduleid. | def get_module_uuid(plpy, moduleid):
"""Retrieve page uuid from legacy moduleid."""
plan = plpy.prepare("SELECT uuid FROM modules WHERE moduleid = $1;",
('text',))
result = plpy.execute(plan, (moduleid,), 1)
if result:
return result[0]['uuid'] | csn |
Persist this entity, inserting it if new and otherwise updating it
@param AbstractEntity $entity
@return AbstractEntity | public function persist(AbstractEntity $entity)
{
/** @var InserterTrait $this */
if ($entity->isNew()) {
return $this->insert($entity);
}
/** @var UpdaterTrait $this */
return $this->update($entity);
} | csn |
Return list of all files in directory.
@param string $path
@return \SebastianFeldmann\Ftp\File[]
@throws \Exception | public function ls(string $path = '') : array
{
return version_compare(PHP_VERSION, '7.2.0', '>=')
? $this->ls72($path)
: $this->lsLegacy($path);
} | csn |
public int falsePositives(int classindex) {
int fp = 0;
for(int i = 0; i < confusion[classindex].length; i++) {
if(i != classindex) {
| fp += confusion[classindex][i];
}
}
return fp;
} | csn_ccr |
Convert a value into a bool but handle "truthy" strings eg, yes, true, ok, y | def to_bool(value):
# type: (Any) -> bool
"""
Convert a value into a bool but handle "truthy" strings eg, yes, true, ok, y
"""
if isinstance(value, _compat.string_types):
return value.upper() in ('Y', 'YES', 'T', 'TRUE', '1', 'OK')
return bool(value) | csn |
func (m *EndpointPolicy) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateCidrPolicy(formats); err != nil {
res = append(res, err)
}
if err := m.validateL4(formats); err != nil {
res = append(res, err)
} |
if err := m.validatePolicyEnabled(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
} | csn_ccr |
Parse a cookie.
:param header: the header to be used to parse the cookie.
:param charset: the charset for the cookie values.
:param errors: the error behavior for the charset decoding. | def parse_cookie(header, charset='utf-8', errors='ignore'):
"""Parse a cookie.
:param header: the header to be used to parse the cookie.
:param charset: the charset for the cookie values.
:param errors: the error behavior for the charset decoding.
"""
cookie = _ExtendedCookie()
if header:
... | csn |
python conver to camelcase | def convert_camel_case_to_snake_case(name):
"""Convert CamelCase to snake_case."""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | cosqa |
def _get_pdf_list(self, input_pdfs):
"""
Generate list of PDF documents.
:param input_pdfs: List of PDFs or a directory path
Directory - Scans directory contents
List - Filters list to assert all list items are paths to PDF documents
:return: List of PDF paths
... | if isinstance(input_pdfs, list):
return [pdf for pdf in input_pdfs if self.validate(pdf)]
elif os.path.isdir(input_pdfs):
return [os.path.join(input_pdfs, pdf) for pdf in os.listdir(input_pdfs) if self.validate(pdf)] | csn_ccr |
Sets this layer's pixel size.
@param wide
@param high | void setPixelSize(final int wide, final int high)
{
m_wide = wide;
m_high = high;
if (LienzoCore.IS_CANVAS_SUPPORTED)
{
if (false == isSelection())
{
getElement().getStyle().setWidth(wide, Unit.PX);
getElement().getStyle().se... | csn |
Bring changes from the repository into the working copy.
usage:
update [PATH...]
If no revision given, bring working copy up-to-date with HEAD rev.
Else synchronize working copy to revision given by -r.
For each updated item a line will start with a charact... | def do_update(self, subcmd, opts, *args):
"""Bring changes from the repository into the working copy.
usage:
update [PATH...]
If no revision given, bring working copy up-to-date with HEAD rev.
Else synchronize working copy to revision given by -r.
F... | csn |
[Harshad numbers](http://en.wikipedia.org/wiki/Harshad_number) (also called Niven numbers) are positive numbers that can be divided (without remainder) by the sum of their digits.
For example, the following numbers are Harshad numbers:
* 10, because 1 + 0 = 1 and 10 is divisible by 1
* 27, because 2 + 7 = 9 and 27 is... | from itertools import count, islice
class Harshad:
@staticmethod
def is_valid(number):
return number % sum(map(int, str(number))) == 0
@classmethod
def get_next(cls, number):
return next(i for i in count(number+1) if cls.is_valid(i))
@classmethod
def get_series(cls, c... | apps |
def _get_next_occurrence(haystack, offset, needles):
"""
Find next occurence of one of the needles in the haystack
:return: tuple of (index, needle found)
or: None if no needle was found"""
# make map of first char to full needle (only works if all needles
# have di... | possible_needle = firstcharmap[haystack[offset]]
if haystack[offset:offset + len(possible_needle)] == possible_needle:
return offset, possible_needle
offset += 1
return None | csn_ccr |
// Periodically ping clients over websocket connection. Stop the ping loop by
// closing the returned channel. | func (wsh *WebsocketHub) pingClients() chan<- struct{} {
stopPing := make(chan struct{})
go func() {
// start the client ping ticker
ticker := time.NewTicker(pingInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
wsh.HubRelay <- pstypes.HubMessage{Signal: sigPingAndUserCount}
case _,... | csn |
public void afterPropertiesSet() throws IOException {
Map<String, String> finalConfig = new HashMap<String, String>();
if (systemPropertyMode == SystemPropertyMode.MODE_FALLBACK) {
finalConfig.putAll(lookupSystemProperties());
}
if (config != null) {
finalConfig.p... | List<SpringJolokiaConfigHolder> configs = new ArrayList<SpringJolokiaConfigHolder>(configsMap.values());
Collections.sort(configs, new OrderComparator());
for (SpringJolokiaConfigHolder c : configs) {
if (c != config) {
finalConfig.putAll(c.getConfig());
... | csn_ccr |
Prior to having fancy iPhones, teenagers would wear out their thumbs sending SMS
messages on candybar-shaped feature phones with 3x4 numeric keypads.
------- ------- -------
| | | ABC | | DEF |
| 1 | | 2 | | 3 |
------- ------- -------
------- ------- -------
| GHI | | JKL | | MNO |
... | BUTTONS = [ '1', 'abc2', 'def3',
'ghi4', 'jkl5', 'mno6',
'pqrs7', 'tuv8', 'wxyz9',
'*', ' 0', '#' ]
def presses(phrase):
return sum(1 + button.find(c) for c in phrase.lower() for button in BUTTONS if c in button) | apps |
def get name
# with old libvips, we must fetch properties (as opposed to
# metadata) via VipsObject
unless Vips::at_least_libvips?(8, 5)
return super if parent_get_typeof(name) != 0
end
gvalue = GObject::GValue.alloc
| result = Vips::vips_image_get self, name, gvalue
raise Vips::Error if result != 0
gvalue.get
end | csn_ccr |
func (acl *ACL) AddEntry(entry *Entry) error {
newEntry, err := acl.CreateEntry()
if err != nil {
return err |
}
rv, _ := C.acl_copy_entry(newEntry.e, entry.e)
if rv < 0 {
return fmt.Errorf("unable to copy entry while adding new entry")
}
return nil
} | csn_ccr |
async def get_playback_settings(self) -> List[Setting]:
"""Get playback settings such as shuffle and repeat."""
return [
Setting.make(**x)
| for x in await self.services["avContent"]["getPlaybackModeSettings"]({})
] | csn_ccr |
private function getFiltered(bool $public = true): array
{
$result = [];
foreach ($this->events as $event) {
if ($event['is_public'] === | $public) {
$result[] = $event;
}
}
return $result;
} | csn_ccr |
public Object getAttachment(String key) {
return key | == null ? null : attachments.get(key);
} | csn_ccr |
function compareRouteAndApplyArgs (route, request_url, request_method) {
if (route.method !== request_method) {
return false;
}
let template = route.path.split('/');
if (template[0] === '') {
template = template.slice(1); // Slice kills the emptystring before the leading slash
}
let actual = request_url.pat... |
applyArg(request_url, template_part.substring(1), Number(actual_part));
continue;
}
if (template_part[0] === '$') {
// $ templates accept any non-slash alphanumeric character
applyArg(request_url, template_part.substring(1), String(actual_part));
// Continue so that
continue;
}
// Process ... | csn_ccr |
Returns a new Interval that has the same extent as this one, but which is relative to `that`, an Interval that fully covers this one. | function(that) {
if (this.sourceString !== that.sourceString) {
throw errors.intervalSourcesDontMatch();
}
assert(this.startIdx >= that.startIdx && this.endIdx <= that.endIdx,
'other interval does not cover this one');
return new Interval(this.sourceString,
this.... | csn |
Returns the specified zone.
@throws \Netgen\BlockManager\Exception\API\LayoutException If the zone does not exist | public function getZone(string $zoneIdentifier): APIZone
{
if ($this->hasZone($zoneIdentifier)) {
return $this->zones->get($zoneIdentifier);
}
throw LayoutException::noZone($zoneIdentifier);
} | csn |
@Override
protected AmazonS3Encryption build(AwsSyncClientParams clientParams) {
return new AmazonS3EncryptionClient(
new AmazonS3EncryptionClientParamsWrapper(clientParams,
resolveS3ClientOptions(),
| encryptionMaterials,
cryptoConfig != null ? cryptoConfig : new CryptoConfiguration(),
kms));
} | csn_ccr |
public function rerun($type, $reference = null) {
$this->out('Rerunning...');
$count | = $this->QueuedJobs->rerun($type, $reference);
$this->success($count . ' jobs reset for re-run.');
} | csn_ccr |
Execute scssphp on a .scss file or a scssphp cache structure
The scssphp cache structure contains information about a specific
scss file having been parsed. It can be used as a hint for future
calls to determine whether or not a rebuild is required.
The cache structure contains two important keys that may be used
ext... | public function cachedCompile($in, $force = false)
{
// assume no root
$root = null;
if (is_string($in)) {
$root = $in;
} elseif (is_array($in) and isset($in['root'])) {
if ($force or ! isset($in['files'])) {
// If we are forcing a recompile o... | csn |
// StreamFrameLogsForDevice returns a stream of frames seen by the given device. | func (n *NetworkServerAPI) StreamFrameLogsForDevice(req *ns.StreamFrameLogsForDeviceRequest, srv ns.NetworkServerService_StreamFrameLogsForDeviceServer) error {
frameLogChan := make(chan framelog.FrameLog)
var devEUI lorawan.EUI64
copy(devEUI[:], req.DevEui)
go func() {
err := framelog.GetFrameLogForDevice(srv.C... | csn |
public String visualize(Object obj) throws ConverterException {
Integer pad = 0;
String padc = getConfig("pad-count", "0");
try {
pad = Integer.parseInt(padc);
} catch (Exception e) {
}
char padch = getConfig("pad-char", " ").charAt(0);
String padd = g... | padch);
} else {
res = Utils.padright(res, pad, padch);
}
if (prefix != null) {
res = prefix + res;
}
if (suffix != null) {
res = res + suffix;
}
return res;
} | csn_ccr |
Create a custom domain for your fax services
REST: POST /me/fax/customDomains
@param domain [required] The custom domain of your fax services | public OvhMailDomain2Service fax_customDomains_POST(String domain) throws IOException {
String qPath = "/me/fax/customDomains";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "domain", domain);
String resp = exec(qPath, "POST", sb.toString(), o);
return ... | csn |
Finds the route via uri
@param string $uri
@return \PHPLegends\Routes\Route | null | public function findByUri($uri)
{
return $this->routes->first(function ($route) use($uri) {
return $route->match($uri);
});
} | csn |
Assigns fields to model
@param array $fields
@throws ModelException | protected function assignFields($fields)
{
foreach ($fields as $field) {
if (!$field instanceof FieldInterface) {
throw new ModelException(sprintf('Field must be an instance of FieldInterface, got "%s"', $this->getType($field)));
}
$field->table($t... | csn |
public function updateMappingUser(string $username): array
{
return $this->getAp | i()->request($this->getApi()->sprintf('/admin/ldap/user/:username/mapping', $username),
Request::METHOD_PATCH);
} | csn_ccr |
// MarshalNoEscape is the same functionality as json.Marshal but
// with HTML escaping disabled | func MarshalNoEscape(v interface{}) ([]byte, error) {
buf := bytes.Buffer{}
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
err := enc.Encode(v)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
} | csn |
Sets sound speed mode; 0 or "measured" for measured; 1 or "fixed"
for fixed. | def sound_speed_mode(self, mode):
"""Sets sound speed mode; 0 or "measured" for measured; 1 or "fixed"
for fixed."""
if mode == "measured":
mode = 0
if mode == "fixed":
mode = 1
self.pdx.SoundSpeedMode = mode | csn |
public function setTags($t)
{
// Determine Location to atk_public
if ($this->app->pathfinder && $this->app->pathfinder->atk_public) {
$q = $this->app->pathfinder->atk_public->getURL();
} else {
$q = 'http://www.agiletoolkit.org/';
}
$t->trySet('atk_pa... | $t->eachTag($tag = 'css', array($this, '_locateCSS'));
$t->eachTag($tag = 'page', array($this, 'getBaseURL'));
} catch (BaseException $e) {
throw $e
->addMoreInfo('processing_tag', $tag)
->addMoreInfo('template', $t->template_file)
;... | csn_ccr |
User management list.
@since 2.0.0
@access public
@param mixed $Keywords Term or array of terms to filter list of users.
@param int $Page Page number.
@param string $Order Sort order for list. | public function Index($Keywords = '', $Page = '', $Order = '') {
$this->Permission(
array(
'Garden.Users.Add',
'Garden.Users.Edit',
'Garden.Users.Delete'
),
'',
FALSE
);
// Page setup
$this->AddJsFile('jquery.gardenmo... | csn |
func (a *AdminClient) cToTopicResults(cTopicRes **C.rd_kafka_topic_result_t, cCnt C.size_t) (result []TopicResult, err error) {
result = make([]TopicResult, int(cCnt))
for i := 0; i < int(cCnt); i++ | {
cTopic := C.topic_result_by_idx(cTopicRes, cCnt, C.size_t(i))
result[i].Topic = C.GoString(C.rd_kafka_topic_result_name(cTopic))
result[i].Error = newErrorFromCString(
C.rd_kafka_topic_result_error(cTopic),
C.rd_kafka_topic_result_error_string(cTopic))
}
return result, nil
} | csn_ccr |
function ProgressSpinner(id, anchor){
if(id === undefined){ throw new Error("Missing reqired argument: id"); }
if(anchor === undefined){ throw | new Error("Missing reqired argument: anchor"); }
this._id = id;
this._anchor = anchor;
// we add a prefix for the id label
this._prefix = "progressSpinner:";
} | csn_ccr |
Get a new MUC enter configuration builder.
@param nickname the nickname used when entering the MUC room.
@return a new MUC enter configuration builder.
@since 4.2 | public MucEnterConfiguration.Builder getEnterConfigurationBuilder(Resourcepart nickname) {
return new MucEnterConfiguration.Builder(nickname, connection.getReplyTimeout());
} | csn |
// InitLocal sets up logging at the given level for local consumption. | func InitLocal(level string) {
l, err := logrus.ParseLevel(level)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to setup logging: %v\n", err)
os.Exit(1)
}
logger.Level = l
} | csn |
func NewPhotoUpload(chatID int64, file interface{}) PhotoConfig {
return PhotoConfig{
BaseFile: BaseFile{
BaseChat: | BaseChat{ChatID: chatID},
File: file,
UseExisting: false,
},
}
} | csn_ccr |
public function listUniqueIdentifiers( $msgNum = null )
{
if ( $this->state != self::STATE_TRANSACTION )
{
throw new ezcMailTransportException( "Can't call ListUniqueIdentifiers() on the POP3 transport when not successfully logged in." );
}
// send the command
$r... | $this->connection->sendData( "UIDL" );
$response = $this->connection->getLine();
if ( $this->isPositiveResponse( $response ) )
{
// fetch each of the result lines and add it to the result
while ( ( $response = $this->connection->getLine( true ) ) !=... | csn_ccr |
Yields a new Vcs object that represents a temporary, disposable
copy of the current repository. The copy is deleted at the end
of the context.
The following are not copied:
- ignored files
- easyci private directory (.git/eci for git)
Yields:
Vcs | def temp_copy(self):
"""Yields a new Vcs object that represents a temporary, disposable
copy of the current repository. The copy is deleted at the end
of the context.
The following are not copied:
- ignored files
- easyci private directory (.git/eci for git)
Yie... | csn |
Custom Underscore equality method. | function(b) {
if (b instanceof Model) {
if (this.constructor !== b.constructor) return false;
b = b.attributes;
}
return _.isEqual(this.attributes, b);
} | csn |
Create the schema for the "up" method.
@param string $schema
@param array $meta
@return string
@throws GeneratorException | private function createSchemaForUpMethod($schema, $meta)
{
//dd($schema);
$fields = $this->constructSchema($schema);
if ($meta['action'] == 'create') {
return $this->insert($fields)->into($this->getCreateSchemaWrapper());
}
if ($meta['action'] == 'add') {
... | csn |
Run the dispatcher.
@param string $args Commands to run
@param array $extra Extra parameters
@return int Result of the shell process. 1 on success, 0 otherwise. | public static function run($args, $extra = [])
{
static::$_out = '';
$argv = explode(' ', "dummy-shell.php {$args}");
$dispatcher = new WebShellDispatcher($argv);
ob_start();
$response = $dispatcher->dispatch($extra);
static::$_out = ob_get_clean();
return (... | csn |
public function higherItems($limit = null)
{
if ($this->isNotInList()) return null;
$query = $this->listifyScopedQuery()
->where($this->positionColumn(), '<', $this->getListifyPosition())
->orderBy($this->getTable() . '.' . | $this->positionColumn(), 'DESC');
if (null !== $limit) {
$query->take($limit);
}
return $query->get();
} | csn_ccr |
private void finalizeRePattern(String name, String rePattern) {
// create correct regular expression
rePattern = rePattern.replaceFirst("\\|", "");
/* this was added to reduce the danger of getting unusable groups from user-made repattern
* files with group-producing parentheses (i.e. "(foo|bar)" while matchin... | rePattern = rePattern.replaceAll("\\(([^\\?])", "(?:$1");
rePattern = "(" + rePattern + ")";
rePattern = rePattern.replaceAll("\\\\", "\\\\\\\\");
// add rePattern to hmAllRePattern
hmAllRePattern.put(name, rePattern);
} | csn_ccr |
r"""Return a new set with elements in either the set or other but not both.
>>> ms = Multiset('aab')
>>> sorted(ms.symmetric_difference('abc'))
['a', 'c']
You can also use the ``^`` operator for the same effect. However, the operator version
will only accept a set as other oper... | def symmetric_difference(self, other):
r"""Return a new set with elements in either the set or other but not both.
>>> ms = Multiset('aab')
>>> sorted(ms.symmetric_difference('abc'))
['a', 'c']
You can also use the ``^`` operator for the same effect. However, the operator versi... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.