query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Pad `str` up to total length `max` with `chr`.
If `str` is longer than `max`, padRight will return `str` unaltered.
@param String str string to pad
@param Number max total length of output string
@param String chr optional. Character to pad with. default: ' '
@return String padded str | function padRight(str, max, chr) {
str = str != null ? str : ''
str = String(str)
var length = max - wcwidth(str)
if (length <= 0) return str
return str + repeatString(chr || ' ', length)
} | csn |
Hard stop the server and sub process | def stop(self):
"""Hard stop the server and sub process"""
self._end.value = True
if self.background_process:
try:
self.background_process.terminate()
except Exception:
pass
for task_id, values in self.current_tasks.items():
... | csn |
Evaluate a script and retunr its result.
@param string $script
@param int $numberOfKeys
@param dynamic $arguments
@return mixed | public function eval($script, $numberOfKeys, ...$arguments)
{
return $this->client->eval($script, $arguments, $numberOfKeys);
} | csn |
Creates application and returns Application object. | def create_application(self, name=None, manifest=None):
""" Creates application and returns Application object.
"""
if not manifest:
raise exceptions.NotEnoughParams('Manifest not set')
if not name:
name = 'auto-generated-name'
from qubell.api.private.appl... | csn |
Returns package version as a string, or None if it couldn't be found. | def package_version(package_name: str) -> typing.Optional[str]:
"""
Returns package version as a string, or None if it couldn't be found.
"""
try:
return pkg_resources.get_distribution(package_name).version
except (pkg_resources.DistributionNotFound, AttributeError):
return None | csn |
Builds a sub-query for an IN statement with bound values.
@example buildInQueryBindings(array("a", "b", "c"), "ex") => "(:ex_0, :ex_1, :ex_2)", and adds keys for 'ex_0', 'ex_1' and 'ex_2' to the bound parameters
@param array $values The values to bind.
@param string [$prefix] A prefix to apply to the bound ... | public function buildInQueryBindings ($values, $prefix = "in_", &$bound_parameters = array()) {
$sql = "()";
if (is_array($values) && count($values) > 0) {
$sql = array();
$values = array_values($values);
foreach ($values as $index => $value) {
$label_name = $prefix . "_" . $index;
$sql[] = ... | csn |
// podListMetrics returns a list of metric timeseries for each for the listed nodes | func (a *HistoricalApi) podListMetrics(request *restful.Request, response *restful.Response) {
start, end, err := getStartEndTimeHistorical(request)
if err != nil {
response.WriteError(http.StatusBadRequest, err)
return
}
keys := []core.HistoricalKey{}
if request.PathParameter("pod-id-list") != "" {
for _, ... | csn |
Finds cases where protein A changes state of B, and B is then degraded.
NOTE: THIS PATTERN DOES NOT WORK. KEEPING ONLY FOR HISTORICAL REASONS.
@return the pattern | public static Pattern controlsDegradationIndirectly()
{
Pattern p = controlsStateChange();
p.add(new Size(new ParticipatesInConv(RelType.INPUT), 1, Size.Type.EQUAL), "output PE");
p.add(new Empty(peToControl()), "output PE");
p.add(new ParticipatesInConv(RelType.INPUT), "output PE", "degrading Conv");
p.add(... | csn |
Change account policy.
.. versionadded:: 2015.8.0
name (string)
The name of the account policy
allow_users_to_change_password (bool)
Allows all IAM users in your account to
use the AWS Management Console to change their own passwords.
hard_expiry (bool)
Prevents IAM u... | def account_policy(name=None, allow_users_to_change_password=None,
hard_expiry=None, max_password_age=None,
minimum_password_length=None, password_reuse_prevention=None,
require_lowercase_characters=None, require_numbers=None,
require_symbols=N... | csn |
NAME
plot_cdf.py
DESCRIPTION
makes plots of cdfs of data in input file
SYNTAX
plot_cdf.py [-h][command line options]
OPTIONS
-h prints help message and quits
-f FILE
-t TITLE
-fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is ... | def main():
"""
NAME
plot_cdf.py
DESCRIPTION
makes plots of cdfs of data in input file
SYNTAX
plot_cdf.py [-h][command line options]
OPTIONS
-h prints help message and quits
-f FILE
-t TITLE
-fmt [svg,eps,png,pdf,jpg..] specify format of ou... | csn |
// Pretty print as csv for easy plotting | func (b Bar) String() string {
return fmt.Sprintf("%v, %v, %v\n", b.From, b.To, b.Count)
} | csn |
Converts this VariantAnnotationSet into its GA4GH protocol equivalent. | def toProtocolElement(self):
"""
Converts this VariantAnnotationSet into its GA4GH protocol equivalent.
"""
protocolElement = protocol.VariantAnnotationSet()
protocolElement.id = self.getId()
protocolElement.variant_set_id = self._variantSet.getId()
protocolElemen... | csn |
// Sum64 implements the bigcache.Hasher interface. | func (t trienodeHasher) Sum64(key string) uint64 {
return binary.BigEndian.Uint64([]byte(key))
} | csn |
Register broadcast receiver internal.
@param context
the context
@param action
the action
@param receiver
the receiver
@return the broadcast receiver | private static BroadcastReceiver registerBroadcastReceiverInternal(final Context context,
final String action, final BroadcastReceiver receiver) {
if (receiver == null) {
return null;
}
IntentFilter filter = new ... | csn |
Decodes bencoded data introduced as bytes.
Returns decoded structure(s).
:param bytes encoded: | def decode(cls, encoded):
"""Decodes bencoded data introduced as bytes.
Returns decoded structure(s).
:param bytes encoded:
"""
def create_dict(items):
# Let's guarantee that dictionaries are sorted.
k_v_pair = zip(*[iter(items)] * 2)
return ... | csn |
Fetch and build robots.txt | public function main()
{
$ret = '';
$settings = GeneralUtility::getRootSetting();
// INIT
$this->tsSetup = $GLOBALS['TSFE']->tmpl->setup;
$this->cObj = $GLOBALS['TSFE']->cObj;
$this->rootPid = GeneralUtility::getRootPid();
$this->tsSetupSeo = null;
... | csn |
Get the url to download the page url from
@param string $pageId
@return array | public function getSinglePageDownloadUrl($pageId)
{
try {
$response = $this->client->get($this->PagesUrl . '/' . $pageId, [
'headers' => ['Authorization' => 'Bearer '. $this->login->apiKey],
'verify' => $this->certFile,
]);
$body = json_de... | csn |
Connects this input to the relevant output of the referenced transaction if it's in the given map.
Connecting means updating the internal pointers and spent flags. If the mode is to ABORT_ON_CONFLICT then
the spent output won't be changed, but the outpoint.fromTx pointer will still be updated.
@param transactions Map ... | public ConnectionResult connect(Map<Sha256Hash, Transaction> transactions, ConnectMode mode) {
Transaction tx = transactions.get(outpoint.getHash());
if (tx == null) {
return TransactionInput.ConnectionResult.NO_SUCH_TX;
}
return connect(tx, mode);
} | csn |
Disable the page relative menus if needed.
@param PageInterface $page
@return bool | private function disablePageRelativeMenus(PageInterface $page)
{
$disabledMenus = false;
if (!$page->isEnabled()) {
// Disable menu children query
$disableChildrenQuery = $this->em->createQuery(sprintf(
'UPDATE %s m SET m.enabled = 0 WHERE m.root = :root AND ... | csn |
Delete metadata references with foreign keys to the metadata file id
@param fileId
file id
@return deleted count
@throws SQLException
upon failure | public int deleteByMetadata(long fileId) throws SQLException {
DeleteBuilder<MetadataReference, Void> db = deleteBuilder();
db.where().eq(MetadataReference.COLUMN_FILE_ID, fileId);
int deleted = db.delete();
return deleted;
} | csn |
Returns a dict containing old greek particles grouped by category. | def particles(category=None):
'''
Returns a dict containing old greek particles grouped by category.
'''
filepath = os.path.join(os.path.dirname(__file__), './particles.json')
with open(filepath) as f:
try:
particles = json.load(f)
except ValueError as e:
log.... | csn |
Connect socket to server.
@return void
@throws \RuntimeException | private function connect():void
{
socket_connect($this->socket, $this->host, $this->port) or $this->error();
} | csn |
The self-signed device attestation certificate.
Returns a OpenSSL::X509::Certificate instance. | def cert
@cert ||= OpenSSL::X509::Certificate.new.tap do |c|
c.subject = c.issuer = OpenSSL::X509::Name.parse(cert_subject)
c.not_before = Time.now
c.not_after = Time.now + 365 * 24 * 60 * 60
c.public_key = cert_key
c.serial = 0x1
c.version = 0x0
c.sign cert... | csn |
Polymer vulcanization for browserify
@param {String} src
Web component html source
@param {String} filepath
Source filepath
@return {String}
CommonJS source with external import module and stylesheet
as `require()` calls | function polymerize(src, filepath) {
// Parse web-component source (extract dependency, optimize source, etc.)
var result = parseSource(src, filepath);
// Generate commonjs module source:
var src = [];
// Require imported web-components
result.imports.forEach(function(imp) {
src.push('require("'+imp+... | csn |
Makes sure every language code defined as limitation exists.
Make sure {@link acceptValue()} is checked first!
@param \eZ\Publish\API\Repository\Values\User\Limitation $limitationValue
@return \eZ\Publish\SPI\FieldType\ValidationError[] | public function validate(APILimitationValue $limitationValue): array
{
$validationErrors = array();
$existingLanguages = $this->persistenceLanguageHandler->loadListByLanguageCodes(
$limitationValue->limitationValues
);
$missingLanguages = array_diff(
$limitati... | csn |
// Converts untyped value into bool. The second bool return implies
// success - it returns false in case of a conversion failure. | func (v *Value) bytesToBool() (val bool, ok bool) {
bytes, _ := v.ToBytes()
ok = true
switch strings.ToLower(string(bytes)) {
case "t", "true":
val = true
case "f", "false":
val = false
default:
ok = false
}
return val, ok
} | csn |
// NewCmdPruneRoles implements the OpenShift cli prune roles command. | func NewCmdPruneAuth(f kcmdutil.Factory, name string, streams genericclioptions.IOStreams) *cobra.Command {
o := NewPruneAuthOptions(streams)
cmd := &cobra.Command{
Use: name,
Short: "Removes references to the specified roles, clusterroles, users, and groups.",
Long: "Removes references to the specified role... | csn |
// Get returns the topic list at the given index from the slice. | func (t *Topics) Get(index int) (hashes *Hashes, _ error) {
if index < 0 || index >= len(t.topics) {
return nil, errors.New("index out of bounds")
}
return &Hashes{t.topics[index]}, nil
} | csn |
Delete a release
@link https://developer.github.com/v3/repos/releases/#delete-a-release
@param string $id
@return bool | public function deleteRelease(string $id): bool
{
$this->getApi()->request($this->getApi()->sprintf('/repos/:owner/:repo/releases/:id',
$this->getRepositories()->getOwner(), $this->getRepositories()->getRepo(), $id), Request::METHOD_DELETE);
if ($this->getApi()->getHeaders()['Status'] =... | csn |
Check controller file existence and ask if can be overridden
@return bool | protected function overrideFile()
{
if (!is_file($this->getControllerFile())) {
return true;
}
$question = new ConfirmationQuestion(
"\nThe file <comment>{$this->controllerFile}</comment> already " .
"exists. Override it (y,N)? ",
false,
... | csn |
Gets by name.
@param urlAddr the host
@return the by name | public static InetAddress getByName(final String urlAddr) {
try {
val url = new URL(urlAddr);
return InetAddress.getByName(url.getHost());
} catch (final Exception e) {
LOGGER.trace("Host name could not be determined automatically.", e);
}
return null;... | csn |
Adds a new document to this collection with the specified data, assigning it a document ID
automatically.
@param fields A Map containing the data for the new document.
@return An ApiFuture that will be resolved with the DocumentReference of the newly created
document.
@see #document() | @Nonnull
public ApiFuture<DocumentReference> add(@Nonnull final Map<String, Object> fields) {
final DocumentReference documentReference = document();
ApiFuture<WriteResult> createFuture = documentReference.create(fields);
return ApiFutures.transform(
createFuture,
new ApiFunction<WriteRes... | csn |
Sort the configurations in place. items with lowest memory per proc come first. | def sort_by_mem_per_proc(self, reverse=False):
"""Sort the configurations in place. items with lowest memory per proc come first."""
# Avoid sorting if mem_per_cpu is not available.
if any(c.mem_per_proc > 0.0 for c in self):
self._confs.sort(key=lambda c: c.mem_per_proc, reverse=rev... | csn |
Adds the task as the head of the chain at the index location.
@param tasks the ordered array of the pending operations
@param task the pending operation to add
@param index the array location | void addTaskToChain(Task[] tasks, Task task, int index) {
task.setNext(tasks[index]);
tasks[index] = task;
} | csn |
Get the port number from its name or scheme
@param string $name The name or scheme
@return int The default port number for it | final public function getDefaultPort($name)
{
$this->_getPortKey($name);
if ($this->isNamedPort($name)) {
return constant($this->_port_class . $name);
} else {
throw new \InvalidArgumentException("Unknown name or scheme: {$name}");
}
} | csn |
// SchedulingV1alpha1 retrieves the SchedulingV1alpha1Client | func (c *Clientset) SchedulingV1alpha1() schedulingv1alpha1.SchedulingV1alpha1Interface {
return &fakeschedulingv1alpha1.FakeSchedulingV1alpha1{Fake: &c.Fake}
} | csn |
// EstimateFee provides an estimated fee in bitcoins per kilobyte. | func (c *Client) EstimateFee(numBlocks int64) (float64, error) {
return c.EstimateFeeAsync(numBlocks).Receive()
} | csn |
Register an electron-phonon task. | def register_eph_task(self, *args, **kwargs):
"""Register an electron-phonon task."""
kwargs["task_class"] = EphTask
return self.register_task(*args, **kwargs) | csn |
Validate and resolve options passed in Twig to datasource_results_per_page_widget
@param array $options
@return array | private function resolveMaxResultsOptions(array $options, DataSourceViewInterface $dataSource)
{
$optionsResolver = new OptionsResolver();
$optionsResolver
->setDefaults([
'route' => $this->getCurrentRoute($dataSource),
'active_class' => 'active',
... | csn |
// SetProvisioningArtifactPreferences sets the ProvisioningArtifactPreferences field's value. | func (s *DescribeProvisioningParametersOutput) SetProvisioningArtifactPreferences(v *ProvisioningArtifactPreferences) *DescribeProvisioningParametersOutput {
s.ProvisioningArtifactPreferences = v
return s
} | csn |
// Actions is additional list of actions to present on the page. | func (*DatabaseSettings) Actions(c context.Context) ([]portal.Action, error) {
return nil, nil
} | csn |
// Return a map of VBD references to VBD records for all VBDs known to the system. | func (_class VBDClass) GetAllRecords(sessionID SessionRef) (_retval map[VBDRef]VBDRecord, _err error) {
_method := "VBD.get_all_records"
_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
if _err != nil {
return
}
_result, _err := _class.client.APICall(_method,... | csn |
Sets the geo area for the map.
* africa
* asia
* europe
* middle_east
* south_america
* usa
* world | def set_geo_area(self, area):
'''Sets the geo area for the map.
* africa
* asia
* europe
* middle_east
* south_america
* usa
* world
'''
if area in self.__areas:
self.geo_area = area
else:
raise Unk... | csn |
Return True if the response matches fuzzily exactly.
Insensitivity is taken into account. | def _exact_fuzzy_match(response, match, insensitive):
'''
Return True if the response matches fuzzily exactly.
Insensitivity is taken into account.
'''
if insensitive:
response = response.lower()
match = match.lower()
r_words = response.split()
m_words = match.split()
# m... | csn |
Forgiving input, allows either argument if only one supplied.
@overload initialize(*command_args)
@param command_args [Array<String>]
@overload initialize(version_pattern)
@param version_pattern [Regexp]
@overload initialize(*command_args, version_pattern)
@param command_args [Array<String>]
@param vers... | def detect_version(executable_path)
capture = ShellCapture.new(version_command(executable_path))
unless capture.command_found
raise Cliver::Dependency::NotFound.new(
"Could not find an executable at given path '#{executable_path}'." +
"If this path was not specified explicitl... | csn |
Deletes a subscriber list.
@param Request $request
@param SubscriberList $list
@return View | public function deleteAction(Request $request, SubscriberList $list): View
{
$this->requireAuthentication($request);
$this->subscriberListRepository->remove($list);
return View::create();
} | csn |
Convert the TreeModel into a compiled C struct | def to_struct(cls, name=None):
"""
Convert the TreeModel into a compiled C struct
"""
if name is None:
name = cls.__name__
basic_attrs = dict([(attr_name, value)
for attr_name, value in cls.get_attrs()
if isinsta... | csn |
// Returns whether the region fully covers the argument region | func (r Region) Covers(r2 Region) bool {
return r.Contains(r2.Begin()) && r2.End() <= r.End()
} | csn |
Append a middleware to the attempt step.
@param callable $middleware Middleware function to add.
@param string $name Name of the middleware. | public function appendAttempt(callable $middleware, $name = null)
{
$this->add(self::ATTEMPT, $name, $middleware);
} | csn |
Mark the given TaskItem depends on this taskGroup.
@param dependentTaskItem the task item that depends on this task group
@return key to be used as parameter to taskResult(string) method to retrieve result of
invocation of given task item. | public String addPostRunDependent(FunctionalTaskItem dependentTaskItem) {
IndexableTaskItem taskItem = IndexableTaskItem.create(dependentTaskItem);
this.addPostRunDependent(taskItem);
return taskItem.key();
} | csn |
Add a child to the node. | def add_child(self, obj):
"""Add a child to the node."""
self.children.append(obj)
obj.parents.append(self) | csn |
// Log something to stdout | func (inv *Investigate) Log(s string) {
if inv.verbose {
inv.log.Println(s)
}
} | csn |
Collect all layouts based on existing fields.
@param array &$context The current template context.
@return void | public function getFieldLayouts(&$context)
{
$context['fieldLayouts'] = [];
foreach ($context['fields'] as $field) {
$layouts = [];
foreach ($this->_getRelatedLayoutIds($field) as $row) {
$layouts[] = $this->_getLayoutData($row);
}
$... | csn |
// The unused capacity is calculated on a scale of 0-10
// 0 being the lowest priority and 10 being the highest.
// The more unused resources the higher the score is. | func leastRequestedScore(requested, capacity int64) int64 {
if capacity == 0 {
return 0
}
if requested > capacity {
return 0
}
return ((capacity - requested) * int64(schedulerapi.MaxPriority)) / capacity
} | csn |
Return the state of closing channels in a token network. | def get_channelstate_closing(
chain_state: ChainState,
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
) -> List[NettingChannelState]:
"""Return the state of closing channels in a token network."""
return get_channelstate_filter(
chain_state,
payment_ne... | csn |
Removes the property
@return string The value that was stored for the given property | public function remove($property)
{
if (!array_key_exists($property, $this->data)) {
throw new InvalidArgumentException(sprintf('Property %s does not exist', $property));
}
$value = $this->data[$property];
unset($this->data[$property]);
return $value;
} | csn |
Creates a new collection on the server
This will add the collection on the server and return its id
The id is mainly returned for backwards compatibility, but you should use the collection name for any reference to the collection. *
This will throw if the collection cannot be created
@throws Exception
@param mixed... | public function create($collection, array $options = [])
{
if (is_string($collection)) {
$name = $collection;
$collection = new Collection();
$collection->setName($name);
foreach ($options as $key => $value) {
$collection->{'set' . ucfirs... | csn |
Decoding an event from binary-log buffer.
@return <code>UknownLogEvent</code> if event type is unknown or skipped,
<code>null</code> if buffer is not including a full event. | public LogEvent decode(LogBuffer buffer, LogContext context) throws IOException {
final int limit = buffer.limit();
if (limit >= FormatDescriptionLogEvent.LOG_EVENT_HEADER_LEN) {
LogHeader header = new LogHeader(buffer, context.getFormatDescription());
final int len = hea... | csn |
Build module paths | function(callback) {
async.map(modules, function(module, callback) {
callback && callback(
null,
{
name: module,
path: process.cwd() + '/modules/' +
module + '/controllers/'
... | csn |
// evalIdentifier evaluates IdentifierNode | func (j *JSONPath) evalIdentifier(input []reflect.Value, node *IdentifierNode) ([]reflect.Value, error) {
results := []reflect.Value{}
switch node.Name {
case "range":
j.stack = append(j.stack, j.cur)
j.beginRange += 1
results = input
case "end":
if j.endRange < j.inRange { //inside a loop, break the curren... | csn |
Get store id for the current category.
@param Category $category Category.
@return int | private function getStoreId(Category $category)
{
$storeId = $category->getStoreId();
if ($storeId === 0) {
$defaultStoreId = $this->getDefaultStoreId();
$categoryStoreIds = array_filter($category->getStoreIds());
$storeId = current($categoryStoreIds);
... | csn |
This method finally handles all PHP and user errors as well as the exceptions that
have been thrown through the servlet processing.
@param \AppserverIo\Appserver\ServletEngine\RequestHandler $requestHandler The request handler instance
@param \AppserverIo\Psr\Servlet\Http\HttpServletRequestInterface $servletR... | public function handleErrors(
RequestHandler $requestHandler,
HttpServletRequestInterface $servletRequest,
HttpServletResponseInterface $servletResponse
) {
// return immediately if we don't have any errors
if (sizeof($errors = $requestHandler->getErrors()) === 0) {
... | csn |
// Min returns min side of rectangular polygon | func (p *PostGISPolygon) Min() PostGISPoint {
if len(p.Points) != 5 || p.Points[0] != p.Points[4] ||
p.Points[0].Lon != p.Points[1].Lon || p.Points[0].Lat != p.Points[3].Lat ||
p.Points[1].Lat != p.Points[2].Lat || p.Points[2].Lon != p.Points[3].Lon {
panic("Not an envelope polygon")
}
return p.Points[0]
} | csn |
Takes an SVM regression model produces a starting spec using the parts.
that are shared between all SVMs. | def _generate_base_svm_regression_spec(model):
"""
Takes an SVM regression model produces a starting spec using the parts.
that are shared between all SVMs.
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
spec = _Model_pb... | csn |
List all ProductVersions for a given Product | def list_versions_for_product(id=None, name=None, page_size=200, page_index=0, sort='', q=''):
"""
List all ProductVersions for a given Product
"""
content = list_versions_for_product_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | csn |
// Setup this dag of tasks | func (m *JobExecutor) Setup() error {
if m == nil {
return fmt.Errorf("JobExecutor is nil?")
}
if m.RootTask == nil {
return fmt.Errorf("No task exists for this job")
}
return m.RootTask.Setup(0)
} | csn |
Check if this page print text
Search the content stream for any of the four text showing operators.
We ignore text positioning operators because some editors might
generate maintain these even if text is deleted etc.
This cannot detect raster text (text in a bitmap), text rendered as
... | def has_text(self):
"""Check if this page print text
Search the content stream for any of the four text showing operators.
We ignore text positioning operators because some editors might
generate maintain these even if text is deleted etc.
This cannot detect raster text (text i... | csn |
Return next chunk of resources from resource_iter, and next item.
If first parameter is specified then this will be prepended to
the list.
The chunk will contain self.max_sitemap_entries if the iterator
returns that many. next will have the value of the next value from
the iter... | def get_resources_chunk(self, resource_iter, first=None):
"""Return next chunk of resources from resource_iter, and next item.
If first parameter is specified then this will be prepended to
the list.
The chunk will contain self.max_sitemap_entries if the iterator
returns that m... | csn |
Uses either the exclude or include pattern to determine
if a file should be shown.
@param {String} file filename | function shouldBeIncluded(file) {
if (!showAllFiles && file[0] === '.') {
return false
}
if (hasExcludePattern) {
return !excludePattern.test(file)
}
if (hasIncludePattern) {
return includePattern.test(file)
}
return true
} | csn |
// stoi de-serializes int64 from a sortable string 13 chars long. | func stoi(s string) int64 {
ret, err := strconv.ParseUint(s, 32, 64)
if err != nil {
//TODO handle error?
return 0
}
return int64(ret - int64Adjust)
} | csn |
This function will take care of initializing all caches that were defined
previously by the `CacheService` which allows dynamic caches to be used
for every configuration object type.
@see \Romm\ConfigurationObject\Service\Items\Cache\CacheService::initialize()
@internal | public function registerDynamicCaches()
{
$dynamicCaches = $this->getCache()->getByTag(self::CACHE_TAG_DYNAMIC_CACHE);
foreach ($dynamicCaches as $cacheData) {
$identifier = $cacheData['identifier'];
$options = $cacheData['options'];
$this->registerCacheInternal... | csn |
// messageToPromText converts a single metrics message to prometheus-formatted
// newline-separate strings | func messageToPromText(message producers.MetricsMessage) string {
var buffer bytes.Buffer
for _, d := range message.Datapoints {
name := sanitizeName(d.Name)
labels := getLabelsForDatapoint(message.Dimensions, d.Tags)
t, err := time.Parse(time.RFC3339, d.Timestamp)
if err != nil {
log.Warnf("Encountered b... | csn |
Return a fully-qualified profile string. | def profile_path(cls, project, tenant, profile):
"""Return a fully-qualified profile string."""
return google.api_core.path_template.expand(
"projects/{project}/tenants/{tenant}/profiles/{profile}",
project=project,
tenant=tenant,
profile=profile,
... | csn |
Defines the title of the clock. The title
could be used to show for example the current
city or timezone
@param TITLE | public void setTitle(final String TITLE) {
if (null == title) {
_title = TITLE;
fireUpdateEvent(REDRAW_EVENT);
} else {
title.set(TITLE);
}
} | csn |
// SetNoncurrentVersionTransitions sets the NoncurrentVersionTransitions field's value. | func (s *LifecycleRule) SetNoncurrentVersionTransitions(v []*NoncurrentVersionTransition) *LifecycleRule {
s.NoncurrentVersionTransitions = v
return s
} | csn |
Evaluates condition expression and returns boolean representation.
@param context
@return | private boolean checkCondition(TestContext context) {
if (conditionExpression != null) {
return conditionExpression.evaluate(context);
}
// replace dynamic content with each iteration
String conditionString = context.replaceDynamicContentInString(condition);
if (Vali... | csn |
Adds the parameter to the conversion modifier.
:param idx: Provides the ending index of the parameter string. | def set_param(self, idx):
"""
Adds the parameter to the conversion modifier.
:param idx: Provides the ending index of the parameter string.
"""
self.modifier.set_param(self.format[self.param_begin:idx]) | csn |
Create the genealogy menu.
@param Menu[] $menus
@return string | public function genealogyMenuContent(array $menus): string
{
return implode('', array_map(static function (Menu $menu): string {
return $menu->bootstrap4();
}, $menus));
} | csn |
Remove items from ``list_`` at positions specified in ``index_list``
The original ``list_`` is preserved if ``copy`` is True
Args:
list_ (list):
index_list (list):
copy (bool): preserves original list if True
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list im... | def delete_items_by_index(list_, index_list, copy=False):
"""
Remove items from ``list_`` at positions specified in ``index_list``
The original ``list_`` is preserved if ``copy`` is True
Args:
list_ (list):
index_list (list):
copy (bool): preserves original list if True
Exa... | csn |
Compares the two provided arrays.
@param {*[]} array1 The 1st array to compare.
@param {*[]} array2 The 2nd array to compare.
@param {Map<Object, Object>} traversedValues A map of non-primitive values
traversed in the first structure to their equal counterparts in the
second structure.
@return {boolean} {@code true} i... | function arrayEquals(array1, array2, traversedValues) {
if (array1.length !== array2.length) {
return false
}
return structureEquals(
array1,
array2,
iteratorToArray(array1.keys()),
iteratorToArray(array2.keys()),
(array, key) => array[key],
traversedValues
)
} | csn |
// AutoID returns the auto id of this hprose client.
// If the id is not initialized, it be initialized and returned. | func (client *BaseClient) AutoID() (string, error) {
client.topicManager.locker.RLock()
if client.id != "" {
client.topicManager.locker.RUnlock()
return client.id, nil
}
client.topicManager.locker.RUnlock()
client.topicManager.locker.Lock()
defer client.topicManager.locker.Unlock()
if client.id != "" {
ret... | csn |
Returns array items delimited
@param delim
@param array
@return | public static final String print(String delim, Object... array)
{
return print(null, delim, null, null, null, array);
} | csn |
// DutyCycle reads from pwm duty cycle path and returns value in nanoseconds | func (p *PWMPin) DutyCycle() (duty uint32, err error) {
buf, err := p.read(p.pwmDutyCyclePath())
if err != nil {
return
}
val, e := strconv.Atoi(string(buf))
return uint32(val), e
} | csn |
Returns description by its associated code
@param integer $code Status code
@throws \OutOfRangeException If the supplied code is out of range
@return string | public function getDescriptionByStatusCode($code)
{
// Make sure the expected type supplied
$code = (int) $code;
if (isset($this->statuses[$code])) {
return $this->statuses[$code];
} else {
throw new OutOfRangeException(
sprintf('The status co... | csn |
Apply IOB chemical entity tags and POS tags to text. | def _prep_tags(t, annotations):
"""Apply IOB chemical entity tags and POS tags to text."""
tags = [['O' for _ in sent.tokens] for sent in t.sentences]
for start, end, text in annotations:
done_first = False
for i, sent in enumerate(t.sentences):
for j, token in enumerate(sent.tok... | csn |
Get the order of the elements in descending or ascending order.
@param values A vector of double values.
@param descending Flag indicating if we go descending or not.
@return A vector of indices sorted in the provided order. | public static int[] getOrder(double[] values, boolean descending) {
return DMatrixUtils.getOrder(values, IntStream.range(0, values.length).toArray(), descending);
} | csn |
// You should always use this function to get a new EnableOutOfBandManagementForHostParams instance,
// as then you are sure you have configured all required params | func (s *HostService) NewEnableOutOfBandManagementForHostParams(hostid string) *EnableOutOfBandManagementForHostParams {
p := &EnableOutOfBandManagementForHostParams{}
p.p = make(map[string]interface{})
p.p["hostid"] = hostid
return p
} | csn |
// WithSignalHandler overrides the default signal handler. | func WithSignalHandler(handler SignalHandler) ConnOption {
return func(conn *Conn) error {
conn.signalHandler = handler
return nil
}
} | csn |
getter for timexFreq - gets
@generated
@return value of the feature | public String getTimexFreq() {
if (Timex3_Type.featOkTst && ((Timex3_Type)jcasType).casFeat_timexFreq == null)
jcasType.jcas.throwFeatMissing("timexFreq", "de.unihd.dbs.uima.types.heideltime.Timex3");
return jcasType.ll_cas.ll_getStringValue(addr, ((Timex3_Type)jcasType).casFeatCode_timexFreq);} | csn |
Train a decision tree model for classification.
:param data:
Training data: RDD of LabeledPoint. Labels should take values
{0, 1, ..., numClasses-1}.
:param numClasses:
Number of classes for classification.
:param categoricalFeaturesInfo:
Map storing arit... | def trainClassifier(cls, data, numClasses, categoricalFeaturesInfo,
impurity="gini", maxDepth=5, maxBins=32, minInstancesPerNode=1,
minInfoGain=0.0):
"""
Train a decision tree model for classification.
:param data:
Training data: RDD of ... | csn |
Gets the value of the objectId 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 objectId property.
<p>
For example, to add... | public java.util.List<ObjectId> getObjectId() {
if (objectId == null) {
objectId = new ArrayList<ObjectId>();
}
return this.objectId;
} | csn |
Deletes the user
@method
@memberOf corbel.Iam.UserBuilder
@return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} | function(options) {
var queryParams = '';
if (options && options.avoidNotification) {
queryParams = '?avoidnotification=true';
}
console.log('iamInterface.user.delete');
corbel.validate.value('id', this.id);
... | csn |
Validate and set the host list and remote user parameters. | def validate_host_parameters(self, host_list, remote_user):
'''
Validate and set the host list and remote user parameters.
'''
if host_list is None:
host_list = self.host_list
if remote_user is None:
remote_user = self.remote_user
if host_list is... | csn |
Return CRCPubkey instance from CRC public key string
:param crc_pubkey: CRC public key
:return: | def from_str(cls: Type[CRCPubkeyType], crc_pubkey: str) -> CRCPubkeyType:
"""
Return CRCPubkey instance from CRC public key string
:param crc_pubkey: CRC public key
:return:
"""
data = CRCPubkey.re_crc_pubkey.match(crc_pubkey)
if data is None:
raise E... | csn |
Find file element.
@param string $id element identifier
@param array $relations tag relations (near, in, under)
@return Accessor\Form\FileAccessor | public function findFile($id = null, array $relations = array())
{
return new Accessor\Form\FileAccessor($id, $relations, $this->con);
} | csn |
Display a form to edit Seo settings.
@param Request $request
@param View $view
@throws \Exception
@Route("/{id}/settings", name="victoire_seo_pageSeo_settings")
@Method("GET")
@return JsonResponse | public function settingsAction(Request $request, View $view)
{
$pageSeo = $view->getSeo() ?: new PageSeo();
$form = $this->createSettingsForm($pageSeo, $view);
$form->handleRequest($request);
$response = $this->getNotPersistedSettingsResponse(
$form,
$view,
... | csn |
Stores rules to the selector that should be applied once resized.
@param {String} selector
@param {String} mode min|max
@param {String} property width|height
@param {String} value | function queueQuery(selector, mode, property, value) {
if (typeof(allQueries[selector]) === 'undefined') {
allQueries[selector] = [];
// add animation to trigger animationstart event, so we know exactly when a element appears in the DOM
var id = idToSelectorM... | csn |
Upload multiple files.
@param $error
@param array $notices
@param int $errorCode
@return \Illuminate\Http\JsonResponse | private function errorResponse($error, $notices = [], $errorCode = 400)
{
if (is_array($error)) {
json_encode($error);
}
$payload = ['error' => $error];
if (!empty($notices)) {
$payload['notices'] = $notices;
}
return \Response::json($payload,... | csn |
Computes an approximation to a
TT-matrix in with accuracy EPS | def round(self, eps=1e-14, rmax=100000):
""" Computes an approximation to a
TT-matrix in with accuracy EPS
"""
c = matrix()
c.tt = self.tt.round(eps, rmax)
c.n = self.n.copy()
c.m = self.m.copy()
return c | csn |
Converts "wTimeout" RiakClient constructor option to "wTimeoutMS" for
driver versions 1.4.0+.
Note: RiakClient actually allows case-insensitive option names, but
we'll only process the canonical version here.
@param array $options
@return array | protected function convertWriteTimeout(array $options)
{
if (version_compare(phpversion('mongo'), '1.4.0', '<')) {
return $options;
}
if (isset($options['wTimeout']) && ! isset($options['wTimeoutMS'])) {
$options['wTimeoutMS'] = $options['wTimeout'];
unse... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.