query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
validates the record
@class Record
@method validate
@this Promise | function() {
var self = this
var validations = []
return self
.callInterceptors('beforeValidation', [self])
.then(function() {
for (var field in self.definition.validations) {
var fieldValidations = self.definition.validations[field]
// set the scope of all validato... | csn |
Strip php tags and notations in string.
@param array|string $data
@return array|null|string | public function strip_php_tags($data)
{
if (is_array($data)) {
foreach ($data as $key=>$value) {
$data[$key] = $this->strip_php_tags($value);
}
return $data;
}
return addslashes(htmlspecialchars(strip_tags($data)));
} | csn |
Convert the expression to Tseitin's encoding. | def tseitin(self, auxvarname='aux'):
"""Convert the expression to Tseitin's encoding."""
if self.is_cnf():
return self
_, constraints = _tseitin(self.to_nnf(), auxvarname)
fst = constraints[-1][1]
rst = [Equal(v, ex).to_cnf() for v, ex in constraints[:-1]]
re... | csn |
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See y... | def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=... | csn |
Infer the length of a signal from a dat file.
Parameters
----------
file_name : str
Name of the dat file
fmt : str
WFDB fmt of the dat file
n_sig : int
Number of signals contained in the dat file
Notes
-----
sig_len * n_sig * bytes_per_sample == file_size | def _infer_sig_len(file_name, fmt, n_sig, dir_name, pb_dir=None):
"""
Infer the length of a signal from a dat file.
Parameters
----------
file_name : str
Name of the dat file
fmt : str
WFDB fmt of the dat file
n_sig : int
Number of signals contained in the dat file
... | csn |
Return an integer if it is an Integer or can get Integer from String, else null | public static Integer getInteger(Object object) {
try {
if(object instanceof Integer)
return (Integer) object;
if(object instanceof String)
return Integer.valueOf((String) object);
} catch(NumberFormatException nfe) {
}
return nul... | csn |
Returns an array of trending topic names. | def trending_topics
result = http_get("/services/data/v#{self.version}/chatter/topics/trending")
result = JSON.parse(result.body)
result["topics"].collect { |topic| topic["name"] }
end | csn |
Generate the full tag for the given image, concatenating the org,
project, env, image name, and version.
Pass `version: nil` to exclude the version portion.
@example
image_tag("app") # => jutonz/dctl-dev-app:1 | def image_tag(image, version: current_version_for_image(image))
org = settings.org
project = settings.project
tag = "#{org}/#{project}-#{env}-#{image}"
if !version.nil?
version = version.to_i
tag +=
if version.negative?
current_version = current_ver... | csn |
Validates the virtual machine | def validate
super
validates_presence_of :name, :os_type_id, :memory_size, :vram_size, :cpu_count
validates_numericality_of :memory_balloon_size, :monitor_count
validates_inclusion_of :accelerate_3d_enabled, :accelerate_2d_video_enabled, :teleporter_enabled, :in => [true, false]
if !erro... | csn |
Mie-simulated field behind a dielectric sphere
Parameters
----------
radius: float
Radius of the sphere [m]
sphere_index: float
Refractive index of the sphere
medium_index: float
Refractive index of the surrounding medium
wavelength: float
Vacuum wavelength of th... | def mie(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80),
center=(39.5, 39.5), focus=0, arp=True):
"""Mie-simulated field behind a dielectric sphere
Parameters
----------
radius: float
Radius of the sphere [m]
sphere... | csn |
// QuoteMapKeys sets up the encoder to encode
// maps with string type keys with quoted TOML keys.
//
// This relieves the character limitations on map keys. | func (e *Encoder) QuoteMapKeys(v bool) *Encoder {
e.quoteMapKeys = v
return e
} | csn |
Safely capitalizes a string by converting the first character to upper
case. Handles null, empty, and strings of length of 1 or greater. For
example, this will convert "joe" to "Joe". If the string is null, this
will return null. If the string is empty such as "", then it'll just
return an empty string such as "".
@... | static public String capitalize(String string0) {
if (string0 == null) {
return null;
}
int length = string0.length();
// if empty string, just return it
if (length == 0) {
return string0;
} else if (length == 1) {
return string0.toUppe... | csn |
// factory to make sure modtime is set | func newMemFile(name string, isdir bool) *memFile {
return &memFile{
name: name,
modtime: time.Now(),
isdir: isdir,
}
} | csn |
Update player information.
@param PlayerModel $player Login of the player. | protected function updatePlayer($player)
{
$time = time();
$upTime = $time - $this->playerLastUpTime[$player->getLogin()];
$this->playerLastUpTime[$player->getLogin()] = $time;
$player->setOnlineTime($player->getOnlineTime() + $upTime);
} | csn |
// RoundRobin balances peers in a round-robin fashion | func RoundRobin() Balancer {
logger.Debugf("Creating Round-robin balancer")
counter := rollingcounter.New()
return func(peers []fab.Peer) []fab.Peer {
logger.Debugf("Load balancing %d peers using Round-Robin strategy...", len(peers))
index := counter.Next(len(peers))
balancedPeers := make([]fab.Peer, len(peer... | csn |
Draws a box on the current plot.
Parameters
----------
b : :obj:`autolab_core.Box`
box to draw
line_width : int
width of lines on side of box
color : :obj:`str`
color of box
style : :obj:`str`
style of lines to draw | def box(b, line_width=2, color='g', style='-'):
""" Draws a box on the current plot.
Parameters
----------
b : :obj:`autolab_core.Box`
box to draw
line_width : int
width of lines on side of box
color : :obj:`str`
color of box
s... | csn |
Private helper to init values from a dictionary, wraps children into
AttributeFilter objects
:param from_dictionary: dictionary to get attribute names and visibility from
:type from_dictionary: dict
:param template_model:
:type template_model: DataCollection | def _init_from_dictionary(self, from_dictionary, template_model=None):
"""
Private helper to init values from a dictionary, wraps children into
AttributeFilter objects
:param from_dictionary: dictionary to get attribute names and visibility from
:type from_dictionary: dict
... | csn |
// ListPipelineGroupsAction handles the interaction between the cli flags and the action handler for
// list-pipeline-groups | func listPipelineGroupsAction(client *gocd.Client, c *cli.Context) (r interface{}, resp *gocd.APIResponse, err error) {
return client.PipelineGroups.List(context.Background(), c.String("group-name"))
} | csn |
Logs in using the provided credentials. | protected function login()
{
// Perform a request with the login credentials in the request header.
$response = $this->client->get('services/login', [
'headers' => ['username'=> $this->username, 'password' => $this->password],
]);
// Parse the response body.
$jso... | csn |
r"""
Iterative knapsack method
Math:
maximize \sum_{i \in T} v_i
subject to \sum_{i \in T} w_i \leq W
Notes:
dpmat is the dynamic programming memoization matrix.
dpmat[i, w] is the total value of the items with weight at most W
T is idx_subset, the set of indicies i... | def knapsack_iterative_int(items, maxweight):
r"""
Iterative knapsack method
Math:
maximize \sum_{i \in T} v_i
subject to \sum_{i \in T} w_i \leq W
Notes:
dpmat is the dynamic programming memoization matrix.
dpmat[i, w] is the total value of the items with weight at mos... | csn |
Searches for the specified key and returns the zero-based index within the entire SortedList.
@param {Object} key The key to locate in the SortedList.
@returns {Number} | function (key) {
assertNotNull(key);
return binarySearch(this.slot.keys, 0, this.slot.size, key, this.slot.comparer.compare);
} | csn |
Draw the visual. | def on_draw(self):
"""Draw the visual."""
# Skip the drawing if the program hasn't been built yet.
# The program is built by the interact.
if self.program:
# Draw the program.
self.program.draw(self.gl_primitive_type)
else: # pragma: no cover
... | csn |
Specified whether or not a username and password have been provided for
use with an authenticated proxy
@return bool true if both proxyUser and proxyPassword are present | public static function isAuthenticatedProxy()
{
$proxyUser = self::$global->getProxyUser();
$proxyPwd = self::$global->getProxyPassword();
return !empty($proxyUser) && !empty($proxyPwd);
} | csn |
// StickerFn add a function to be called when a sticker arrives. | func (bot *TgBot) StickerFn(f func(TgBot, Message, Sticker, string)) *TgBot {
bot.addToConditionalFuncs(StickerConditionalCall{f})
return bot
} | csn |
Reads the next token from the tokeniser.
This method throws a ParseException when reading EOF.
@param tokeniser
@param in
@param ignoreEOF
@return int value of the ttype field of the tokeniser
@throws ParseException When reading EOF. | private int nextToken(StreamTokenizer tokeniser, Reader in, boolean ignoreEOF) throws IOException, ParserException {
int token = tokeniser.nextToken();
if (!ignoreEOF && token == StreamTokenizer.TT_EOF) {
throw new ParserException("Unexpected end of file", getLineNumber(tokeniser, in));
... | csn |
// Verify check for a valid token in request Cookie, form field or header.
// It also checks if header "Referer" is present and that host values of
// the request and referrer are the same | func Verify(r *http.Request, opts ...VerifyOption) error {
o := &VerifyOptions{
cookieName: XSRFCookieName,
headerName: XSRFHeaderName,
formFieldName: XSRFFormFieldName,
}
for _, opt := range opts {
opt(o)
}
if contains(safeMethods, r.Method) {
return nil
}
referer, err := url.Parse(r.Header.Ge... | csn |
ifOk validates and saves before calling back | function getSavingCallbacks(callbacks){
return {
ifError: callbacks.ifError,
ifNotEnoughFunds: callbacks.ifNotEnoughFunds,
ifOk: function(objJoint, private_payload, composer_unlock){
var objUnit = objJoint.unit;
var unit = objUnit.unit;
validation.validate(objJoint, {
ifUnitError: function(err){
... | csn |
A small pin that represents the result of the build process | def pin(value):
'''A small pin that represents the result of the build process'''
if value is False:
return draw_pin('Build Failed', 'red')
elif value is True:
return draw_pin('Build Passed')
elif value is NOT_FOUND:
return draw_pin('Build N / A', 'lightGray', 'black')
return... | csn |
Collects link items for visible page numbers. | def windowed_links
prev = nil
visible_page_numbers.inject [] do |links, n|
# detect gaps:
links << gap_marker if prev and n > prev + 1
links << page_link_or_span(n, 'current')
prev = n
links
end
end | csn |
Returns the WorkspaceResources instance that provides access to Workspace resources.
@return the workspace resources | public WorkspaceResources workspaceResources() {
if (workspaces.get() == null) {
workspaces.compareAndSet(null, new WorkspaceResourcesImpl(this));
}
return workspaces.get();
} | csn |
- - - - - -
i a u T r
- - - - - -
Transpose an r-matrix.
This function is part of the International Astronomical Union's
SOFA (Standards Of Fundamental Astronomy) software collection.
Status: vector/matrix support function.
Given:
r double[3][3] r-matrix
Returned:
rt double[3][3] transpose
Not... | public static function Tr(array $r, array &$rt) {
$wm = [];
$i;
$j;
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$wm[$i][$j] = $r[$j][$i];
}
}
IAU::Cr($wm, $rt);
return;
} | csn |
Create a placeholder image.
@param string $destination
The absolute file path where the image should be stored.
@param int $min_resolution
@param int $max_resolution
@return string
Path to image file. | public function image($destination, $min_resolution, $max_resolution) {
$extension = pathinfo($destination, PATHINFO_EXTENSION);
$min = explode('x', $min_resolution);
$max = explode('x', $max_resolution);
$width = rand((int) $min[0], (int) $max[0]);
$height = rand((int) $min[1], (int) $max[1]);
... | csn |
Constructor. Sets up communication infrastructure. | function paypal_curl($params = array()) {
foreach ($params as $name => $value) {
$this->setParam($name, $value);
}
} | csn |
Parses a port specification in two forms into the same form.
In the first form the specification is just an integer. In this case a
tuple is returned containing the same integer twice.
In the second form the specification is two numbers separated by a hyphen
('-' by default, specifiable with :param se... | def parsePortSpec(spec, separator='-'):
'''
Parses a port specification in two forms into the same form.
In the first form the specification is just an integer. In this case a
tuple is returned containing the same integer twice.
In the second form the specification is two numbers separated by a hy... | csn |
Qualify a template url
@param string $url The template to qualify
@param string $base A fully qualified template url used to qualify.
@return string|false The qualified template path or FALSE if the path could not be qualified | public function qualify($url, $base)
{
if(!parse_url($url, PHP_URL_SCHEME))
{
if ($url[0] != '/')
{
//Relative path
$url = dirname($base) . '/' . $url;
}
else
{
//Absolute path
... | csn |
Generate the array for a given element.
@return array | protected function defineElement($element, $name = null, $description = null, array $values = [], array $options = [], array $params = [])
{
return [
'name' => $name ?: $element,
'description' => $description,
'element' => $element,
'values' => $values,
... | csn |
Create a Batch Writer for single-use mutations in this class.
@return WriteBatch | protected function batchFactory()
{
return new WriteBatch(
$this->connection,
$this->valueMapper,
$this->databaseFromName($this->name)
);
} | csn |
recovers the data of the dataLogger and provides the recovered data to the connection via the replaylistener | @Override
public void recover() {
// not revoverable
if (this.getCoreConnection() == null || !ImplementorUtils.isImplementationOf(getCoreConnection(), IXADataRecorderAware.class)) {
return;
}
IXADataRecorderAware con = ImplementorUtils.cast(getCoreConnection(), IXADataR... | csn |
Apply the zip operator to a set of variables.
This uses the python zip iterator to combine multiple lists of variables such that
the nth variable in each list is aligned.
Args:
variables: The variables object
parent: Unused | def iterator_zip(variables: VarType, parent: str = None) -> Iterable[VarMatrix]:
"""Apply the zip operator to a set of variables.
This uses the python zip iterator to combine multiple lists of variables such that
the nth variable in each list is aligned.
Args:
variables: The variables object
... | csn |
Converts the Request to a plain JavaScript object, which is also how the request is
represented in a collection file.
@returns {{url: (*|string), method: *, header: (undefined|*), body: *, auth: *, certificate: *}} | function () {
var obj = PropertyBase.toJSON(this);
// remove header array if blank
if (_.isArray(obj.header) && !obj.header.length) {
delete obj.header;
}
return obj;
} | csn |
u""" Transliterates given unicode `src` text
to transliterated variant according to a given transliteration table.
Official ukrainian transliteration is used by default
:param src: string to transliterate
:type src: str
:param table: transliteration table
:type table: transliteration table obje... | def translit(src, table=UkrainianKMU, preserve_case=True):
u""" Transliterates given unicode `src` text
to transliterated variant according to a given transliteration table.
Official ukrainian transliteration is used by default
:param src: string to transliterate
:type src: str
:param table: tr... | csn |
Returns the localized list of supported examples modes
@return array | public static function available_example_modes_list() {
$options = array();
$options[self::EXAMPLES_VOLUNTARY] = get_string('examplesvoluntary', 'workshop');
$options[self::EXAMPLES_BEFORE_SUBMISSION] = get_string('examplesbeforesubmission', 'workshop');
$options[self::EXAMPLES_B... | csn |
Downloads a segmentation image.
Parameters
----------
plate_id: int
ID of the parent experiment
mapobject_type_name: str
name of the segmented objects
plate_name: str
name of the plate
well_name: str
name of the well in whi... | def download_segmentation_image(self, mapobject_type_name,
plate_name, well_name, well_pos_y, well_pos_x, tpoint=0, zplane=0, align = False):
'''Downloads a segmentation image.
Parameters
----------
plate_id: int
ID of the parent experiment
mapobject_type... | csn |
// MapClientIp creates a mapper that allows rate limiting of requests per client ip | func MapClientIp(req request.Request) (string, int64, error) {
t, err := RequestToClientIp(req)
return t, 1, err
} | csn |
Clears the threads snapshot. | def clear_threads(self):
"""
Clears the threads snapshot.
"""
for aThread in compat.itervalues(self.__threadDict):
aThread.clear()
self.__threadDict = dict() | csn |
Date a proxy record
Parameters
----------
proxy : ProxyRecord
how : str
How to perform the dating. 'median' returns the average of the MCMC ensemble. 'ensemble' returns a 'n'
randomly selected members of the MCMC ensemble. Default is 'median'.
n : int
... | def date(self, proxy, how='median', n=500):
"""Date a proxy record
Parameters
----------
proxy : ProxyRecord
how : str
How to perform the dating. 'median' returns the average of the MCMC ensemble. 'ensemble' returns a 'n'
randomly selected members of the ... | csn |
Assert if the strategy is ok when the internal url already has a public url.
@param string $conflictingInternalUrlStrategy
@return void | public static function validateInternalConflictingStrategy($conflictingInternalUrlStrategy)
{
if (!in_array($conflictingInternalUrlStrategy, [self::STRATEGY_IGNORE, self::STRATEGY_MOVE_PREVIOUS_TO_NEW, self::STRATEGY_MOVE_NEW_TO_PREVIOUS])) {
throw new \InvalidArgumentException("Invalid \$confli... | csn |
// GetQueriesRegexp returns the expanded regular expressions used to match the
// route queries.
// This is useful for building simple REST API documentation and for instrumentation
// against third-party services.
// An error will be returned if the route does not have queries. | func (r *Route) GetQueriesRegexp() ([]string, error) {
if r.err != nil {
return nil, r.err
}
if r.regexp.queries == nil {
return nil, errors.New("mux: route doesn't have queries")
}
var queries []string
for _, query := range r.regexp.queries {
queries = append(queries, query.regexp.String())
}
return quer... | csn |
// Min returns minimun value of the given sample. | func Min(values []int64) int64 {
if len(values) == 0 {
return 0
}
if isSorted(values) {
return values[0]
}
min := values[0]
for i := 1; i < len(values); i++ {
v := values[i]
if min > v {
min = v
}
}
return min
} | csn |
Replace the HTML contained in an element by another piece of HTML.
@param {aria.templates.CfgBeans:Div} idOrElt div whose content have to be replaced
@param {String} newHTML html to set
@return {Object} Reference to the html element, or null if the element was not found in the DOM. If the
element was not found in the D... | function (idOrElt, newHTML) {
// PROFILING // var msr1 = this.$startMeasure("ReplaceHTML");
var domElt = idOrElt;
if (typeof(domElt) == "string") {
domElt = this.getElementById(domElt);
}
if (domElt) {
if ((ariaCoreBrowser.isIE... | csn |
Build the pluginRequest object
@return ActionRequest | protected function buildPluginRequest()
{
/** @var $parentRequest ActionRequest */
$parentRequest = $this->runtime->getControllerContext()->getRequest();
$pluginRequest = new ActionRequest($parentRequest);
$pluginRequest->setArgumentNamespace('--' . $this->getPluginNamespace());
... | csn |
// Checks whether or not that request is authorized based on the path and method
// It will extract the token out of the Authorization header and call the appropriate method | func (tam *TokenAuthorizationMiddleware) BearerRequestIsAuthorized(ctx context.Context, r *http.Request) (bool, error) {
token := tam.TokenFromBearerRequest(ctx, r)
xptid := r.Header.Get("X-PacketFence-Tenant-Id")
tokenInfo, _ := tam.tokenBackend.TokenInfoForToken(token)
if tokenInfo == nil {
return false, erro... | csn |
Generate an array contining all nececerry value to generate a form
with Twig.
@return array The form fields data | public function generate()
{
$form = collect([]);
// Loop all the the fields in the schema
foreach ($this->schema->all() as $name => $input) {
// Skip the one that don't have a `form` definition
if (isset($input['form'])) {
// Get the value from the... | csn |
Add listener for open events.
@param handler the event handler.
@return the HandlerRegistration that manages the listener. | @Nonnull
public final HandlerRegistration addOpenHandler( @Nonnull final OpenEvent.Handler handler )
{
return _eventBus.addHandler( OpenEvent.getType(), handler );
} | csn |
Process a key pair object after it was retrieved from the provider. Purpose
is to unlock secure key pairs.
@param KeyPairInterface $keyPair Key pair object that was just retrieved
@return KeyPairInterface Original instance of the key pair | protected function afterRetrieveKeyPair(KeyPairInterface $keyPair)
{
if ($keyPair instanceof SecureKeyPairInterface) {
$masterKeyPairProvider = $this->getMasterKeyPairProvider();
$masterKeyName = $this->getMasterKeyName();
if ($masterKeyPairProvider === null || !$masterKe... | csn |
Adds a path | int addPathFromMultiPath(MultiPath multi_path, int ipath, boolean as_polygon) {
int newgeom = createGeometry(as_polygon ? Geometry.Type.Polygon
: Geometry.Type.Polyline, multi_path.getDescription());
MultiPathImpl mp_impl = (MultiPathImpl) multi_path._getImpl();
if (multi_path.getPathSize(ipath) < 2)
retu... | csn |
Decode the RTP packet. | def decode(self, byteStream):
"""Decode the RTP packet."""
self.header = bytearray(byteStream[:HEADER_SIZE])
self.payload = byteStream[HEADER_SIZE:] | csn |
// CTCLoss returns the ctc costs and gradients, given the probabilities and labels. | func (co *Context) CTCLoss(probsDesc *TensorDescriptor, probs Memory, labels []int, labelLengths []int, inputLengths []int, costs Memory, gradientsDesc *TensorDescriptor, gradients Memory, algo CTCLossAlgo, ctcLossDesc *CTCLoss, workspace Memory, workSpaceSizeInBytes uintptr) error {
// DOUBLECHECK: "cudnnCTCLoss" ret... | csn |
Compute an initial feasible solution by assigning zero labels to the
workers and by assigning to each job a label equal to the minimum cost
among its incident edges. | protected void computeInitialFeasibleSolution() {
for (int j = 0; j < dim; j++) {
labelByJob[j] = Double.POSITIVE_INFINITY;
}
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
if (costMatrix[w][j] < labelByJob[j]) {
labelB... | csn |
// WriteReader adds an io.Reader to get the content of a file. The reader is
// not accessed until the multipart.Reader is copied to some output writer. | func (m *MultipartStreamer) WriteReader(key, filename string, size int64, reader io.Reader) (err error) {
m.reader = reader
m.contentLength = size
_, err = m.bodyWriter.CreateFormFile(key, filename)
return
} | csn |
r"""Defines command line options
Args:
**kwargs:
key: A name for the option.
value : Default value or a tuple of (default value, description).
Returns:
None
For example,
```
# Either of the following two lines will define `--n_epoch` command line argument and set its ... | def sg_arg_def(**kwargs):
r"""Defines command line options
Args:
**kwargs:
key: A name for the option.
value : Default value or a tuple of (default value, description).
Returns:
None
For example,
```
# Either of the following two lines will define `--n_epoch` comm... | csn |
// IncAll increments all instances by the same value and panics on an error | func (g *PCPGaugeVector) IncAll(val float64) {
for ins := range g.indom.instances {
g.MustInc(val, ins)
}
} | csn |
the character encoding of the request, usually only set in POST type requests | def encoding(self):
"""the character encoding of the request, usually only set in POST type requests"""
encoding = None
ct = self.get_header('content-type')
if ct:
ah = AcceptHeader(ct)
if ah.media_types:
encoding = ah.media_types[0][2].get("charse... | csn |
Method returns class alias by given class name.
@param string $className with namespace.
@return string|null | public function getClassAliasName($className)
{
/*
* Sanitize input: class names in namespaces should not, but may include a leading backslash
*/
$className = ltrim($className, '\\');
$classAlias = array_search($className, $this->classMap);
if ($classAlias === fals... | csn |
Render the polygons as an image and then do a pixel-by-pixel comparison
against the target image. The fitness score is the total error. A lower
score means a closer match.
@param candidate The image to evaluate.
@param population Not used.
@return A number indicating how close the candidate image is to the target ima... | public double getFitness(List<ColouredPolygon> candidate,
List<? extends List<ColouredPolygon>> population)
{
// Use one renderer per thread because they are not thread safe.
Renderer<List<ColouredPolygon>, BufferedImage> renderer = threadLocalRenderer.get();
if ... | csn |
Read messages.
@return \StdClass | protected function readMessages()
{
$len = $this->readHeader('v', 2);
$instructions = rtrim($this->readHeaderRaw($len), "\0");
$len = $this->readHeader('v', 2);
$hints = rtrim($this->readHeaderRaw($len), "\0");
$len = $this->readHeader('v', 2);
$victory = rtrim($this-... | csn |
// NodeAddresses returns the NodeAddresses of the instance with the specified nodeName. | func (v *Cloud) NodeAddresses(ctx context.Context, nodeName types.NodeName) ([]v1.NodeAddress, error) {
name := mapNodeNameToInstanceName(nodeName)
instance, err := v.fetchInstance(name)
if err != nil {
return nil, err
}
var address net.IP
if instance.IPAddress != "" {
address = net.ParseIP(instance.IPAddre... | csn |
// addAuthorizationToRequest adds an Authorization header to an http.Request, having ensured
// that the token is sufficiently fresh. This may invoke network calls, so should not be
// relied on to return quickly. | func (tr *tokenRequester) addAuthorizationToRequest(request *retryablehttp.Request) error {
token, err := tr.getUsableToken()
if err != nil {
return fmt.Errorf("Error obtaining authorization token: %s", err)
}
request.Header.Add("Authorization", fmt.Sprintf("%s %s", token.TokenType, token.AccessToken))
return n... | csn |
This function uses woodoo magic to resolve package class name
@param string $name
@throws \Exception
@return string | public function resolvePackage($name)
{
$packages = $this->getPackages();
//most commonly we have Foobar or SupraPackageFoobar, which maps directly to package class
//the other options is "foobar", which is mapped to AbstractPackage::getName
foreach ($packages as $instance) {
$class = get_class($instance);... | csn |
Builds and returns the resolver handler chain
@return ResolverHandlerInterface | private function getResolverHandlerChain()
{
$randomResolver = $this->resolverFactory->create(Random::class);
$nonMutualResolver = $this->resolverFactory->create(NonMutual::class, $randomResolver);
return $this->resolverFactory->create(FromExistingPair::class, $nonMutualResolver);
} | csn |
Load a rotation scheme and other options from a configuration file.
:param location: Any value accepted by :func:`coerce_location()`.
:returns: The configured or given :class:`Location` object. | def load_config_file(self, location):
"""
Load a rotation scheme and other options from a configuration file.
:param location: Any value accepted by :func:`coerce_location()`.
:returns: The configured or given :class:`Location` object.
"""
location = coerce_location(loca... | csn |
Create table of key-value items in 'file_type'. | def make_basic_table(self, file_type):
""" Create table of key-value items in 'file_type'.
"""
table_data = {sample: items['kv']
for sample, items
in self.mod_data[file_type].items()
}
table_headers = {}
for column_header, (description, h... | csn |
// TaskGroupStatus returns the eligibility status of the task group. | func (e *EvalEligibility) TaskGroupStatus(tg, class string) ComputedClassFeasibility {
// COMPAT: Computed node class was introduced in 0.3. Clients running < 0.3
// will not have a computed class. The safest value to return is the escaped
// case, since it disables any optimization.
if class == "" {
return EvalC... | csn |
// ArchiveBlockReferences implements the BlockServer interface for
// BlockServerRemote | func (b *BlockServerRemote) ArchiveBlockReferences(ctx context.Context,
tlfID tlf.ID, contexts kbfsblock.ContextMap) (err error) {
ctx = rpc.WithFireNow(ctx)
b.log.LazyTrace(ctx, "BServer: ArchiveRef %v", contexts)
defer func() {
b.log.LazyTrace(ctx, "BServer: ArchiveRef %v done (err=%v)", contexts, err)
if err... | csn |
// Get gets the object for the given key. | func (cd *Codec) Get(key string, object interface{}) error {
return cd.get(nil, key, object)
} | csn |
Produce lemmas from a tokenized sentence and its postags.
@param tokens the tokens
@param posTags the pos tags
@return the lemmas | public List<String> lemmatize(String[] tokens, String[] posTags) {
String[] annotatedLemmas = lemmatizer.lemmatize(tokens, posTags);
String[] decodedLemmas = lemmatizer.decodeLemmas(tokens, annotatedLemmas);
final List<String> lemmas = new ArrayList<String>(Arrays.asList(decodedLemmas));
return lemmas;
... | csn |
// Noop keeps a session alive. | func (c *Client) Noop() (err error) {
res := struct {
Status string `xmlrpc:"status"`
}{}
err = c.Call("NoOperation", []interface{}{c.Token}, &res)
if err == nil && res.Status != StatusSuccess {
err = fmt.Errorf("NoOp: %s", res.Status)
}
return
} | csn |
Relays are entities or routes, context is an array of values required for
the match, among these values "owner" is a special idenfication value.
For inpage elements you must provide attribute restrictions. An
attribute is an element on the page.
@return boolean | function matches($entity, array $context = null, $attribute = null) {
// cycle though acceptable entities
foreach ($this->entities as $name) {
// found an entity
if ($name === $entity) {
if ($this->parameters !== null) {
// we check if every paramter registered for this permission
// definition... | csn |
Lock resources from the command line, for example for maintenance. | def lock(resources, *args, **kwargs):
""" Lock resources from the command line, for example for maintenance. """
# all resources are locked if nothing is specified
if not resources:
client = redis.Redis(decode_responses=True, **kwargs)
resources = find_resources(client)
if not resources... | csn |
// Use appends a middleware to the existing middleware chain. | func (app *Application) Use(m ...MiddlewareHandlerFunc) {
for _, fn := range m {
app.middlewareChain.Append(fn)
}
app.handlerChain = app.middlewareChain.Final(app.handler)
} | csn |
Delete Display Profile.
@return bool | public function delete()
{
$this->getLogger()->info('Deleting Display profile ID ' . $this->displayProfileId);
$this->doDelete('/displayprofile/' . $this->displayProfileId);
return true;
} | csn |
Gets a list of the third party identifiers that the homeserver has associated with the user's account.
@return mixed|null 3pid list
@throws Exception | public function get3pid()
{
if ($this->check()) {
return $this->matrix()->request('GET', $this->endpoint('account/3pid'), [], [
'access_token' => $this->data['access_token']
]);
}
throw new \Exception('Not authenticated');
} | csn |
Set schemaspy command parameters.
@return array | protected function setParameters()
{
$parameters = [];
// Set output directory
$parameters['-o'] = Config::get('spy.output', base_path('database/schema'));
// Set database connection details
$connections = Config::get('database.connections', []);
$connection = ($this->argument('connection')) ?: Config::g... | csn |
Parses an integer constant pool entry. | private IntegerConstant parseIntegerConstant(int index)
throws IOException
{
int value = readInt();
return new IntegerConstant(_class.getConstantPool(), index, value);
} | csn |
Override this method to provide the ordering of the sort.
<p>
if lhs should be build before rhs, return a negative value. Or put another way, think of the comparison
as a process of converting a {@link BuildableItem} into a number, then doing num(lhs)-num(rhs).
<p>
The default implementation does FIFO. | public int compare(BuildableItem lhs, BuildableItem rhs) {
return compare(lhs.buildableStartMilliseconds,rhs.buildableStartMilliseconds);
} | csn |
Search the document for UL elements with the correct CLASS name, then process them | function convertTrees() {
setDefault("treeClass","mktree");
setDefault("nodeClosedClass","liClosed");
setDefault("nodeOpenClass","liOpen");
setDefault("nodeBulletClass","liBullet");
setDefault("nodeLinkClass","bullet");
setDefault("preProcessTrees",true);
if (preProcessTrees) {
if (!document.createElement) { r... | csn |
Returns textarea filled with text to edit.
@param int $width editor width
@param int $height editor height
@param \OxidEsales\Eshop\Core\Model\BaseModel $object object passed to editor
@param string $field object fi... | protected function _getPlainEditor($width, $height, $object, $field)
{
$objectValue = $this->_getEditValue($object, $field);
$textEditor = oxNew(\OxidEsales\Eshop\Application\Controller\TextEditorHandler::class);
return $textEditor->renderPlainTextEditor($width, $height, $objectValue, $fie... | csn |
Calls is_a_string and raises a type error if the check fails. | def check_is_a_string(var, allow_none=False):
""" Calls is_a_string and raises a type error if the check fails.
"""
if not is_a_string(var, allow_none=allow_none):
raise TypeError("var must be a string, however type(var) is {}"
.format(type(var))) | csn |
Safely change to a state
todo check if state direction matches
@param $state
@return boolean | public function changeState($state)
{
$availableStates = $this->dbObject('Status')->enumValues();
if (in_array($state, $availableStates)) {
$this->Status = $state;
return true;
} else {
user_error(_t('Reservation.STATE_CHANGE_ERROR', 'Selected state is not... | csn |
validated object contain 'get or 'is' Method
@param vo ValidateClass
@param getOrIs 'get or 'is' String
@param cpmd ConfigProperty metadata
@param section section in the spec document
@param failMsg fail or warn message
@param failures list of failures
@throws NoSuchMethodException | private static void containGetOrIsMethod(ValidateClass vo, String getOrIs,
ConfigProperty cpmd, String section, String failMsg, List<Failure> failures)
throws NoSuchMethodException
{
String methodName = getOrIs + cpmd.getConfigPropertyName().getValue().substring(0, 1).toUpperCase(Locale.US);
... | csn |
Method to delete a Rest Api named defined in the swagger file's Info Object's title value.
ret
a dictionary for returning status to Saltstack | def delete_api(self, ret):
'''
Method to delete a Rest Api named defined in the swagger file's Info Object's title value.
ret
a dictionary for returning status to Saltstack
'''
exists_response = __salt__['boto_apigateway.api_exists'](name=self.rest_api_name,
... | csn |
Require a new composer package.
@param string $package
@return void | public function install($package)
{
if (! is_null($package)) {
$package = '"'.$package.'"';
}
$process = $this->getProcess();
$process->setCommandLine(trim($this->findComposer().' require '.$package));
$process->run($this->output);
} | csn |
Create a ORCSchemaProvider from it's fully qualified class name. The
class passed in by name must be assignable to ORCSchemaProvider and have
1-parameter constructor accepting a SecorConfig. Allows the ORCSchemaProvider
to be pluggable by providing the class name of a desired ORCSchemaProvider in
config.
See the secor... | public static ORCSchemaProvider createORCSchemaProvider(
String className, SecorConfig config) throws Exception {
Class<?> clazz = Class.forName(className);
if (!ORCSchemaProvider.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format(
... | csn |
// Convert_v1alpha1_SchedulerPolicyConfigMapSource_To_config_SchedulerPolicyConfigMapSource is an autogenerated conversion function. | func Convert_v1alpha1_SchedulerPolicyConfigMapSource_To_config_SchedulerPolicyConfigMapSource(in *v1alpha1.SchedulerPolicyConfigMapSource, out *config.SchedulerPolicyConfigMapSource, s conversion.Scope) error {
return autoConvert_v1alpha1_SchedulerPolicyConfigMapSource_To_config_SchedulerPolicyConfigMapSource(in, out,... | csn |
Deletes user,
called from bulkDelete and delete functions.
@param int $id
@return array|bool | private function deleteUser($id)
{
// check if user has permissions to access this link
if(!User::hasAccess('user', 'delete')) {
return $this->noPermission();
}
$user = User::find($id);
// user can't be deleted if it has related data to him, like posts, categorie... | csn |
Handles the creation of the LTPA file monitor. | private void createFileMonitor() {
try {
ltpaFileMonitor = new SecurityFileMonitor(this);
setFileMonitorRegistration(ltpaFileMonitor.monitorFiles(Arrays.asList(keyImportFile), monitorInterval));
} catch (Exception e) {
if (TraceComponent.isAnyTracingEnabled() && tc.is... | csn |
Compile the rules into the internal lexer state. | def _compile_rules(self):
"""Compile the rules into the internal lexer state."""
for state, table in self.RULES.items():
patterns = list()
actions = list()
nextstates = list()
for i, row in enumerate(table):
if len(row) == 2:
... | csn |
Given a single search result, create and return an object
:param tuple search_result: a single search result returned by an LDAP query,
position 0 is the DN and position 1 is a dictionary of key/value pairs
:return: A single AD object instance
:rtype: Object (ADUser, ADGroup, etc.) | def _object_factory(self, search_result):
"""Given a single search result, create and return an object
:param tuple search_result: a single search result returned by an LDAP query,
position 0 is the DN and position 1 is a dictionary of key/value pairs
:return: A single AD object in... | csn |
Reset x and y scales | def reset_position_scales(self):
"""
Reset x and y scales
"""
if not self.facet.shrink:
return
with suppress(AttributeError):
self.panel_scales_x.reset()
with suppress(AttributeError):
self.panel_scales_y.reset() | csn |
Populate columns necessary for an RV dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables` | def _populate_rv(self, dataset, **kwargs):
"""
Populate columns necessary for an RV dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables`
"""
logger.debug("{}._populate_rv(dataset={})".format(se... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.