comment stringlengths 16 255 | code stringlengths 52 3.87M |
|---|---|
// Value returns the value of the Coin | func (c *SimpleCoin) Value() btcutil.Amount {
return btcutil.Amount(c.txOut().Value)
} |
Set XML property or method argument value.
@param string $value
@param \DOMElement $node
@param ClassMetadata[] $classesMetadata | protected function setAttribute(string $value, \DOMElement $node, array $classesMetadata)
{
if (array_key_exists($value, $classesMetadata)) {
$node->setAttribute('service', $value);
} elseif (class_exists($value)) {
$node->setAttribute('class', $value);
} else {
... |
Get valid string length
@param string $string Some string
@return int | protected function _strlen($string)
{
$encoding = function_exists('mb_detect_encoding') ? mb_detect_encoding($string) : false;
return $encoding ? mb_strlen($string, $encoding) : strlen($string);
} |
Marshall the given parameter object. | public void marshall(ImportCatalogToGlueRequest importCatalogToGlueRequest, ProtocolMarshaller protocolMarshaller) {
if (importCatalogToGlueRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(i... |
Send "insert" etc. command, returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, the command message. | def write_command(self, request_id, msg):
self.send_message(msg, 0)
reply = self.receive_message(request_id)
result = reply.command_response()
# Raises NotMasterError or OperationFailure.
helpers._check_command_response(result)
return result |
Returns a copy of d with compressed leaves. | def compress(self, d=DEFAULT):
""""""
if d is DEFAULT:
d = self
if isinstance(d, list):
l = [v for v in (self.compress(v) for v in d)]
try:
return list(set(l))
except TypeError:
# list contains not hashables
... |
Returns all the {@link JavaClassSource} objects from the given {@link Project} | public List<JavaResource> getProjectClasses(Project project)
{
final List<JavaResource> classes = new ArrayList<>();
if (project != null)
{
project.getFacet(JavaSourceFacet.class).visitJavaSources(new JavaClassSourceVisitor(classes));
}
return classes;
} |
// SetGroupMemberList sets the GroupMemberList field's value. | func (s *ListGroupMembershipsOutput) SetGroupMemberList(v []*GroupMember) *ListGroupMembershipsOutput {
s.GroupMemberList = v
return s
} |
// GameControllerAddMapping adds support for controllers that SDL is unaware of or to cause an existing controller to have a different binding.
// (https://wiki.libsdl.org/SDL_GameControllerAddMapping) | func GameControllerAddMapping(mappingString string) int {
_mappingString := C.CString(mappingString)
defer C.free(unsafe.Pointer(_mappingString))
return int(C.SDL_GameControllerAddMapping(_mappingString))
} |
update spectating coordinates in "spectate" mode | function(client, packet) {
var x = packet.readFloat32LE();
var y = packet.readFloat32LE();
var zoom = packet.readFloat32LE();
if(client.debug >= 4)
client.log('spectate FOV update: x=' + x + ' y=' + y + ' zoom=' + zoom);
client.... |
Validate label and its shape. | def _check_valid_label(self, label):
""""""
if len(label.shape) != 2 or label.shape[1] < 5:
msg = "Label with shape (1+, 5+) required, %s received." % str(label)
raise RuntimeError(msg)
valid_label = np.where(np.logical_and(label[:, 0] >= 0, label[:, 3] > label[:, 1],
... |
<pre>
Use this operation to enable/disable ntpd.
</pre> | public static ntp_sync update(nitro_service client, ntp_sync resource) throws Exception
{
resource.validate("modify");
return ((ntp_sync[]) resource.update_resource(client))[0];
} |
This function sanitize the user given field and return a common Array structure field
list
@param {DataModel} dataModel the dataModel operating on
@param {Array} fieldArr user input of field Array
@return {Array} arrays of field name | function getFieldArr (dataModel, fieldArr) {
const retArr = [];
const fieldStore = dataModel.getFieldspace();
const dimensions = fieldStore.getDimension();
Object.entries(dimensions).forEach(([key]) => {
if (fieldArr && fieldArr.length) {
if (fieldArr.indexOf(key) !== -1) {
... |
// Get returns value for the given key. | func (r *RedisStore) Get(key string) (interface{}, error) {
cmd := redis.NewCmd("get", key)
if err := r.client.Process(cmd); err != nil {
if err == redis.Nil {
return nil, nil
}
return nil, err
}
return cmd.Val(), cmd.Err()
} |
Return all tags found in the value stream.
Returns:
A `{tagType: ['list', 'of', 'tags']}` dictionary. | def Tags(self):
return {
TENSORS: list(self.tensors_by_tag.keys()),
# Use a heuristic: if the metagraph is available, but
# graph is not, then we assume the metagraph contains the graph.
GRAPH: self._graph is not None,
META_GRAPH: self._meta_graph is not None,
RU... |
// Source returns serializable JSON of the TermsOrder. | func (order *TermsOrder) Source() (interface{}, error) {
source := make(map[string]string)
if order.Ascending {
source[order.Field] = "asc"
} else {
source[order.Field] = "desc"
}
return source, nil
} |
// Minify minifies SVG data, it reads from r and writes to w. | func (o *Minifier) Minify(m *minify.M, w io.Writer, r io.Reader, _ map[string]string) error {
var tag svg.Hash
defaultStyleType := cssMimeBytes
defaultStyleParams := map[string]string(nil)
defaultInlineStyleParams := map[string]string{"inline": "1"}
p := NewPathData(o)
minifyBuffer := buffer.NewWriter(make([]byt... |
Declarative Services method for unsetting the connection manager service reference
@param ref reference to the service | protected void unsetConnectionManager(ServiceReference<ConnectionManagerService> ref) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(this, tc, "unsetConnectionManager", ref);
} |
Filter out optional query parameters with no value provided in request data
@private
@param {json} data Generated Data
@returns {json} return all the properties information | function filterOutOptionalQueryParams(data) {
data.queryParameters = data.queryParameters.filter(function(queryParam) {
// Let's be conservative and treat params without explicit required field as not-optional
var optional = queryParam.required !== undefined && !queryParam.required;
var dataProvided = dat... |
// Del removes a section or key from Ini returning whether or not it did.
// Set the key to an empty string to remove a section. | func (ini *INI) Del(section, key string) bool {
// Remove the section.
if key == "" {
if section == "" {
ini.global = iniSection{}
return true
}
return ini.rmSection(section)
}
// Remove the key for the section.
return ini.getSection(section).rmItem(key, ini.isCaseSensitive)
} |
http://bookofzeus.com/articles/convert-simplexml-object-into-php-array/
Convert a simpleXMLElement in to an array
@todo this is duplicated from CIMAbstractResponse. Put somewhere shared.
@param \SimpleXMLElement $xml
@return array | public function xml2array(\SimpleXMLElement $xml)
{
$arr = array();
foreach ($xml as $element) {
$tag = $element->getName();
$e = get_object_vars($element);
if (!empty($e)) {
$arr[$tag][] = $element instanceof \SimpleXMLElement ? $this->xml2array($... |
// parseAlterRetentionPolicyStatement parses a string and returns an alter retention policy statement.
// This function assumes the ALTER RETENTION POLICY tokens have already been consumed. | func (p *Parser) parseAlterRetentionPolicyStatement() (*AlterRetentionPolicyStatement, error) {
stmt := &AlterRetentionPolicyStatement{}
// Parse the retention policy name.
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok == DEFAULT {
stmt.Name = "default"
} else if tok == IDENT {
stmt.Name = lit
} else {
... |
Checks to see if the current user object is registered. If so, it queries that records
default language. Otherwise, it falls back to sitewide settings.
@return string | public function getUserLanguageToDisplay()
{
if ($this->getUserDefaultLanguage() != '') {
return $this->getUserDefaultLanguage();
} else {
$app = Application::getFacadeApplication();
$config = $app['config'];
return $config->get('concrete.locale');
... |
Returns an array of field values
@return array | protected function getListFieldValue()
{
$id = $this->getParam(0);
if (!isset($id)) {
return $this->field_value->getList(array('limit' => $this->getLimit()));
}
if ($this->getParam('field')) {
return $this->field_value->getList(array('field_id' => $id, 'limi... |
Add a new review | protected function addReview()
{
if (!$this->isError()) {
$id = $this->review->add($this->getSubmitted());
if (empty($id)) {
$this->errorAndExit($this->text('Unexpected result'));
}
$this->line($id);
}
} |
Delete ------------- | public function delete( $model, $config = [] ) {
// Delete files
$this->fileService->deleteMultiple( [ $model->avatar, $model->banner, $model->video ] );
$this->fileService->deleteMultiple( $model->files );
// Delete File Mappings - Shared Files
$this->modelFileService->deleteMultiple( $model->modelFiles );... |
elem = a graphic element will have an attribute like marker-start attr - marker-start, marker-mid, or marker-end returns the marker element that is linked to the graphic element | function getLinked(elem, attr) {
var str = elem.getAttribute(attr);
if(!str) {return null;}
var m = str.match(/\(\#(.*)\)/);
if(!m || m.length !== 2) {
return null;
}
return S.getElem(m[1]);
} |
Free all the child sFields.
@param bIncludeToolScreens If true, also free the toolScreens. | public void freeAllSFields(boolean bIncludeToolScreens)
{
int iToolScreens = 0;
while (this.getSFieldCount() > iToolScreens)
{ // First, get rid of all child screens.
ScreenField sField = this.getSField(iToolScreens);
if ((!bIncludeToolScreens) && (sField instanceof... |
If the entry is being prepopulated, we may want to filter other views by this entry's
value. This function will create that filter query string.
@since Symphony 2.5.2
@return string | public function getFilterString()
{
$filter_querystring = '';
if (isset($_REQUEST['prepopulate']) && is_array($_REQUEST['prepopulate'])) {
foreach ($_REQUEST['prepopulate'] as $field_id => $value) {
$handle = FieldManager::fetchHandleFromID($field_id);
//... |
Prepare the validator.
@param \Asgard\Validation\ValidatorInterface $validator
@param array $locales
@return \Asgard\Validation\ValidatorInterface | public function prepareValidator(\Asgard\Validation\ValidatorInterface $validator, array $locales=[]) {
$this->getDefinition()->trigger('validation', [$this, $validator], function($chain, $entity, $validator) use($locales) {
$messages = [];
foreach($this->getDefinition()->properties() as $name=>$property) {
... |
Return a format string for printing an `expr_type`
ket/bra/ketbra/braket | def _braket_fmt(self, expr_type):
""""""
if self._settings['unicode_sub_super']:
sub_sup_fmt = SubSupFmt
else:
sub_sup_fmt = SubSupFmtNoUni
mapping = {
'bra': {
True: sub_sup_fmt('⟨{label}|', sup='({space})'),
'subscript... |
Escape special characters in HTML | def escape(self, text, quote = True):
if isinstance(text, bytes):
return escape_b(text, quote)
else:
return escape(text, quote) |
Returns the URL for the given model and admin url name. | def admin_url(model, url, object_id=None):
opts = model._meta
url = "admin:%s_%s_%s" % (opts.app_label, opts.object_name.lower(), url)
args = ()
if object_id is not None:
args = (object_id,)
return reverse(url, args=args) |
getEndTag - returns the end tag representation as HTML string
@return - String of end tag | def getEndTag(self):
'''
'''
# If this is a self-closing tag, we have no end tag (opens and closes in the start)
if self.isSelfClosing is True:
return ''
tagName = self.tagName
# Do not add any indentation to the end of preformatted tags.
... |
//Each runs through the function lists and executing with args | func (f *ListenerStack) Each(d Event) {
if f.Size() <= 0 {
return
}
f.lock.RLock()
// var ro sync.Mutex
var stop bool
for _, fx := range f.listeners {
if stop {
break
}
//TODO: is this critical that we send it into a goroutine with a mutex?
fx(d, func() {
// ro.Lock()
stop = true
// ro.Un... |
Gets the type for a property setter.
@param name the name of the property
@return the Class of the property setter
@throws NoSuchMethodException when a setter method cannot be found | public Class<?> getSetterType(String name) throws NoSuchMethodException {
Class<?> type = setterTypes.get(name);
if (type == null) {
throw new NoSuchMethodException("There is no WRITABLE property named '" + name +
"' in class '" + className + "'");
}
retur... |
// EjectIso removes the iso file based backing and replaces with the default cdrom backing. | func (l VirtualDeviceList) EjectIso(device *types.VirtualCdrom) *types.VirtualCdrom {
l.setDefaultCdromBacking(device)
return device
} |
Helper function that handles creating the lower and upper bounds for calling {@link
SortedMap#subMap(Object, Object)}.
@see SortedMap#subMap(Object, Object) | private static <E> SortedMap<PrefixKey, E> getPrefixSubMap(
TreeMap<PrefixKey, E> map, PrefixKey lowerBound) {
PrefixKey upperBound =
new PrefixKey(lowerBound.getBucket(), lowerBound.getObjectName() + Character.MAX_VALUE);
return map.subMap(lowerBound, upperBound);
} |
Returns the **real** type for the real or imaginary part of a **real** complex type.
For instance:
COMPLEX128_t -> FLOAT64_t
Args:
cysparse: | def cysparse_real_type_from_real_cysparse_complex_type(cysparse_type):
r_type = None
if cysparse_type in ['COMPLEX64_t']:
r_type = 'FLOAT32_t'
elif cysparse_type in ['COMPLEX128_t']:
r_type = 'FLOAT64_t'
elif cysparse_type in ['COMPLEX256_t']:
r_type = 'FLOAT128_t'
else... |
Invokes $fn with $args while managing our internal invocation context
in order to ensure our view of the test DSL's call graph is accurate. | public function invokeWithin($fn, $args = array())
{
$this->invocation_context->activate();
$this->invocation_context->push($this);
try {
$result = call_user_func_array($fn, $args);
$this->invocation_context->pop();
$this->invocation_context->deactivate()... |
// NewDefaultTrimaWithSrcLen creates a Triangular Moving Average Indicator (Trima) for offline usage with default parameters | func NewDefaultTrimaWithSrcLen(sourceLength uint) (indicator *Trima, err error) {
ind, err := NewDefaultTrima()
// only initialise the storage if there is enough source data to require it
if sourceLength-uint(ind.GetLookbackPeriod()) > 1 {
ind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod()))
... |
Obtains all the tags assigned to this area and its child areas (not all descendant areas).
@return a set of tags | protected Set<Tag> getAllTags(Area area)
{
Set<Tag> ret = new HashSet<Tag>(area.getTags().keySet());
for (int i = 0; i < area.getChildCount(); i++)
ret.addAll(area.getChildAt(i).getTags().keySet());
return ret;
} |
Answer a pending approval
:param issue_id_or_key: str
:param approval_id: str
:param decision: str
:return: | def answer_approval(self, issue_id_or_key, approval_id, decision):
url = 'rest/servicedeskapi/request/{0}/approval/{1}'.format(issue_id_or_key, approval_id)
data = {'decision': decision}
return self.post(url, headers=self.experimental_headers, data=data) |
Encode the given object into a series of statements and expressions.
<p>
The implementation simply finds the <code>PersistenceDelegate</code> responsible for the object's class, and delegate the call to it.
</p>
@param o
the object to encode | protected void writeObject(Object o)
{
if (o == null)
{
return;
}
getPersistenceDelegate(o.getClass()).writeObject(o, this);
} |
Store an item in the cache for a given number of minutes.
@param string $key
@param mixed $value
@param int $minutes
@return void | public function put($key, $value, $minutes) {
$this->cache[$key] = [
'value' => $value,
'ttl' => $this->getNow() + ($minutes * 60),
];
} |
Retourne l'ann�e et mois format�s
@param integer $mmaaaa
@param string $format
@param string $separator default ' '
@return string | public static function getmoisanneemini($mmaaaa, $format = 'mm/aaaa', $separator = ' ')
{
$str = '';
switch ($format) {
case 'aaaamm':
$str = self::getmoismini(substr($mmaaaa, 4, 2)) . $separator . substr($mmaaaa, 0, 4);
break;
case 'mmaaaa':
... |
Parse and yield array items from the token stream. | def array_items(self, number_type, *, number_suffix=''):
""""""
for token in self.collect_tokens_until('CLOSE_BRACKET'):
is_number = token.type == 'NUMBER'
value = token.value.lower()
if not (is_number and value.endswith(number_suffix)):
raise self.err... |
Build the transaction dictionary without sending | def buildTransaction(self, transaction=None):
if transaction is None:
built_transaction = {}
else:
built_transaction = dict(**transaction)
if 'data' in built_transaction:
raise ValueError("Cannot set data in build transaction")
if not self.a... |
// Convert_image_ImageLayerData_To_v1_ImageLayerData is an autogenerated conversion function. | func Convert_image_ImageLayerData_To_v1_ImageLayerData(in *image.ImageLayerData, out *v1.ImageLayerData, s conversion.Scope) error {
return autoConvert_image_ImageLayerData_To_v1_ImageLayerData(in, out, s)
} |
Apply a series of transformations defined as closures in the configuration file.
@param string $string
@return string | private function applyTransformers(string $string): string
{
foreach (Transformer::getAll() as $transformer) {
$string = $transformer($string);
}
return $string;
} |
Return selector special pseudo class info (steps and other). | def extract_selector_info(sel):
""""""
# walk the parsed_tree, looking for pseudoClass selectors, check names
# add in steps and/or deferred extras
steps, extras = _extract_sel_info(sel.parsed_tree)
steps = sorted(set(steps))
extras = sorted(set(extras))
if len(steps) == 0:
steps = ... |
// SetGatewayARN sets the GatewayARN field's value. | func (s *DescribeVTLDevicesInput) SetGatewayARN(v string) *DescribeVTLDevicesInput {
s.GatewayARN = &v
return s
} |
Retrieves the project start date. If an explicit start date has not been
set, this method calculates the start date by looking for
the earliest task start date.
@return project start date | public Date getStartDate()
{
Date result = (Date) getCachedValue(ProjectField.START_DATE);
if (result == null)
{
result = getParentFile().getStartDate();
}
return (result);
} |
Merges and returns current query data with defined data and returns as query string
@param string $ns Target namespace (Group)
@param array $data Data to be merged
@param boolean $mark Whether to prepend question mark
@return string | public function getWithNsQuery($ns, array $data, $mark = true)
{
if ($this->hasQuery($ns)) {
$query = $this->getQuery($ns);
$url = null;
if ($mark === true) {
$url = '?';
}
$url .= http_build_query(array($ns => array_merge($query,... |
Represent date and datetime objects as MATCH strings. | def _safe_match_date_and_datetime(graphql_type, expected_python_types, value):
""""""
# Python datetime.datetime is a subclass of datetime.date,
# but in this case, the two are not interchangeable.
# Rather than using isinstance, we will therefore check for exact type equality.
value_type = type(val... |
// GasTable returns the gas table corresponding to the current phase (homestead or homestead reprice).
//
// The returned GasTable's fields shouldn't, under any circumstances, be changed. | func (c *ChainConfig) GasTable(num *big.Int) GasTable {
if num == nil {
return GasTableHomestead
}
switch {
case c.IsConstantinople(num):
return GasTableConstantinople
case c.IsEIP158(num):
return GasTableEIP158
case c.IsEIP150(num):
return GasTableEIP150
default:
return GasTableHomestead
}
} |
Register the bindings for the main JWTAuth class.
@return void | protected function registerJWTAuth()
{
$this->app->singleton('tymon.jwt.auth', function ($app) {
return (new JWTAuth(
$app['tymon.jwt.manager'],
$app['tymon.jwt.provider.auth'],
$app['tymon.jwt.parser']
))->lockSubject($this->config('lo... |
If the prefix is a JSON string with key-value data, extract it as an
associative array. Otherwise return null.
@param mixed $prefix The raw prefix string.
@return null|array | private function extractPrefixKeyValueData($prefix)
{
$result = null;
// If it has key-value data, as evidenced by the raw prefix string
// being a JSON object (not JSON array), use it.
if (substr($prefix, 0, 1) === '{') {
if ($this->isJsonString($prefix)) {
... |
Finds all the snapshots in all the places we know of which could possibly
store snapshots, like command log snapshots, auto snapshots, etc.
@return All snapshots | private Map<String, Snapshot> getSnapshots() {
/*
* Use the individual snapshot directories instead of voltroot, because
* they can be set individually
*/
Map<String, SnapshotPathType> paths = new HashMap<String, SnapshotPathType>();
if (VoltDB.instance().getConfig().m... |
------------------------------------------------------------------------ | private void serializeMasterState(MasterState state, DataOutputStream dos) throws IOException {
// magic number for error detection
dos.writeInt(MASTER_STATE_MAGIC_NUMBER);
// for safety, we serialize first into an array and then write the array and its
// length into the checkpoint
final ByteArrayOutputStre... |
Call a RPC method.
return object: a result | def rpc_call(self, request, method=None, params=None, **kwargs):
args = []
kwargs = dict()
if isinstance(params, dict):
kwargs.update(params)
else:
args = list(as_tuple(params))
method_key = "{0}.{1}".format(self.scheme_name, method)
if m... |
Transform reference catalog sky positions (self.all_radec)
to reference tangent plane (self.wcs) to create output X,Y positions. | def transformToRef(self):
if 'refxyunits' in self.pars and self.pars['refxyunits'] == 'pixels':
log.info('Creating RA/Dec positions for reference sources...')
self.outxy = np.column_stack([self.all_radec[0][:,np.newaxis],self.all_radec[1][:,np.newaxis]])
skypos = sel... |
// Strings reflects over a structure and calls Parse when strings are located | func Strings(parser StringParser, obj interface{}) {
parsers := Parsers{
StringParser: parser,
}
parseRecursive(parsers, reflect.ValueOf(obj))
} |
Recalculate dynamic property values
@param {any} entity Entity instance
@param {any} properties Entity's properties' configuration
@memberof EnTTExt | function recalculateAllDynamicProperties(entity, properties) {
// Find all dynamic properties
_lodash2.default.forEach(properties, function (propertyConfiguration, propertyName) {
if (isDynamicProperty(propertyConfiguration)) {
// Recalculate dynamic property value
var dynamicValue = propertyConfigu... |
Set twitterImage w/ proxy.
@param Image $twitterImage
@return PageSeo | public function setTwitterImage($twitterImage, $locale = null)
{
$this->translate($locale, false)->setTwitterImage($twitterImage);
$this->mergeNewTranslations();
return $this;
} |
Notify a danger alert.
@param string $message
@param string|null $title
@param array $options | protected function notifyDanger($message, $title = null, array $options = [])
{
$this->notifyFlash($message, 'danger', $title, $options);
} |
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"jira.py") if it can't be found. | def fetch_command(self, subcommand):
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
# This might trigger ImproperlyConfigured (masked in get_commands)
... |
Executes a command on the server and returns an array of string.
@param string $command Command to execute
@param string $target First parameter
@param string $value Second parameter
@return array The result of the command as an array of string | public function getStringArray($command, $target = null, $value = null)
{
$string = $this->getString($command, $target, $value);
$results = preg_split('/(?<!\\\),/', $string);
foreach ($results as &$result) {
$result = str_replace('\,', ',', $result);
}
return $... |
Setup WordPress conditions.
@param array $conditions | public function setConditions(array $conditions = [])
{
$config = $this->container->has('config') ? $this->container->make('config') : null;
if (! is_null($config)) {
$this->conditions = array_merge(
$config->get('app.conditions', []),
$conditions
... |
Ensure that the field counts match the validation rule counts.
@param array $data | private function check_fields(array $data)
{
$ruleset = $this->validation_rules();
$mismatch = array_diff_key($data, $ruleset);
$fields = array_keys($mismatch);
foreach ($fields as $field) {
$this->errors[] = array(
'field' => $field,
'val... |
Return a list of IR blocks with all Backtrack blocks removed. | def remove_backtrack_blocks_from_fold(folded_ir_blocks):
""""""
new_folded_ir_blocks = []
for block in folded_ir_blocks:
if not isinstance(block, Backtrack):
new_folded_ir_blocks.append(block)
return new_folded_ir_blocks |
Generate header with module table entries for builtin modules.
:param List[(module_name, obj_module, enabled_define)] modules: module defs
:return: None | def generate_module_table_header(modules):
# Print header file for all external modules.
mod_defs = []
print("// Automatically generated by makemoduledefs.py.\n")
for module_name, obj_module, enabled_define in modules:
mod_def = "MODULE_DEF_{}".format(module_name.upper())
mod_defs.... |
Builds a property transform from a kernel and some options
@param kernel The transform kernel
@param options Some options regarding the property transform | function buildPropertyTransform(kernel, options = {}) {
if (options.splitArrays == null)
options.splitArrays = true;
if (options.neverSkip == null)
options.neverSkip = false;
const ret = kernel;
ret.splitArrays = options.splitArrays;
ret.neverSkip = options.neverSkip;
return ret;... |
LOWER LEVEL INDEX OPERATIONS | def with_index(new_index) # :yields: new_index
old_index = @index
set_index(new_index, false)
return_value = yield @index
set_index(old_index)
return_value
end |
Loads project data by namespace:name
@param string $project_name namespace:name
@return \stdClass
@throws \Exception | protected function getByName($project_name) {
if (!strstr($project_name, ":")) {
throw (new \Exception("You must search for project with namespace: prefix"));
}
$parts = explode(':', $project_name);
$projects = $this->_client->get('/projects/search/' . urlencode($parts[1]))... |
Validates subscription data before creating Outbound message | def post(self, request, *args, **kwargs):
schedule_disable.delay(kwargs["subscription_id"])
return Response({"accepted": True}, status=201) |
If this node is newly selected, scroll it into view. Also, move the selection or
context boxes as appropriate. | function (prevProps, prevState) {
var wasSelected = prevProps.entry.get("selected"),
isSelected = this.props.entry.get("selected");
if (isSelected && !wasSelected) {
// TODO: This shouldn't really know about project-files-container
// directly. I... |
// CapFromCenterHeight constructs a cap with the given center and height. A
// negative height yields an empty cap; a height of 2 or more yields a full cap.
// The center should be unit length. | func CapFromCenterHeight(center Point, height float64) Cap {
return CapFromCenterChordAngle(center, s1.ChordAngleFromSquaredLength(2*height))
} |
Get valid user attempts that match the given request and credentials. | def get_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet:
attempts = filter_user_attempts(request, credentials)
if settings.AXES_COOLOFF_TIME is None:
log.debug('AXES: Getting all access attempts from database because no AXES_COOLOFF_TIME is configured')
retur... |
Remove all of the event listeners for the model.
@return void | public static function flushEventListeners()
{
if (! isset(static::$dispatcher)) {
return;
}
$instance = new static;
foreach ($instance->getObservableEvents() as $event) {
static::$dispatcher->forget("eloquent.{$event}: ".static::class);
}
f... |
// SetShippingOption sets the ShippingOption field's value. | func (s *UpdateClusterInput) SetShippingOption(v string) *UpdateClusterInput {
s.ShippingOption = &v
return s
} |
Raise the given event.
@param object $event
@return void | protected function raise($event)
{
$qualified = get_class($event);
$name = str_replace('\\', '.', $qualified);
$this->events->fire($name, [$event]);
} |
Adds the main file definitions from the root package.
@param Config $config
@param PackageInterface $package
@param string $section
@return PackageInterface | public static function addMainFiles(Config $config, PackageInterface $package, $section = 'main-files')
{
if ($package instanceof Package) {
$packageExtra = $package->getExtra();
$rootMainFiles = $config->getArray($section);
foreach ($rootMainFiles as $packageName => $fi... |
Return dict of extra fields added to the historical record model | def get_extra_fields(self, model, fields):
""""""
def revert_url(self):
"""URL for this change in the default admin site."""
opts = model._meta
app_label, model_name = opts.app_label, opts.model_name
return reverse(
"%s:%s_%s_simple_histor... |
Remove the appropriate target listeners to this component
and all its children. | protected void removeTargetListeners (Component comp)
{
comp.removeMouseListener(_targetListener);
comp.removeMouseMotionListener(_targetListener);
if (comp instanceof Container) { // again, always true for JComp...
Container cont = (Container) comp;
cont.removeContai... |
Adjust a single component (red, green, blue or alpha) of a colour.
@param component The value to mutate.
@return The mutated component value. | private int mutateColourComponent(int component)
{
int mutatedComponent = (int) Math.round(component + mutationAmount.nextValue());
mutatedComponent = Maths.restrictRange(mutatedComponent, 0, 255);
return mutatedComponent;
} |
Perform fling action.
Usage:
d().fling() # default vertically, forward
d().fling.horiz.forward()
d().fling.vert.backward()
d().fling.toBeginning(max_swipes=100) # vertically
d().fling.horiz.toEnd() | def fling(self):
'''
'''
@param_to_property(
dimention=["vert", "vertically", "vertical", "horiz", "horizental", "horizentally"],
action=["forward", "backward", "toBeginning", "toEnd"]
)
def _fling(dimention="vert", action="forward", max_swipes=10... |
Marshall the given parameter object. | public void marshall(ReservationPurchaseRecommendationSummary reservationPurchaseRecommendationSummary, ProtocolMarshaller protocolMarshaller) {
if (reservationPurchaseRecommendationSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {... |
Given one format, one block id and, optionally, one moduleid, return the corresponding backup_xxx_block_task() | public static function get_backup_block_task($format, $blockid, $moduleid = null) {
global $CFG, $DB;
// Check blockid exists
if (!$block = $DB->get_record('block_instances', array('id' => $blockid))) {
throw new backup_task_exception('block_task_block_instance_not_found', $blockid)... |
Pretty version
:param diff_to_increase_ratio: Ratio to convert number of changes into
version increases
:return: string: Pretty version of this repository | def get_pretty_version(self, diff_to_increase_ratio):
version = self.get_version(diff_to_increase_ratio)
build = self.get_last_commit_hash()
return str(version) + " (" + build + ")" |
// GetUint32 gets given key as a uint32 | func (e *Entity) GetUint32(name string) (uint32, bool) {
if v := e.Get(name); v != nil {
switch x := v.(type) {
case uint32:
return x, true
case uint64:
return uint32(x), true
}
}
return 0, false
} |
Returns an iterator over this page's {@code results} that:
<ul>
<li>Will not be {@code null}.</li>
<li>Will not support {@link java.util.Iterator#remove()}.</li>
</ul>
@return a non-null iterator. | @Override
public java.util.Iterator<com.google.api.ads.admanager.axis.v201805.User> iterator() {
if (results == null) {
return java.util.Collections.<com.google.api.ads.admanager.axis.v201805.User>emptyIterator();
}
return java.util.Arrays.<com.google.api.ads.admanager.axis.v2018... |
A wrapper around {@link FileSystem#rename(Path, Path)} which throws {@link IOException} if
{@link FileSystem#rename(Path, Path)} returns False. | public static void renamePath(FileSystem fs, Path oldName, Path newName, boolean overwrite) throws IOException {
if (!fs.exists(oldName)) {
throw new FileNotFoundException(String.format("Failed to rename %s to %s: src not found", oldName, newName));
}
if (fs.exists(newName)) {
if (overwrite) {
... |
Read a single message from the connection.
Re-assemble data frames if the message is fragmented.
Return ``None`` when the closing handshake is started. | async def read_message(self) -> Optional[Data]:
frame = await self.read_data_frame(max_size=self.max_size)
# A close frame was received.
if frame is None:
return None
if frame.opcode == OP_TEXT:
text = True
elif frame.opcode == OP_BINARY:
... |
Log an error. By default this will also raise an exception. | def error(self, *args):
""""""
if _canShortcutLogging(self.logCategory, ERROR):
return
errorObject(self.logObjectName(), self.logCategory,
*self.logFunction(*args)) |
Get type from vmodl name | def GetVmodlType(name):
# If the input is already a type, just return
if isinstance(name, type):
return name
# Try to get type from vmodl type names table
typ = vmodlTypes.get(name)
if typ:
return typ
# Else get the type from the _wsdlTypeMap
isArray = name.endswith("[]")
if i... |
Prints a nice side block with an optional header.
@param block_contents $bc HTML for the content
@param string $region the region the block is appearing in.
@return string the HTML to be output. | public function block(block_contents $bc, $region) {
$bc = clone($bc); // Avoid messing up the object passed in.
if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
$bc->collapsible = block_contents::NOT_HIDEABLE;
}
$id = !empty($bc->attributes['id']) ? $bc->attrib... |
// SetGracePeriod sets the health check initial grace period, in seconds | func (p *PodHealthCheck) SetGracePeriod(gracePeriodSeconds int) *PodHealthCheck {
p.GracePeriodSeconds = &gracePeriodSeconds
return p
} |
// UpdateSplunk updates a specific splunk. | func (c *Client) UpdateSplunk(i *UpdateSplunkInput) (*Splunk, error) {
if i.Service == "" {
return nil, ErrMissingService
}
if i.Version == 0 {
return nil, ErrMissingVersion
}
if i.Name == "" {
return nil, ErrMissingName
}
path := fmt.Sprintf("/service/%s/version/%d/logging/splunk/%s", i.Service, i.Vers... |
Helper around 'locate' | def find(pattern, root=os.curdir):
''' '''
hits = ''
for F in locate(pattern, root):
hits = hits + F + '\n'
l = hits.split('\n')
if(not len(l[-1])): l.pop()
if len(l) == 1 and not len(l[0]):
return None
else:
return l |
Subsets and Splits
SQL Console for sentence-transformers/codesearchnet
Identifies examples where both requests.get() and beautifulsoup libraries are used together in code comments, revealing common web scraping patterns in the training data.
Golang Code and Comments
Retrieves all entries containing the term 'golang' in either the comment or code, providing a basic filter for data related to the Go programming language.