query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Check the input configuration for the buffer size to use when parsing
the incoming headers.
@param props | private void parseIncomingHdrBufferSize(Map<Object, Object> props) {
Object value = props.get(HttpConfigConstants.PROPNAME_INCOMING_HDR_BUFFSIZE);
if (null != value) {
try {
this.incomingHdrBuffSize = rangeLimit(convertInteger(value), HttpConfigConstants.MIN_BUFFER_SIZE, Http... | csn |
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SortableRuleSlice. | func (in SortableRuleSlice) DeepCopy() SortableRuleSlice {
if in == nil {
return nil
}
out := new(SortableRuleSlice)
in.DeepCopyInto(out)
return *out
} | csn |
// FilterIncorrectIPVersion filters out the incorrect IP version case from a slice of IP strings. | func FilterIncorrectIPVersion(ipStrings []string, isIPv6Mode bool) ([]string, []string) {
return filterWithCondition(ipStrings, isIPv6Mode, utilnet.IsIPv6String)
} | csn |
read a variable length integer in unsigned LEB128 format | public static long readVariableValueLength(final byte[] array, final int offset, final boolean reverse) {
long len = 0;
byte v;
long p = 0;
int i = offset;
do {
v = array[i];
len += ((long) (v & (byte) 0x7f)) << p;
p += 7;
if (reverse) {
--i;
} else {
++i;
}
} while (... | csn |
Check the JSON response of the Address API result data.
Will throw an exception if there is an exception or other not expected response.
@param array $response Response data
@throws PostcodeNl_Api_RestClient_AddressNotFoundException
@throws PostcodeNl_Api_RestClient_AuthenticationException
@throws PostcodeNl_Api_RestC... | protected function _checkResponse(array $response)
{
// Data present and status code class is 200-299: all is ok
if (is_array($response['data']) && $response['statusCodeClass'] == 200)
return;
// No valid exception message was returned in the JSON (or no JSON at all)
// Make our own messages based on the H... | csn |
The function creates a private dict for a font that was not CID
All the keys are copied as is except for the subrs key
@param Font the font
@param Subr The OffsetItem for the subrs of the private | void CreateNonCIDPrivate(int Font,OffsetItem Subr)
{
// Go to the beginning of the private dict and read until the end
seek(fonts[Font].privateOffset);
while (getPosition() < fonts[Font].privateOffset+fonts[Font].privateLength)
{
int p1 = getPosition();
getDictItem();
int... | csn |
Turns out we can't deal with remotes if the refspec is missing | def _assert_refspec(self):
"""Turns out we can't deal with remotes if the refspec is missing"""
config = self.config_reader
unset = 'placeholder'
try:
if config.get_value('fetch', default=unset) is unset:
msg = "Remote '%s' has no refspec set.\n"
... | csn |
Increment the counter of sent messages and disconnect the underlying transport if needed. | private function trackLimit()
{
++$this->sent;
if ($this->sent >= $this->limit) {
$this->sent = 0;
$this->transport->disconnect();
}
} | csn |
Store the date the user asked for being asked again later.
@param context | private static void storeAskLaterDate(final Context context) {
SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putLong(KEY_ASK_LATER_DATE, System.currentTimeMillis());
editor.apply();
} | csn |
Removes processed queues and corresponding nodes
@method _autoPurge
@private | function() {
if (purging) {
return;
}
purging = true;
for (var i in queues) {
var q = queues[i];
if (q.autopurge && q.finished) {
_purge(q.tId);
delete queues[i];
}
}
purging = false;
} | csn |
Rename every sequence based on a prefix and a number. | def rename_with_num(self, prefix="", new_path=None, remove_desc=True):
"""Rename every sequence based on a prefix and a number."""
# Temporary path #
if new_path is None: numbered = self.__class__(new_temp_path())
else: numbered = self.__class__(new_path)
# Generat... | csn |
Encode some OffsetFetchRequest structs
:param bytes client_id: string
:param int correlation_id: int
:param bytes group: string, the consumer group you are fetching offsets for
:param list payloads: list of :class:`OffsetFetchRequest` | def encode_offset_fetch_request(cls, client_id, correlation_id,
group, payloads):
"""
Encode some OffsetFetchRequest structs
:param bytes client_id: string
:param int correlation_id: int
:param bytes group: string, the consumer group you are f... | csn |
Get the constructor with size hint for the field type.
@param fieldTypeFullyResolved
the field type
@param classFieldCache
the class field cache
@return the constructor with size hint for the field type | public Constructor<?> getConstructorForFieldTypeWithSizeHint(final Type fieldTypeFullyResolved,
final ClassFieldCache classFieldCache) {
if (!isTypeVariable) {
return constructorForFieldTypeWithSizeHint;
} else {
final Class<?> fieldRawTypeFullyResolved = JSONUtils.ge... | csn |
Plot the swim speed during experimental indices
Args
----
exp_ind: ndarray
Indices of tag data where experiment is active
swim_speed: ndarray
Swim speed data at sensor sampling rate | def plot_swim_speed(exp_ind, swim_speed):
'''Plot the swim speed during experimental indices
Args
----
exp_ind: ndarray
Indices of tag data where experiment is active
swim_speed: ndarray
Swim speed data at sensor sampling rate
'''
import numpy
fig, ax = plt.subplots()
... | csn |
Get the cols and rows ranges to use to loop the original gridcoverage.
@param gridCoverage the coverage.
@param subregion the sub region of the coverage to get the cols and rows to loop on.
@return the array of looping values in the form [minCol, maxCol, minRow, maxRow].
@throws Exception | public static int[] getLoopColsRowsForSubregion( GridCoverage2D gridCoverage, Envelope2D subregion ) throws Exception {
GridGeometry2D gridGeometry = gridCoverage.getGridGeometry();
GridEnvelope2D subRegionGrid = gridGeometry.worldToGrid(subregion);
int minCol = subRegionGrid.x;
int maxC... | csn |
Method to warn the user if the schema has already been added to the
spec. | def warn_if_schema_already_in_spec(self, schema_key):
"""Method to warn the user if the schema has already been added to the
spec.
"""
if schema_key in self.openapi.refs:
warnings.warn(
"{} has already been added to the spec. Adding it twice may "
... | csn |
Retrieves a group based on group id
@param string $groupId The unique identifier for the group
@return Zend_Gdata_Gapps_GroupEntry The group entry as returned by the server. | public function retrieveGroup($groupId)
{
$query = $this->newGroupQuery($groupId);
//$query->setGroupId($groupId);
try {
$group = $this->getGroupEntry($query);
} catch (Zend_Gdata_Gapps_ServiceException $e) {
// Set the group to null if not found
... | csn |
// Satisfy the go-health.ICheckable interface | func (c *customCheck) Status() (interface{}, error) {
// perform some sort of check
if false {
return nil, fmt.Errorf("Something major just broke")
}
// You can return additional information pertaining to the check as long
// as it can be JSON marshalled
return map[string]int{"foo": 123, "bar": 456}, nil
} | csn |
// copyAttributes copies attributes of src not found on dst to dst. | func copyAttributes(dst *Node, src Token) {
if len(src.Attr) == 0 {
return
}
attr := map[string]string{}
for _, t := range dst.Attr {
attr[t.Key] = t.Val
}
for _, t := range src.Attr {
if _, ok := attr[t.Key]; !ok {
dst.Attr = append(dst.Attr, t)
attr[t.Key] = t.Val
}
}
} | csn |
Get authorize response
@param array $params
@param mixed $user_id
@return array | public function getAuthorizeResponse($params, $user_id = null)
{
// build the URL to redirect to
$result = array('query' => array());
$params += array('scope' => null, 'state' => null);
/*
* a refresh token MUST NOT be included in the fragment
*
* @see ht... | csn |
Return the middleware chain to enforce oAuth 2.0 authentication and
authorization
@param {Object} [options] Options object
- scope
- jwt | function authenticate(options) {
options = options || {};
var authenticators = [
passport.authenticate(['copress-oauth2-bearer', 'copress-oauth2-mac'],
options)];
if (options.scopes || options.scope) {
authenticators.push(scopeValidator(options));
... | csn |
// Write adds more data to the running hash.
// Length of data MUST BE less than 1 Gigabytes. | func (self *XXHash) Write(data []byte) (nn int, err error) {
if data == nil {
return 0, errors.New("Data cannot be nil.")
}
l := len(data)
if l > 1<<30 {
return 0, errors.New("Cannot add more than 1 Gigabytes at once.")
}
self.feed(data)
return len(data), nil
} | csn |
Initialize request processing.
This sets home, host, and other request-related properties
based on current request URI. | private function init_request() {
$this->autodetect_home();
$this->autodetect_host();
# initialize from request uri
$url = isset($_SERVER['REQUEST_URI'])
? $_SERVER['REQUEST_URI'] : '';
# remove query string
$rpath = parse_url($url)['path'];
# remove home
if ($rpath != '/')
$rpath = substr($r... | csn |
Writes the font definition | public void writeDefinition(final OutputStream result) throws IOException
{
result.write(FONT_FAMILY);
result.write(FONT_CHARSET);
result.write(intToByteArray(charset));
result.write(DELIMITER);
document.filterSpecialChar(result, fontName, true, false);
} | csn |
Convert a parameter space specification to a directory tree with a
nested structure. | def space_to_folders(self, current_result_list, current_query, param_space,
runs, current_directory):
"""
Convert a parameter space specification to a directory tree with a
nested structure.
"""
# Base case: we iterate over the runs and copy files in the ... | csn |
Returns the form field.
Although FieldHolder is generally what is inserted into templates, all of the field holder
templates make use of $Field. It's expected that FieldHolder will give you the "complete"
representation of the field on the form, whereas Field will give you the core editing widget,
such as an input tag... | public function Field($properties = array())
{
$context = $this;
$this->extend('onBeforeRender', $context, $properties);
if (count($properties)) {
$context = $context->customise($properties);
}
$result = $context->renderWith($this->getTemplates());
// ... | csn |
Creates a new class based on the supplied template, and returnsit.
class Template(object):
def __call__(self, context):
return ''.join(self._iterator(context))
def _iterator(self, context):
return map(str, self._root(context)
def _root(self, context):
y... | def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs):
'''
Creates a new class based on the supplied template, and returnsit.
class Template(object):
def __call__(self, context):
return ''.join(self._iterator(context))
def _iterator(self, context):
... | csn |
On set replicate on write.
@param cfDef
the cf def
@param cfProperties
the cf properties
@param builder
the builder | private void onSetReplicateOnWrite(CfDef cfDef, Properties cfProperties, StringBuilder builder)
{
String replicateOnWrite = cfProperties.getProperty(CassandraConstants.REPLICATE_ON_WRITE);
if (builder != null)
{
String replicateOn_Write = CQLTranslator.getKeyword(CassandraConstan... | csn |
Retorna el Requerimiento actual
@return Support\Request | public function getRequest(){
if($this->httpCore != NULL){
return $this->httpCore->httpRequest;
}else{
return $this->cronCore->cronRequest;
}
} | csn |
Store a new value at the given key
kwargs can hold `cas` and `flags` params | def set(self, key, value, **kwargs):
'''
Store a new value at the given key
kwargs can hold `cas` and `flags` params
'''
return requests.put(
'{}/{}/kv/{}'.format(
self.master, pyconsul.__consul_api_version__, key),
data=value,
... | csn |
get self to other mapping | def get_mapping(self, other):
"""
get self to other mapping
"""
m = next(self._matcher(other).isomorphisms_iter(), None)
if m:
return {v: k for k, v in m.items()} | csn |
Drop index by it's forming columns.
@param array $columns
@return self
@throws SchemaException | public function dropIndex(array $columns): AbstractTable
{
if (empty($schema = $this->current->findIndex($columns))) {
throw new SchemaException(
"Undefined index ['" . join("', '", $columns) . "'] in '{$this->getName()}'"
);
}
//Dropping index from c... | csn |
Creates a new migration.
This command creates a new migration using the available migration template.
After using this command, developers should modify the created migration
skeleton by filling up the actual migration logic.
~~~
yii migrate/create create_user_table
yii migrate/create create_user_table module_name
~~... | public function actionCreate($name, $module = null)
{
if (!empty($module)) {
if (empty($this->allMigrationPaths[$module])) {
throw new Exception("Module $module does not exist or does not contains 'migrations' directory");
}
$this->migrationPath = $this->a... | csn |
Make a POST HTTP request
@param $url
@param $data
@return \Alfredoem\Ragnarok\Soul\RagnarokCurlResponse | public function httpPosRequest($url, $data)
{
$enc = EncryptAes::encrypt($data);
$dataEncrypt = 'data='.$enc;
$dataEncrypt = str_replace('+', '%2B', $dataEncrypt);
$curl = curl_init();
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, count($data... | csn |
Retrieves a map with the predecessors states and the node associated
to each predecessor state.
@param current current state to calculate predecessors of
@return map pairs of <state, node> with the visited predecessors of the state | private Map<Transition<A, S>, N> predecessorsMap(S current){
//Map<Transition, Node> containing predecessors relations
Map<Transition<A, S>, N> mapPredecessors = new HashMap<Transition<A, S>, N>();
//Fill with non-null pairs of <Transition, Node>
for (Transition<A, S> predecessor : prede... | csn |
Performs q-transform on each tile for each q-plane and selects
tile with the maximum energy. Q-transform can then
be interpolated to a desired frequency and time resolution.
Parameters
----------
qplane_tile_dict:
Dictionary containing a list of q-tile tupples for each q-plane
fse... | def qplane(qplane_tile_dict, fseries, return_complex=False):
"""Performs q-transform on each tile for each q-plane and selects
tile with the maximum energy. Q-transform can then
be interpolated to a desired frequency and time resolution.
Parameters
----------
qplane_tile_dict:
Dic... | csn |
// lexToken represents the initial state for token identification. | func lexToken(l *lexer) stateFn {
for {
{
r := l.peek()
switch r {
case binding:
l.next()
return lexBinding
case slash:
return lexNode
case underscore:
l.next()
return lexBlankNode
case quote:
return lexPredicateOrLiteral
}
if unicode.IsLetter(r) {
return lexKeywor... | csn |
Create a socket connection, setting m_socket, using configured parameters. | private void createSocket() throws Exception {
// Some socket options, notably setReceiveBufferSize, must be set before the
// socket is connected. So, first create the socket, then set options, then connect.
if (m_sslParams != null) {
SSLSocketFactory factory = m_sslParams.creat... | csn |
// init registers a driver for the NeutrinoNotify concrete implementation of
// the chainntnfs.ChainNotifier interface. | func init() {
// Register the driver.
notifier := &chainntnfs.NotifierDriver{
NotifierType: notifierType,
New: createNewNotifier,
}
if err := chainntnfs.RegisterNotifier(notifier); err != nil {
panic(fmt.Sprintf("failed to register notifier driver '%s': %v",
notifierType, err))
}
} | csn |
Whether two strings are equal | def is_equal(self, other):
"""
Whether two strings are equal
"""
other = StringCell.coerce(other)
empties = [None,'']
if self.value in empties and other.value in empties:
return True
return self.value == other.value | csn |
Getting the grouped result by the given property
:@param property
:@type property: string
:@return self | def group_by(self, property):
"""Getting the grouped result by the given property
:@param property
:@type property: string
:@return self
"""
self.__prepare()
group_data = {}
for data in self._json_data:
if data[property] not in group_data:
... | csn |
Get a token for specific user.
@param mixed $userId An identify of current user.
@param boolean $forceNew Force create new token.
@return string
@throws \RuntimeException
@throws \UnexpectedValueException
@throws \Exception | public function getFormToken($userId = null, $forceNew = false)
{
$userId = $userId ?: $this->userManager->getUser()->id;
$userId = $userId ?: $this->session->getId();
$config = $this->config;
return md5($config['system.secret'] . $userId . $this->getToken($forceNew));
} | csn |
Gets an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@returns A generator of Vertex or Edge objects | def get(self, key, value):
"""Gets an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@returns A generator of Vertex or Edge objects"""
for element in self.neoindex[key][value]:
if self.indexCl... | csn |
Checks for required fields in table `page`
@return \BackBee\Console\Command\UpgradeToPageSectionCommand
@throws BBException Raises if table `page` doesn't exists or is incomplete | private function checksPageTable()
{
$schemaManager = $this->em->getConnection()->getSchemaManager();
$tableName = $this->em->getClassMetadata('BackBee\NestedNode\Page')->getTableName();
$this->output->write(sprintf(' - Existing table `%s` - ', $tableName));
if (false === $schemaMa... | csn |
// IsFormat checks if input is a correctly formatted e-mail address | func (f EmailFormatChecker) IsFormat(input interface{}) bool {
asString, ok := input.(string)
if !ok {
return false
}
_, err := mail.ParseAddress(asString)
return err == nil
} | csn |
Install or upgrade setuptools and EasyInstall. | def main():
"""Install or upgrade setuptools and EasyInstall."""
options = _parse_args()
archive = download_setuptools(**_download_args(options))
return _install(archive, _build_install_args(options)) | csn |
Finds the right most box out of the given boxes.
:param boxes: Array of Box objects
:return: The right-most Box object | def right_most(boxes):
"""
Finds the right most box out of the given boxes.
:param boxes: Array of Box objects
:return: The right-most Box object
"""
x_list = [(box.x, box) for box in boxes]
x_list.sort()
return x_list[-1][1] | csn |
// Required returns a comma separated list of the required properties for this resource | func (r Resource) Required() string {
required := []string{}
for name, property := range r.Properties {
if property.Required {
required = append(required, `"`+name+`"`)
}
}
// As Go doesn't provide ordering guarentees for maps, we should
// sort the required property names by alphabetical order so that
/... | csn |
Parse experiment parameters from the data directory name
Args
----
name_exp: str
Name of data directory with experiment parameters
Returns
-------
tag_params: dict of str
Dictionary of parsed experiment parameters | def parse_experiment_params(name_exp):
'''Parse experiment parameters from the data directory name
Args
----
name_exp: str
Name of data directory with experiment parameters
Returns
-------
tag_params: dict of str
Dictionary of parsed experiment parameters
'''
if ('/... | csn |
Returns pages in given category with respect to parameters
API Calls for parameters:
- https://www.mediawiki.org/w/api.php?action=help&modules=query%2Bcategorymembers
- https://www.mediawiki.org/wiki/API:Categorymembers
:param page: :class:`WikipediaPage`
:param kwargs: parame... | def categorymembers(
self,
page: 'WikipediaPage',
**kwargs
) -> PagesDict:
"""
Returns pages in given category with respect to parameters
API Calls for parameters:
- https://www.mediawiki.org/w/api.php?action=help&modules=query%2Bcategorymembers
... | csn |
Convert a `Time` into `LIGOTimeGPS`.
This method uses `datetime.datetime` underneath, which restricts
to microsecond precision by design. This should probably be fixed...
Parameters
----------
time : `~astropy.time.Time`
formatted `Time` object to convert
Returns
-------
gps :... | def _time_to_gps(time):
"""Convert a `Time` into `LIGOTimeGPS`.
This method uses `datetime.datetime` underneath, which restricts
to microsecond precision by design. This should probably be fixed...
Parameters
----------
time : `~astropy.time.Time`
formatted `Time` object to convert
... | csn |
Compiles the CSDL of this object
@param string $csdl If a CSDL string is passed to compile it will set the CSDL for the object
@return array Response from the compile | public function compile($csdl = false)
{
if ($csdl) {
$this->_csdl = $csdl;
}
if (strlen($this->_csdl) == 0) {
throw new DataSift_Exception_InvalidData('Cannot compile an empty definition.');
}
$res = $this->_user->post('pylon/compile', array('csdl' ... | csn |
// The return bool value indicates if a cluster IP is allocated successfully. | func initClusterIP(service *api.Service, serviceIPs ipallocator.Interface) (bool, error) {
switch {
case service.Spec.ClusterIP == "":
// Allocate next available.
ip, err := serviceIPs.AllocateNext()
if err != nil {
// TODO: what error should be returned here? It's not a
// field-level validation failure... | csn |
Register a handler that will execute once for an event. Otherwise the same as `on`.
@param {string|Array<string>|Object} evt
@param {function} handler
@param {Object} [thisArg] | function once(evt, handler) {
var thisArg = arguments[2] === undefined ? null : arguments[2];
var wrapper = undefined,
self = this;
// add a wrapper around the handler and listen to the requested event
this.on(evt, wrapper = function () {
... | csn |
Adds a fragment of an RTF document to the current RTF document being generated.
Since this fragment doesn't contain font or color tables, all fonts and colors
are mapped to the default font and color. If the font and color mappings are
known, they can be specified via the mappings parameter.
@param documentSource The ... | public void importRtfFragment(InputStream documentSource, RtfImportMappings mappings) throws IOException, DocumentException {
importRtfFragment(documentSource, mappings, null);
} | csn |
Remove never allowed string, afterwards.
<p>
<br />
INFO: clean-up also some string, if there is no html-tag
</p>
@param string $str
@return string | private function _do_never_allowed_afterwards(string $str): string
{
if (\stripos($str, 'on') !== false) {
foreach (self::$_never_allowed_on_events_afterwards as $event) {
if (\stripos($str, $event) !== false) {
$regex = '(?<before>[^\p{L}]|^)(?:' . $event . '... | csn |
This works just like link_to, but with one difference..
If the link is to the current page, a class of 'active' is added | def link(name, options={}, html_options={})
link_to_unless_current(name, options, html_options) do
html_options[:class] = (html_options[:class] || "").split(" ").push("active").join(" ")
link_to(name, options, html_options)
end
end | csn |
Return the query text to preview.
@return string | private function getQueryText()
{
$queryText = trim(strtolower((string) $this->getRequest()->getParam('query_text_preview', '')));
if ($queryText == '') {
$queryText = null;
}
return $queryText;
} | csn |
The fields returned by default. Typically the output is done via display formatters and hence nearly no
field is necessary. Returning all fields might cause performance problems.
@return the default return fields. | String getDefaultReturnFields() {
StringBuffer fields = new StringBuffer("");
fields.append(CmsSearchField.FIELD_PATH);
fields.append(',');
fields.append(CmsSearchField.FIELD_INSTANCEDATE).append('_').append(getSearchLocale().toString()).append("_dt");
fields.append(',');
... | csn |
Deserialize double data
@param {ArrayBuffer} buffer
@param {number} start - byteOffset
@param {DeserializeOptions} options
@returns {{anchor: number, value: number}} anchor: byteOffset, value: double
@private | function __deserializeFloat64(buffer, start, options) {
let end = start + 8;
let dataView = new DataView(buffer);
let data = dataView.getFloat64(start, true);
return { anchor: end, value: data };
} | csn |
// UpsertCertAuthority updates or inserts a new certificate authority | func (s *CA) UpsertCertAuthority(ca services.CertAuthority) error {
if err := ca.Check(); err != nil {
return trace.Wrap(err)
}
value, err := services.GetCertAuthorityMarshaler().MarshalCertAuthority(ca)
if err != nil {
return trace.Wrap(err)
}
item := backend.Item{
Key: backend.Key(authoritiesPrefix, s... | csn |
// CreateDNSDomain creates a new DNS domain name on Vultr | func (c *Client) CreateDNSDomain(domain, serverIP string) error {
values := url.Values{
"domain": {domain},
"serverip": {serverIP},
}
if err := c.post(`dns/create_domain`, values, nil); err != nil {
return err
}
return nil
} | csn |
Returns the Dynamic Metadata class name from the API name.
@param string $name The Metadata name from the API
@return string The DynamicMetadata class name, as fully qualified class name | public static function getDynamicMetadataClassName($name)
{
// Convert to a CamelCase class name.
// See Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter::denormalize()
$camelCasedName = preg_replace_callback('/(^|_|\.)+(.)/', function ($match) {
retur... | csn |
save model to database
@return $this
@throws HttpForbiddenException | final public function save()
{
if (!$this->createdAt) {
$this->createdAt = new DateTime();
} else {
$this->updatedAt = new DateTime();
}
try {
app('em')->persist($this);
app('em')->flush();
} catch (\Exception $exception) {
... | csn |
Remove a custom field setting on the project.
Parameters
----------
project : {Id} The project to associate the custom field with
[data] : {Object} Data for the request
- [custom_field] : {Id} The id of the custom field to remove from this project. | def remove_custom_field_setting(self, project, params={}, **options):
"""Remove a custom field setting on the project.
Parameters
----------
project : {Id} The project to associate the custom field with
[data] : {Object} Data for the request
- [custom_field] : {Id} Th... | csn |
Checks the validity of the version of the give CWL document.
Returns the document and the validated version string. | def checkversion(doc, # type: Union[CommentedSeq, CommentedMap]
metadata, # type: CommentedMap
enable_dev # type: bool
):
# type: (...) -> Tuple[Union[CommentedSeq, CommentedMap], Text]
"""Checks the validity of the version of the give CWL document.
Returns the d... | csn |
Should be a list of absolute paths | def volumes(val, **kwargs): # pylint: disable=unused-argument
'''
Should be a list of absolute paths
'''
val = helpers.translate_stringlist(val)
for item in val:
if not os.path.isabs(item):
raise SaltInvocationError(
'\'{0}\' is not an absolute path'.format(item)... | csn |
Process a word into a list of strings representing the syllables of the word. This
method describes rules for consonant grouping behaviors and then iteratively applies those
rules the list of letters that comprise the word, until all the letters are grouped into
appropriate syllable groups.
... | def _process(self, word: str) -> List[str]:
"""
Process a word into a list of strings representing the syllables of the word. This
method describes rules for consonant grouping behaviors and then iteratively applies those
rules the list of letters that comprise the word, until all the le... | csn |
// DynamicStatusValuesDo implements the MonitorBackend interface. | func (b *stdBackend) DynamicStatusValuesDo(f func(DynamicStatusValue)) error {
resp, err := b.command(cmdDynamicStatusRetrieversReadAll, f)
if err != nil {
return err
}
dsvs := resp.(DynamicStatusValues)
for _, dsv := range dsvs {
f(dsv)
}
return nil
} | csn |
fast equivalent to % | protected static String print(BiConsumer<Integer,Integer> wait_strategy) {
if(wait_strategy == null) return null;
if(wait_strategy == SPIN) return "spin";
else if(wait_strategy == YIELD) return "yield";
else if(wait_strategy == PARK) r... | csn |
Update the privacy list.
@memberof QB.chat.privacylist
@param {String} name - The name of the list.
@param {updatePrivacylistCallback} callback - The callback function. | function(listWithUpdates, callback) {
/**
* Callback for QB.chat.privacylist.update().
* @param {Object} error - The error object
* @param {Object} response - The privacy list object
* @callback updatePrivacylistCallback
* */
var self = this;
self.g... | csn |
Return datetime of oldest existing data record whose
datetime is >= idx.
Might not even be in the same year! If no such record exists,
return None. | def after(self, idx):
"""Return datetime of oldest existing data record whose
datetime is >= idx.
Might not even be in the same year! If no such record exists,
return None."""
if not isinstance(idx, datetime):
raise TypeError("'%s' is not %s" % (idx, datetime))
... | csn |
Return the gui and mpl backend. | def find_gui_and_backend():
"""Return the gui and mpl backend."""
matplotlib = sys.modules['matplotlib']
# WARNING: this assumes matplotlib 1.1 or newer!!
backend = matplotlib.rcParams['backend']
# In this case, we need to find what the appropriate gui selection call
# should be for IPython, so ... | csn |
Creates an identical expectation for each of the given columns with the specified arguments, if any.
Args:
df (great_expectations.dataset): A great expectations dataset object.
columns (list): A list of column names represented as strings.
expectation_type (string): The expectation type.
... | def create_multiple_expectations(df, columns, expectation_type, *args, **kwargs):
"""Creates an identical expectation for each of the given columns with the specified arguments, if any.
Args:
df (great_expectations.dataset): A great expectations dataset object.
columns (list): A list of column ... | csn |
Return the label of the holiday, if the date is a holiday | def get_holiday_label(self, day):
"""Return the label of the holiday, if the date is a holiday"""
day = cleaned_date(day)
return {day: label for day, label in self.holidays(day.year)
}.get(day) | csn |
Function returns the inverse square root of R matrix on step k. | def R_isrk(self, k):
"""
Function returns the inverse square root of R matrix on step k.
"""
ind = int(self.index[self.R_time_var_index, k])
R = self.R[:, :, ind]
if (R.shape[0] == 1): # 1-D case handle simplier. No storage
# of the result, just compute it e... | csn |
Return the short url in HTML. | def get_short_url(self, entry):
"""
Return the short url in HTML.
"""
try:
short_url = entry.short_url
except NoReverseMatch:
short_url = entry.get_absolute_url()
return format_html('<a href="{url}" target="blank">{url}</a>',
... | csn |
Binds the given callable to the monad's managed code-block's successful execution.
@param callable $codeBlock Is expected to return an instance of Eventually.
@return Eventually | public function bind(callable $codeBlock)
{
assert($this->result === null, "'Eventually' instance may not be mutated after code-block execution.");
return static::unit(function ($success) use ($codeBlock) {
$this->run(function ($value) use ($codeBlock, $success) {
return... | csn |
// AddFlags adds flags related to AttachDetachController for controller manager to the specified FlagSet. | func (o *AttachDetachControllerOptions) AddFlags(fs *pflag.FlagSet) {
if o == nil {
return
}
fs.BoolVar(&o.DisableAttachDetachReconcilerSync, "disable-attach-detach-reconcile-sync", false, "Disable volume attach detach reconciler sync. Disabling this may cause volumes to be mismatched with pods. Use wisely.")
fs... | csn |
Retrieve node with passed name | def get_node(self, node_name):
"""Retrieve node with passed name"""
for node in self.nodes:
if node.__name__ == node_name:
return node | csn |
Determines whether the priority passed as parameter is enabled in the
underlying SLF4J logger. Each log4j priority is mapped directly to its
SLF4J equivalent, except for FATAL which is mapped as ERROR.
@param p
the priority to check against
@return true if this logger is enabled for the given level, false
otherwise. | public boolean isEnabledFor(Priority p) {
switch (p.level) {
case Level.TRACE_INT:
return slf4jLogger.isTraceEnabled();
case Level.DEBUG_INT:
return slf4jLogger.isDebugEnabled();
case Level.INFO_INT:
return slf4jLogger.isInfoEnabled();
case Lev... | csn |
// GetToken will parse the token from http Authorization Header. | func GetToken(r *http.Request) (string, error) {
header := r.Header.Get("Authorization")
if header == "" {
return "", ErrAuthHeaderMissing
}
if !strings.HasPrefix(header, tokenScheme) {
return "", ErrAuthBadScheme
}
return header[len(tokenScheme):], nil
} | csn |
// List retrieves a list of registered customers. | func (c *CustomersService) List(options *ListCustomersOptions) ([]*Customer, *http.Response, error) {
return c.ListWithContext(context.TODO(), options)
} | csn |
// Change requests a change in the given device's features. | func (e *Ethtool) Change(intf string, config map[string]bool) error {
names, err := e.FeatureNames(intf)
if err != nil {
return err
}
length := uint32(len(names))
features := ethtoolSfeatures{
cmd: ETHTOOL_SFEATURES,
size: (length + 32 - 1) / 32,
}
for key, value := range config {
if index, ok := nam... | csn |
Return the HTTP header
@return array | public function getHeaders()
{
$headerFields = array_keys($this->headers);
$result = array();
foreach ($headerFields as $field) {
$result[] = sprintf('%s: %s', $field, $this->getHeader($field));
}
return $result;
} | csn |
Get the element matching the given selector.
@param string $selector
@return ?Element | public function element(string $selector): ?Element
{
$element = $this->resolver->find($selector);
return self::convertElement($element, $this->driver);
} | csn |
Converts a PHP boolean to an SQL boolean
@param bool $boolean The boolean to convert
@param Provider $provider The provider to convert to
@return mixed The SQL boolean suitable for database storage | public function toSqlBoolean(bool $boolean, Provider $provider = null)
{
$this->setParameterProvider($provider);
return $provider->convertToSqlBoolean($boolean);
} | csn |
Check a constant value and report if it is a string that is
too large. | private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
if (nerrs != 0 || // only complain about a long string once
constValue == null ||
!(constValue instanceof String) ||
((String)constValue).length() < Pool.MAX_STRING_LENGTH)
return;
... | csn |
Reads one or more text files and returns them joined together.
A title is automatically created based on the file name.
Args:
*file_paths: list of files to aggregate
Returns: content of files | def read_local_files(*file_paths: str) -> str:
"""
Reads one or more text files and returns them joined together.
A title is automatically created based on the file name.
Args:
*file_paths: list of files to aggregate
Returns: content of files
"""
def _read_single_file(file_path):
... | csn |
When date_order is less then check-in date or
Checkout date should be greater than the check-in date. | def check_in_out_dates(self):
"""
When date_order is less then check-in date or
Checkout date should be greater than the check-in date.
"""
if self.checkout and self.checkin:
if self.checkin < self.date_order:
raise ValidationError(_('Check-in date sho... | csn |
Factory to create same parent checker function
@param preprocessFn called on each value before comparison
@returns {Function} same parent checker function | function sameParentChecker (preprocessFn) {
return function (suggestions) {
if (suggestions.length === 0) {
return false;
}
if (suggestions.length === 1) {
return true;
}
var parentValue = preprocessFn(suggestions[0].value),
aliens = sugge... | csn |
Determines if the chosen hash function is long enough for the table
configuration used. | private static boolean isHashConfigurationIsSupported(long numBuckets, int tagBits, int hashSize) {
int hashBitsNeeded = getTotalBitsNeeded(numBuckets, tagBits);
switch (hashSize) {
case 32:
case 64:
return hashBitsNeeded <= hashSize;
default:
}
if (hashSize >= 128)
return tagBits <= 64 && ... | csn |
Generate sensorimotor sequences of length sequenceLength.
@param sequenceLength (int)
Length of the sensorimotor sequence.
@return (tuple) Contains:
sensorySequence (list)
Encoded sensory input for whole sequence.
motorSequence (list)
... | def generateSensorimotorSequence(self, sequenceLength):
"""
Generate sensorimotor sequences of length sequenceLength.
@param sequenceLength (int)
Length of the sensorimotor sequence.
@return (tuple) Contains:
sensorySequence (list)
Encoded sensory input for wh... | csn |
// Debugf print a formatted debug line. | func (api *Client) Debugf(format string, v ...interface{}) {
if api.debug {
api.log.Output(2, fmt.Sprintf(format, v...))
}
} | csn |
Restores a number tuple from hashed using the given `alphabet` index. | def _unhash(hashed, alphabet):
"""Restores a number tuple from hashed using the given `alphabet` index."""
number = 0
len_alphabet = len(alphabet)
for character in hashed:
position = alphabet.index(character)
number *= len_alphabet
number += position
return number | csn |
// cancelConnReqs stops all persistent connection requests for a given pubkey.
// Any attempts initiated by the peerTerminationWatcher are canceled first.
// Afterwards, each connection request removed from the connmgr. The caller can
// optionally specify a connection ID to ignore, which prevents us from
// canceling ... | func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
// First, cancel any lingering persistent retry attempts, which will
// prevent retries for any with backoffs that are still maturing.
if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
close(cancelChan)
delete(s.persistentRetryCancels, pubS... | csn |
Put a custom value into context.
@param key The key to get value.
@param value The value.
@param <T> The type of value. | public <T> void putCustom(String key, T value) {
custom.put(key, value);
} | csn |
// CreateDatabase creates a new database with given name and opens a connection to it.
// If the a database with given name already exists, a DuplicateError is returned. | func (c *client) CreateDatabase(ctx context.Context, name string, options *CreateDatabaseOptions) (Database, error) {
input := struct {
CreateDatabaseOptions
Name string `json:"name"`
}{
Name: name,
}
if options != nil {
input.CreateDatabaseOptions = *options
}
req, err := c.conn.NewRequest("POST", path.J... | csn |
Instructs the speech recognizer how to process the speech audio.
Generated from protobuf field <code>.google.cloud.dialogflow.v2.InputAudioConfig audio_config = 1;</code>
@param \Google\Cloud\Dialogflow\V2\InputAudioConfig $var
@return $this | public function setAudioConfig($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dialogflow\V2\InputAudioConfig::class);
$this->writeOneof(1, $var);
return $this;
} | csn |
Delete an update campaign.
:param str campaign_id: Campaign ID to delete (Required)
:return: void | def delete_campaign(self, campaign_id):
"""Delete an update campaign.
:param str campaign_id: Campaign ID to delete (Required)
:return: void
"""
api = self._get_api(update_service.DefaultApi)
api.update_campaign_destroy(campaign_id)
return | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.