query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
def change_dylib_id(new_id, options = {})
raise ArgumentError, "argument must be a String" unless new_id.is_a?(String)
return unless machos.all?(&:dylib?)
each_macho(options) do | |macho|
macho.change_dylib_id(new_id, options)
end
repopulate_raw_machos
end | csn_ccr |
shows structured information of a object, list, tuple etc | def var_dump(*obs):
"""
shows structured information of a object, list, tuple etc
"""
i = 0
for x in obs:
str = var_dump_output(x, 0, ' ', '\n', True)
print (str.strip())
#dump(x, 0, i, '', object)
i += 1 | csn |
public static String getDataStoreIdentifier(URI location, String apiKey) {
checkArgument(getLocationType(location) != LocationType.STASH, "Stash locations do not have a data source ID");
UriBuilder uriBuilder = UriBuilder.fromUri(location)
.userInfo(apiKey)
.replacePath(null)
.replaceQuery(null);
if (getLocationType(location) == LocationType.EMO_HOST_DISCOVERY) {
| Optional<String> zkConnectionStringOverride = getZkConnectionStringOverride(location);
if (zkConnectionStringOverride.isPresent()) {
uriBuilder.queryParam(ZK_CONNECTION_STRING_PARAM, zkConnectionStringOverride.get());
}
Optional<List<String>> hosts = getHostOverride(location);
if (hosts.isPresent()) {
for (String host : hosts.get()) {
uriBuilder.queryParam(HOST_PARAM, host);
}
}
}
return uriBuilder.build().toString();
} | csn_ccr |
add all SearchResult objects from the SearchResults which fall
within the time range of this partition into this partition.
@param results | public void filter(CaptureSearchResults results) {
Iterator<CaptureSearchResult> itr = results.iterator();
while(itr.hasNext()) {
CaptureSearchResult result = itr.next();
String captureDate = result.getCaptureTimestamp();
if((captureDate.compareTo(startDateStr) >= 0)
&& (captureDate.compareTo(endDateStr) < 0)) {
matches.add(result);
}
}
} | csn |
Helper to handle methods, functions, generators, strings and raw code objects | def get_code_object(x):
"""Helper to handle methods, functions, generators, strings and raw code objects"""
if hasattr(x, '__func__'): # Method
x = x.__func__
if hasattr(x, '__code__'): # Function
x = x.__code__
if hasattr(x, 'gi_code'): # Generator
x = x.gi_code
if isinstance(x, str): # Source code
x = _try_compile(x, "<disassembly>")
if hasattr(x, 'co_code'): # Code object
return x
raise TypeError("don't know how to disassemble %s objects" %
type(x).__name__) | csn |
func AddAllExposedPodEdges(g osgraph.MutableUniqueGraph) {
for _, node := range g.(graph.Graph).Nodes() | {
if serviceNode, ok := node.(*kubegraph.ServiceNode); ok {
AddExposedPodEdges(g, serviceNode)
}
}
} | csn_ccr |
Add a property to the parameter
@param Parameter $property Properties to set
@return self | public function addProperty(Parameter $property)
{
$this->properties[$property->getName()] = $property;
$property->setParent($this);
$this->propertiesCache = null;
return $this;
} | csn |
python convolve gaussian kernel | def convolve_gaussian_2d(image, gaussian_kernel_1d):
"""Convolve 2d gaussian."""
result = scipy.ndimage.filters.correlate1d(
image, gaussian_kernel_1d, axis=0)
result = scipy.ndimage.filters.correlate1d(
result, gaussian_kernel_1d, axis=1)
return result | cosqa |
Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class,
tak si to namapujme | def _map_table_name(self, model_names):
"""
Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class,
tak si to namapujme
"""
for model in model_names:
if isinstance(model, tuple):
model = model[0]
try:
model_cls = getattr(self.models, model)
self.table_to_class[class_mapper(model_cls).tables[0].name] = model
except AttributeError:
pass | csn |
initialize Config Source Object for given resource
@param Smarty_Internal_Config $_config config object
@return Smarty_Config_Source Source Object | public static function config(Smarty_Internal_Config $_config)
{
static $_incompatible_resources = array('eval' => true, 'string' => true, 'extends' => true, 'php' => true);
$config_resource = $_config->config_resource;
$smarty = $_config->smarty;
// parse resource_name
self::parseResourceName($config_resource, $smarty->default_config_type, $name, $type);
// make sure configs are not loaded via anything smarty can't handle
if (isset($_incompatible_resources[$type])) {
throw new SmartyException ("Unable to use resource '{$type}' for config");
}
// load resource handler, identify unique resource name
$resource = Smarty_Resource::load($smarty, $type);
$unique_resource_name = $resource->buildUniqueResourceName($smarty, $name);
// check runtime cache
$_cache_key = 'config|' . $unique_resource_name;
if (isset(self::$sources[$_cache_key])) {
return self::$sources[$_cache_key];
}
// create source
$source = new Smarty_Config_Source($resource, $smarty, $config_resource, $type, $name, $unique_resource_name);
$resource->populate($source, null);
// runtime cache
self::$sources[$_cache_key] = $source;
return $source;
} | csn |
Searches for a comboitem that has a date range equivalent to the specified range.
@param range The date range to locate.
@return A comboitem containing the date range, or null if not found. | public Dateitem findMatchingItem(DateRange range) {
for (BaseComponent item : getChildren()) {
if (range.equals(item.getData())) {
return (Dateitem) item;
}
}
return null;
} | csn |
Return the Brizo component url.
:param config: Config
:return: Url, str | def get_brizo_url(config):
"""
Return the Brizo component url.
:param config: Config
:return: Url, str
"""
brizo_url = 'http://localhost:8030'
if config.has_option('resources', 'brizo.url'):
brizo_url = config.get('resources', 'brizo.url') or brizo_url
brizo_path = '/api/v1/brizo'
return f'{brizo_url}{brizo_path}' | csn |
// Group defines group's child group | func (g *Group) Group(p string, o interface{}) {
gr := getGroup(o)
for _, gchild := range gr.routers {
g.Route(gchild.methods, joinRoute(p, gchild.url), gchild.c, append(gr.handlers, gchild.handlers...)...)
}
} | csn |
// FuncHasQuery returns the offset of the string parameter named "query", or
// none if no such parameter exists. | func FuncHasQuery(sqlPackages sqlPackage, s *types.Signature) (offset int, ok bool) {
params := s.Params()
for i := 0; i < params.Len(); i++ {
v := params.At(i)
for _, paramName := range sqlPackages.paramNames {
if v.Name() == paramName {
return i, true
}
}
}
return 0, false
} | csn |
Returns a dictionary of all settings set for this object, including
any values of its parents or hardcoded defaults. | def freeze(self) -> dict:
"""
Returns a dictionary of all settings set for this object, including
any values of its parents or hardcoded defaults.
"""
settings = {}
for key, v in self._h.defaults.items():
settings[key] = self._unserialize(v.value, v.type)
if self._parent:
settings.update(getattr(self._parent, self._h.attribute_name).freeze())
for key in self._cache():
settings[key] = self.get(key)
return settings | csn |
Helper function to obtain the shape of an array | def get_input_shape(sym, proto_obj):
"""Helper function to obtain the shape of an array"""
arg_params = proto_obj.arg_dict
aux_params = proto_obj.aux_dict
model_input_shape = [data[1] for data in proto_obj.model_metadata.get('input_tensor_data')]
data_names = [data[0] for data in proto_obj.model_metadata.get('input_tensor_data')]
# creating dummy inputs
inputs = []
for in_shape in model_input_shape:
inputs.append(nd.ones(shape=in_shape))
data_shapes = []
for idx, input_name in enumerate(data_names):
data_shapes.append((input_name, inputs[idx].shape))
ctx = context.cpu()
# create a module
mod = module.Module(symbol=sym, data_names=data_names, context=ctx, label_names=None)
mod.bind(for_training=False, data_shapes=data_shapes, label_shapes=None)
mod.set_params(arg_params=arg_params, aux_params=aux_params)
data_forward = []
for idx, input_name in enumerate(data_names):
val = inputs[idx]
data_forward.append(val)
mod.forward(io.DataBatch(data_forward))
result = mod.get_outputs()[0].asnumpy()
return result.shape | csn |
Add a profile to a role | def add_profile(project_root)
roles = Bebox::Role.list(project_root)
profiles = Bebox::Profile.list(project_root)
role = choose_option(roles, _('wizard.choose_role'))
profile = choose_option(profiles, _('wizard.role.choose_add_profile'))
if Bebox::Role.profile_in_role?(project_root, role, profile)
warn _('wizard.role.profile_exist')%{profile: profile, role: role}
output = false
else
output = Bebox::Role.add_profile(project_root, role, profile)
ok _('wizard.role.add_profile_success')%{profile: profile, role: role}
end
return output
end | csn |
// FailAction is part of the operation.Callbacks interface. | func (opc *operationCallbacks) FailAction(actionId, message string) error {
if !names.IsValidAction(actionId) {
return errors.Errorf("invalid action id %q", actionId)
}
tag := names.NewActionTag(actionId)
err := opc.u.st.ActionFinish(tag, params.ActionFailed, nil, message)
if params.IsCodeNotFoundOrCodeUnauthorized(err) {
err = nil
}
return err
} | csn |
python fallback on not found values | def apply_to_field_if_exists(effect, field_name, fn, default):
"""
Apply function to specified field of effect if it is not None,
otherwise return default.
"""
value = getattr(effect, field_name, None)
if value is None:
return default
else:
return fn(value) | cosqa |
public function setCoreSymlinkMergeFields($value)
{
$this->setFieldName('symlink_merge_fields');
$this->loadObject(true); |
$this->setFieldValue($value);
return $this;
} | csn_ccr |
// SetReadTimeout sets the maximum time that can pass between reads.
// If no data is received in the set duration the connection will be closed
// and Read returns an error. | func (c *BaseConn) SetReadTimeout(timeout time.Duration) {
c.readTimeout = timeout
// apply new timeout immediately
_ = c.resetTimeout()
} | csn |
function(script) {
script[ STR_ONREADYSTATECHANGE ]
= script[ STR_ONLOAD ]
= script[STR_ONERROR]
| = null;
head().removeChild( script );
} | csn_ccr |
def transform_predict(self, X, y):
"""
Apply transforms to the data, and predict with the final estimator.
Unlike predict, this also returns the transformed target
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
y : array-like
target
Returns
-------
| yt : array-like
Transformed target
yp : array-like
Predicted transformed target
"""
Xt, yt, _ = self._transform(X, y)
yp = self._final_estimator.predict(Xt)
return yt, yp | csn_ccr |
// Send mockcore sending seek info to the deliver server | func (c *MockConnection) Send(sinfo *ab.SeekInfo) error {
if c.Closed() {
return errors.New("mock connection is closed")
}
switch seek := sinfo.Start.Type.(type) {
case *ab.SeekPosition_Specified:
// Deliver all blocks from the given block number
fromBlock := seek.Specified.Number
c.Ledger().SendFrom(fromBlock)
case *ab.SeekPosition_Oldest:
// Deliver all blocks from the beginning
c.Ledger().SendFrom(0)
}
return nil
} | csn |
def send(self, value):
"""
Send text to stdin. Can only be used on non blocking commands
Args:
value (str): the text to write on stdin
Raises:
TypeError: If command is blocking
Returns:
ShellCommand: return this ShellCommand instance for chaining
| """
if not self.block and self._stdin is not None:
self.writer.write("{}\n".format(value))
return self
else:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE) | csn_ccr |
public function isAllowedHost($fullHost)
{
$host = \MUtil_String::stripToHost($fullHost);
$request = $this->request;
if ($request instanceof \Zend_Controller_Request_Http) {
if ($host == \MUtil_String::stripToHost($request->getServer('HTTP_HOST'))) {
return true;
}
}
if (isset($this->project)) {
foreach ($this->project->getAllowedHosts() as $allowedHost) {
if ($host == \MUtil_String::stripToHost($allowedHost)) {
return true;
| }
}
}
$loader = $this->getLoader();
foreach ($loader->getUserLoader()->getOrganizationUrls() as $url => $orgId) {
if ($host == \MUtil_String::stripToHost($url)) {
return true;
}
}
return false;
} | csn_ccr |
Add Scheduling Block to the database.
Args:
config_dict (dict): SBI configuration | def add_sched_block_instance(self, config_dict):
"""Add Scheduling Block to the database.
Args:
config_dict (dict): SBI configuration
"""
# Get schema for validation
schema = self._get_schema()
LOG.debug('Adding SBI with config: %s', config_dict)
# Validates the schema
validate(config_dict, schema)
# Add status field and value to the data
updated_block = self._add_status(config_dict)
# Splitting into different names and fields before
# adding to the database
scheduling_block_data, processing_block_data = \
self._split_sched_block_instance(updated_block)
# Adding Scheduling block instance with id
name = "scheduling_block:" + updated_block["id"]
self._db.set_specified_values(name, scheduling_block_data)
# Add a event to the scheduling block event list to notify
# of a new scheduling block being added to the db.
self._db.push_event(self.scheduling_event_name,
updated_block["status"],
updated_block["id"])
# Adding Processing block with id
for value in processing_block_data:
name = ("scheduling_block:" + updated_block["id"] +
":processing_block:" + value['id'])
self._db.set_specified_values(name, value)
# Add a event to the processing block event list to notify
# of a new processing block being added to the db.
self._db.push_event(self.processing_event_name,
value["status"],
value["id"]) | csn |
public function view($action, $view = null)
{
if (is_array($action)) {
foreach ($action as $realAction => $realView) {
| $this->action($realAction)->view($realView);
}
return;
}
$this->action($action)->view($view);
} | csn_ccr |
Get the config dependency.
@return \Asgard\Config\ConfigInterface | public function getConfig() {
if(!$this->config) {
$this->config = $config = new \Asgard\Config\Config($this->getCache());
if(file_exists($this->params['root'].'/config'))
$config->loadDir($this->params['root'].'/config', $this->getEnv());
}
return $this->config;
} | csn |
Toggle the drone's emergency state. | def reset(self):
"""Toggle the drone's emergency state."""
self.at(ardrone.at.ref, False, True)
time.sleep(0.1)
self.at(ardrone.at.ref, False, False) | csn |
Read JSON config file and return array
@param string $file
@return array $config | public static function getConfigFile($filename)
{
$filename = addslashes($filename);
if (is_file($filename)) {
$data = str_replace("\\", "\\\\", file_get_contents($filename));
$json = json_decode($data, true);
if (empty($json)) {
throw new \Exception("Config file has a json parse error, $filename");
}
} else {
throw new \Exception("Config file not found, $filename");
}
return $json;
} | csn |
The base implementation of `_.conforms` which doesn't clone `source`.
@private
@param {Object} source The object of property predicates to conform to.
@returns {Function} Returns the new spec function. | function baseConforms(source) {
var props = keys(source);
return function(object) {
return baseConformsTo(object, source, props);
};
} | csn |
Create a User. | def create_user(self, data):
"""Create a User."""
# http://teampasswordmanager.com/docs/api-users/#create_user
log.info('Create user with %s' % data)
NewID = self.post('users.json', data).get('id')
log.info('User has been created with ID %s' % NewID)
return NewID | csn |
Construct the matrix that rotates vector a about
vector vec by an angle of theta_deg degrees
Taken from
http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Input:
theta_deg (float) Angle through which vectors should be
rotated in degrees
Returns:
A matrix
To rotate a vector, premultiply by this matrix.
To rotate the coord sys underneath the vector, post multiply | def rotateAboutVectorMatrix(vec, theta_deg):
"""Construct the matrix that rotates vector a about
vector vec by an angle of theta_deg degrees
Taken from
http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Input:
theta_deg (float) Angle through which vectors should be
rotated in degrees
Returns:
A matrix
To rotate a vector, premultiply by this matrix.
To rotate the coord sys underneath the vector, post multiply
"""
ct = np.cos(np.radians(theta_deg))
st = np.sin(np.radians(theta_deg))
# Ensure vector has normal length
vec /= np.linalg.norm(vec)
assert( np.all( np.isfinite(vec)))
# compute the three terms
term1 = ct * np.eye(3)
ucross = np.zeros( (3,3))
ucross[0] = [0, -vec[2], vec[1]]
ucross[1] = [vec[2], 0, -vec[0]]
ucross[2] = [-vec[1], vec[0], 0]
term2 = st*ucross
ufunny = np.zeros( (3,3))
for i in range(0,3):
for j in range(i,3):
ufunny[i,j] = vec[i]*vec[j]
ufunny[j,i] = ufunny[i,j]
term3 = (1-ct) * ufunny
return term1 + term2 + term3 | csn |
Helper to handle the return type. | def _handle_type(self, other):
"""Helper to handle the return type."""
if isinstance(other, Int):
return Int
elif isinstance(other, Float):
return Float
else:
raise TypeError(
f"Unsuported operation between `{type(self)}` and `{type(other)}`."
) | csn |
func (l *StubLogger) Panicf(format string, args ...interface{}) {
| panic(fmt.Sprintf(format, args...))
} | csn_ccr |
Creates a new CachedConditionGenerator instance for the given ConditionGenerator.
Note: When no cache driver was configured the original ConditionGenerator
is returned instead.
@param int|\DateInterval|null $ttl Optional. The TTL value of this item. If no value is sent and
the driver supports TTL then the library may set a default value
for it or let the driver take care of that. | public function createCachedConditionGenerator(ConditionGenerator $conditionGenerator, $ttl = 0): ConditionGenerator
{
if (null === $this->cacheDriver) {
return $conditionGenerator;
}
return new CachedConditionGenerator($conditionGenerator, $this->cacheDriver, $ttl);
} | csn |
From instance to pretty json string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> print(human.to_pretty_json())
{
"favorites": [
{
"name": "Apple",
"names_by_lang": {
"de": "Apfel",
"en": "Apple"
}
},
{
"name": "Orange"
}
],
"id": 1,
"name": "Tom"
} | def to_pretty_json(self, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to pretty json string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> print(human.to_pretty_json())
{
"favorites": [
{
"name": "Apple",
"names_by_lang": {
"de": "Apfel",
"en": "Apple"
}
},
{
"name": "Orange"
}
],
"id": 1,
"name": "Tom"
}
"""
return self.to_json(4, ignore_none, ignore_empty) | csn |
Generate hidden fields not related to inputs
@return string | private function buildHiddenFields()
{
$this->debug->groupCollapsed(__METHOD__);
$cfg = $this->form->cfg;
$printOpts = &$cfg['output'];
$hiddenFields = '';
if ($printOpts['inputKey']) { // && $cfg['persist_method'] != 'none'
$hiddenFields .= '<input type="hidden" name="_key_" value="'.\htmlspecialchars($this->keyValue).'" />';
}
if (\strtolower($cfg['attribs']['method']) == 'get') {
$this->debug->warn('get method');
$urlParts = \parse_url(\html_entity_decode($cfg['attribs']['action']));
// $attribs['action'] = $urlParts['path'];
if (!empty($urlParts['query'])) {
\parse_str($urlParts['query'], $params);
$fieldNames = array();
foreach ($this->form->currentFields as $field) {
$fieldNames[] = $field->attribs['name'];
}
foreach ($params as $k => $v) {
if (\in_array($k, $fieldNames)) {
continue;
}
$hiddenFields .= '<input type="hidden" name="'.\htmlspecialchars($k).'" value="'.\htmlspecialchars($v).'" />'."\n";
}
}
}
$this->debug->log('hiddenFields', $hiddenFields);
$this->debug->groupEnd();
return $hiddenFields;
} | csn |
def rename(self, *args, **kwargs):
"""
Alter axes labels.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.
See the :ref:`user guide <basics.rename>` for more.
Parameters
----------
mapper : dict-like or function
Dict-like or functions transformations to apply to
that axis' values. Use either ``mapper`` and ``axis`` to
specify the axis to target with ``mapper``, or ``index`` and
``columns``.
index : dict-like or function
Alternative to specifying axis (``mapper, axis=0``
is equivalent to ``index=mapper``).
columns : dict-like or function
Alternative to specifying axis (``mapper, axis=1``
is equivalent to ``columns=mapper``).
axis : int or str
Axis to target with ``mapper``. Can be either the axis name
('index', 'columns') or number (0, 1). The default is 'index'.
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Whether to return a new DataFrame. If True then value of copy is
ignored.
level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified
level.
errors : {'ignore', 'raise'}, default 'ignore'
If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
or `columns` contains labels that are not present in the Index
being transformed.
If 'ignore', existing keys will be renamed and extra keys will be
ignored.
Returns
-------
DataFrame
DataFrame with the renamed axis labels.
Raises
------
KeyError
If any of the labels is not found in the selected axis and
"errors='raise'".
See Also
--------
DataFrame.rename_axis : Set the name of the axis.
Examples
| --------
``DataFrame.rename`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
We *highly* recommend using keyword arguments to clarify your
intent.
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(index=str, columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6
>>> df.rename(index=str, columns={"A": "a", "C": "c"})
a B
0 1 4
1 2 5
2 3 6
>>> df.rename(index=str, columns={"A": "a", "C": "c"}, errors="raise")
Traceback (most recent call last):
KeyError: ['C'] not found in axis
Using axis-style parameters
>>> df.rename(str.lower, axis='columns')
a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2, 2: 4}, axis='index')
A B
0 1 4
2 2 5
4 3 6
"""
axes = validate_axis_style_args(self, args, kwargs, 'mapper', 'rename')
kwargs.update(axes)
# Pop these, since the values are in `kwargs` under different names
kwargs.pop('axis', None)
kwargs.pop('mapper', None)
return super().rename(**kwargs) | csn_ccr |
Gets the value of the resourceRequestCriterion property.
<p>
This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a <CODE>set</CODE> method for the resourceRequestCriterion property.
<p>
For example, to add a new item, do as follows:
<pre>
getResourceRequestCriterion().add(newItem);
</pre>
<p>
Objects of the following type(s) are allowed in the list
{@link ResourceRequestType.ResourceRequestCriterion } | public List<ResourceRequestType.ResourceRequestCriterion> getResourceRequestCriterion()
{
if (resourceRequestCriterion == null)
{
resourceRequestCriterion = new ArrayList<ResourceRequestType.ResourceRequestCriterion>();
}
return this.resourceRequestCriterion;
} | csn |
Retrieves a child component by its index.
@param index the index of the child component to be retrieved.
@return the child component at the given index. | WComponent getChildAt(final int index) {
ComponentModel model = getComponentModel();
return model.getChildren().get(index);
} | csn |
def thing_type_absent(name, thingTypeName,
region=None, key=None, keyid=None, profile=None):
'''
Ensure thing type with passed properties is absent.
.. versionadded:: 2016.11.0
name
The name of the state definition.
thingTypeName
Name of the thing type.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': thingTypeName,
'result': True,
'comment': '',
'changes': {}
}
_describe = __salt__['boto_iot.describe_thing_type'](
thingTypeName=thingTypeName,
region=region, key=key, keyid=keyid, profile=profile
)
if 'error' in _describe:
ret['result'] = False
ret['comment'] = 'Failed to delete thing type: {0}.'.format(_describe['error']['message'])
return ret
if _describe and not _describe['thing_type']:
ret['comment'] = 'Thing Type {0} does not exist.'.format(thingTypeName)
return ret
_existing_thing_type = _describe['thing_type']
_thing_type_metadata = _existing_thing_type.get('thingTypeMetadata')
_deprecated = _thing_type_metadata.get('deprecated', False)
if __opts__['test']:
if _deprecated:
_change_desc = 'removed'
else:
_change_desc = 'deprecated and removed'
ret['comment'] = 'Thing Type {0} is set to be {1}.'.format(thingTypeName, _change_desc)
ret['result'] = None
return ret
# initialize a delete_wait_timer to be 5 minutes
# AWS does not allow delete thing type until 5 minutes
# after a thing type is marked deprecated.
_delete_wait_timer = 300
if _deprecated is False:
_deprecate = __salt__['boto_iot.deprecate_thing_type'](
thingTypeName=thingTypeName,
undoDeprecate=False,
region=region, key=key, keyid=keyid, profile=profile
)
if 'error' in _deprecate:
ret['result'] = False
ret['comment'] = 'Failed to deprecate thing type: {0}.'.format(_deprecate['error']['message'])
return ret
else:
# grab the deprecation date string from _thing_type_metadata
_deprecation_date_str = _thing_type_metadata.get('deprecationDate')
if _deprecation_date_str:
# see if we can wait less than 5 minutes
_tz_index = _deprecation_date_str.find('+')
| if _tz_index != -1:
_deprecation_date_str = _deprecation_date_str[:_tz_index]
_deprecation_date = datetime.datetime.strptime(
_deprecation_date_str,
"%Y-%m-%d %H:%M:%S.%f"
)
_elapsed_time_delta = datetime.datetime.utcnow() - _deprecation_date
if _elapsed_time_delta.seconds >= 300:
_delete_wait_timer = 0
else:
_delete_wait_timer = 300 - _elapsed_time_delta.seconds
# wait required 5 minutes since deprecation time
if _delete_wait_timer:
log.warning(
'wait for %s seconds per AWS (5 minutes after deprecation time) '
'before we can delete iot thing type', _delete_wait_timer
)
time.sleep(_delete_wait_timer)
# delete thing type
r = __salt__['boto_iot.delete_thing_type'](
thingTypeName=thingTypeName,
region=region, key=key, keyid=keyid, profile=profile
)
if not r['deleted']:
ret['result'] = False
ret['comment'] = 'Failed to delete thing type: {0}.'.format(r['error']['message'])
return ret
ret['changes']['old'] = _describe
ret['changes']['new'] = {'thing_type': None}
ret['comment'] = 'Thing Type {0} deleted.'.format(thingTypeName)
return ret | csn_ccr |
def parse_signature(cls, signature):
"""Parse signature declartion string
Uses :py:attr:`signature_pattern` to parse out pieces of constraint
signatures. Pattern should provide the following named groups:
prefix
Object prefix, such as a namespace
member
Object member name
arguments
Declaration arguments, if this is a callable constraint
:param signature: construct signature
:type signature: string
"""
assert cls.signature_pattern is not None
pattern = re.compile(cls.signature_pattern, re.VERBOSE)
match = pattern.match(signature)
if match:
| groups = match.groupdict()
arguments = None
if 'arguments' in groups and groups['arguments'] is not None:
arguments = re.split(r'\,\s+', groups['arguments'])
return DotNetSignature(
prefix=groups.get('prefix', None),
member=groups.get('member', None),
arguments=arguments
)
raise ValueError('Could not parse signature: {0}'.format(signature)) | csn_ccr |
public static Optional<Element> getChildElement(final Element elem, final DitaClass cls) {
final NodeList children = elem.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
final Node child = children.item(i);
| if (cls.matches(child)) {
return Optional.of((Element) child);
}
}
return Optional.empty();
} | csn_ccr |
Get a single or a collection of remote objects from the object store.
This method is identical to `ray.get` except it adds support for tuples,
ndarrays and dictionaries.
Args:
object_ids: Object ID of the object to get, a list, tuple, ndarray of
object IDs to get or a dict of {key: object ID}.
Returns:
A Python object, a list of Python objects or a dict of {key: object}. | def get(object_ids):
"""Get a single or a collection of remote objects from the object store.
This method is identical to `ray.get` except it adds support for tuples,
ndarrays and dictionaries.
Args:
object_ids: Object ID of the object to get, a list, tuple, ndarray of
object IDs to get or a dict of {key: object ID}.
Returns:
A Python object, a list of Python objects or a dict of {key: object}.
"""
if isinstance(object_ids, (tuple, np.ndarray)):
return ray.get(list(object_ids))
elif isinstance(object_ids, dict):
keys_to_get = [
k for k, v in object_ids.items() if isinstance(v, ray.ObjectID)
]
ids_to_get = [
v for k, v in object_ids.items() if isinstance(v, ray.ObjectID)
]
values = ray.get(ids_to_get)
result = object_ids.copy()
for key, value in zip(keys_to_get, values):
result[key] = value
return result
else:
return ray.get(object_ids) | csn |
Config for FACE_DETECTION.
Generated from protobuf field <code>.google.cloud.videointelligence.v1beta2.FaceDetectionConfig face_detection_config = 5;</code>
@param \Google\Cloud\VideoIntelligence\V1beta2\FaceDetectionConfig $var
@return $this | public function setFaceDetectionConfig($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\VideoIntelligence\V1beta2\FaceDetectionConfig::class);
$this->face_detection_config = $var;
return $this;
} | csn |
public function clear()/*# : bool */
{
$ends = [ $this->front, $this->back ];
foreach ($ends as $end) {
if (!$end->clear()) {
return $this->falseAndSetError(
| $end->getError(),
$end->getErrorCode()
);
}
}
return $this->trueAndFlushError();
} | csn_ccr |
public function handle( \AltoRouter $router, \PowerOn\Network\Request $request ) {
$match = $router->match($request->path);
if ( $match ) {
$target = explode('#', $match['target']);
$this->controller = $target[0];
$this->action = key_exists(1, $target) ? $target[1] : 'index';
} else {
$url = $request->urlToArray();
$controller = array_shift($url);
$action = array_shift($url);
$this->controller = $controller ? $controller : 'index';
$this->action = $action ? | $action : 'index';
}
$handler = $this->loadController();
if ( !$handler || !method_exists($handler, $this->action) ) {
throw new NotFoundException('El sitio al que intenta ingresar no existe.');
}
return $handler;
} | csn_ccr |
parse an color
@param mixed $color | public static function create( $color )
{
// our return
$rgb = array();
if ( is_array( $color ) )
{
$color = array_values( $color );
$rgb[0] = $color[0];
$rgb[1] = $color[1];
$rgb[2] = $color[2];
}
// parse hex color
elseif ( is_string( $color ) && substr( $color, 0, 1 ) == '#' )
{
$color = substr( $color, 1 );
if( strlen( $color ) == 3 )
{
$rgb[0] = hexdec( substr( $color, 0, 1 ) . substr( $color, 0, 1 ) );
$rgb[1] = hexdec( substr( $color, 1, 1 ) . substr( $color, 1, 1 ) );
$rgb[2] = hexdec( substr( $color, 2, 1 ) . substr( $color, 2, 1 ) );
}
elseif( strlen( $color ) == 6 )
{
$rgb[0] = hexdec( substr( $color, 0, 2 ) );
$rgb[1] = hexdec( substr( $color, 2, 2 ) );
$rgb[2] = hexdec( substr( $color, 4, 2 ) );
}
}
// could not be parsed
else
{
return false;
}
return new static( $rgb );
} | csn |
def checkReference(self, reference):
"""
Check the reference for security. Tries to avoid any characters
necessary for doing a script injection.
"""
| pattern = re.compile(r'[\s,;"\'&\\]')
if pattern.findall(reference.strip()):
return False
return True | csn_ccr |
def parse(datetime_str, timezone=None, isofirst=True, dayfirst=True, yearfirst=True):
"""
Parses a datetime string and returns a `Delorean` object.
:param datetime_str: The string to be interpreted into a `Delorean` object.
:param timezone: Pass this parameter and the returned Delorean object will be normalized to this timezone. Any
offsets passed as part of datetime_str will be ignored.
:param isofirst: try to parse string as date in ISO format before everything else.
:param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the day
(True) or month (False). If yearfirst is set to True, this distinguishes between YDM and YMD.
:param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the
year. If True, the first number is taken to be the year, otherwise the last number is taken to be the year.
.. testsetup::
from delorean import Delorean
from delorean import parse
.. doctest::
>>> parse('2015-01-01 00:01:02')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC')
If a fixed offset is provided in the datetime_str, it will be parsed and the returned `Delorean` object will store a
`pytz.FixedOffest` as it's timezone.
.. doctest::
>>> parse('2015-01-01 00:01:02 -0800')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone=pytz.FixedOffset(-480))
If the timezone argument is supplied, the returned Delorean object will | be in the timezone supplied. Any offsets in
the datetime_str will be ignored.
.. doctest::
>>> parse('2015-01-01 00:01:02 -0500', timezone='US/Pacific')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='US/Pacific')
If an unambiguous timezone is detected in the datetime string, a Delorean object with that datetime and
timezone will be returned.
.. doctest::
>>> parse('2015-01-01 00:01:02 PST')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='America/Los_Angeles')
However if the provided timezone is ambiguous, parse will ignore the timezone and return a `Delorean` object in UTC
time.
>>> parse('2015-01-01 00:01:02 EST')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC')
"""
# parse string to datetime object
dt = None
if isofirst:
try:
dt = isocapture(datetime_str)
except Exception:
pass
if dt is None:
dt = capture(datetime_str, dayfirst=dayfirst, yearfirst=yearfirst)
if timezone:
dt = dt.replace(tzinfo=None)
do = Delorean(datetime=dt, timezone=timezone)
elif dt.tzinfo is None:
# assuming datetime object passed in is UTC
do = Delorean(datetime=dt, timezone='UTC')
elif isinstance(dt.tzinfo, tzoffset):
utcoffset = dt.tzinfo.utcoffset(None)
total_seconds = (
(utcoffset.microseconds + (utcoffset.seconds + utcoffset.days * 24 * 3600) * 10**6) / 10**6)
tz = pytz.FixedOffset(total_seconds / 60)
dt = dt.replace(tzinfo=None)
do = Delorean(dt, timezone=tz)
elif isinstance(dt.tzinfo, tzlocal):
tz = get_localzone()
dt = dt.replace(tzinfo=None)
do = Delorean(dt, timezone=tz)
else:
dt = pytz.utc.normalize(dt)
# making dt naive so we can pass it to Delorean
dt = dt.replace(tzinfo=None)
# if parse string has tzinfo we return a normalized UTC
# delorean object that represents the time.
do = Delorean(datetime=dt, timezone='UTC')
return do | csn_ccr |
Try to set us as active | function (element, scroller) {
if (!element || !_Global.document.body || !_Global.document.body.contains(element)) {
return false;
}
if (!_ElementUtilities._setActive(element, scroller)) {
return false;
}
return (element === _Global.document.activeElement);
} | csn |
Set active only to true or false on a copy of this query | def show_active_only(self, state):
"""
Set active only to true or false on a copy of this query
"""
query = self._copy()
query.active_only = state
return query | csn |
protected RefProperty registerErrorModel(Swagger swagger) {
String ref = Error.class.getSimpleName();
if (swagger.getDefinitions() != null && swagger.getDefinitions().containsKey(ref)) {
// model already registered
return new RefProperty(ref);
}
ModelImpl model = new ModelImpl();
swagger.addDefinition(ref, model);
model.setDescription("an error message");
model.addProperty("statusCode", new IntegerProperty().readOnly().description("http status code"));
model.addProperty("statusMessage", new StringProperty().readOnly().description("description of the http status code"));
model.addProperty("requestMethod", new StringProperty().readOnly().description("http request method"));
| model.addProperty("requestUri", new StringProperty().readOnly().description("http request path"));
model.addProperty("message", new StringProperty().readOnly().description("application message"));
if (settings.isDev()) {
// in DEV mode the stacktrace is returned in the error message
model.addProperty("stacktrace", new StringProperty().readOnly().description("application stacktrace"));
}
return new RefProperty(ref);
} | csn_ccr |
Yields each object indexed by the index with
name ``name`` with ``values`` matching on indexed
field values. | def each_indexed_object(collection, index_name, **where):
"""Yields each object indexed by the index with
name ``name`` with ``values`` matching on indexed
field values."""
index = _db[collection].indexes[index_name]
for id in index.value_map.get(indexed_value(index, where), []):
yield get_object(collection, id) | csn |
def symlink_create(self, symlink, target, type_p):
"""Creates a symbolic link in the guest.
in symlink of type str
Path to the symbolic link that should be created. Guest path
style.
in target of type str
The path to the symbolic link target. If not an absolute, this will
be relative to the @a symlink location at access time. Guest path
style.
in type_p of type :class:`SymlinkType`
The symbolic link type (mainly for Windows). See :py:class:`SymlinkType`
for more information.
raises :class:`OleErrorNotimpl`
The method is not implemented yet.
|
"""
if not isinstance(symlink, basestring):
raise TypeError("symlink can only be an instance of type basestring")
if not isinstance(target, basestring):
raise TypeError("target can only be an instance of type basestring")
if not isinstance(type_p, SymlinkType):
raise TypeError("type_p can only be an instance of type SymlinkType")
self._call("symlinkCreate",
in_p=[symlink, target, type_p]) | csn_ccr |
function animate(Promise, TweenModule) {
var animateTo = _animateFunc.bind(null, TweenModule.to);
var util = animateTo;
util.to = animateTo;
util.from = _animateFunc.bind(null, TweenModule.from);
util.set = function animateSet(element, params) {
params = Object.assign({}, params);
return new Promise(function(resolve, reject) {
params.onComplete = resolve;
TweenModule.set(element, params);
});
};
util.fromTo = function animateFromTo(element, duration, from, to) {
to = Object.assign({}, | to);
var tween;
return new Promise(function(resolve, reject, onCancel) {
to.onComplete = resolve;
tween = TweenModule.fromTo(element, duration, from, to);
onCancel &&
onCancel(function() {
tween.kill();
});
});
};
util.killTweensOf = TweenModule.killTweensOf.bind(TweenModule);
util.all = Promise.all;
return util;
} | csn_ccr |
update the attributes of a vod media
@param $mediaId string, mediaId of the media
@param $title string, new title of the media
@param $description string, new description of the media
@param array $options Supported options:
{
config: the optional bce configuration, which will overwrite the
default vod client configuration that was passed in constructor.
}
@return mixed the result of updating
@throws BceClientException | public function updateMedia($mediaId, $title, $description, $options = array())
{
list($config) = $this->parseOptions($options, 'config');
if (empty($mediaId)) {
throw new BceClientException("The parameter mediaId should NOT be null or empty string");
}
if (empty($title)) {
throw new BceClientException("The parameter title should NOT be null or empty string");
}
$body = array(
'title' => $title,
'description' => $description,
);
$params = array(
'attributes' => null,
);
return $this->sendRequest(
HttpMethod::PUT,
array(
'config' => $config,
'body' => json_encode($body),
'params' => $params,
),
"/media/$mediaId"
);
} | csn |
Get the bounding box of all paths in the map combined. | function (paths) {
var maxX = Number.MIN_VALUE,
minX = Number.MAX_VALUE,
maxY = Number.MIN_VALUE,
minY = Number.MAX_VALUE;
// Find the bounding box
each(paths || this.options.data, function (point) {
var path = point.path,
i = path.length,
even = false, // while loop reads from the end
pointMaxX = Number.MIN_VALUE,
pointMinX = Number.MAX_VALUE,
pointMaxY = Number.MIN_VALUE,
pointMinY = Number.MAX_VALUE;
while (i--) {
if (typeof path[i] === 'number' && !isNaN(path[i])) {
if (even) { // even = x
pointMaxX = Math.max(pointMaxX, path[i]);
pointMinX = Math.min(pointMinX, path[i]);
} else { // odd = Y
pointMaxY = Math.max(pointMaxY, path[i]);
pointMinY = Math.min(pointMinY, path[i]);
}
even = !even;
}
}
// Cache point bounding box for use to position data labels
point._maxX = pointMaxX;
point._minX = pointMinX;
point._maxY = pointMaxY;
point._minY = pointMinY;
maxX = Math.max(maxX, pointMaxX);
minX = Math.min(minX, pointMinX);
maxY = Math.max(maxY, pointMaxY);
minY = Math.min(minY, pointMinY);
});
this.minY = minY;
this.maxY = maxY;
this.minX = minX;
this.maxX = maxX;
} | csn |
Creates a floating-point symbol.
:param name: The name of the symbol
:param sort: The sort of the floating point
:param explicit_name: If False, an identifier is appended to the name to ensure uniqueness.
:return: An FP AST. | def FPS(name, sort, explicit_name=None):
"""
Creates a floating-point symbol.
:param name: The name of the symbol
:param sort: The sort of the floating point
:param explicit_name: If False, an identifier is appended to the name to ensure uniqueness.
:return: An FP AST.
"""
n = _make_name(name, sort.length, False if explicit_name is None else explicit_name, prefix='FP_')
return FP('FPS', (n, sort), variables={n}, symbolic=True, length=sort.length) | csn |
Returns the first mapping for a table name | def _get_mapping_for_table(self, table):
""" Returns the first mapping for a table name """
for mapping in self.mappings.values():
if mapping["table"] == table:
return mapping | csn |
public String transBinaryXml(String path) throws IOException {
byte[] data = getFileData(path);
if (data == null) {
return null;
}
parseResourceTable();
XmlTranslator xmlTranslator | = new XmlTranslator();
transBinaryXml(data, xmlTranslator);
return xmlTranslator.getXml();
} | csn_ccr |
Processes a regex match for a module to create a CodeElement. | def _process_module(self, name, contents, parent, match, filepath=None):
"""Processes a regex match for a module to create a CodeElement."""
#First, get hold of the name and contents of the module so that we can process the other
#parts of the module.
modifiers = []
#We need to check for the private keyword before any type or contains declarations
if self.RE_PRIV.search(contents):
modifiers.append("private")
#The only other modifier for modules ought to be implicit none
if re.search("implicit\s+none", contents):
modifiers.append("implicit none")
#Next, parse out the dependencies of the module on other modules
dependencies = self._parse_use(contents)
publics, pubstart = self._process_publics(match.string)
#We can now create the CodeElement
result = Module(name, modifiers, dependencies, publics, contents, parent)
if filepath is not None:
result.filepath = filepath.lower()
result.start = match.start()
result.end = match.end()
result.refstring = match.string
result.set_public_start(pubstart)
if self.RE_PRECOMP.search(contents):
result.precompile = True
self.xparser.parse(result)
self.tparser.parse(result)
#It is possible for the module to have members, parse those
self._parse_members(contents, result)
self.iparser.parse(result)
#Now we can update the docstrings for the types. They rely on data
#extracted during parse_members() which is why they have to run
#separately over here.
for t in result.types:
self.tparser.update_docs(result.types[t], result)
return result | csn |
Import network data from CSVs in a folder.
The CSVs must follow the standard form, see pypsa/examples.
Parameters
----------
csv_folder_name : string
Name of folder
encoding : str, default None
Encoding to use for UTF when reading (ex. 'utf-8'). `List of Python
standard encodings
<https://docs.python.org/3/library/codecs.html#standard-encodings>`_
skip_time : bool, default False
Skip reading in time dependent attributes | def import_from_csv_folder(network, csv_folder_name, encoding=None, skip_time=False):
"""
Import network data from CSVs in a folder.
The CSVs must follow the standard form, see pypsa/examples.
Parameters
----------
csv_folder_name : string
Name of folder
encoding : str, default None
Encoding to use for UTF when reading (ex. 'utf-8'). `List of Python
standard encodings
<https://docs.python.org/3/library/codecs.html#standard-encodings>`_
skip_time : bool, default False
Skip reading in time dependent attributes
"""
basename = os.path.basename(csv_folder_name)
with ImporterCSV(csv_folder_name, encoding=encoding) as importer:
_import_from_importer(network, importer, basename=basename, skip_time=skip_time) | csn |
Deletes references to the external google fonts in the Home
Documentation's index.html file | def make_offline():
"""Deletes references to the external google fonts in the Home
Documentation's index.html file
"""
dir_path = Path(os.getcwd()).absolute()
css_path = dir_path / "site" / "assets" / "stylesheets"
material_css = css_path / "material-style.css"
if not material_css.exists():
file_path = Path(__file__).resolve().parent
copyfile(file_path / "material-style.css", material_css)
copyfile(file_path / "material-icons.woff2", css_path / "material-icons.woff2")
indexes = []
for root, _, filenames in os.walk(dir_path / "site"):
for filename in fnmatch.filter(filenames, "index.html"):
indexes.append(os.path.join(root, filename))
for index_file in indexes:
update_index_to_offline(index_file) | csn |
Wraps a GET request with a url check | def _get(self, url, params=None, headers=None):
"""Wraps a GET request with a url check"""
url = self.clean_url(url)
response = requests.get(url, params=params, verify=self.verify,
timeout=self.timeout, headers=headers)
return response | csn |
def _unzip_file(self, src_path, dest_path, filename):
"""unzips file located at src_path into destination_path"""
self.logger.info("unzipping file...")
# construct full path (including file name) for unzipping
unzip_path = os.path.join(dest_path, | filename)
utils.ensure_directory_exists(unzip_path)
# extract data
with zipfile.ZipFile(src_path, "r") as z:
z.extractall(unzip_path)
return True | csn_ccr |
func (f FunctionNameList) Less(i, j int) bool {
if f[i].Str == "" && f[j].Str != "" {
return true
}
if f[i].Str != "" && f[j].Str == "" {
return false
}
if f[i].Str != "" && f[j].Str != "" | {
if f[i].Str > f[j].Str {
return true
} else if f[i].Str < f[j].Str {
return false
}
}
return f[i].Name < f[j].Name
} | csn_ccr |
function createControllerFunction(func) {
var Handlebars = protos.require('handlebars');
var context, newFunc, compile, source,
funcSrc = func.toString();
var code = funcSrc
.trim()
.replace(/^function\s+(.*?)(\s+)?\{(\s+)?/, '')
.replace(/(\s+)?\}$/, '');
// Get source file path
var alias = protos.lib.controller.prototype.getAlias(func.name),
srcFile = this.mvcpath + 'controllers/' + alias + '.js';
try {
source = fs.readFileSync(srcFile, 'utf-8');
} catch(e){
source = fs.readFileSync(srcFile.replace(/\.js$/, '_controller.js'), 'utf-8');
}
// Detect pre & post function code
var si = source.indexOf(funcSrc),
preFuncSrc = source.slice(0, si).trim(),
postFuncSrc = source.slice(si + funcSrc.length).trim();
// Controller code
var template = Handlebars.compile('\n\
with (locals) {\n\n\
function {{{name}}}(app) {\n\
this.filters | = this.filters["{{{name}}}"] || [];\n\
}\n\n\
require("util").inherits({{{name}}}, protos.lib.controller);\n\n\
protos.extend({{{name}}}, protos.lib.controller);\n\n\
{{{name}}}.filter = {{{name}}}.prototype.filter;\n\
{{{name}}}.handler = {{{name}}}.prototype.handler;\n\n\
var __funKeys__ = Object.keys({{{name}}});\n\
\n\
(function() { \n\
{{{preFuncSrc}}}\n\n\
with(this) {\n\n\
{{{code}}}\n\
}\n\n\
{{{postFuncSrc}}}\n\n\
}).call({{{name}}});\n\n\
for (var key in {{{name}}}) {\n\
if (__funKeys__.indexOf(key) === -1) { \n\
{{{name}}}.prototype[key] = {{{name}}}[key];\n\
delete {{{name}}}[key];\n\
}\n\
}\n\
\n\
if (!{{{name}}}.prototype.authRequired) {\n\
{{{name}}}.prototype.authRequired = protos.lib.controller.prototype.authRequired;\n\
} else {\n\
{{{name}}}.prototype.authRequired = true; \n\
}\n\n\
return {{{name}}};\n\n\
}');
var fnCode = template({
name: func.name,
code: code,
preFuncSrc: preFuncSrc,
postFuncSrc: postFuncSrc,
});
// console.exit(fnCode);
/*jshint evil:true */
compile = new Function('locals', fnCode);
newFunc = compile({
app: this,
protos: protos,
module: {},
require: require,
console: console,
__dirname: this.mvcpath + 'controllers',
__filename: srcFile,
process: process
});
return newFunc;
} | csn_ccr |
Returns the unique text-based ID for a todo item. | def uid(self, p_todo):
"""
Returns the unique text-based ID for a todo item.
"""
try:
return self._todo_id_map[p_todo]
except KeyError as ex:
raise InvalidTodoException from ex | csn |
put cookieMap to result
@param result a Map you want to put dumping info to. | @Override
protected void putDumpInfoTo(Map<String, Object> result) {
if(this.cookieMap.size() > 0) {
result.put(DumpConstants.COOKIES, cookieMap);
}
} | csn |
def create_processors_from_settings(self):
"""
Expects the Django setting "EVENT_TRACKING_PROCESSORS" to be defined and
point to a list of backend engine configurations.
Example::
EVENT_TRACKING_PROCESSORS = [
{
'ENGINE': 'some.arbitrary.Processor'
},
{
'ENGINE': 'some.arbitrary.OtherProcessor',
| 'OPTIONS': {
'user': 'foo'
}
},
]
"""
config = getattr(settings, DJANGO_PROCESSOR_SETTING_NAME, [])
processors = self.instantiate_objects(config)
return processors | csn_ccr |
public function getAncestors()
{
$ancestors = new Collection();
$ancestor = $this;
while (($ancestor = $ancestor->parent) && !$ancestors->contains($ancestor)) {
| $ancestors->push($ancestor);
break;
}
return $ancestors;
} | csn_ccr |
def get_version(*args):
"""Extract the version number from a Python module."""
contents | = get_contents(*args)
metadata = dict(re.findall('__([a-z]+)__ = [\'"]([^\'"]+)', contents))
return metadata['version'] | csn_ccr |
Request info of callable remote methods.
Arguments for :meth:`call` except for `name` can be applied to
this function too. | def methods(self, *args, **kwds):
"""
Request info of callable remote methods.
Arguments for :meth:`call` except for `name` can be applied to
this function too.
"""
self.callmanager.methods(self, *args, **kwds) | csn |
Output a string
@param string $str String to output
@param false|int $row The optional row to output to
@param false|int $col The optional column to output to | public static function string( $str, $row = null, $col = null ) {
if( $col !== null || $row !== null ) {
Cursor::rowcol($row, $col);
}
fwrite(self::$stream, $str);
} | csn |
python base64 decode byte array | def decode_arr(data):
"""Extract a numpy array from a base64 buffer"""
data = data.encode('utf-8')
return frombuffer(base64.b64decode(data), float64) | cosqa |
// NewServer constructs a server from the provided config. | func NewServer(ctx context.Context, c Config) (*Server, error) {
return newServer(ctx, c, defaultRotationStrategy(
value(c.RotateKeysAfter, 6*time.Hour),
value(c.IDTokensValidFor, 24*time.Hour),
))
} | csn |
An internal method to find the parent directory record and name given a
Joliet path. If the parent is found, return a tuple containing the
basename of the path and the parent directory record object.
Parameters:
joliet_path - The absolute Joliet path to the entry on the ISO.
Returns:
A tuple containing just the name of the entry and a Directory Record
object representing the parent of the entry. | def _joliet_name_and_parent_from_path(self, joliet_path):
# type: (bytes) -> Tuple[bytes, dr.DirectoryRecord]
'''
An internal method to find the parent directory record and name given a
Joliet path. If the parent is found, return a tuple containing the
basename of the path and the parent directory record object.
Parameters:
joliet_path - The absolute Joliet path to the entry on the ISO.
Returns:
A tuple containing just the name of the entry and a Directory Record
object representing the parent of the entry.
'''
splitpath = utils.split_path(joliet_path)
name = splitpath.pop()
if len(name) > 64:
raise pycdlibexception.PyCdlibInvalidInput('Joliet names can be a maximum of 64 characters')
parent = self._find_joliet_record(b'/' + b'/'.join(splitpath))
return (name.decode('utf-8').encode('utf-16_be'), parent) | csn |
public function sortBy(SortBy $sortBy): self
{
if ($sortBy->isSortedByGeoDistance()) {
if (!$this->coordinate instanceof Coordinate) {
throw InvalidFormatException::querySortedByDistanceWithoutCoordinate();
}
| $sortBy->setCoordinate($this->coordinate);
}
$this->sortBy = $sortBy;
return $this;
} | csn_ccr |
Properties of a StringValue.
@memberof google.protobuf
@interface IStringValue
@property {string|null} [value] StringValue value
Constructs a new StringValue.
@memberof google.protobuf
@classdesc Represents a StringValue.
@implements IStringValue
@constructor
@param {google.protobuf.IStringValue=} [properties] Properties to set | function StringValue(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
} | csn |
Return the first string term in the conjunction, or `None`. | def string(self):
"""
Return the first string term in the conjunction, or `None`.
"""
for term in self._terms:
if isinstance(term, String):
return str(term)
return None | csn |
Generate new random Bitcoin private key, using os.urandom and
double-sha256. Hex format. | def genkeyhex():
'''
Generate new random Bitcoin private key, using os.urandom and
double-sha256. Hex format.
'''
while True:
key = hash256(
hexlify(os.urandom(40) + str(datetime.datetime.now())
.encode("utf-8")))
# 40 bytes used instead of 32, as a buffer for any slight
# lack of entropy in urandom
# Double-sha256 used instead of single hash, for entropy
# reasons as well.
# I know, it's nit-picking, but better safe than sorry.
if int(key,16) > 1 and int(key,16) < N:
break
return key | csn |
// NewStateBackend converts a state.State into a Backend. | func NewStateBackend(st *state.State) (Backend, error) {
m, err := st.Model()
if err != nil {
return nil, err
}
if m.Type() != state.ModelTypeIAAS {
return nil, errors.NotSupportedf("Firewall Rules for non-IAAS models")
}
return &stateShim{
State: st,
Model: m,
}, nil
} | csn |
Logs the names of the entities the loader is attempting
to load. | private function logAutoloadedEntities()
{
$cpts = array_keys($this->getConfiguration());
$message = sprintf("Found %s custom post types : %s", count($cpts), implode(", ", $cpts));
Strata::app()->setConfig("runtime.custom_post_types", $cpts);
} | csn |
def get_as_list(self, tag_name):
"""
Return the value of a tag, making sure that it's a list. Absent
tags are returned as an empty-list; single tags are returned as a
one-element list.
The returned list is a copy, and modifications do not affect the
| original object.
"""
val = self.get(tag_name, [])
if isinstance(val, list):
return val[:]
else:
return [val] | csn_ccr |
Respond with the asset.
@param \Psr\Http\Message\ResponseInterface $response The response to augment
@param string $contents The asset contents.
@param \MiniAsset\AssetTarget $build The build target.
@return \Psr\Http\Message\ResponseInterface | protected function respond($response, $contents, $build)
{
// Deliver built asset.
$body = $response->getBody();
$body->write($contents);
$body->rewind();
return $response->withHeader('Content-Type', $this->mapType($build));
} | csn |
function _supportColorProps(props) {
var p;
for (p = 0; p < props.length; p += 1) { |
$.fx.step[props[p]] = _animateColor;
}
} | csn_ccr |
call multiple python files in a script | def load_files(files):
"""Load and execute a python file."""
for py_file in files:
LOG.debug("exec %s", py_file)
execfile(py_file, globals(), locals()) | cosqa |
assigning the actual script settings depending on the iterator type
this might be overwritten by classes that inherit form ScriptIterator
Args:
sub_scripts: dictionary with the subscripts
script_order: execution order of subscripts
script_execution_freq: execution frequency of subscripts
Returns:
the default setting for the iterator | def get_default_settings(sub_scripts, script_order, script_execution_freq, iterator_type):
"""
assigning the actual script settings depending on the iterator type
this might be overwritten by classes that inherit form ScriptIterator
Args:
sub_scripts: dictionary with the subscripts
script_order: execution order of subscripts
script_execution_freq: execution frequency of subscripts
Returns:
the default setting for the iterator
"""
def populate_sweep_param(scripts, parameter_list, trace=''):
'''
Args:
scripts: a dict of {'class name': <class object>} pairs
Returns: A list of all parameters of the input scripts
'''
def get_parameter_from_dict(trace, dic, parameter_list, valid_values=None):
"""
appends keys in the dict to a list in the form trace.key.subkey.subsubkey...
Args:
trace: initial prefix (path through scripts and parameters to current location)
dic: dictionary
parameter_list: list to which append the parameters
valid_values: valid values of dictionary values if None dic should be a dictionary
Returns:
"""
if valid_values is None and isinstance(dic, Parameter):
valid_values = dic.valid_values
for key, value in dic.items():
if isinstance(value, dict): # for nested parameters ex {point: {'x': int, 'y': int}}
parameter_list = get_parameter_from_dict(trace + '.' + key, value, parameter_list,
dic.valid_values[key])
elif (valid_values[key] in (float, int)) or \
(isinstance(valid_values[key], list) and valid_values[key][0] in (float, int)):
parameter_list.append(trace + '.' + key)
else: # once down to the form {key: value}
# in all other cases ignore parameter
print(('ignoring sweep parameter', key))
return parameter_list
for script_name in list(scripts.keys()):
from pylabcontrol.core import ScriptIterator
script_trace = trace
if script_trace == '':
script_trace = script_name
else:
script_trace = script_trace + '->' + script_name
if issubclass(scripts[script_name], ScriptIterator): # gets subscripts of ScriptIterator objects
populate_sweep_param(vars(scripts[script_name])['_SCRIPTS'], parameter_list=parameter_list,
trace=script_trace)
else:
# use inspect instead of vars to get _DEFAULT_SETTINGS also for classes that inherit _DEFAULT_SETTINGS from a superclass
for setting in \
[elem[1] for elem in inspect.getmembers(scripts[script_name]) if elem[0] == '_DEFAULT_SETTINGS'][0]:
parameter_list = get_parameter_from_dict(script_trace, setting, parameter_list)
return parameter_list
if iterator_type == 'loop':
script_default_settings = [
Parameter('script_order', script_order),
Parameter('script_execution_freq', script_execution_freq),
Parameter('num_loops', 0, int, 'times the subscripts will be executed'),
Parameter('run_all_first', True, bool, 'Run all scripts with nonzero frequency in first pass')
]
elif iterator_type == 'sweep':
sweep_params = populate_sweep_param(sub_scripts, [])
script_default_settings = [
Parameter('script_order', script_order),
Parameter('script_execution_freq', script_execution_freq),
Parameter('sweep_param', sweep_params[0], sweep_params, 'variable over which to sweep'),
Parameter('sweep_range',
[Parameter('min_value', 0, float, 'min parameter value'),
Parameter('max_value', 0, float, 'max parameter value'),
Parameter('N/value_step', 0, float,
'either number of steps or parameter value step, depending on mode')]),
Parameter('stepping_mode', 'N', ['N', 'value_step'],
'Switch between number of steps and step amount'),
Parameter('run_all_first', True, bool, 'Run all scripts with nonzero frequency in first pass')
]
else:
print(('unknown iterator type ' + iterator_type))
raise TypeError('unknown iterator type ' + iterator_type)
return script_default_settings | csn |
public static List<String> getAIALocations(X509Certificate userCertificate)
throws CertificateVerificationException {
List<String> locations;
//List the AIA locations from the certificate. Those are the URL's of CA s.
try {
locations = OCSPVerifier.getAIALocations(userCertificate);
| } catch (CertificateVerificationException e) {
throw new CertificateVerificationException("Failed to find AIA locations in the cetificate", e);
}
return locations;
} | csn_ccr |
Returns a formatted link with all of the attributes
@param array $link This should be an array containing all of the set link values
@param string $activeClass If the link is active should have the active class string set else should be empty
@param boolean If the element has any child elements set to true else set to false
@return string The HTML link element will be returned | public static function formatLink($link, $activeClass, $hasChild = false, $breadcrumbLink = false) {
return "<a".self::href($link).self::title($link).self::htmlClass(($breadcrumbLink ? '' : self::$linkDefaults['a_default'].' ').(isset($link['class']) ? $link['class'] : ''), $activeClass).self::target($link).self::rel($link).self::htmlID($link).($hasChild ? self::$dropdownLinkExtras : '').">".($breadcrumbLink ? '' : self::fontIcon($link)).self::label($link).($hasChild ? self::$caretElement : '')."</a>";
} | csn |
def update_ebounds(hdu_in, hdu=None):
""" 'Update' the EBOUNDS HDU
This checks hdu exists and creates it from hdu_in if it does not.
If hdu does exist, this raises an exception if it doesn not match hdu_in
"""
if hdu is None:
hdu = fits.BinTableHDU(
data=hdu_in.data, header=hdu_in.header, name=hdu_in.name)
else:
| for col in ['CHANNEL', 'E_MIN', 'E_MAX']:
if (hdu.data[col] != hdu_in.data[col]).any():
raise ValueError("Energy bounds do not match : %s %s" %
(hdu.data[col], hdu_in.data[col]))
return hdu | csn_ccr |
Given a field key or name, return it's field key. | def get_field_key(self, key, using_name=True):
"""Given a field key or name, return it's field key.
"""
try:
if using_name:
return self.f_name[key].key
else:
return self.f[key].key
except KeyError:
raise ValueError("'%s' are not found!" % key) | csn |
private function grabAttribsBeforeToken(Tokens $tokens, $index, array $tokenAttribsMap, array $attribs)
{
while (true) {
$token = $tokens[--$index];
if (!$token->isArray()) {
if ($token->equalsAny(['{', '}', '(', ')'])) {
break;
}
continue;
}
// if token is attribute
if (array_key_exists($token->getId(), $tokenAttribsMap)) {
// set token attribute if token map defines attribute name for token
if ($tokenAttribsMap[$token->getId()]) {
$attribs[$tokenAttribsMap[$token->getId()]] = clone $token; |
}
// clear the token and whitespaces after it
$tokens[$index]->clear();
$tokens[$index + 1]->clear();
continue;
}
if ($token->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) {
continue;
}
break;
}
return $attribs;
} | csn_ccr |
perform elliptic curve addition | def add(self, p, q):
"""
perform elliptic curve addition
"""
if p.iszero():
return q
if q.iszero():
return p
lft = 0
# calculate the slope of the intersection line
if p == q:
if p.y == 0:
return self.zero()
lft = (3 * p.x ** 2 + self.a) / (2 * p.y)
elif p.x == q.x:
return self.zero()
else:
lft = (p.y - q.y) / (p.x - q.x)
# calculate the intersection point
x = lft ** 2 - (p.x + q.x)
y = lft * (p.x - x) - p.y
return self.point(x, y) | csn |
def default(event, data):
"""The default handler prints basic event info."""
messages = defaultdict(lambda: 'Avast:')
messages['start'] = 'Thar she blows!'
messages['tag'] = 'Thar she blows!'
messages['stop'] = 'Away into the depths:'
messages['destroy'] = 'Away into the depths:'
messages['delete'] | = 'Away into the depths:'
status = get_status(event)
message = messages[status] + ' %s/%s'
log.info(message, status, get_id(event))
log.debug('"data": %s', form_json(data)) | csn_ccr |
generate a dotfile in python d tree | def to_dotfile(self):
""" Writes a DOT graphviz file of the domain structure, and returns the filename"""
domain = self.get_domain()
filename = "%s.dot" % (self.__class__.__name__)
nx.write_dot(domain, filename)
return filename | cosqa |
def runtime_error(self, msg, method):
"""
Show the error in the bar
"""
if self.testing:
self._py3_wrapper.report_exception(msg)
raise KeyboardInterrupt
if self.error_hide:
self.hide_errors()
return
# only show first line of error
msg = msg.splitlines()[0]
| errors = [self.module_nice_name, u"{}: {}".format(self.module_nice_name, msg)]
# if we have shown this error then keep in the same state
if self.error_messages != errors:
self.error_messages = errors
self.error_index = 0
self.error_output(self.error_messages[self.error_index], method) | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.