query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
split a FileName in Parts
@param fileName
@return new String[]{name[,extension]} | public static String[] splitFileName(String fileName) {
int pos = fileName.lastIndexOf('.');
if (pos == -1) {
return new String[] { fileName };
}
return new String[] { fileName.substring(0, pos), fileName.substring(pos + 1) };
} | csn |
Gets last seen configuration.
@return the last seen configuration.
@throws IOException in case of IO failure. | ClusterConfiguration getLastSeenConfig() throws IOException {
File file = getLatestFileWithPrefix(this.rootDir, "cluster_config");
if (file == null) {
return null;
}
try {
Properties prop = FileUtils.readPropertiesFromFile(file);
return ClusterConfiguration.fromProperties(prop);
} ... | csn |
Check for any mysql errors. | public function throwErrorIfNoRowsAffected($sqlStatement, $ignoreDuplicate = false)
{
if (! $this->hasFetchedRows($sqlStatement)) {
$error = print_r($sqlStatement->errorInfo(), true);
if ($ignoreDuplicate and preg_match('/duplicate/i', $error)) {
return $sqlStatement... | csn |
Sync the device to the cluster group
:param device: bigip object -- device to sync to group | def _sync_to_group(self, device):
'''Sync the device to the cluster group
:param device: bigip object -- device to sync to group
'''
config_sync_cmd = 'config-sync to-group %s' % self.name
device.tm.cm.exec_cmd('run', utilCmdArgs=config_sync_cmd) | csn |
Get the current Render for this response.
@return INabuHTTPResponseRender Returns tge Render instance. | public function getRender()
{
if ($this->render_factory !== null) {
$retval = $this->render_factory->getInterface();
} else {
$retval = $this->render;
}
return $retval;
} | csn |
Creates a Polygon formed by the given shell.
@param shell
@return | public static Polygon makePolygon(Geometry shell) throws IllegalArgumentException {
if(shell == null) {
return null;
}
LinearRing outerLine = checkLineString(shell);
return shell.getFactory().createPolygon(outerLine, null);
} | csn |
Build result map in provided path and write result to file
@param string $file
@param array|string $searchPath | public static function build($file, $searchPath)
{
$builder = self::getInstance();
$searchPath = empty($searchPath) ? __DIR__ : $searchPath;
$searchPath = (array) $searchPath;
$builder->setFile($file);
$builder->readMap();
foreach ($searchPath as $folder) {
... | csn |
// FromTrigger derives the request properties from the given trigger. | func (r *RequestBuilder) FromTrigger(t *internal.Trigger) {
switch p := t.Payload.(type) {
case *internal.Trigger_Cron:
r.FromCronTrigger(p.Cron)
case *internal.Trigger_Webui:
r.FromWebUITrigger(p.Webui)
case *internal.Trigger_Noop:
r.FromNoopTrigger(p.Noop)
case *internal.Trigger_Gitiles:
r.FromGitilesTri... | csn |
Returns the MongoDB database with the given name.
@param string|null $name database name, if null default one will be used.
@param bool $refresh whether to reestablish the database connection even, if it is found in the cache.
@return Database database instance. | public function getDatabase($name = null, $refresh = false)
{
if ($name === null) {
$name = $this->getDefaultDatabaseName();
}
if ($refresh || !array_key_exists($name, $this->_databases)) {
$this->_databases[$name] = $this->selectDatabase($name);
}
re... | csn |
a burrito. a lettuce burrito with ketchup and raspberry. | def describe_dish(self):
"""a burrito. a lettuce burrito with ketchup and raspberry."""
resp = random.choice(foodpreparations)
if random.random() < .85:
resp = self.describe_ingredient() + ' ' + resp
if random.random() < .2:
resp = self.describe_ingredient... | csn |
Returns the charcode for an event
@method getCharCode
@param {Event} ev the event
@return {int} the event's charCode
@static | function(ev) {
var code = ev.keyCode || ev.charCode || 0;
// webkit key normalization
if (YAHOO.env.ua.webkit && (code in webkitKeymap)) {
code = webkitKeymap[code];
}
return code;
} | csn |
Finds all the graph files that can be imported.
@param appDirectory the application's directory
@param editedFile the graph file that is being edited
@param fileContent the file content (not null)
@return a non-null set of (relative) file paths | public static Set<String> findGraphFilesToImport( File appDirectory, File editedFile, String fileContent ) {
File graphDir = new File( appDirectory, Constants.PROJECT_DIR_GRAPH );
return findFilesToImport( graphDir, Constants.FILE_EXT_GRAPH, editedFile, fileContent );
} | csn |
Retorna todas as linhas destes detalhes.
@return string | public function getEncoded()
{
$text = array();
foreach ($this->listSegmento() as $segmento) {
$text[] = $segmento->getEncoded();
}
return implode(Arquivo::QUEBRA_LINHA, $text);
} | csn |
Sends a single, synchronous HTTP POST request to the agent. This function is synchronous, that is, it blocks the
event loop!
YOU MUST NOT USE THIS FUNCTION, except for the one use case where it is actually required to block the event loop
(reporting an uncaught exception tot the agent in the process.on('uncaughtExcept... | function sendHttpPostRequestSync(port, path, data) {
logger.debug({ payload: data }, 'Sending payload synchronously to %s', path);
try {
var payload = JSON.stringify(data);
var payloadLength = buffer.fromString(payload, 'utf8').length;
} catch (payloadSerializationError) {
logger.warn('Could not seria... | csn |
Remove tags from a trail
Returns {tagged: true} if the trail was tagged and returns
{tagged: False} if the trail was not tagged.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.remove_tags my_trail tag_a=tag_value tag_b=tag_value | def remove_tags(TagKeys, DomainName=None, ARN=None,
region=None, key=None, keyid=None, profile=None):
'''
Remove tags from a trail
Returns {tagged: true} if the trail was tagged and returns
{tagged: False} if the trail was not tagged.
CLI Example:
.. code-block:: bash
salt... | csn |
Creates a vector given its origin and destiny points
@param {Vector} pointA - vector origin
@param {Vector} pointB - vector point
@return {Vector} Resulting vector | function( pointA, pointB ) {
return { x: pointB.x - pointA.x, y: -( pointB.y - pointA.y ) };
} | csn |
Creates a plan for an SQL select statement, using the supplied planner.
@param qry
the SQL query string
@param tx
the transaction
@return the scan corresponding to the query plan | public Plan createQueryPlan(String qry, Transaction tx) {
Parser parser = new Parser(qry);
QueryData data = parser.queryCommand();
Verifier.verifyQueryData(data, tx);
return qPlanner.createPlan(data, tx);
} | csn |
// Rename via afero.Fs.Rename | func (fs *fakeFs) Rename(oldpath, newpath string) error {
return fs.a.Fs.Rename(oldpath, newpath)
} | csn |
Return localized string with file permissions
@param Object file
@return String | function(f) {
var p = [];
f.read && p.push(this.i18n('read'));
f.write && p.push(this.i18n('write'));
return p.length ? p.join(' '+this.i18n('and')+' ') : this.i18n('noaccess');
} | csn |
after configuring a connection with .new - send commands via ssh to open directory
@command [Symbol] - required -- to choose the action wanted
@params [Hash] - required -- necessary information to accomplish action
@output [String] - optional -- 'xml' or 'plist' will return responses using xml format
response [Hash... | def run(command:, params:, output: nil)
answer = {}
params[:format] = output
# just in case clear record_name and calculate later
params[:record_name] = nil
ssh_cmds = send(command, params, dir_info)
# pp ssh_cmds
results = send_cmds_to_od_server(ssh_cmds)
# pp results
... | csn |
Compile a file and returns the compiled file's path. | def compile_file(self, filepath, write=True, package=False, *args, **kwargs):
"""Compile a file and returns the compiled file's path."""
set_ext = False
if write is False:
destpath = None
elif write is True:
destpath = filepath
set_ext = True
e... | csn |
Parse a YAML specification of a service port connector into this
object. | def parse_yaml(self, y):
'''Parse a YAML specification of a service port connector into this
object.
'''
self.connector_id = y['connectorId']
self.name = y['name']
if 'transMethod' in y:
self.trans_method = y['transMethod']
else:
self.tran... | csn |
// AddP2PKHInput updates the weight estimate to account for an additional input
// spending a P2PKH output. | func (twe *TxWeightEstimator) AddP2PKHInput() *TxWeightEstimator {
twe.inputSize += InputSize + P2PKHScriptSigSize
twe.inputWitnessSize++
twe.inputCount++
return twe
} | csn |
Configure state and files on disk to match current processing status.
:param str status: Name of new status designation for pipeline. | def _set_status_flag(self, status):
"""
Configure state and files on disk to match current processing status.
:param str status: Name of new status designation for pipeline.
"""
# Remove previous status flag file.
flag_file_path = self._flag_file_path()
try:
... | csn |
Gets all the services in the application resource.
The operation returns the service descriptions of all the services in the
application resource.
@param application_resource_name [String] Service Fabric application resource
name.
@param custom_headers [Hash{String => String}] A hash of custom headers that
will... | def get_services(application_resource_name, custom_headers:nil)
response = get_services_async(application_resource_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end | csn |
"Two quantities are equivalent values for a command if either both are null, or both are strings and they're equal and the command does not define any equivalent values, or both are strings and the command defines equivalent values and they match the definition." | function areEquivalentValues(command, val1, val2) {
if (val1 === null && val2 === null) {
return true;
}
if (typeof val1 == "string"
&& typeof val2 == "string"
&& val1 == val2
&& !("equivalentValues" in commands[command])) {
return true;
}
if (typeof val1 == "string"
&& typeof val2 == "string"
&& "equiv... | csn |
Increment the number of killed tasks on a tracker.
@param trackerName The name of the tracker. | public void recordKilledTask(String trackerName) {
synchronized (this) {
NodeUsageReport usageReport = getReportUnprotected(trackerName);
usageReport.setNumKilled(usageReport.getNumKilled() + 1);
}
} | csn |
Parse
Parse a CSV file or string
@param string|null $input The CSV string or a direct file path
@param integer $offset Number of rows to ignore from the
beginning of the data
@param integer $limit Limits the number of returned rows to
specified amount
@param string $conditions Basic SQL... | public function parse($input = null, $offset = null, $limit = null, $conditions = null) {
if (is_null($input)) {
$input = $this->file;
}
if (empty($input)) {
return false;
}
$this->init($offset, $limit, $conditions);
if (strlen($input) <= PHP_MA... | csn |
// removeSettings removes the Settings for key. | func removeSettings(db Database, collection, key string) error {
err := db.RunTransaction([]txn.Op{removeSettingsOp(collection, key)})
if err == txn.ErrAborted {
return errors.NotFoundf("settings")
} else if err != nil {
return errors.Trace(err)
}
return nil
} | csn |
Add tracks to the playlist.
If no $position is passed the track will be added to the end of the playlist
@param UriInterface[] $tracks The tracks to add
@param int $position The position to insert the track in the playlist (zero-based)
@return void | protected function addUris(array $tracks, int $position = null)
{
if ($position === null) {
$position = $this->getNextPosition();
}
foreach ($tracks as $track) {
$data = $this->soap("AVTransport", "AddURIToSavedQueue", [
"UpdateID" => $t... | csn |
Check if provided value is an array
@param value
@param {string} message
@param {string} id
@returns void | function isArray(value, message, id) {
if (message === void 0) { message = ''; }
if (id === void 0) { id = ''; }
if (this.enabled && !Array.isArray(value)) {
throw TypeException.unexpectedType(assertionTypes.IS_ARRAY, value, '<array>', message, id);
}
} | csn |
// CreateDomain instructs Mailgun to create a new domain for your account.
// The name parameter identifies the domain.
// The smtpPassword parameter provides an access credential for the domain.
// The spamAction domain must be one of Delete, Tag, or Disabled.
// The wildcard parameter instructs Mailgun to treat all s... | func (mg *MailgunImpl) CreateDomain(ctx context.Context, name string, opts *CreateDomainOptions) (DomainResponse, error) {
r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint))
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
payload := newUrlEncodedPayload()
payload.addValue("name", n... | csn |
Thrown if the class isn't mapped.
@param aClass class to analyze | public static void classNotMapped(Class<?> aClass){
throw new ClassNotMappedException(MSG.INSTANCE.message(classNotMappedException1,aClass.getSimpleName()));
} | csn |
Configure the TensorFlow logger. | def set_up_logging():
"""Configure the TensorFlow logger."""
tf.logging.set_verbosity(tf.logging.INFO)
logging.getLogger('tensorflow').propagate = False | csn |
Append volume mappings to the runtime option list. | def add_volumes(self,
pathmapper, # type: PathMapper
runtime, # type: List[Text]
tmpdir_prefix, # type: Text
secret_store=None, # type: Optional[SecretStore]
any_path_okay=False # type: bool... | csn |
Returns a promise that is resolved when all promises in the results array are settled. The promise returned from this function is always resolved, never rejected. This function modifies the input argument, it replaces the promises with the value returned from the promise. | function(results) {
// Create a sequence of all the results starting with a resolved promise.
return results.reduce(function(memo, result) {
// If this result isn't a promise skip it in the sequence.
if (!v.isPromise(result.error)) {
return memo;
}
return memo.then... | csn |
a wrapper around GetProvider
@param provider_id [String] optional Allscripts user id
@param user_name [String] optional Allscripts user_name
@return [Array<Hash>, Array, MagicError] a list of providers | def get_provider(provider_id = nil, user_name = nil)
params =
MagicParams.format(
parameter1: provider_id,
parameter2: user_name
)
results = magic("GetProvider", magic_params: params)
results["getproviderinfo"]
end | csn |
// GetDisabledOrgs returns the DisabledOrgs field if it's non-nil, zero value otherwise. | func (o *OrgStats) GetDisabledOrgs() int {
if o == nil || o.DisabledOrgs == nil {
return 0
}
return *o.DisabledOrgs
} | csn |
A window of pricing data with adjustments applied assuming that the
end of the window is the day before the current simulation time.
Parameters
----------
assets : iterable of Assets
The assets in the window.
dts : iterable of datetime64-like
The datetime... | def history(self, assets, dts, field, is_perspective_after):
"""
A window of pricing data with adjustments applied assuming that the
end of the window is the day before the current simulation time.
Parameters
----------
assets : iterable of Assets
The assets ... | csn |
// RemoveEventListenerBreakpointWithParams - Removes breakpoint on particular DOM event. | func (c *DOMDebugger) RemoveEventListenerBreakpointWithParams(v *DOMDebuggerRemoveEventListenerBreakpointParams) (*gcdmessage.ChromeResponse, error) {
return gcdmessage.SendDefaultRequest(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "DOMDebugger.removeEventListenerBreakpoint",... | csn |
A string that will be automatically included at the beginning of the url generated for doing each http request.
:param value: The host to be connected with, e.g. (http://hostname) or (https://X.X.X.X:port) | def host(self, value):
"""
A string that will be automatically included at the beginning of the url generated for doing each http request.
:param value: The host to be connected with, e.g. (http://hostname) or (https://X.X.X.X:port)
"""
scheme, host, port = get_hostname_paramete... | csn |
// ByNodeID is a query option to select elements by their NodeIDs. | func ByNodeID(s *Selector) {
ids, ok := s.sel.([]cdp.NodeID)
if !ok {
panic("ByNodeID can only work on []cdp.NodeID")
}
ByFunc(func(ctx context.Context, n *cdp.Node) ([]cdp.NodeID, error) {
for _, id := range ids {
err := dom.RequestChildNodes(id).WithPierce(true).Do(ctx)
if err != nil {
return nil, ... | csn |
// initQueryParams extract the query parameters from the action params. | func (a *ActionDefinition) initQueryParams() {
// 3. Compute QueryParams from Params and set all path params as non zero attributes
if params := a.AllParams(); params != nil {
queryParams := DupAtt(params)
queryParams.Type = Dup(queryParams.Type)
if a.Params == nil {
a.Params = &AttributeDefinition{Type: Obj... | csn |
Make the server instance.
@param string $name
@return GlideServer | protected function makeServer($name)
{
$config = $this->getConfig($name);
if (empty($config)) {
throw new \InvalidArgumentException("Unable to instantiate Glide server because you provide en empty configuration, \"{$name}\" is probably a wrong server name.");
}
if (arra... | csn |
Tell whether the server is accepting new connections or shutting down. | def is_serving(self) -> bool:
"""
Tell whether the server is accepting new connections or shutting down.
"""
try:
# Python ≥ 3.7
return self.server.is_serving() # type: ignore
except AttributeError: # pragma: no cover
# Python < 3.7
... | csn |
Invoked when a bus itinerary was added in the attached line.
<p>This function exists to allow be override to provide a specific behaviour
when a bus itinerary has been added.
@param itinerary is the new itinerary.
@param index is the index of the bus itinerary.
@return <code>true</code> if the events was fired, other... | protected boolean onBusItineraryAdded(BusItinerary itinerary, int index) {
if (this.autoUpdate.get()) {
try {
addMapLayer(index, new BusItineraryLayer(itinerary, isLayerAutoUpdated()));
return true;
} catch (Throwable exception) {
//
}
}
return false;
} | csn |
Soften a BooleanSuppler that throws a checked exception into one that still throws the exception, but doesn't need to declare it.
<pre>
{@code
assertThat(ExceptionSoftener.softenBooleanSupplier(()->true).getAsBoolean(),equalTo(true));
BooleanSupplier supplier = ExceptionSoftener.softenBooleanSupplier(()->{throw new... | public static BooleanSupplier softenBooleanSupplier(final CheckedBooleanSupplier s) {
return () -> {
try {
return s.getAsBoolean();
} catch (final Throwable e) {
throw throwSoftenedException(e);
}
};
} | csn |
// WithCancel calls context.WithCancel and automatically
// updates context on the containing lars.Ctx object. | func (c *Ctx) WithCancel() context.CancelFunc {
ctx, cf := context.WithCancel(c.request.Context())
c.request = c.request.WithContext(ctx)
return cf
} | csn |
Set the protocol version
@param string $version
@return $this | public function withProtocolVersion($version)
{
if (!is_string($version)) {
throw new \InvalidArgumentException("Expected protocol version to be a string");
}
$this->protocolVersion = $version;
$this->sendStatusHeader();
return $this;
... | csn |
Recent posts widget
@return \Illuminate\Contracts\View\Factory|\Illuminate\View\View | public function recentBlogPosts($numPosts = 4)
{
$posts = BlogPost::where([
['status', '=', 'PUBLISHED'],
])->whereDate('published_date', '<=', Carbon::now())
->limit($numPosts)
->orderBy('created_at', 'desc')
->get();
return view("{$this->vie... | csn |
"IP not allowed" page
@return \Cake\Network\Response|null|void | public function ipNotAllowed()
{
//If the user's IP address is not banned
if (!$this->request->isBanned()) {
return $this->redirect($this->referer(['_name' => 'homepage'], true));
}
$this->viewBuilder()->setLayout('login');
} | csn |
// Retrieves a registered driver by name. | func GetDriver(name string) Driver {
driversMu.Lock()
defer driversMu.Unlock()
driver := drivers[name]
return driver
} | csn |
Parses the annotation-line down to its components.
array(
'namespace' => $namespace,
'name' => $name,
'attributes' => array(
'someKey' => 'someValue',
'otherKey' => 'otherValue',
),
'tags' => array(
'foo',
'bar',
'baz'
)
)
@return array | protected function parseData()
{
if (is_null($this->dataCache)) {
$patternNamespace = '(?P<namespace>[a-zA-Z0-9\\\\]+\\\\)?';
$patternName = '(?P<name>[a-zA-Z0-9]+)';
$patternString = '\"[^\"]*\"|\'[^\']*\'';
$patternFloat = '[0-9]+\.[0-9]+';
... | csn |
run validation of partial module configuration
@param array $data
@return Illuminate\Support\Facades\Response | public function run(ProcessListener $listener, array $data)
{
try {
if (empty($data)) {
throw new Exception\InvalidArgumentException('Invalid method arguments.');
}
$validator = null;
$values = null;
if (isset($data['cid'])) {
... | csn |
Return the path.
@param string $path
@return string | protected function getPath($path)
{
$pathsFile = __DIR__.'/../../../../../config/rinvex.composable.php';
$paths = file_exists($pathsFile) ? require $pathsFile : [];
return $paths[$path] ?? __DIR__.$this->paths[$path];
} | csn |
Validar valores pela regra.
@param array $rules
@param array|null $values
@param array $customAttrs
@return bool | protected function validate(array $rules, $values = null, array $customAttrs = [])
{
// Se os valores forem nulos, buscar no request
if (is_null($values)) {
$values = request()->all();
}
// Validar valores pela regra
return Validator::validate($values, $rules, $c... | csn |
Handles getting all entity links both dynamically set and via annotations and merges them together overriding with
the proper precedence order which is Dynamic > SubEntity > Entity. Href and uri's are resolved with the correct data
bound in.
@param builder assumed not <code>null</code>.
@param context assumed not <cod... | private void handleEntityLinks(EntityBuilder builder, EntityContext context) throws Siren4JException {
Class<?> clazz = context.getCurrentObject().getClass();
Map<String, Link> links = new HashMap<String, Link>();
/* Caution!! Order matters when adding to the links map */
Siren4J... | csn |
Refresh an instance on the given target and method.
@param string $abstract
@param mixed $target
@param string $method
@return mixed | public function refresh($abstract, $target, $method)
{
return $this->rebinding($abstract, function ($app, $instance) use ($target, $method) {
$target->{$method}($instance);
});
} | csn |
Called during serialization of the object.
You are not supposed to call this directly. Instead, use PHP's global
`serialize()` call:
```php
$savedStr = serialize($obj);
```
This serializer is thin and efficient. It simply recursively packs all
nested, internal `LazyJsonMapper` objects as a single, plain data array,
... | final public function serialize()
{
// Tell all of our LJM-properties to pack themselves as plain arrays.
// NOTE: We don't do any value-conversion or validation of properties,
// since that's not our job. The user wants to SERIALIZE our data, so
// translation of array entries to "c... | csn |
// NewShowcaseRestoredDetails returns a new ShowcaseRestoredDetails instance | func NewShowcaseRestoredDetails(EventUuid string) *ShowcaseRestoredDetails {
s := new(ShowcaseRestoredDetails)
s.EventUuid = EventUuid
return s
} | csn |
// BuildZip loades the given folder and include all the files on the zip. | func (b *Builder) BuildZip(folder string) error {
w := zip.NewWriter(b.Content)
defer w.Close()
if err := b.generateKeyIfNeeded(); err != nil {
return err
}
keyFile, err := w.Create(keyFilename)
if err != nil {
return err
}
size, err := b.saveKeyFile(keyFile)
if err != nil {
return err
}
fmt.Printf... | csn |
// ingestBundleEntry writes the data from `be` to disk
//
// Returns closed == true if `be` was terminal and the stream can be closed now. | func (s *stream) ingestBundleEntry(be *logpb.ButlerLogBundle_Entry) (closed bool, err error) {
for _, le := range be.GetLogs() {
curFile, err := s.getCurFile()
if err != nil {
return false, err
}
switch x := le.Content.(type) {
case *logpb.LogEntry_Datagram:
dg := x.Datagram
_, err = s.curFile.Writ... | csn |
Construct an Verifier instance from a public key or public
certificate string.
Args:
public_key (Union[str, bytes]): The public key in PEM format or the
x509 public key certificate.
Returns:
Verifier: The constructed verifier.
Raises:
... | def from_string(cls, public_key):
"""Construct an Verifier instance from a public key or public
certificate string.
Args:
public_key (Union[str, bytes]): The public key in PEM format or the
x509 public key certificate.
Returns:
Verifier: The cons... | csn |
Pads `string` on the left side if it is shorter then the given padding
length. The `chars` string may be truncated if the number of padding
characters exceeds the padding length.
@static
@memberOf _
@category Strings
@param {string} [string=''] The string to pad.
@param {number} [length=0] The padding length.
@param {... | function padLeft(string, length, chars) {
string = string == null ? '' : String(string);
return createPad(string, length, chars) + string;
} | csn |
Search prompt and send command, while process is opened
@yield [match] Send operations when found prompt
@yieldparam match [String] Expect matches string (prompt) | def do_on_interactive_process
until @reader.closed? || @reader.eof?
@reader.expect(expect_regexp, @timeout) do |match|
yield match
end
end
rescue Errno::EIO => error
# on linux, PTY raises Errno::EIO when spawned process closed.
@logger.debug "PTY raises Errno::EIO,... | csn |
Parse Genesis response to stdClass and
apply transformation to known fields
@param string $response
@throws \Genesis\Exceptions\ErrorAPI
@throws \Genesis\Exceptions\InvalidArgument
@throws \Genesis\Exceptions\InvalidResponse | public function parseResponse($response)
{
$this->responseRaw = $response;
try {
$parser = new \Genesis\Parser('xml');
$parser->skipRootNode();
$parser->parseDocument($response);
$this->responseObj = $parser->getObject();
} catch (\Exception ... | csn |
Return the usage string for the primary command. | def get_primary_command_usage(message=''):
# type: (str) -> str
"""Return the usage string for the primary command."""
if not settings.merge_primary_command and None in settings.subcommands:
return format_usage(settings.subcommands[None].__doc__)
if not message:
message = '\n{}\n'.format... | csn |
Set password DB settings.
@param string $name | public function setPasswordDb ($name)
{
$value = Yii::$app->settings->get($name);
if (empty($value))
{
return;
}
$this->password = $value;
} | csn |
Parse the next address. | def getaddress(self):
"""Parse the next address."""
self.commentlist = []
self.gotonext()
oldpos = self.pos
oldcl = self.commentlist
plist = self.getphraselist()
self.gotonext()
returnlist = []
if self.pos >= len(self.field):
# Bad e... | csn |
// DumpPacket prints a human-readable description of the packet. | func DumpPacket(packetData libmemif.RawPacketData) {
packet := gopacket.NewPacket(packetData, layers.LayerTypeEthernet, gopacket.Default)
fmt.Println(packet.Dump())
} | csn |
This method will get a runtime property from the sib.properties file as a boolean.
@param property The property key used to look up in the file.
@param defaultValue The default value if the property is not in the file.
@return Returns the property value. | public static boolean getRuntimeBooleanProperty(String property, String defaultValue)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getRuntimeBooleanProperty", new Object[] {property, defaultValue});
boolean runtimeProp = B... | csn |
Use thread pool for executing a task if self.enable_thread_pool is True.
Return an instance of future when flag is_async is True otherwise will to
block waiting for the result until timeout then returns the result. | def _enable_thread_pool(func):
"""
Use thread pool for executing a task if self.enable_thread_pool is True.
Return an instance of future when flag is_async is True otherwise will to
block waiting for the result until timeout then returns the result.
"""
@functools.wraps(func)
def wrapper(*... | csn |
// AddSSHKeyToAllInstances is not implemented for OpenStack | func (i *Instances) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error {
return cloudprovider.NotImplemented
} | csn |
// forEachBit executes fn for every bit set in the fragment.
// Errors returned from fn are passed through. | func (f *fragment) forEachBit(fn func(rowID, columnID uint64) error) error {
f.mu.Lock()
defer f.mu.Unlock()
var err error
f.storage.ForEach(func(i uint64) {
// Skip if an error has already occurred.
if err != nil {
return
}
// Invoke caller's function.
err = fn(i/ShardWidth, (f.shard*ShardWidth)+(i%... | csn |
validate block begin token
@param array<string,array|string|integer> $context current compile context
@param array<boolean|integer|string|array> $vars parsed arguments list
@return boolean Return true always | protected static function blockBegin(&$context, $vars) {
switch ((isset($vars[0][0]) && is_string($vars[0][0])) ? $vars[0][0] : null) {
case 'with':
return static::with($context, $vars);
case 'each':
return static::section($context, $vars, true);
... | csn |
simple function to generate the text of the task list so that it can be used in various places | function generateTaskList (user) {
var text = '';
for (var t = 0; t < user.tasks.length; t++) {
text = text + '> `' + (t + 1) + '`) ' + user.tasks[t] + '\n';
}
return text;
} | csn |
Convert the name of a month to the corresponding int value.
@return the int representation of the month. | private int parseMonth(String month) {
for (int i = 0; i < months.length; i++)
if (months[i].startsWith(month))
return i;
return -1;
} | csn |
// Unexport writes pin to pwm unexport path | func (p *PWMPin) Unexport() (err error) {
_, err = p.write(p.pwmUnexportPath(), []byte(p.pin))
return
} | csn |
Get IMAP resource stream.
@throws InvalidResourceException
@return resource | public function getStream()
{
if (false === \is_resource($this->resource) || 'imap' !== \get_resource_type($this->resource)) {
throw new InvalidResourceException('Supplied resource is not a valid imap resource');
}
$this->initMailbox();
return $this->resource;
} | csn |
Add a new column with the corresponding header and values to the
dataframe.
Args:
header: The name of the new column.
values: A list of size :func:`~amplpy.DataFrame.getNumRows` with
all the values of the new column. | def addColumn(self, header, values=[]):
"""
Add a new column with the corresponding header and values to the
dataframe.
Args:
header: The name of the new column.
values: A list of size :func:`~amplpy.DataFrame.getNumRows` with
all the values of the n... | csn |
// RecordMachineInState records and saves into the state machine the provisioned machine | func RecordMachineInState(client ProvisioningClientAPI, machineParams params.AddMachineParams) (machineId string, err error) {
results, err := client.AddMachines([]params.AddMachineParams{machineParams})
if err != nil {
return "", errors.Trace(err)
}
// Currently, only one machine is added, but in future there ma... | csn |
Unloads event instance.
@param string $className Event name
@return null | final public static function clearInstance($className)
{
if (isset(self::$_instances[$className])) {
$name = self::_configName($className);
Config::clearInstance($name);
self::$_instances[$className]->_loadObservers();
}
} | csn |
All operations running at cache initialization stage | public void startup() {
underlying.startup();
OProfiler.getInstance().registerHookValue(profilerPrefix + "enabled", new OProfilerHookValue() {
public Object getValue() {
return isEnabled();
}
});
OProfiler.getInstance().registerHookValue(profilerPrefix + "current", new OPr... | csn |
Helper method to obtain the neighbouring bonds from an adjacency list
graph and edge->bond map.
@param v vertex
@param g graph (adj list)
@param bondMap map of edges to bonds
@return neighboring bonds | private static IBond[] neighbors(int v, int[][] g, EdgeToBondMap bondMap) {
int[] ws = g[v];
IBond[] bonds = new IBond[ws.length];
for (int i = 0; i < ws.length; i++) {
bonds[i] = bondMap.get(v, ws[i]);
}
return bonds;
} | csn |
Convert string x to the most useful type, i.e. int, float or unicode string.
If x is a quoted string (single or double quotes) then the quotes are
stripped and the enclosed string returned. The string can contain any
number of quotes, it is only important that it begins and ends with either
single or d... | def besttype(x, encoding="utf-8", percentify=True):
"""Convert string x to the most useful type, i.e. int, float or unicode string.
If x is a quoted string (single or double quotes) then the quotes are
stripped and the enclosed string returned. The string can contain any
number of quotes, it is only im... | csn |
// SetFunc sets the counter's value to the lazily-called return value of the
// given function. | func (c Counter) SetFunc(f func() uint64) {
cm.Lock()
defer cm.Unlock()
counterFuncs[string(c)] = f
} | csn |
Keep only folders that don't contain patterns in `DIR_EXCLUDE_PATTERNS`. | def keep_folder(raw_path):
"""
Keep only folders that don't contain patterns in `DIR_EXCLUDE_PATTERNS`.
"""
keep = True
for pattern in DIR_EXCLUDE_PATTERNS:
if pattern in raw_path:
LOGGER.debug('rejecting', raw_path)
keep = False
return keep | csn |
target should be a Table or SyntheticTable | def add(self, name, target):
"target should be a Table or SyntheticTable"
if not isinstance(target, (table.Table, SyntheticTable)):
raise TypeError(type(target), target)
if name in self:
# note: this is critical for avoiding cycles
raise ScopeCollisionError('scope already has', name)
s... | csn |
Parse the given ``input_text`` and
append the extracted fragments to ``syncmap``.
:param input_text: the input text as a Unicode string (read from file)
:type input_text: string
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap` | def parse(self, input_text, syncmap):
"""
Parse the given ``input_text`` and
append the extracted fragments to ``syncmap``.
:param input_text: the input text as a Unicode string (read from file)
:type input_text: string
:param syncmap: the syncmap to append to
:t... | csn |
// Recalculates the internal Polygon with the Width, Height and Position. | func (box *BoxShape) UpdatePoly() {
hw := box.Width / 2.0
hh := box.Height / 2.0
if hw < 0 {
hw = -hw
}
if hh < 0 {
hh = -hh
}
box.verts = [4]vect.Vect{
{-hw, -hh},
{-hw, hh},
{hw, hh},
{hw, -hh},
}
poly := box.Polygon
poly.SetVerts(box.verts[:], box.Position)
} | csn |
History of a specific alarm. | def history(self, **kwargs):
"""History of a specific alarm."""
url_str = self.base_url + '/%s/state-history' % kwargs['alarm_id']
del kwargs['alarm_id']
if kwargs:
url_str = url_str + '?%s' % parse.urlencode(kwargs, True)
resp = self.client.list(url_str)
retu... | csn |
// Create a Bgp object | func CreateBgp(obj *Bgp) error {
// Validate parameters
err := ValidateBgp(obj)
if err != nil {
log.Errorf("ValidateBgp retruned error for: %+v. Err: %v", obj, err)
return err
}
// Check if we handle this object
if objCallbackHandler.BgpCb == nil {
log.Errorf("No callback registered for Bgp object")
retu... | csn |
Check if route is from element api
@return boolean | private function isElementApiRoute()
{
$plugin = \Craft::$app->getPlugins()->getPlugin('element-api');
if ($plugin) {
$elementApiRoutes = $plugin->getSettings()->endpoints;
$routes = array_keys($elementApiRoutes);
foreach ($routes as $route) {
... | csn |
Puts the expected value for a particular key and column
@param store the store to put the expected key column value
@param key the key to put the expected value for
@param column the column to put the expected value for
@param expectedValue the expected value to put | public void putKeyColumnOnlyIfItIsNotYetChangedInTx(final AbstractDynamoDbStore store, final StaticBuffer key, final StaticBuffer column,
final StaticBuffer expectedValue) {
expectedValues.computeIfAbsent(store, s -> new HashMap<>());
expectedValues.get(store).computeIfAbsent(key, k -> new HashM... | csn |
Sets the behavior of associative entities. If a hasMany relation is marked as a "junction table",
associative entities will be removed once a foreign key is unsetted. When a hasMany relation is
not marked as a "junction table", associative entities will simply have their foreign key unsetted.
@param boolean $boolean ... | public function junction($boolean = null)
{
if (func_num_args()) {
$this->_junction = $boolean;
return $this;
}
return $this->_junction;
} | csn |
Local test helper. | def ready_print(worker, output, error): # pragma : no cover
"""Local test helper."""
global COUNTER
COUNTER += 1
print(COUNTER, output, error) | csn |
// CreateTemplate will save the provided template struct as a new template
// and return the ID of the new template. | func (client *Client) CreateTemplate(ctx context.Context, template Template) (string, error) {
content := map[string]interface{}{
"name": template.Name,
"template": template.Content,
}
if err := client.request(ctx, "POST", "templates", content, &template); err != nil {
return "", err
}
return template.... | csn |
Executes the processing of every attached loader.
Run each loader with limit and offset as long as it
returns not less than the limit of items persist
after each batch.
@throws \Assert\InvalidArgumentException in case no loader is attached. | public function run()
{
Assertion::notEmpty(
$this->loaders,
'No loader attached.',
DataAggregatorException::NO_LOADER_ATTACHED
);
foreach ($this->loaders as $identifier => $loader) {
$this->executeLoader($loader);
}
} | csn |
Expand a file path specified on the command-line.
<p>Most file paths on the command-line allow an %outname% placeholder. The placeholder will
expand to a different value depending on the current output mode. There are three scenarios:
<p>1) Single JS output, single extra output: sub in jsOutputPath. 2) Multiple JS ou... | @GwtIncompatible("Unnecessary")
private String expandCommandLinePath(String path, JSModule forModule) {
String sub;
if (forModule != null) {
sub = config.moduleOutputPathPrefix + forModule.getName() + ".js";
} else if (!config.module.isEmpty()) {
sub = config.moduleOutputPathPrefix;
} else... | csn |
// DiffLine diffs on words | func DiffLine(a, b string) *DiffSolution {
aw := splitLine(a)
bw := splitLine(b)
if len(aw)*len(bw) > 100000000 {
return nil
}
return NewSequenceDiffer(aw, bw).Solve()
} | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.