query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Includes FormZ configuration JavaScript declaration. If the file exists,
it is directly included, otherwise the JavaScript code is calculated,
then put in the cache file.
@return $this | public function generateAndIncludeFormzConfigurationJavaScript()
{
$formzConfigurationJavaScriptAssetHandler = $this->getFormzConfigurationJavaScriptAssetHandler();
$fileName = $formzConfigurationJavaScriptAssetHandler->getJavaScriptFileName();
$this->assetHandlerConnectorManager->createFil... | csn |
// NewCmdCreatePodDisruptionBudget is a macro command to create a new pod disruption budget. | func NewCmdCreatePodDisruptionBudget(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
options := &PodDisruptionBudgetOpts{
CreateSubcommandOptions: NewCreateSubcommandOptions(ioStreams),
}
cmd := &cobra.Command{
Use: "poddisruptionbudget NAME --selector=SELECTOR --min... | csn |
Avoid polluting results with some builtin python caches | def trace_memory_clean_caches(self):
""" Avoid polluting results with some builtin python caches """
urllib.parse.clear_cache()
re.purge()
linecache.clearcache()
copyreg.clear_extension_cache()
if hasattr(fnmatch, "purge"):
fnmatch.purge() # pylint: disable... | csn |
// add assigns an ID to the given tx buffer. | func (m *idManager) add(b *queue.TxBuffer) uint64 {
if i := m.freeList; i != nilID {
// There is an id available in the free list, just use it.
m.ids[i].buf = b
m.freeList = m.ids[i].nextFree
return i
}
// We need to expand the id descriptor.
m.ids = append(m.ids, idDescriptor{buf: b})
return uint64(len(m... | csn |
Check if a type is a subclass of any node in class_or_seq
:param node: A given node
:param class_or_seq: Union[Nodes.NodeNG, Sequence[nodes.NodeNG]]
:rtype: bool
:raises AstroidTypeError: if the given ``classes_or_seq`` are not types
:raises AstroidError: if the type of the given node cannot be in... | def object_issubclass(node, class_or_seq, context=None):
"""Check if a type is a subclass of any node in class_or_seq
:param node: A given node
:param class_or_seq: Union[Nodes.NodeNG, Sequence[nodes.NodeNG]]
:rtype: bool
:raises AstroidTypeError: if the given ``classes_or_seq`` are not types
... | csn |
Gets first character from file pointer
@param string $message
@param bool $nl
@return string | public static function readChar(string $message = '', bool $nl = false): string
{
$line = self::readln($message, $nl);
return $line !== '' ? $line[0] : '';
} | csn |
Tells if preemption is allowed for a resource type.
@param type The type of the resource.
@return Is preemption allowed for the the specified type. | public static boolean canBePreempted(ResourceType type) {
// Preemption is not allowed for JOBTRACKER grants.
switch (type) {
case MAP:
return true;
case REDUCE:
return true;
case JOBTRACKER:
return false;
default:
throw new RuntimeException("Undefined Preemption behavior... | csn |
Converts sweep to a product of zips of single sweeps, if possible. | def _to_zip_product(sweep: Sweep) -> Product:
"""Converts sweep to a product of zips of single sweeps, if possible."""
if not isinstance(sweep, Product):
sweep = Product(sweep)
if not all(isinstance(f, Zip) for f in sweep.factors):
factors = [f if isinstance(f, Zip) else Zip(f) for f in swee... | csn |
Validates attributes to determine if the values contain valid IP addresses.
Set the :no_mask option to restrict the IP address to singular addresses only. | def validate_each(record, attribute, value)
begin
unless value.blank?
IPAddr.new(value)
if options[:no_mask]
if value =~ /\//
record.errors[attribute] << (options[:message] || 'must not contain a mask')
end
elsif options[:require_mask]
... | csn |
Remove a child deferred reference data to this scope. | public synchronized void removeDeferredReferenceData(DeferredReferenceData refData) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "removeDeferredReferenceData", "this=" + this, refData);
}
if (deferredReferenceDatas != null) {
deferred... | csn |
Returns the UID of the current page.
If manualPageUidSource is set to SOURCE_FRONT_END or SOURCE_BACK_END, this
function returns the UID set in this part. Otherwise starts with looking
into the manually set page UID, then if a FE page UID is present
and finally if a BE page UID is present.
@return int the ID of the c... | public function getPageUid()
{
switch ($this->getCurrentSource()) {
case self::SOURCE_MANUAL:
$result = $this->storedPageUid;
break;
case self::SOURCE_FRONT_END:
$result = (int)$this->getFrontEndController()->id;
break;
... | csn |
Return whether we must start a login process if the first client is an indirect one.
@param context the web context
@param currentClients the current clients
@return whether we must start a login process | protected boolean startAuthentication(final C context, final List<Client> currentClients) {
return isNotEmpty(currentClients) && currentClients.get(0) instanceof IndirectClient;
} | csn |
// IsEmail is a constraint to do a simple validation for email addresses, it only check if the string contains "@"
// and that it is not in the first or last character of the string
// https://en.wikipedia.org/wiki/Email_address#Valid_email_addresses | func IsEmail(s string) bool {
if !strings.Contains(s, "@") || string(s[0]) == "@" || string(s[len(s)-1]) == "@" {
return false
}
return true
} | csn |
Looks up the current domain or IP.
@return string Content of whois lookup. | public function lookup()
{
if ($this->ip) {
$result = $this->lookupIp($this->ip);
} else {
$result = $this->lookupDomain($this->domain);
}
return $result;
} | csn |
Entry point for the `bolt` executable. | def run():
"""
Entry point for the `bolt` executable.
"""
options = btoptions.Options()
btlog.initialize_logging(options.log_level, options.log_file)
app = btapp.get_application()
app.run() | csn |
Returns the KNX device descriptor type 0 of the USB interface.
@return device descriptor type 0
@throws KNXPortClosedException on closed port
@throws KNXTimeoutException on response timeout
@throws InterruptedException on interrupt
@see tuwien.auto.calimero.DeviceDescriptor | public final DD0 deviceDescriptor() throws KNXPortClosedException, KNXTimeoutException, InterruptedException {
return DD0.from((int) toUnsigned(getFeature(BusAccessServerFeature.DeviceDescriptorType0)));
} | csn |
Refresh maybe-expired sessions in the pool.
This method is designed to be called from a background thread,
or during the "idle" phase of an event loop. | def ping(self):
"""Refresh maybe-expired sessions in the pool.
This method is designed to be called from a background thread,
or during the "idle" phase of an event loop.
"""
while True:
try:
ping_after, session = self._sessions.get(block=False)
... | csn |
Find matches for words in the format "3 thousand 6 hundred 2".
The words parameter should be the list of words to check for
such as "hundred". | def find_word_groups(string, words):
"""
Find matches for words in the format "3 thousand 6 hundred 2".
The words parameter should be the list of words to check for
such as "hundred".
"""
scale_pattern = '|'.join(words)
# For example:
# (?:(?:\d+)\s+(?:hundred|thousand)*\s*)+(?:\d+|hundr... | csn |
Return a JSON Schema object for a Django Form. | def get_form_schema(form):
"""Return a JSON Schema object for a Django Form."""
schema = {
'type': 'object',
'properties': {},
}
for name, field in form.base_fields.items():
schema['properties'][name] = get_field_schema(name, field)
if field.required:
schema.... | csn |
Decode hex string to a byte array
@param encoded
encoded string
@return return array of byte to encode | static public byte[] decode(String encoded) {
if (encoded == null)
return null;
int lengthData = encoded.length();
if (lengthData % 2 != 0)
return null;
char[] binaryData = encoded.toCharArray();
int lengthDecode = lengthData / 2;
byte[] decodedData = new byte[lengthDecode];
byte temp1, temp2;
ch... | csn |
// waitAnyInstanceAddresses waits for at least one of the instances
// to have addresses, and returns them. | func waitAnyInstanceAddresses(
env Environ,
ctx context.ProviderCallContext,
instanceIds []instance.Id,
) ([]network.Address, error) {
var addrs []network.Address
for a := AddressesRefreshAttempt.Start(); len(addrs) == 0 && a.Next(); {
instances, err := env.Instances(ctx, instanceIds)
if err != nil && err != E... | csn |
Returns the list of options with a value.
@return array | public function getOptions()
{
$result = [];
foreach ($this->options as $option) {
$value = $option->getValue();
if ($value !== null) {
$result[$option->getShort() ?: $option->getLong()] = $value;
if ($short = $option->getShort()) {
... | csn |
Search tags for port info, returning it
Args:
tags: A list of tags to check
Returns:
None or (is_source, port, connected_value|disconnected_value)
where port is one of the Enum entries of Port | def port_tag_details(cls, tags):
# type: (Sequence[str]) -> Union[Tuple[bool, Port, str], None]
"""Search tags for port info, returning it
Args:
tags: A list of tags to check
Returns:
None or (is_source, port, connected_value|disconnected_value)
wher... | csn |
Update the chart keeping the current animation but suppressing a new one
@param {object} config - animation options | function update(config) {
var me = this;
var preservation = config && config.preservation;
var tooltip, lastActive, tooltipLastActive, lastMouseEvent;
if (preservation) {
tooltip = me.tooltip;
lastActive = me.lastActive;
tooltipLastActive = tooltip._lastActive;
me._bufferedRender = true;
}
Chart.prototy... | csn |
Handles plugin updates.
@since 1.3.0
@return void | public function update()
{
$version = get_option($this->plugin . 'version');
if ($version != STATICWP_VERSION) {
update_option($this->plugin . 'version', STATICWP_VERSION);
}
} | csn |
Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Example::
2015-07-16 -0.012143
2015-07-17... | def cum_returns(returns, starting_value=0, out=None):
"""
Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Ex... | csn |
// SetTuningJobName sets the TuningJobName field's value. | func (s *HyperParameterTrainingJobSummary) SetTuningJobName(v string) *HyperParameterTrainingJobSummary {
s.TuningJobName = &v
return s
} | csn |
Updates the current Account's Team name
@param string $name New Team name
@return Team
@throws BaseException | public function updateTeamName($name)
{
$response = $this->rest->post(
static::TEAM_PATH,
array(
'name' => $name
)
);
$this->checkResponse($response);
return new Team($response);
} | csn |
Returns a responder that supports HTTP requests.
@param HttpRequest $request the request to satisfy. | private static function getHttpResponder(HttpRequest $request)
{
$responder = null;
$responderClassName = $request->getResponderClassName();
if (class_exists($responderClassName)) {
$responder = new $responderClassName($request);
Logger::get()->debug(
... | csn |
Get self-conversation parameters.
@return external_function_parameters | public static function get_self_conversation_parameters() {
return new external_function_parameters(
array(
'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing self-conversations for'),
'messagelimit' => new external_value(PARAM_INT, 'Limi... | csn |
// Fetches the range of offsets between which the key exists,
// if present at all. The returned leftPos and rightPos can
// directly be used as the left and right extreme cursors
// while binary searching over the source segment. | func (s *segmentKeysIndex) lookup(key []byte) (leftPos int, rightPos int) {
i, j := 0, s.numKeys
if i == j || s.numKeys < 2 {
// The index either wasn't used or isn't of any use.
rightPos = s.srcKeyCount
return
}
// If key smaller than the first key, return early.
keyStart := s.offsets[0]
keyEnd := s.offs... | csn |
Retrieve the catalog of drivers
Retrieve the catalog of drivers # noqa: E501
:rtype: Response | def get_driver_list(): # noqa: E501
"""Retrieve the catalog of drivers
Retrieve the catalog of drivers # noqa: E501
:rtype: Response
"""
response = errorIfUnauthorized(role='admin')
if response:
return response
else:
response = ApitaxResponse()
response.body.add({'d... | csn |
Show error and warning screen | function(message) {
// If an error already has been thrown, exit
if (errorTarget) return message
utils.doCallback('errorTriggered', message);
utils.logError(message)
// If no target DOM element exists, only do the logging
if (!rootTarget) return message
var messageProcessed = message
... | csn |
Fetches Data for Table Rows and returns as json
uses POST vars page, pageSize, sort, sortDir
@return string JSON Data
@throws Exception | public function jsonRows()
{
$arrWhat = array_values($this->getHeaderColumns());
$arrWhere = [];
$arrOrder = ['`id` DESC'];
$start = 0;
$pageSize = 15;
if (isset($_POST['page']) && isset($_POST['pageSize'])) {
$page = (int) $_POST['page'];
$pag... | csn |
// SetTargetAttribute is used to populate this property set without also storing allowed count
// This is used when evaluating spread stanzas | func (p *propertySet) SetTargetAttribute(targetAttribute string, taskGroup string) {
p.setTargetAttributeWithCount(targetAttribute, 0, taskGroup)
} | csn |
If threads is empty we wait on condition for DEFAULT_TEMPORISATION millis to be notified,
otherwise we wait for 1s | public void waitThreadStopped() { // FIXME: method named in confusing way
long sleepTime = threads.isEmpty() ? DEFAULT_TEMPORISATION : MIN_CHECK_TIME;
lock.lock();
try {
condition.await(sleepTime, TimeUnit.MILLISECONDS); // NOSONAR
} catch (InterruptedException e) {
... | csn |
get data and stat for a path
@param path the path being queried
@param stat the stat for this path
@param watcher the watcher function
@return
@throws KeeperException.NoNodeException | public byte[] getData(String path, Stat stat, Watcher watcher)
throws KeeperException.NoNodeException {
return dataTree.getData(path, stat, watcher);
} | csn |
// Find searches the Node that matches by the specified XPath expr. | func Find(top *Node, expr string) []*Node {
exp, err := xpath.Compile(expr)
if err != nil {
panic(err)
}
t := exp.Select(CreateXPathNavigator(top))
var elems []*Node
for t.MoveNext() {
elems = append(elems, getCurrentNode(t))
}
return elems
} | csn |
// CallBlock is the same as call except that it expects the last
// argument to be a Proc that will be passed into the function call.
// It is an error if args is empty or if there is no block on the end. | func (v *MrbValue) CallBlock(method string, args ...Value) (*MrbValue, error) {
if len(args) == 0 {
return nil, fmt.Errorf("args must be non-empty and have a proc at the end")
}
n := len(args)
return v.call(method, args[:n-1], args[n-1])
} | csn |
// GetTypeByString returns a ServiceType associated with
// given typeName and nil, if type is known, otherwise
// instantiates a ServiceType with given typeName
// but returns ErrServiceTypeNotFound | func GetTypeByString(typeName string) (ServiceType, error) {
switch ServiceType(typeName) {
case HTTP:
return HTTP, nil
case HTTPS:
return HTTPS, nil
case TCP:
return TCP, nil
case UDP:
return UDP, nil
case Custom:
return Custom, nil
default:
return ServiceType(typeName), ErrServiceTypeNotFound
}
} | csn |
Detect the type for the HTTP response.
Should only be done for an `attach` request. | protected function detectReturnType()
{
if (isset($_GET['cookie'])) {
$this->returnType = 'none';
return;
} elseif (!empty($_GET['return_url'])) {
$this->returnType = 'redirect';
} elseif (!empty($_GET['callback'])) {
$this->returnType = 'jsonp... | csn |
Gets a ConversationMessage listing with default pagination options.
@param conversationId Conversation to get messages for.
@return List of messages. | public ConversationMessageList listConversationMessages(
final String conversationId
) throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 10;
return listConversationMessages(conversationId, offset, limit);
} | csn |
Update status informations in tkinter window. | def update_status(self):
"""Update status informations in tkinter window."""
try:
# all this may fail if the connection to the fritzbox is down
self.update_connection_status()
self.max_stream_rate.set(self.get_stream_rate_str())
self.ip.set(self.status.ext... | csn |
Stop the workers and wait for them to terminate. | def stop_workers(self, _join_arbiter=True):
"""Stop the workers and wait for them to terminate."""
# _join_arbiter is used internally when the arbiter is shutting down
# the full engine itself. This is because the arbiter thread cannot
# join itself.
self._must_stop.set()
... | csn |
Settle all promises.
@return void | public function wait() : void
{
if (!empty($this->promises)) {
Promise\settle($this->promises)->wait();
}
} | csn |
// NewIncStrSingle is just like NewIncSingle but takes table and key as strings. | func NewIncStrSingle(ctx context.Context, table, key, family, qualifier string,
amount int64, options ...func(Call) error) (*Mutate, error) {
return NewIncSingle(ctx, []byte(table), []byte(key), family, qualifier, amount, options...)
} | csn |
Create new query insert builder
@param string $table
@return Query\Insert | public function insert(string $table): Query\Insert
{
$query = new Query\Insert();
$query->insert($table);
return $query;
} | csn |
Regular "text" input.
@option 'type' {string} HTML type attribute, e.g. <code>email</code> or <code>tel</code>. | public function textField($key, $label=null, array $attr=[]){
$field = $this->factory("text", $key, $label, $attr);
return $this->addField($field);
} | csn |
Get he extension by url.
@param url url.
@return extension name. | public static String getUrlExtension(String url) {
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return TextUtils.isEmpty(extension) ? "" : extension;
} | csn |
// Id specifies the identifier of the document to update. | func (r *BulkUpdateRequest) Id(id string) *BulkUpdateRequest {
r.id = id
r.source = nil
return r
} | csn |
Match the request methods.
@param string $methods router request method
@param string $requestMethod Requested method
@since 2.0.3
@return bool | public function methodMatch($methods, $requestMethod, Request $request)
{
$match = false;
if ($requestMethod === null) {
$requestMethod = ($request->getRequestMethod()) ? $request->getRequestMethod() : 'GET';
}
$methods = explode('|', $methods);
foreach ($methods ... | csn |
// WithPullUnpack is used to unpack an image after pull. This
// uses the snapshotter, content store, and diff service
// configured for the client. | func WithPullUnpack(_ *Client, c *RemoteContext) error {
c.Unpack = true
return nil
} | csn |
Close and discard a writer that experienced a potentially-corrupting
error.
@param f writer with problem
@throws IOException | public synchronized void invalidateFile(WriterPoolMember f)
throws IOException {
try {
destroyWriter(f);
} catch (Exception e) {
// Convert exception.
throw new IOException(e.getMessage());
}
// It'll have been closed. Rename with an '.invalid' su... | csn |
// Marshal is an alias for Serialize | func (prof *Profiler) Marshal(ut *util.CPUUtil) ([]byte, error) {
return prof.Serialize(ut)
} | csn |
Strips unsafe tags and attributes from HTML.
@param {string} inputHtml The HTML to sanitize.
@param {?function(?string): ?string} opt_naiveUriRewriter A transform to
apply to URI attributes. If not given, URI attributes are deleted.
@param {function(?string): ?string} opt_nmTokenPolicy A transform to apply
to attribut... | function sanitize(inputHtml, opt_naiveUriRewriter, opt_nmTokenPolicy) {
var tagPolicy = makeTagPolicy(opt_naiveUriRewriter, opt_nmTokenPolicy);
return sanitizeWithPolicy(inputHtml, tagPolicy);
} | csn |
// onNextGoroutine returns true if this thread is on the goroutine requested by the current 'next' command | func onNextGoroutine(thread Thread, breakpoints *BreakpointMap) (bool, error) {
var bp *Breakpoint
for i := range breakpoints.M {
if breakpoints.M[i].Kind != UserBreakpoint && breakpoints.M[i].internalCond != nil {
bp = breakpoints.M[i]
break
}
}
if bp == nil {
return false, nil
}
// Internal breakpoi... | csn |
Adds information about the first frame to incomplete stack traces.
Safari and IE require this to get complete data on the first frame.
@param {Object.<string, *>} stackInfo Stack trace information from
one of the compute* methods.
@param {string} url The URL of the script that caused an error.
@param {(number|string)} ... | function augmentStackTraceWithInitialElement(stackInfo, url, lineNo, message) {
var initial = {
'url': url,
'line': lineNo
};
if (initial.url && initial.line) {
stackInfo.incomplete = false;
if (!initial.func) {
initial.func = gue... | csn |
// Delete deletes an directional-pool | func (s *IPDirectionalPoolsService) Delete(k IPDirectionalPoolKey) (*http.Response, error) {
return s.client.delete(k.URI(), nil)
} | csn |
Call bindingHandler.preprocess on each respective binding string.
The `preprocess` property of bindingHandler must be a static
function (i.e. on the object or constructor). | function preProcessBindings(bindingString) {
var results = [];
var bindingHandlers = this.bindingHandlers;
var preprocessed;
// Check for a Provider.preprocessNode property
if (typeof this.preprocessNode === 'function') {
preprocessed = this.preprocessNode(bindingString, this);
if (preprocessed) { bi... | csn |
Close the image and save the changes to a file.
@param string|null $destination Destination path where the image should be saved. If it is empty the original image file will be overwritten.
@throws \RuntimeException
@return Image image or false, based on success. | public function save($destination = null)
{
if (empty($destination)) {
$destination = $this->source;
}
$this->image->save($destination);
// Clear the cached file size and refresh the image information.
clearstatcache();
chmod($destination, 0644);
... | csn |
Tries to login to the SMTP server with 'AUTH CRAM-MD5' and returns true if
successful.
@throws ezcMailTransportSmtpException
if the SMTP server returned an error
@return bool | protected function authCramMd5()
{
$this->sendData( 'AUTH CRAM-MD5' );
if ( $this->getReplyCode( $response ) !== '334' )
{
throw new ezcMailTransportSmtpException( 'SMTP server does not accept AUTH CRAM-MD5.' );
}
$serverDigest = trim( substr( $response, 4 ) );
... | csn |
Returns the list of all the field name of a table.
@param meta DataBase meta data
@param table Table identifier [[catalog.]schema.]table
@return The list of field name.
@throws SQLException If jdbc throws an error | public static List<String> getFieldNames(DatabaseMetaData meta, String table) throws SQLException {
List<String> fieldNameList = new ArrayList<String>();
TableLocation location = TableLocation.parse(table);
ResultSet rs = meta.getColumns(location.getCatalog(null), location.getSchema(null), locat... | csn |
This method positions the dropdown menu.
The specified mouseEvent is ignored. However, subclasses
can override this method if they wish to take the mouse
position contained in the mouse event into account.
@param {MouseEvent} mouseEvent | function(mouseEvent) {//Sub classes can override this to position the drop down differently.
this._dropdownNode.style.left = "";
this._dropdownNode.style.top = "";
if(this._positioningNode) {
this._dropdownNode.style.left = this._positioningNode.offsetLeft + "px";
return;
}
var bounds = l... | csn |
// Returns the metadata for the file associated with the Fid, or an Error. | func (clnt *Clnt) Stat(fid *Fid) (*Dir, error) {
tc := clnt.NewFcall()
err := PackTstat(tc, fid.Fid)
if err != nil {
return nil, err
}
rc, err := clnt.Rpc(tc)
if err != nil {
return nil, err
}
return &rc.Dir, nil
} | csn |
Determines if a filename can be added to the depot under the current client
:param filename: File path to add
:type filename: str | def canAdd(self, filename):
"""Determines if a filename can be added to the depot under the current client
:param filename: File path to add
:type filename: str
"""
try:
result = self.run(['add', '-n', '-t', 'text', filename])[0]
except errors.CommandError as... | csn |
Read a RES2DINV-style file produced by the ABEM export program. | def add_dat_file(filename, settings, container=None, **kwargs):
""" Read a RES2DINV-style file produced by the ABEM export program.
"""
# each type is read by a different function
importers = {
# general array type
11: _read_general_type,
}
file_type, content = _read_file(filena... | csn |
Parses YAML into a JS representation.
The parse method, when supplied with a YAML stream (file),
will do its best to convert YAML in a file into a JS representation.
Usage:
<code>
obj = yaml.parseFile('config.yml');
</code>
@param string input Path of YAML file
@return array The YAML converted to a JS representatio... | function(file /* String */, callback /* Function */)
{
if ( callback == null )
{
var input = this.getFileContents(file);
var ret = null;
try
{
ret = this.parse(input);
}
catch ( e )
{
if ( e instanceof YamlParseException ) {
e.setParsedFile(file);
}
throw e;
}
return... | csn |
// defaultGoPath returns the system's default GOPATH. If the system
// has multiple GOPATHs then the first is used. | func defaultGoPath() string {
gpDefault := build.Default.GOPATH
gps := filepath.SplitList(gpDefault)
return gps[0]
} | csn |
builds an order-by clause | def clause(grouped_columns_calculations = nil)
return nil if sorts_by_method? || default_sorting?
# unless the sorting is by method, create the sql string
order = []
each do |sort_column, sort_direction|
next if constraint_columns.include? sort_column.name
sql = grouped_columns_... | csn |
Load cart purchasables prices.
@param CartInterface $cart Cart | public function loadCartPurchasablesAmount(CartInterface $cart)
{
$currency = $this
->currencyWrapper
->get();
$purchasableAmount = Money::create(0, $currency);
/**
* Calculate Amount and PurchasableAmount.
*/
foreach ($cart->getCartLines()... | csn |
// PollEvents gets events from termbox, converts them, then sends them to each of its channels. | func PollEvents() <-chan Event {
ch := make(chan Event)
go func() {
for {
ch <- convertTermboxEvent(tb.PollEvent())
}
}()
return ch
} | csn |
Converts a Z3 model to a name->primitive dict. | def _generic_model(self, z3_model):
"""
Converts a Z3 model to a name->primitive dict.
"""
model = { }
for m_f in z3_model:
n = _z3_decl_name_str(m_f.ctx.ctx, m_f.ast).decode()
m = m_f()
me = z3_model.eval(m)
model[n] = self._abstra... | csn |
The authentication information. Optional when creating an HTTP check;
defaults to empty.
Generated from protobuf field <code>.google.monitoring.v3.UptimeCheckConfig.HttpCheck.BasicAuthentication auth_info = 4;</code>
@param \Google\Cloud\Monitoring\V3\UptimeCheckConfig\HttpCheck\BasicAuthentication $var
@return $this | public function setAuthInfo($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Monitoring\V3\UptimeCheckConfig_HttpCheck_BasicAuthentication::class);
$this->auth_info = $var;
return $this;
} | csn |
Convert a size value from page to a number with a magnitude appended.
Input:
Request Handle
Size in page
Output:
Converted value with a magnitude | def getSizeFromPage(rh, page):
"""
Convert a size value from page to a number with a magnitude appended.
Input:
Request Handle
Size in page
Output:
Converted value with a magnitude
"""
rh.printSysLog("Enter generalUtils.getSizeFromPage")
bSize = float(page) * 4096
... | csn |
Generate the keys we need for a GRR server. | def GenerateKeys(config, overwrite_keys=False):
"""Generate the keys we need for a GRR server."""
if not hasattr(key_utils, "MakeCACert"):
raise OpenSourceKeyUtilsRequiredError(
"Generate keys can only run with open source key_utils.")
if (config.Get("PrivateKeys.server_key", default=None) and
n... | csn |
Convert a roman numeral to decimal
@param string $roman
@return int | public function romanNumeralsToNumber(string $roman): int
{
$num = 0;
foreach (self::ROMAN_NUMERALS as $key => $value) {
while (strpos($roman, $value) === 0) {
$num += $key;
$roman = substr($roman, strlen($value));
}
}
return $... | csn |
Process event data. | def process(self, data, **kwargs):
"""Process event data."""
data = super(RequestIdProcessor, self).process(data, **kwargs)
if g and hasattr(g, 'request_id'):
tags = data.get('tags', {})
tags['request_id'] = g.request_id
data['tags'] = tags
return data | csn |
// Unmarshal exists to fit gogoprotobuf custom type interface. | func (r *Raw) Unmarshal(data []byte) error {
if len(data) == 0 {
r = nil
return nil
}
id := Raw(make([]byte, len(data)))
copy(id, data)
*r = id
return nil
} | csn |
// GetFrameLogForGateway subscribes to the uplink and downlink frame logs
// for the given gateway and sends this to the given channel. | func GetFrameLogForGateway(ctx context.Context, p *redis.Pool, gatewayID lorawan.EUI64, frameLogChan chan FrameLog) error {
uplinkKey := fmt.Sprintf(gatewayFrameLogUplinkPubSubKeyTempl, gatewayID)
downlinkKey := fmt.Sprintf(gatewayFrameLogDownlinkPubSubKeyTempl, gatewayID)
return getFrameLogs(ctx, p, uplinkKey, down... | csn |
Return the cosecant of ``x``. | def csc(x, context=None):
"""
Return the cosecant of ``x``.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_csc,
(BigFloat._implicit_convert(x),),
context,
) | csn |
When switching between 2 connections, report existing connection parameter to the new used
connection.
@param from used connection
@param to will-be-current connection
@throws SQLException if catalog cannot be set | public void syncConnection(Protocol from, Protocol to) throws SQLException {
if (from != null) {
proxy.lock.lock();
try {
to.resetStateAfterFailover(from.getMaxRows(), from.getTransactionIsolationLevel(),
from.getDatabase(), from.getAutocommit());
} finally {
proxy.lo... | csn |
read_full reads exactly `size` bytes from reader. returns
`size` bytes.
:param data: Input stream to read from.
:param size: Number of bytes to read from `data`.
:return: Returns :bytes:`part_data` | def read_full(data, size):
"""
read_full reads exactly `size` bytes from reader. returns
`size` bytes.
:param data: Input stream to read from.
:param size: Number of bytes to read from `data`.
:return: Returns :bytes:`part_data`
"""
default_read_size = 32768 # 32KiB per read operation.
... | csn |
Checks that the current field includes a reference to the supplied document. | public function includesReferenceTo(object $document) : self
{
$this->requiresCurrentField();
$mapping = $this->getReferenceMapping();
$reference = $this->dm->createReference($document, $mapping);
$storeAs = $mapping['storeAs'] ?? null;
$keys = [];
switch ($... | csn |
Send the request represented by the given header and optional body. | private void sendRequest(String header, byte[] body) throws IOException {
// Send entire message in one write, else suffer the fate of weird TCP/IP stacks.
byte[] headerBytes = Utils.toBytes(header);
byte[] requestBytes = headerBytes;
if (body != null && body.length > 0) {
... | csn |
read single wallet, If amount of wallets is bigger than one, will throw an error
@param {object} conn - database connection
@param {function} handleWallet - callback | function readSingleWallet(conn, handleWallet){
conn.query("SELECT wallet FROM wallets", function(rows){
if (rows.length === 0)
throw Error("no wallets");
if (rows.length > 1)
throw Error("more than 1 wallet");
handleWallet(rows[0].wallet);
});
} | csn |
Determines what ranges of a scanline that needs to be supersampled.
@param array $scanline Array of edges in the current scanline.
@return array Array of SuperSampleRange. | private static function getSuperSampleRanges(&$scanline, $width)
{
$superSampleRanges = array();
$rangeIndex = 0;
$scanlineCount = count($scanline);
while ($rangeIndex < $scanlineCount) {
$range = $scanline[$rangeIndex];
if ($range->fromX >= $w... | csn |
Answers the default detail fields config for the extended object.
@return array | public function getDefaultDetailFieldsConfig()
{
if (is_array($this->owner->config()->default_detail_fields)) {
return $this->owner->config()->default_detail_fields;
}
return [];
} | csn |
Ask For Path | function askForPath() {
if (this.regenerate) return;
const done = this.async();
const deploymentApplicationType = this.deploymentApplicationType;
let messageAskForPath;
if (deploymentApplicationType === 'monolith') {
messageAskForPath = 'Enter the root directory where your applications are ... | csn |
// WithDefaults set some sane defaults into the given Info | func WithDefaults(info Info) Info {
if info.Bindir == "" {
info.Bindir = "/usr/local/bin"
}
if info.Platform == "" {
info.Platform = "linux"
}
if info.Description == "" {
info.Description = "no description given"
}
info.Version = strings.TrimPrefix(info.Version, "v")
return info
} | csn |
Reflect a given table from the database. | def _load_table(self, name):
""" Reflect a given table from the database. """
table = self._tables.get(name, None)
if table is not None:
return table
if not self.engine.has_table(name):
raise BindingException('Table does not exist: %r' % name,
... | csn |
Render a dump for a boolean value.
@param Model $model
The data we are analysing.
@return string
The rendered markup. | public function process(Model $model)
{
$data = $model->getData() ? 'TRUE' : 'FALSE';
return $this->pool->render->renderSingleChild(
$model->setData($data)
->setNormal($data)
->setType(static::TYPE_BOOL)
);
} | csn |
returns a dict with values from both collections for a given grouping name
Warning: collection2 overrides collection1 if there is a group_key conflict | def _combined_grouping_values(grouping_name,collection_a,collection_b):
"""
returns a dict with values from both collections for a given grouping name
Warning: collection2 overrides collection1 if there is a group_key conflict
"""
new_grouping= collection_a.groupings.get(grouping_name,{}).copy()
... | csn |
Load a test file, run the classifier on it, and then write a Viterbi search
graph for each sequence.
@param testFile
The file to test on. | public void classifyAndWriteViterbiSearchGraph(String testFile, String searchGraphPrefix, DocumentReaderAndWriter<IN> readerAndWriter) throws IOException {
Timing timer = new Timing();
ObjectBank<List<IN>> documents =
makeObjectBankFromFile(testFile, readerAndWriter);
int numWords = 0;
int nu... | csn |
Checks a returned Javascript value where we expect a boolean but could
get null.
@param val The value from Javascript to be checked.
@param def The default return value, which can be null.
@return The actual value, or if null, returns false. | protected Boolean checkBoolean(Object val, Boolean def) {
return (val == null) ? def : (Boolean) val;
} | csn |
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
... | def wrapper(ruby_string, wrapper_prefix, runas=None, *binaries):
'''
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not speci... | csn |
Save paused progress state into Git config. | def set_paused_state(self):
"""Save paused progress state into Git config."""
if self.chosen_config_path is not None:
save_cfg_vals_to_git_cfg(config_path=self.chosen_config_path)
set_state(WORKFLOW_STATES.BACKPORT_PAUSED) | csn |
Delete a file from the filesystem | def remove_resource_file(issue, filepath, ignore_layouts):
"""
Delete a file from the filesystem
"""
if os.path.exists(filepath) and (ignore_layouts is False or issue.elements[0][0] != 'layout'):
print('removing resource: {0}'.format(filepath))
os.remove(os.path.abspath(filepath)) | csn |
Returns true if the given type has a method with the given annotation | public static boolean hasMethodWithAnnotation(Class<?> type,
Class<? extends Annotation> annotationType,
boolean checkMetaAnnotations) {
try {
do {
Method[] methods = type.getDeclaredM... | csn |
Enter main function. | def main(): # pragma: no cover
"""Enter main function."""
entry_point.add_command(CLI.version)
entry_point.add_command(UserCLI.user)
entry_point.add_command(GroupCLI.group)
entry_point.add_command(AuditCLI.audit)
entry_point.add_command(KeyCLI.key)
entry_point() | csn |
Log original response
@param httpServletResponse
@param history
@throws URIException | private void logOriginalResponseHistory(
PluginResponse httpServletResponse, History history) throws URIException {
RequestInformation requestInfo = requestInformation.get();
if (requestInfo.handle && requestInfo.client.getIsActive()) {
logger.info("Storing original response history"... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.