query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Return an inverted dictionary, where former values are keys
and former keys are values.
.. warning::
If more than one key maps to any given value in input dictionary,
it is undefined which one will be chosen for the result.
:param dict_: Dictionary to swap keys and values in
:return: ... | def invert(dict_):
"""Return an inverted dictionary, where former values are keys
and former keys are values.
.. warning::
If more than one key maps to any given value in input dictionary,
it is undefined which one will be chosen for the result.
:param dict_: Dictionary to swap keys a... | csn |
Removes extension from path.
@param string $path
@return string | static function RemoveExtension($path)
{
$ext = self::Extension($path);
if ($ext)
{
$newLength = System\Str::Length($path) -
System\Str::Length($ext) - 1; //dot length = 1!
return System\Str::Start($path, $newLength);
}
return $path;
... | csn |
Show multiple choice problems | def show_input(self, template_helper, language, seed):
""" Show multiple choice problems """
choices = []
limit = self._limit
if limit == 0:
limit = len(self._choices) # no limit
rand = Random("{}#{}#{}".format(self.get_task().get_id(), self.get_id(), seed))
... | csn |
Update the object with the given data object, and with any other key-value args. Returns a
set containing all the property names that were changed. | def update(self, data_=None, **kwargs):
"""Update the object with the given data object, and with any other key-value args. Returns a
set containing all the property names that were changed.
"""
if data_ is None:
data_ = dict()
else:
data_ = dict(data_)
data_.update(**kwargs)
cha... | csn |
Returns the column display size for the given Vertica type with
consideration of the type modifier.
The display size of a column is the maximum number of characters needed to
display data in character form. | def getDisplaySize(data_type_oid, type_modifier):
"""
Returns the column display size for the given Vertica type with
consideration of the type modifier.
The display size of a column is the maximum number of characters needed to
display data in character form.
"""
if data_type_oid == Verti... | csn |
The encoding type used by the API to calculate offsets.
Generated from protobuf field <code>.google.cloud.language.v1.EncodingType encoding_type = 3;</code>
@param int $var
@return $this | public function setEncodingType($var)
{
GPBUtil::checkEnum($var, \Google\Cloud\Language\V1\EncodingType::class);
$this->encoding_type = $var;
return $this;
} | csn |
Sets errors for a single field
### Example
```
// Sets the error messages for a single field
$entity->setError('salary', ['must be numeric', 'must be a positive number']);
```
@param string $field The field to get errors for, or the array of errors to set.
@param string|array $errors The errors to be set for $field
... | public function setError($field, $errors, $overwrite = false)
{
if (is_string($errors)) {
$errors = [$errors];
}
return $this->setErrors([$field => $errors], $overwrite);
} | csn |
Render a summary of the zip file import
@param assignfeedback_file_import_summary $summary - Stats about the zip import
@return string The html response | public function render_assignfeedback_file_import_summary($summary) {
$o = '';
$o .= $this->container(get_string('userswithnewfeedback', 'assignfeedback_file', $summary->userswithnewfeedback));
$o .= $this->container(get_string('filesupdated', 'assignfeedback_file', $summary->feedbackfilesupdate... | csn |
Resolves typeString into type. Returns true if the type is primitive
and false otherwise. | private boolean defaultResolve() {
switch (typeString.charAt(0)) {
case 'I':
type = int.class;
return true;
case 'B':
type = byte.class;
return true;
case 'C':
type = char.class;
return true;
case 'S':
... | csn |
// ClusterRoleBindings mocks base method | func (m *MockRbacV1Interface) ClusterRoleBindings() v11.ClusterRoleBindingInterface {
ret := m.ctrl.Call(m, "ClusterRoleBindings")
ret0, _ := ret[0].(v11.ClusterRoleBindingInterface)
return ret0
} | csn |
Deactivate extension by adding disable module class information to disabled module array
@param \OxidEsales\Eshop\Core\Module\Module $module
@return bool | public function deactivate(\OxidEsales\Eshop\Core\Module\Module $module)
{
$result = false;
if ($moduleId = $module->getId()) {
$this->_callEvent('onDeactivate', $moduleId);
$this->_addToDisabledList($moduleId);
//removing recoverable options
$this->... | csn |
Rewrite CSS URIs.
@param string $css
@param array $options
@return string | public static function rewriteUris($css, $options = array())
{
// Prepend the base URL and symlink schema so the proper root path gets prepended.
$symlinks = array();
if (is_link($_SERVER['DOCUMENT_ROOT'])) {
$symlinks = array(
'/'.$options['baseUrl'] => readlink... | csn |
Protects a public method from being available as an controller action.
These methods could be defined in a controller to override a behavior default action.
Such methods should be defined as public, to allow the behavior object to access it.
By default public methods of a controller are considered as actions.
To preven... | protected function hideAction($methodName)
{
if (!is_array($methodName)) {
$methodName = [$methodName];
}
$this->controller->hiddenActions = array_merge($this->controller->hiddenActions, $methodName);
} | csn |
Return a deep copy of the state | def deep_copy(self):
'''Return a deep copy of the state'''
c = KalmanState(self.observation_matrix, self.translation_matrix)
c.state_vec = self.state_vec.copy()
c.state_cov = self.state_cov.copy()
c.noise_var = self.noise_var.copy()
c.state_noise = self.state_noise.copy()... | csn |
Deletes a user from a chat.
@param string $chat The chat you want the user to delete from. Gets escaped with escapePeer().
@param string $user The user you want to delete. Gets escaped with escapePeer().
@return boolean true on success, false otherwise
@uses exec()
@uses escapePeer() | public function chatDeleteUser($chat, $user)
{
return $this->exec('chat_del_user', $this->escapePeer($chat), $this->escapePeer($user));
} | csn |
Reproject a vector layer to a specific CRS.
Issue https://github.com/inasafe/inasafe/issues/3183
:param layer: The layer to reproject.
:type layer: QgsVectorLayer
:param output_crs: The destination CRS.
:type output_crs: QgsCoordinateReferenceSystem
:param callback: A function to all to indi... | def reproject(layer, output_crs, callback=None):
"""Reproject a vector layer to a specific CRS.
Issue https://github.com/inasafe/inasafe/issues/3183
:param layer: The layer to reproject.
:type layer: QgsVectorLayer
:param output_crs: The destination CRS.
:type output_crs: QgsCoordinateReferen... | csn |
Frame the given message with our wire protocol | def frame_msg(body, header=None, raw_body=False): # pylint: disable=unused-argument
'''
Frame the given message with our wire protocol
'''
framed_msg = {}
if header is None:
header = {}
framed_msg['head'] = header
framed_msg['body'] = body
return salt.utils.msgpack.dumps(framed... | csn |
Moves an ``Authorization`` from one ``Vault`` to another.
Mappings to other ``Vaults`` are unaffected.
arg: authorization_id (osid.id.Id): the ``Id`` of the
``Authorization``
arg: from_vault_id (osid.id.Id): the ``Id`` of the current
``Vault``
arg:... | def reassign_authorization_to_vault(self, authorization_id, from_vault_id, to_vault_id):
"""Moves an ``Authorization`` from one ``Vault`` to another.
Mappings to other ``Vaults`` are unaffected.
arg: authorization_id (osid.id.Id): the ``Id`` of the
``Authorization``
... | csn |
Deleting Calendar Item Event
@param Array $postValues, this containing the calendar id $postValues['cal_id']
@return Int|null if the deletion is failed | public function deleteCalendarEvent($postValues)
{
$calId = null;
$calendarTable = $this->getServiceLocator()->get('MelisCalendarTable');
$resultEvent = $calendarTable->getEntryById($postValues['cal_id']);
if (!empty($resultEvent)){
$event = $resultEvent->current();
... | csn |
Return the absolute cache directory path
@param string $subdir the subdirectory related to cache base, or null to get the cache base directory.
@param bool $create_if_not_exists create the directory if it is not found
@throws \RuntimeException if cache directory cannot be created
@throws \InvalidArgumentExcep... | protected function getCachePath($subdir = null, $create_if_not_exists = true)
{
$cache_base = $this->getCachePathFromWebRoot($subdir);
$web_root = rtrim(THELIA_WEB_DIR, '/');
$path = sprintf("%s/%s", $web_root, $cache_base);
// Create directory (recursively) if it does not exists.... | csn |
Finalizes, closes and releases the given editor. | def closeEditor(self, editor, hint):
""" Finalizes, closes and releases the given editor.
"""
# It would be nicer if this method was part of ConfigItemDelegate since createEditor also
# lives there. However, QAbstractItemView.closeEditor is sometimes called directly,
# without th... | csn |
Return a CSV document of the competition entry and its user
details | def csv_export(self, request):
""" Return a CSV document of the competition entry and its user
details
"""
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=competitionentries.csv'
# create the csv writer with th... | csn |
Gets an area object based on the current authentication and URI.
@return AreaContract | public function getCurrentArea(): AreaContract
{
$segment = $this->request->segment(1);
$area = $segment ? $this->getById($segment) : null;
if (!$area && $this->auth->check()) {
$user = $this->auth->user();
$areas = $user->getArea();
if (is_array($ar... | csn |
Checks whether or not a node is a constructor.
@param {ASTNode} node - A function node to check.
@returns {boolean} Wehether or not a node is a constructor. | function isES5Constructor(node) {
return node.id &&
node.id.name[0] !== node.id.name[0].toLocaleLowerCase();
} | csn |
Get the LUID for the SeCreateSymbolicLinkPrivilege | def get_symlink_luid():
"""
Get the LUID for the SeCreateSymbolicLinkPrivilege
"""
symlink_luid = privilege.LUID()
res = privilege.LookupPrivilegeValue(
None, "SeCreateSymbolicLinkPrivilege", symlink_luid)
if not res > 0:
raise RuntimeError("Couldn't lookup privilege value")
return symlink_luid | csn |
Check if given key exists in array with dot notation support.
@param array $array
@param string $key
@return bool | public static function exists($array, $key)
{
$key = static::normalizeKey($key);
if ($key === null || $key === '' || static::isEmpty($array))
{
return false;
}
$keys = explode('.', $key);
$currentElement = $array;
foreach ($keys as $currentKey)
... | csn |
Display either a link to the login screen or displays the name of the current user
and a logoff link.
Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the... | protected function _layoutLogin(array $args = null)
{
// During error reporting the user or menu are not always known.
if ($this->currentUser && $this->menu) {
$div = \MUtil_Html::create('div', array('id' => 'login'), $args);
$p = $div->p();
if ($this->currentUse... | csn |
Executes a db query, gets all the values, and closes the connection. | def query_fetch_all(self, query, values):
"""
Executes a db query, gets all the values, and closes the connection.
"""
self.cursor.execute(query, values)
retval = self.cursor.fetchall()
self.__close_db()
return retval | csn |
Exports information about password resets.
@param int $userid The user ID
@param \context $context Context for this user. | protected static function export_password_resets(int $userid, \context $context) {
global $DB;
$records = $DB->get_records('user_password_resets', ['userid' => $userid]);
if (!empty($records)) {
$passwordresets = (object) array_map(function($record) {
return [
... | csn |
Processes the bundler audit output.
@param original the dependency
@param engine the dependency-check engine
@param rdr the reader of the report
@throws IOException thrown if the report cannot be read
@throws CpeValidationException if there is an error building the
CPE/VulnerableSoftware object | private void processBundlerAuditOutput(Dependency original, Engine engine, BufferedReader rdr) throws IOException, CpeValidationException {
final String parentName = original.getActualFile().getParentFile().getName();
final String fileName = original.getFileName();
final String filePath = origin... | csn |
Delegate the method to the Model
@param [Symbol] method
the name of the method in the model to execute
@param [Array] *args
the arguments for the method
@return [Object]
the return value of the model method
@api private | def delegate_to_model(method, *args, &block)
model = self.model
model.send(:with_scope, query) do
model.send(method, *args, &block)
end
end | csn |
return the config for a given message type
@param string $type Message type.
@param array $replacements Replacements
@return array
@throws \Exception for a missing or undefined message type | public function message($type, array $replacements = [])
{
if (empty($type)) {
throw new \Exception('Missing message type');
}
$crud = $this->_crud();
$config = $this->getConfig('messages.' . $type);
if (empty($config)) {
$config = $crud->getConfig('... | csn |
Echo status of an SCP operation.
Purpose: Callback function for an SCP operation. Used to show
| the progress of an actively running copy. This directly
| prints to stdout, one line for each file as it's copied.
| The parameters received by this function are those r... | def _copy_status(self, filename, size, sent):
""" Echo status of an SCP operation.
Purpose: Callback function for an SCP operation. Used to show
| the progress of an actively running copy. This directly
| prints to stdout, one line for each file as it's copied.
... | csn |
Creates the Signature Base String.
The Signature Base String is a consistent reproducible concatenation of
the request elements into a single string. The string is used as an
input in hashing or signing algorithms.
@param RequestInterface $request Request being signed
@param array $params Associative arra... | protected function createBaseString(RequestInterface $request, array $params)
{
// Remove query params from URL. Ref: Spec: 9.1.2.
$url = $request->getUri()->withQuery('');
$query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
return strtoupper($request->getMethod())
... | csn |
Restore Image resource from backup | public function reset() {
if (!$this->_image_resource_backup) {
throw new ImageException('Cannot restore, no backup has been taken for image resource');
}
$cloned = $this->cloneResource($this->_image_resource_backup);
$this->_image_resource = $cloned['resource'];
$this->updateImageInfo($cloned['width'], ... | csn |
Register the provider services. | public function register()
{
parent::register();
if (class_exists('Laravel\Lumen\Application') && !defined('SOCIALITEPROVIDERS_STATELESS')) {
define('SOCIALITEPROVIDERS_STATELESS', true);
}
$this->app->singleton(ConfigRetrieverInterface::class, function () {
... | csn |
Retry function. Will wait up to the wait interval, with some random noise if one is provided. Otherwise, will go immediately. | function retry() {
if (!self.waitInterval) {
setImmediate(function() {
self._read(size);
});
} else {
setTimeout(function() {
self._read(size);
}, self.waitInterval * Math.random()).unref();
}
} | csn |
Sync payment profile on Authorize.NET if sync kwarg is not False | def save(self, *args, **kwargs):
"""Sync payment profile on Authorize.NET if sync kwarg is not False"""
if kwargs.pop('sync', True):
self.push_to_server()
self.card_code = None
self.card_number = "XXXX%s" % self.card_number[-4:]
super(CustomerPaymentProfile, self).sav... | csn |
Removes current temp files. | public function clear()
{
if (!empty($this->files)) {
$fs = new FileSystem();
foreach ($this->files as $file) {
$fs->remove($file);
}
}
} | csn |
//Used internally to determine if the dataset needs to use iteself as a source.
//If the dataset has an order or limit it will select from itself | func (me *Dataset) compoundFromSelf() *Dataset {
if me.clauses.Order != nil || me.clauses.Limit != nil {
return me.FromSelf()
}
return me.copy()
} | csn |
Registers an option in this argument parser.
@param name The name of the option to recognize (e.g. {@code --foo}).
@param meta The meta-variable to associate with the value of the option.
@param help A short description of this option.
@throws IllegalArgumentException if the given name was already used.
@throws Illegal... | public void addOption(final String name,
final String meta,
final String help) {
if (name.isEmpty()) {
throw new IllegalArgumentException("empty name");
} else if (name.charAt(0) != '-') {
throw new IllegalArgumentException("name must start with a `-':... | csn |
Constructs a FunctionVersionContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext
:rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext | def get(self, sid):
"""
Constructs a FunctionVersionContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext
:rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext
"""
... | csn |
Establishes the connection to the given WebSocket Server Address. | public void connect() {
readyState = ReadyState.CONNECTING;
try {
if (webSocketHandler == null) {
webSocketHandler = new WebSocketHandlerAdapter();
}
container.connectToServer(new SimpleWebSocketClientEndpoint(), ClientEndpointConfig.Builder.create(... | csn |
Get the Security Information for the given domain.
For details, see https://investigate.umbrella.com/docs/api#securityInfo | def security(self, domain):
'''Get the Security Information for the given domain.
For details, see https://investigate.umbrella.com/docs/api#securityInfo
'''
uri = self._uris["security"].format(domain)
return self.get_parse(uri) | csn |
// Parse reads the hostsfile and populates the byName and byAddr maps. | func (h *Hostsfile) parse(r io.Reader, override *hostsMap) *hostsMap {
hmap := newHostsMap()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Bytes()
if i := bytes.Index(line, []byte{'#'}); i >= 0 {
// Discard comments.
line = line[0:i]
}
f := bytes.Fields(line)
if len(f) < 2 {
... | csn |
Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet | def fbresnet152(num_classes=1000, pretrained='imagenet'):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes)
if pretrained is not None:
settings = pretra... | csn |
Handles function declaration | def FUNCTION_DECL(self, cursor):
"""Handles function declaration"""
# FIXME to UT
name = self.get_unique_name(cursor)
if self.is_registered(name):
return self.get_registered(name)
returns = self.parse_cursor_type(cursor.type.get_result())
attributes = []
... | csn |
Find the oldest females.
@param int $total
@return string | public function topTenOldestFemale(int $total = 10): string
{
$records = $this->topTenOldestQuery('F', $total);
return view('statistics/individuals/top10-nolist', [
'records' => $records,
]);
} | csn |
attempt to retrieve message from queue head | public Object tryGet() {
Object o = null;
if (head != null) {
o = head.getContents();
head = head.getNext();
count--;
if (head == null) {
tail = null;
count = 0;
}
}
return o;
} | csn |
Make an attempt at converting a format spec to a regular expression. | def format_spec_to_regex(field_name, format_spec):
"""Make an attempt at converting a format spec to a regular expression."""
# NOTE: remove escaped backslashes so regex matches
regex_match = fmt_spec_regex.match(format_spec.replace('\\', ''))
if regex_match is None:
raise Va... | csn |
Returns true if user can delete current category and all its contents
To be able to delete course category the user must have permission
'moodle/category:manage' in ALL child course categories AND
be able to delete all courses
@return bool | public function can_delete_full() {
global $DB;
if (!$this->id) {
// Fool-proof.
return false;
}
$context = $this->get_context();
if (!$this->is_uservisible() ||
!has_capability('moodle/category:manage', $context)) {
return fal... | csn |
Get the latest license data from the API server.
The current API version is 2.
@since 1.0.0
@return mixed $response The remote license data object or error string. | private function getRemoteLicense() {
$call = new Api\Call( Configs::get( 'api' ) . '/api/plugin/getLicense?v=' .
$this->apiVersion );
if ( ! $response = $call->getError() ) {
$response = $call->getResponse()->result->data;
}
return $response;
} | csn |
Return the next URL to scrape, given the current URL and its index.
Recursion stops if the fetching URL returns an empty string or an error.
If @paginated is not set (the default), this method returns an empty string.
If @paginated is set, this method will return the next pagination URL
to scrape using @paginati... | def next_index_page_url(url, pagination_index)
return url unless @paginated
if pagination_index > @pagination_max_pages
puts "Exceeded pagination limit of #{@pagination_max_pages}" if @verbose
EMPTY_STRING
else
uri = URI.parse(url)
query = uri.query ? Hash[URI.decode_w... | csn |
Perform validation of the returned state with the previously generated state.
@param string $state
@return boolean | public function validate($state)
{
$valid = $this->store->get(self::STATE_NAME) == $state;
$this->store->delete(self::STATE_NAME);
return $valid;
} | csn |
return true if the coordinates has changed. | static boolean mergeVertices(Point pt_1, Point pt_2, double w_1,
int rank_1, double w_2, int rank_2, Point pt_res, double[] w_res,
int[] rank_res) {
assert (!pt_1.isEmpty() && !pt_2.isEmpty());
boolean res = pt_1.equals(pt_2);
if (rank_1 > rank_2) {
pt_res = pt_1;
if (w_res != null) {
rank_res[0]... | csn |
Execute textlint and send comment
@return [void] | def lint
return if target_files.empty?
bin = textlint_path
result_json = run_textlint(bin, target_files)
errors = parse(result_json)
send_comment(errors)
end | csn |
// Convert_v1_Node_To_core_Node is an autogenerated conversion function. | func Convert_v1_Node_To_core_Node(in *v1.Node, out *core.Node, s conversion.Scope) error {
return autoConvert_v1_Node_To_core_Node(in, out, s)
} | csn |
Test to see if a GPS second is a leap second | private static boolean isleap( double gpsTime ) {
boolean isLeap = false;
double[] leaps = getleaps();
for( int i = 0; i < leaps.length; i += 1 ) {
if (gpsTime == leaps[i]) {
isLeap = true;
break;
}
}
return isLeap;
} | csn |
Whitespace and non-breaking space have the same width? | def com_google_fonts_check_whitespace_widths(ttFont):
"""Whitespace and non-breaking space have the same width?"""
from fontbakery.utils import get_glyph_name
space_name = get_glyph_name(ttFont, 0x0020)
nbsp_name = get_glyph_name(ttFont, 0x00A0)
space_width = ttFont['hmtx'][space_name][0]
nbsp_width = ttF... | csn |
Eagerly fetch this association fetching some of the properties. | protected R fetchProperties(TQProperty<?>... props) {
((TQRootBean) _root).query().fetch(_name, properties(props));
return _root;
} | csn |
Translates a high-level abstraction definition into rules.
@param def a {@link HighLevelAbstractionDefinition}. Cannot be
<code>null</code>.
@throws KnowledgeSourceReadException if an error occurs accessing the
knowledge source during rule creation. | @Override
public void visit(HighLevelAbstractionDefinition def) throws ProtempaException {
LOGGER.log(Level.FINER, "Creating rule for {0}", def);
try {
Set<ExtendedPropositionDefinition> epdsC = def
.getExtendedPropositionDefinitions();
/*
* ... | csn |
// ParseExtendedDuration parses a duration, with the ability to specify time
// units in days, weeks, months, and years. | func ParseExtendedDuration(s string) (time.Duration, error) {
if len(s) == 0 {
return 0, errDurationEmpty
}
var isNegative bool
if s[0] == '-' {
isNegative = true
s = s[1:]
}
var d time.Duration
i := 0
for i < len(s) {
if !isDigit(s[i]) {
return 0, fmt.Errorf("invalid duration %s, no value specifie... | csn |
Listen for start of workers.
@param WorkerPoolInterface $pool
@return void | public function onWorkersStart(WorkerPoolInterface $pool)
{
$workers = $pool->getWorkers();
$count = count($workers);
$this->eventEmitter->emit('peridot.concurrency.stream-select.start', [$count]);
} | csn |
This method performs a JSON-RPC request via the object's ZMQ socket. If successful,
the result is returned, otherwise exceptions are raised. Server side exceptions are
raised using the same type as on the server if they are part of the exceptions-module.
Otherwise, a RemoteException is raised.
... | def _make_request(self, method, *args):
"""
This method performs a JSON-RPC request via the object's ZMQ socket. If successful,
the result is returned, otherwise exceptions are raised. Server side exceptions are
raised using the same type as on the server if they are part of the exceptio... | csn |
// cleans up listener and corresponding target group | func (c *Cloud) deleteListenerV2(listener *elbv2.Listener) error {
_, err := c.elbv2.DeleteListener(&elbv2.DeleteListenerInput{ListenerArn: listener.ListenerArn})
if err != nil {
return fmt.Errorf("Error deleting load balancer listener: %q", err)
}
_, err = c.elbv2.DeleteTargetGroup(&elbv2.DeleteTargetGroupInput{... | csn |
return the index of the node array at which the given node resides
@access public
@author Lionel Lecaque <lionel.lecaque@tudor.lu>
@param Object object
@return int | public function indexOf( common_Object $object)
{
$returnValue = (int) 0;
$returnValue = -1;
foreach($this->sequence as $index => $_object){
if($object === $_object){
return $index;
}
}
return (int) $returnValue;
} | csn |
Get relative y position on the page.
@return x position in pixels | public final int getRelativeY() {
NativeEvent e = getNativeEvent();
Element target = getTarget();
return e.getClientY() - target.getAbsoluteTop() + target.getScrollTop() +
target.getOwnerDocument().getScrollTop();
} | csn |
Records a parameter that gets disposed.
@return {@code true} if all the parameters was recorded and
{@code false} if a parameter with the same name was already defined | public boolean recordDisposesParameter(List<String> parameterNames) {
for (String parameterName : parameterNames) {
if ((currentInfo.hasParameter(parameterName) ||
parameterName.equals("*")) &&
currentInfo.setDisposedParameter(parameterName)) {
populated = true;
} else {
... | csn |
Send a SAML 2 message using the SOAP binding.
Note: This function never returns.
@param \SAML2\Message $message The message we should send.
@return void | public function send(Message $message) : void
{
header('Content-Type: text/xml', true);
$xml = $this->getOutputToSend($message);
if ($xml !== false) {
Utils::getContainer()->debugMessage($xml, 'out');
echo $xml;
}
// DOMDocument::saveXML() returned f... | csn |
Concatenate two semigroups.
@param Semigroup $that
@return Semigroup | public function concat(Semigroup $that): Semigroup {
if (!$that instanceof self) {
throw new \LogicException('Semigroup cannot concatenate two distinct types.');
}
return new Sum($this->value + $that->value);
} | csn |
Gets exchange rates for all defined on-chain exchange services. | def get_onchain_exchange_rates(deposit_crypto=None, withdraw_crypto=None, **modes):
"""
Gets exchange rates for all defined on-chain exchange services.
"""
from moneywagon.onchain_exchange import ALL_SERVICES
rates = []
for Service in ALL_SERVICES:
srv = Service(verbose=modes.get('verbo... | csn |
Creates a new BPMNShape XML element for given node parameters and adds it to 'plane' element.
:param node_id: string representing ID of given flow node,
:param params: dictionary with node parameters,
:param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for nod... | def export_node_di_data(node_id, params, plane):
"""
Creates a new BPMNShape XML element for given node parameters and adds it to 'plane' element.
:param node_id: string representing ID of given flow node,
:param params: dictionary with node parameters,
:param plane: object of E... | csn |
Returns size object for given file name. If file name contains `@Nx` token,
the final dimentions will be downscaled by N
@param {String} fileName
@param {Object} size
@return {Object} | function sizeForFileName(fileName, size) {
const m = fileName.match(/@(\d+)x\./);
const scale = m ? +m[1] : 1;
return {
realWidth: size.width,
realHeight: size.height,
width: Math.floor(size.width / scale),
height: Math.floor(size.height / scale)
};
} | csn |
Return True if search term is found in given line, False otherwise. | def search_line(line, search, searchtype):
"""Return True if search term is found in given line, False otherwise."""
if searchtype == 're' or searchtype == 'word':
return re.search(search, line) #, re.IGNORECASE)
elif searchtype == 'pos':
return searcher.search_out(line, search)
elif se... | csn |
Checks mask shape against input image shape. | def _verify_shape_compatibility(self, img, img_type):
"""Checks mask shape against input image shape."""
if self.input_image.shape[:-1] != img.shape:
raise ValueError('Shape of the {} ({}) is not compatible '
'with input image shape: {} '
... | csn |
Sets the migration references for each valid migrated object.
@param row (see #migrate_row)
@param [Array] migrated the migrated objects
@return [Array] the valid migrated objects | def migrate_valid_references(row, migrated)
# Split the valid and invalid objects. The iteration is in reverse dependency order,
# since invalidating a dependent can invalidate the owner.
ordered = migrated.transitive_closure(:dependents)
ordered.keep_if { |obj| migrated.include?(obj) }.reverse!... | csn |
Helper function for creating a contact object.
@param \stdClass $contact
@param string $prefix
@return \stdClass | public static function create_contact($contact, $prefix = '') {
global $PAGE;
// Create the data we are going to pass to the renderable.
$userfields = \user_picture::unalias($contact, array('lastaccess'), $prefix . 'id', $prefix);
$data = new \stdClass();
$data->userid = $userfi... | csn |
quantitate expression, all programs run here should be multithreaded to
take advantage of the threaded run_parallel environment | def quantitate_expression_parallel(samples, run_parallel):
"""
quantitate expression, all programs run here should be multithreaded to
take advantage of the threaded run_parallel environment
"""
data = samples[0][0]
samples = run_parallel("generate_transcript_counts", samples)
if "cufflinks"... | csn |
Set the collapsed panel height in pixels
@param val A height in pixels | public void setPanelHeight(int val) {
if (getPanelHeight() == val) {
return;
}
mPanelHeight = val;
if (!mFirstLayout) {
requestLayout();
}
if (getPanelState() == PanelState.COLLAPSED) {
smoothToBottom();
invalidate();
... | csn |
Normalizes a string of characters representing a phone number by replacing all characters found
in the accompanying map with the values therein, and stripping all other characters if
removeNonMatches is true.
@param string $number a string of characters representing a phone number
@param array $normalizationReplacemen... | protected static function normalizeHelper($number, array $normalizationReplacements, $removeNonMatches)
{
$normalizedNumber = '';
$strLength = mb_strlen($number, 'UTF-8');
for ($i = 0; $i < $strLength; $i++) {
$character = mb_substr($number, $i, 1, 'UTF-8');
if (isset... | csn |
Use this API to update vpnclientlessaccessprofile resources. | public static base_responses update(nitro_service client, vpnclientlessaccessprofile resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
vpnclientlessaccessprofile updateresources[] = new vpnclientlessaccessprofile[resources.length];
for (int i=0;i<re... | csn |
Returns a string containing the html output of one table row | private static Element row(int row, Table table, ElementCreator elements, HtmlWriteOptions options) {
Element tr = elements.create("tr", null, row);
for (Column<?> col : table.columns()) {
if (options.escapeText()) {
tr.appendChild(elements.create("td", col, row)
... | csn |
Attempts to purchase a user shop item, returns result
Uses the associated user and buyURL to attempt to purchase the user shop item. Returns
whether or not the item was successfully bought.
Returns
bool - True if successful, false otherwise | def buy(self):
""" Attempts to purchase a user shop item, returns result
Uses the associated user and buyURL to attempt to purchase the user shop item. Returns
whether or not the item was successfully bought.
Returns
bool - True if successful, false other... | csn |
// RenderString is a helper function that renders the template as a string. | func (t *Template) RenderString(context ...interface{}) (string, error) {
b := &bytes.Buffer{}
err := t.Render(b, context...)
return b.String(), err
} | csn |
// isCausedBy returns true if the given error returns true on the given predicate,
// unwrapping various standard library error wrappers. | func isCausedBy(err error, p func(error) bool) bool {
if p(err) {
return true
}
err = Cause(err)
for {
if p(err) {
return true
} else if err == nil {
return false
}
if xerr, ok := err.(*ResponseError); ok {
err = xerr.Err
} else if xerr, ok := err.(*url.Error); ok {
err = xerr.Err
} else i... | csn |
Write the views in the given workspace as PlantUML definitions, to stdout.
@param workspace the workspace containing the views to be written | public void toStdOut(Workspace workspace) {
if (workspace == null) {
throw new IllegalArgumentException("A workspace must be provided.");
}
StringWriter stringWriter = new StringWriter();
write(workspace, stringWriter);
System.out.println(stringWriter.toString());
... | csn |
Initialize the response handler.
@param parent the parent resource
@param resource the resource
@return the response builder | public ResponseBuilder initialize(final Resource parent, final Resource resource) {
setResource(DELETED_RESOURCE.equals(resource) || MISSING_RESOURCE.equals(resource) ? null : resource);
// Check the cache
if (getResource() != null) {
final Instant modified = getResource().getModifi... | csn |
Create a list-item using overly simple mechanics. | function pedanticListItem(ctx, value, position) {
var offsets = ctx.offset
var line = position.line
// Remove the list-item’s bullet.
value = value.replace(pedanticBulletExpression, replacer)
// The initial line was also matched by the below, so we reset the `line`.
line = position.line
return value.re... | csn |
// IsBinaryLiteral checks whether an expression is a binary literal | func IsBinaryLiteral(expr Expression) bool {
con, ok := expr.(*Constant)
return ok && con.Value.Kind() == types.KindBinaryLiteral
} | csn |
Method to get the photo link
@param string $type Type of link to return
@return string Link or false on failure
@since 1.0 | public function getLink($type = 'edit')
{
$links = $this->xml->link;
foreach ($links as $link)
{
if ($link->attributes()->rel == $type)
{
return (string) $link->attributes()->href;
}
}
return false;
} | csn |
Show the accumulated results of how many times each rule was used | def get_profile_info(self):
"""Show the accumulated results of how many times each rule was used"""
return sorted(self.profile_info.items(),
key=lambda kv: kv[1],
reverse=False)
return | csn |
List files recurisvely | def listrecursive(path, ext=None):
"""
List files recurisvely
"""
filenames = set()
for root, dirs, files in os.walk(path):
if ext:
if ext == 'tif' or ext == 'tiff':
tmp = fnmatch.filter(files, '*.' + 'tiff')
files = tmp + fnmatch.filter(files, '*.... | csn |
Translate a PRArray to a PdfArray. Also translate all of the objects contained
in it | protected PdfArray copyArray(PdfArray in) throws IOException, BadPdfFormatException {
PdfArray out = new PdfArray();
for (Iterator i = in.listIterator(); i.hasNext();) {
PdfObject value = (PdfObject)i.next();
out.add(copyObject(value));
}
return out;
... | csn |
Internal piece data read function.
<p>
This function will read the piece data without checking if the piece has
been validated. It is simply meant at factoring-in the common read code
from the validate and read functions.
</p>
@param offset Offset inside this piece where to start reading.
@param length Number of byte... | private ByteBuffer _read(long offset, long length, ByteBuffer buffer) throws IOException {
if (offset + length > this.length) {
throw new IllegalArgumentException("Piece#" + this.index +
" overrun (" + offset + " + " + length + " > " +
this.length + ") !");
}
// TODO: remo... | csn |
Named container of edited source
@type EditContainer
@param {String} source
@param {Object} options | function EditContainer(source, options) {
this.options = utils.extend({offset: 0}, options);
/**
* Source code of edited structure. All changes in the structure are
* immediately reflected into this property
*/
this.source = source;
/**
* List of all editable children
* @private
*/
thi... | csn |
Get user's permissions seeds.
@return array | private function getUsersPermissions()
{
return [
[
'name' => 'Users - List all users',
'description' => 'Allow to list all users.',
'slug' => UsersPolicy::PERMISSION_LIST,
],
[
'name' =>... | csn |
Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't exist.
<p>Sample code:
<pre><code>
try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {
String formattedParent = TranslationServiceClient.formatLocationName("[PROJECT]", "[LOCATION]");
String filter = "";... | public final ListGlossariesPagedResponse listGlossaries(String parent, String filter) {
if (!parent.isEmpty()) {
LOCATION_PATH_TEMPLATE.validate(parent, "listGlossaries");
}
ListGlossariesRequest request =
ListGlossariesRequest.newBuilder().setParent(parent).setFilter(filter).build();
retu... | csn |
Initialize the database Manager | public void initialiseDatabase() {
if (!databaseInitialized) {
sendConsoleMessage(Level.INFO, getLanguageManager().getString("loading_database_manager"));
storageHandler = new StorageHandler();
//TODO: Re-support that
if (getMainConfig().getBoolean("System.Databa... | csn |
Reads a string of single byte characters from the input array.
This method assumes that the string finishes either at the
end of the array, or when char zero is encountered.
Reading begins at the supplied offset into the array.
@param data byte array of data
@param offset offset into the array
@return string value | public static final String getString(byte[] data, int offset)
{
StringBuilder buffer = new StringBuilder();
char c;
for (int loop = 0; offset + loop < data.length; loop++)
{
c = (char) data[offset + loop];
if (c == 0)
{
break;
}
buff... | csn |
// Create a new machine in the given org | func (m *MachinesClient) Create(ctx context.Context, orgID, teamID *identity.ID,
name string, output ProgressFunc) (*apitypes.MachineSegment, *base64.Value, error) {
secret, err := createTokenSecret()
if err != nil {
return nil, nil, err
}
mcr := apitypes.MachinesCreateRequest{
Name: name,
OrgID: orgID,... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.