query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Update the configuration hold by this object
@param pExtractor an extractor for retrieving the configuration from some external object | public void updateGlobalConfiguration(ConfigExtractor pExtractor) {
Enumeration e = pExtractor.getNames();
while (e.hasMoreElements()) {
String keyS = (String) e.nextElement();
ConfigKey key = ConfigKey.getGlobalConfigKey(keyS);
if (key != null) {
glob... | csn |
Returns a presigned URL string with given HTTP method, expiry time and custom request params for a specific object
in the bucket.
</p><b>Example:</b><br>
<pre>{@code String url = minioClient.getPresignedObjectUrl(Method.DELETE, "my-bucketname", "my-objectname",
60 * 60 * 24, reqParams);
System.out.println(url); }</pre... | public String getPresignedObjectUrl(Method method, String bucketName, String objectName, Integer expires,
Map<String, String> reqParams)
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoRespon... | csn |
// NewMetaLink creates a new link with metadata encoded as an object. | func NewMetaLink(href string, meta map[string]interface{}) *Link {
return &Link{
HREF: href,
Meta: meta,
}
} | csn |
Configure all providers.
@return void | protected function configureEach() {
foreach ($this->providers as $class => &$data) {
if ( ! array_contains(array_get($data, 'tags'), ProviderTag::CONFIGURED)) {
$this->create();
array_add($data, 'tags', ProviderTag::CONFIGURED);
$instance = array_get... | csn |
Upload the file. You can upload files up to 2 GB with the REST API. | function (attachment) {
// Define custom metadata properties for the file before saving
var customFileMetadata = {};
var parentItemId = model.getParentItemId();
if (parentItemId && parentItemId != '') customFileMetadata[scope.attachmentFilt... | csn |
Maintains state of the Live Preview menu item | function _setupGoLiveMenu() {
LiveDevImpl.on("statusChange", function statusChange(event, status) {
// Update the checkmark next to 'Live Preview' menu item
// Add checkmark when status is STATUS_ACTIVE; otherwise remove it
CommandManager.get(Commands.FILE_LIVE_FILE_PREVIEW).... | csn |
Returns a list of SSL certificates for a particular user
ListType : All
Possible values:
- All
- Processing
- EmailSent
- TechnicalProblem
- InProgress
- Completed
- Deactivated
- Active
- Cancelled
- NewPurchase
- New... | def get_list(**kwargs):
'''
Returns a list of SSL certificates for a particular user
ListType : All
Possible values:
- All
- Processing
- EmailSent
- TechnicalProblem
- InProgress
- Completed
- Deactivated
- Active
- Cancelled... | csn |
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash | def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key) | csn |
error message manipulator | def filter_backtrace(bt)
case IRB.conf[:CONTEXT_MODE]
when 0
return nil if bt =~ /\(irb_local_binding\)/
when 1
if(bt =~ %r!/tmp/irb-binding! or
bt =~ %r!irb/.*\.rb! or
bt =~ /irb\.rb/)
return nil
end
when 2
return nil if bt =~ /irb\/.*\.rb/
when 3
return nil if bt =~ /irb\... | csn |
// NewLogger allocates and returns a new logger which sends events to handler. | func NewLogger(handler Handler) *Logger {
return &Logger{
Handler: handler,
EnableSource: true,
EnableDebug: true,
}
} | csn |
Generatesa random string
@param int $length [optional] <p>The length of the random string to generate
</p>
@return self | public static function createRandomAlphaNumeric($length = 8)
{
$chars = array("abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "123456789");
$count = array((strlen($chars[0]) - 1), (strlen($chars[1]) - 1));
$prefix = "";
for ($i = 0; $i < $length; $i++) {
$type = ... | csn |
Return a dictionary to send to the API.
Returns:
dict: Mapping representing this object that can be sent to the
API. | def to_api(self):
"""Return a dictionary to send to the API.
Returns:
dict: Mapping representing this object that can be sent to the
API.
"""
vals = {}
for attribute, attribute_type in self._props.items():
prop = getattr(self, attribute)
... | csn |
Handler when selected radio button changed. | def radio_buttons_clicked(self):
"""Handler when selected radio button changed."""
# Disable all spin boxes
for spin_box in list(self.spin_boxes.values()):
spin_box.setEnabled(False)
# Disable list widget
self.list_widget.setEnabled(False)
# Get selected radi... | csn |
Load events from history file
=== Return
events(Array):: List of historical events with each being a hash of
:time(Integer):: Time in seconds in Unix-epoch when event occurred
:pid(Integer):: Process id of agent recording the event
:event(Object):: Event object in the form String or {String => Object},
... | def load
events = []
File.open(@history, "r") { |f| events = f.readlines.map { |l| JSON.legacy_load(l) } } if File.readable?(@history)
events
end | csn |
Create a focus listener to attach to the textComponent and dataEditorButton that will decide what
happens with the changed value. Here a revert can be done if no value is selected or a new value can be
created as needed.
@return a focus listener. | protected FocusListener createFocusListener() {
return new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
String textFieldValue = getKeyComponentText();
boolean empty = "".equals(textFieldValue.trim());
Object ref = Looku... | csn |
True if the user commented the ticket in given time frame | def updated(self, user):
""" True if the user commented the ticket in given time frame """
for who, what, old, new in self.history(user):
if (what == "comment" or what == "description") and new != "":
return True
return False | csn |
// getMirrorReference returns the reference to the metadata file containing mirrors for the specified content and cloud. | func (mirrorRefs *MirrorRefs) getMirrorReference(datatype, contentId string, cloud CloudSpec) (*MirrorReference, error) {
candidates := mirrorRefs.extractMirrorRefs(contentId)
if len(candidates) == 0 {
return nil, errors.NotFoundf("mirror data for %q", contentId)
}
// Restrict by cloud spec and datatype.
hasRigh... | csn |
Starts a new agent using the data in the given object, creating a new bureau if necessary. | public void startAgent (AgentObject agent)
{
agent.setLocal(AgentData.class, new AgentData());
Bureau bureau = _bureaus.get(agent.bureauId);
if (bureau != null && bureau.ready()) {
_omgr.registerObject(agent);
log.info("Bureau ready, sending createAgent", "agent", a... | csn |
Ensure path has a trailing slash.
@param string $path
@param string $slash
@return string | public static function addTrailingSlash( $path, $slash = DIRECTORY_SEPARATOR ) {
$path = static::normalizePath( $path, $slash );
$path = preg_replace( '~' . preg_quote( $slash, '~' ) . '*$~', $slash, $path );
return $path;
} | csn |
Saves archive modules
@return boolean | public function saveAsOption($key)
{
$key = 'modularity_' . $key;
$optionName = $key . '_modules';
if (isset($_POST['modularity_modules'])) {
$data = $this->sanitizeModuleData($_POST['modularity_modules']);
if (get_option($optionName)) {
update_option... | csn |
Delete variables that are already defined in the main configuration file
@param Config $means Main configuration file
@param Config $target Imported configuration file
@return Config | public function clear(Config $means, Config $target)
{
foreach ($target as $key => $value) {
if ($value instanceof BaseConfig && isset($means[$key])) {
$this->clear($means[$key], $value);
} else {
if (isset($means[$key])) {
$target-... | csn |
Calculating string width
@param text String to calculate
@return width of String in pixels | private float measureStringWidth(String text) {
Paint mPaint = new Paint();
mPaint.setTextSize(baselineDropDownViewFontSize * bootstrapSize);
return (float) (DimenUtils.dpToPixels(mPaint.measureText(text)));
} | csn |
Check if PNGs passed are interlaced and make a temporary de-interlaced
version if they are.
De-interlaced versions are stored in the system temp directory and are
unlinked when the class is destructed.
@param string $file Filename of the PNG file to be checked
@return string Filename of a non-interlaced PNG | private function fixInterlacedPNG($file)
{
if (isset($this->interlacedPNGs[$file])) {
return $this->interlacedPNGs[$file];
}
$handle = fopen($file, "r");
if (!$handle) {
$this->Error("Cannot open ".$file);
}
$contents = fread($handle, 32);
... | csn |
// isValid returns true if, and only if,
// a Message instance is sufficiently initialized to send via the Mailgun interface. | func isValid(m *Message) bool {
if m == nil {
return false
}
if !m.specific.isValid() {
return false
}
if m.RecipientCount() == 0 {
return false
}
if !validateStringList(m.tags, false) {
return false
}
if !validateStringList(m.campaigns, false) || len(m.campaigns) > 3 {
return false
}
return t... | csn |
// Init builds the underlying structs for the network processes. | func (sdn *OpenShiftSDN) Init() error {
// Build the informers
var err error
err = sdn.buildInformers()
if err != nil {
return fmt.Errorf("failed to build informers: %v", err)
}
// Configure SDN
err = sdn.initSDN()
if err != nil {
return fmt.Errorf("failed to initialize SDN: %v", err)
}
// Configure the... | csn |
Copies a file to a target directory | def copy_file_if_missing(file, to_directory)
unless File.exists? File.join(to_directory, File.basename(file))
FileUtils.cp(file, to_directory)
end
end | csn |
Gives the Flesch-Kincaid Reading Ease of text entered rounded to one digit
@param boolean|string $strText Text to be checked
@return int|float | public function fleschKincaidReadingEase($strText = false)
{
$strText = $this->setText($strText);
$score = Maths::bcCalc(
Maths::bcCalc(
206.835,
'-',
Maths::bcCalc(
1.015,
'*',
T... | csn |
Convert hours, minutes, seconds, and microseconds to fractional days.
Parameters
----------
hour : int, optional
Hour number. Defaults to 0.
min : int, optional
Minute number. Defaults to 0.
sec : int, optional
Second number. Defaults to 0.
micro : int, optional
... | def hmsm_to_days(hour=0,min=0,sec=0,micro=0):
"""
Convert hours, minutes, seconds, and microseconds to fractional days.
Parameters
----------
hour : int, optional
Hour number. Defaults to 0.
min : int, optional
Minute number. Defaults to 0.
sec : int, optional
Seco... | csn |
//createFields makes the map of tags for the logstash config including the type | func createFields(hostID string, hostIPs string, svcPath string, service *service.Service, instanceID string, logConfig *servicedefinition.LogConfig) map[string]string {
fields := make(map[string]string)
fields["type"] = logConfig.Type
fields["service"] = service.ID
fields["instance"] = instanceID
fields["hostips"... | csn |
Put a list of dates for blog posts into the template context. | def blog_months(*args):
"""
Put a list of dates for blog posts into the template context.
"""
dates = BlogPost.objects.published().values_list("publish_date", flat=True)
date_dicts = [{"date": datetime(d.year, d.month, 1)} for d in dates]
month_dicts = []
for date_dict in date_dicts:
... | csn |
Invoke the given the watcher appropriately given a Event object. | def _call_watcher(self_, watcher, event):
"""
Invoke the given the watcher appropriately given a Event object.
"""
if self_.self_or_cls.param._TRIGGER:
pass
elif watcher.onlychanged and (not self_._changed(event)):
return
if self_.self_or_cls.para... | csn |
Drops a driver from the DriverManager's list. | protected void unregisterDriver(){
String jdbcURL = this.config.getJdbcUrl();
if ((jdbcURL != null) && this.config.isDeregisterDriverOnClose()){
logger.info("Unregistering JDBC driver for : "+jdbcURL);
try {
DriverManager.deregisterDriver(DriverManager.getDriver(jdbcURL));
} catch (SQLException e... | csn |
Get config from local config file, first try cache, then fallback. | def get_conf_file(self):
"""
Get config from local config file, first try cache, then fallback.
"""
for conf_file in [self.collection_rules_file, self.fallback_file]:
logger.debug("trying to read conf from: " + conf_file)
conf = self.try_disk(conf_file, self.gpg)
... | csn |
Logout and provides an authentication result.
@param Adapter\AdapterInterface|null $adapter
@param Request $request
@return AuthenticationResult
@throws \Xloit\Bridge\Zend\Authentication\Exception\AuthenticationStopException
@throws \Xloit\Bridge\Zend\Authentication\Exception\RuntimeException
@t... | public function logout(Adapter\AdapterInterface $adapter = null, Request $request = null)
{
$event = $this->prepareEvent($adapter, $request);
$event->setResult($event->getAdapter()->logout());
$this->clearIdentity();
return $this->triggerEventResult(AuthenticationEvent::AUTH_LOGOU... | csn |
returns the number of search hits for a manufacturer.
@param int $iShopSearchCacheId
@param bool $bApplyActiveFilter - set to true if you want to count only hits that match the current filter
@return int | public function GetNumberOfHitsForSearchCacheId($iShopSearchCacheId, $bApplyActiveFilter = false)
{
$iNumHits = 0;
if ($bApplyActiveFilter) {
$query = "SELECT COUNT(DISTINCT `shop_search_cache_item`.`id`) AS hits
FROM `shop_search_cache_item`
INNER JOIN... | csn |
Increase the latitude and longitude of the Location.
@param $latitude
@param $longitude
@return $this | public function add($latitude, $longitude)
{
$this->latitude += $latitude;
$this->longitude += $longitude;
return $this;
} | csn |
returns OrderHash so you can fetch it and cancel it... but there is a OrderNumber that you can
intercept if you need to. | @Override
public String placeLimitOrder(LimitOrder placeOrder) {
OrderType type = placeOrder.getType();
Currency baseCurrency = placeOrder.getCurrencyPair().base;
Currency counterCurrency = placeOrder.getCurrencyPair().counter;
BigDecimal originalAmount = placeOrder.getOriginalAmount();
BigDecimal... | csn |
Force the values of the criterion to be evolved.
@api private
@example Force values to booleans.
selectable.force_typing(criterion) do |val|
Boolean.evolve(val)
end
@param [ Hash ] criterion The criterion.
@since 1.0.0 | def typed_override(criterion, operator)
if criterion
criterion.update_values do |value|
yield(value)
end
end
__override__(criterion, operator)
end | csn |
Get query builder to load Content Info data.
@see loadContentInfo(), loadContentInfoByRemoteId(), loadContentInfoList(), loadContentInfoByLocationId()
@param bool $joinMainLocation
@return \Doctrine\DBAL\Query\QueryBuilder | private function createLoadContentInfoQueryBuilder(bool $joinMainLocation = true): DoctrineQueryBuilder
{
$queryBuilder = $this->connection->createQueryBuilder();
$expr = $queryBuilder->expr();
$joinCondition = $expr->eq('c.id', 't.contentobject_id');
if ($joinMainLocation) {
... | csn |
Extract content from Maxima TeX output.
@param string $data
@return bool|mixed | protected static function _parseTex(string $data) {
preg_match('{\\$\\$([\\S\\s]*?)\\$\\$}', $data, $matches);
if (isset($matches[0])) {
$str = str_replace(["\r", "\n"], '', $matches[1]);
return $str;
}
return false;
} | csn |
// BlockSize returns the block size to use for the given file size | func BlockSize(fileSize int64) int {
var blockSize int
for _, blockSize = range BlockSizes {
if fileSize < DesiredPerFileBlocks*int64(blockSize) {
break
}
}
return blockSize
} | csn |
Pretty print an object as YAML. | def print_yaml(o):
"""Pretty print an object as YAML."""
print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8')) | csn |
Return True iff mime_type is acceptable for one of accept_patterns.
Note that this function assumes that all patterns in accept_patterns
will be simple types of the form "type/subtype", where one or both
of these can be "*". We do not support parameters (i.e. "; q=") in
patterns.
Args:
accep... | def AcceptableMimeType(accept_patterns, mime_type):
"""Return True iff mime_type is acceptable for one of accept_patterns.
Note that this function assumes that all patterns in accept_patterns
will be simple types of the form "type/subtype", where one or both
of these can be "*". We do not support param... | csn |
// RuleMatching implements the ScanCallbackMatch interface for
// MatchRules. | func (mr *MatchRules) RuleMatching(r *Rule) (abort bool, err error) {
metas := r.Metas()
// convert int to int32 for code that relies on previous behavior
for s := range metas {
if i, ok := metas[s].(int); ok {
metas[s] = int32(i)
}
}
*mr = append(*mr, MatchRule{
Rule: r.Identifier(),
Namespace: r.... | csn |
Select a persona for each entity declared in the scene.
:param personae: A sequence of Personae.
:param bool relative: Affects imports from namespace packages.
Used for testing only.
:param int roles: The maximum number of roles allocated to each persona.
:return: An Ordered... | def select(self, personae, relative=False, roles=1):
"""Select a persona for each entity declared in the scene.
:param personae: A sequence of Personae.
:param bool relative: Affects imports from namespace packages.
Used for testing only.
:param int roles: The maximum number... | csn |
End access-context use for DBFlute. | public static void endAccessContext() {
AccessContext.clearAccessContextOnThread();
final AccessContext accessContext = SuspendedAccessContext.getAccessContextOnThread();
if (accessContext != null) { // resume
AccessContext.setAccessContextOnThread(accessContext);
Suspend... | csn |
setter for the policy descriptor | def policy(self, args):
"""
setter for the policy descriptor
"""
word = args[0]
if word == 'reject':
self.accepted_ports = None
self.rejected_ports = []
target = self.rejected_ports
elif word == 'accept':
self.accepted_por... | csn |
Order the results by the specified fields
The fields are the names of the fields to sort, defaulting to sorting by descending.
You can prefix a field name with '-' to indicate sorting by descending or '+' to sort by ascending
@param field Field to use
@param ordering Ordering type | public void _orderByDescending(String field, OrderingType ordering) {
assertNoRawQuery();
String f = ensureValidFieldName(field, false);
orderByTokens.add(OrderByToken.createDescending(f, ordering));
} | csn |
Count the number of blank lines in the header | def count_header_blanks(lines, count):
"""
Count the number of blank lines in the header
"""
blanks = 0
for i in range(2, count + 2):
pair = _extract_header_value(lines[i])
if not pair:
blanks += 1
return blanks | csn |
The user making this call must be a member of the team in order to add others.
The user to add must exist in the same organization as the team in order to be added.
The user to add can be referenced by their globally unique user ID or their email address.
Returns the full user record for the added user.
@param team G... | public ItemRequest<Team> addUser(String team) {
String path = String.format("/teams/%s/addUser", team);
return new ItemRequest<Team>(this, Team.class, path, "POST");
} | csn |
Returns custom HTTP method for provided list of resources, arguments, method.
@param string $httpMethod current HTTP method
@param string[] $resources resources list
@param \ReflectionParameter[] $arguments list of method arguments
@return string | private function getCustomHttpMethod($httpMethod, array $resources, array $arguments)
{
if (in_array($httpMethod, $this->availableConventionalActions)) {
// allow hypertext as the engine of application state
// through conventional GET actions
return 'get';
}
... | csn |
Depends on the directory
@param $directory
@return mixed | protected function directory( $directory = null )
{
switch ( $directory ) {
case 'storage':
$this->comment('Cleaning assets library in storage.');
$count = 0;
foreach ($this->filesystem->files( $this->directory['storage'] ) as $file)
... | csn |
// Extract bits from uint64 using LSB 0 numbering, including lo. | func eb64(bits uint64, hi uint8, lo uint8) uint64 {
m := uint64(((1 << (hi - lo)) - 1) << lo)
return (bits & m) >> lo
} | csn |
Get file for scan by id
@param int $appId
@param int $scanId
@param int $fileId
@param array $queryParams
@return FileResponse | public function getById($appId, $scanId, $fileId, array $queryParams = [])
{
$response = $this->api
->applications()
->scans()
->files()
->getById($appId, $scanId, $fileId, $queryParams);
return new FileResponse($response);
} | csn |
Count total number of items in collection
@return mixed | public function totalCount()
{
if (!isset($this->parameters['conditions'])) {
return count($this->value);
}
if (!$this->totalCount) {
if (is_callable($this->totalCountCalculation)) {
$this->totalCount = ($this->totalCountCalculation)();
} ... | csn |
Attach an iface to a vm. | def _attach(cls, iface_id, vm_id):
""" Attach an iface to a vm. """
oper = cls.call('hosting.vm.iface_attach', vm_id, iface_id)
return oper | csn |
Is the host name one allowed by the system
@param string $fullHost
@return boolean | public function isAllowedHost($fullHost)
{
$host = \MUtil_String::stripToHost($fullHost);
$request = $this->request;
if ($request instanceof \Zend_Controller_Request_Http) {
if ($host == \MUtil_String::stripToHost($request->getServer('HTTP_HOST'))) {
return true;
... | csn |
// PgTsConfigByCfgnameCfgnamespace retrieves a row from 'pg_catalog.pg_ts_config' as a PgTsConfig.
//
// Generated from index 'pg_ts_config_cfgname_index'. | func PgTsConfigByCfgnameCfgnamespace(db XODB, cfgname pgtypes.Name, cfgnamespace pgtypes.Oid) (*PgTsConfig, error) {
var err error
// sql query
const sqlstr = `SELECT ` +
`tableoid, cmax, xmax, cmin, xmin, oid, ctid, cfgname, cfgnamespace, cfgowner, cfgparser ` +
`FROM pg_catalog.pg_ts_config ` +
`WHERE cfgna... | csn |
Find instructions in a certain class that are of a certain set of opcodes.
@param insnList instruction list to search through
@param opcodes opcodes to search for
@return list of instructions that contain the opcodes being searched for
@throws NullPointerException if any argument is {@code null}
@throws IllegalArgument... | public static List<AbstractInsnNode> searchForOpcodes(InsnList insnList, int ... opcodes) {
Validate.notNull(insnList);
Validate.notNull(opcodes);
Validate.isTrue(opcodes.length > 0);
List<AbstractInsnNode> ret = new LinkedList<>();
Set<Integer> opcodeSet = new ... | csn |
Gets or initializes a service context. | private RaftServiceContext getOrInitializeService(PrimitiveId primitiveId, PrimitiveType primitiveType, String serviceName, byte[] config) {
// Get the state machine executor or create one if it doesn't already exist.
RaftServiceContext service = raft.getServices().getService(serviceName);
if (service == nu... | csn |
Get a required property by base property and property name
@param base
base property
@param property
property
@return property value | public static String getProperty(String base, String property) {
return getProperty(base, property, true);
} | csn |
Gets the line number of the character at the specified index.
If the result is unknown, -1 is returned. | def linenum(self, index):
"""Gets the line number of the character at the specified index.
If the result is unknown, -1 is returned."""
if len(self._lines) == 0 and self.refstring != "":
self._lines = self.refstring.split("\n")
#Add one for the \n that we split on for eac... | csn |
// Check if another account is authorized to import from us. | func (a *Account) checkStreamImportAuthorized(account *Account, subject string, imClaim *jwt.Import) bool {
// Find the subject in the exports list.
a.mu.RLock()
defer a.mu.RUnlock()
return a.checkStreamImportAuthorizedNoLock(account, subject, imClaim)
} | csn |
Parse a one or more expected arguments of a given type and add them to
the results.
@param type [Symbol] the type of the individual elements of the list
@param sym [Symbol] the key to store the results under in {results}
@param count [Integer, nil] the size of the list, or nil if the list
absorbs all following a... | def parse_list!(type, sym, count)
args = if count
@args.shift count
else
@args
end
@results[sym] = Parser.parse_list type, args
end | csn |
Validate and process the COMMIT specified.
If validation is successful, return the message to the node.
:param commit: an incoming COMMIT message
:param sender: name of the node that sent the COMMIT | def processCommit(self, commit: Commit, sender: str) -> None:
"""
Validate and process the COMMIT specified.
If validation is successful, return the message to the node.
:param commit: an incoming COMMIT message
:param sender: name of the node that sent the COMMIT
"""
... | csn |
Initialize GET received parameters
:param django.http.HttpRequest request: The current request object | def init_get(self, request):
"""
Initialize GET received parameters
:param django.http.HttpRequest request: The current request object
"""
self.request = request
self.service = request.GET.get('service')
self.renew = bool(request.GET.get('renew') and requ... | csn |
// Verify is not implemented | func (g *GPG) Verify(ctx context.Context, sigf string, in string) error {
sig, err := ioutil.ReadFile(sigf)
if err != nil {
return err
}
b, _ := clearsign.Decode(sig)
infh, err := os.Open(in)
if err != nil {
return err
}
defer infh.Close()
_, err = openpgp.CheckDetachedSignature(g.pubring, infh, bytes.NewR... | csn |
// Source generates the source for the term suggester. | func (q *TermSuggester) Source(includeName bool) (interface{}, error) {
// "suggest" : {
// "my-suggest-1" : {
// "text" : "the amsterdma meetpu",
// "term" : {
// "field" : "body"
// }
// },
// "my-suggest-2" : {
// "text" : "the rottredam meetpu",
// "term" : {
// "fie... | csn |
Not supported. Returns a formatter symbol value.
@param int $attr A symbol specifier, one of the format symbol constants
@return bool|string The symbol value or false on error
@see http://www.php.net/manual/en/numberformatter.getsymbol.php | public function getSymbol($attr)
{
return \array_key_exists($this->style, self::$enSymbols) && \array_key_exists($attr, self::$enSymbols[$this->style]) ? self::$enSymbols[$this->style][$attr] : false;
} | csn |
Determines whether this address should merge to target address and called when two sides are equal on all aspects.
This is a pure function that must produce always the same output when called with the same parameters.
This logic should not be changed, otherwise compatibility will be broken.
@param thisAddress this add... | private boolean shouldMergeTo(Address thisAddress, Address targetAddress) {
String thisAddressStr = "[" + thisAddress.getHost() + "]:" + thisAddress.getPort();
String targetAddressStr = "[" + targetAddress.getHost() + "]:" + targetAddress.getPort();
if (thisAddressStr.equals(targetAddressStr)) ... | csn |
Get all callbacks
@param array $queryParams
@return CallbacksResponse | public function getAll(array $queryParams = [])
{
$response = $this->api->callbacks()->getAll($queryParams);
return new CallbacksResponse($response);
} | csn |
Add a rule to check if a field contains non alpha numeric characters.
@param string $field The field you want to apply the rule to.
@param int $limit The minimum number of non-alphanumeric fields required.
@param string|null $message The error message when the rule fails.
@param string|callable|null $when Either 'crea... | public function containsNonAlphaNumeric($field, $limit = 1, $message = null, $when = null)
{
$extra = array_filter(['on' => $when, 'message' => $message]);
return $this->add($field, 'containsNonAlphaNumeric', $extra + [
'rule' => ['containsNonAlphaNumeric', $limit]
]);
} | csn |
Saves data to a pickled file with optional verbosity | def save_cPkl(fpath, data, verbose=None, n=None):
""" Saves data to a pickled file with optional verbosity """
verbose = _rectify_verb_write(verbose)
if verbose:
print('[util_io] * save_cPkl(%r, data)' % (util_path.tail(fpath, n=n),))
with open(fpath, 'wb') as file_:
# Use protocol 2 to ... | csn |
Marshal the reserved job into a DatabaseJob instance.
@param string $queue
@param \Illuminate\Queue\Jobs\DatabaseJobRecord $job
@return \Illuminate\Queue\Jobs\DatabaseJob | protected function marshalJob($queue, $job)
{
$job = $this->markJobAsReserved($job);
return new DatabaseJob(
$this, $job, $this->connectionName, $queue
);
} | csn |
Return string to use as URL anchor for this comment. | def make_anchor_id(self):
"""Return string to use as URL anchor for this comment.
"""
result = re.sub(
'[^a-zA-Z0-9_]', '_', self.user + '_' + self.timestamp)
return result | csn |
Sort actions by execution time
@param \ArrayIterator $iterator - iterator to append actions | protected function sortActions(\ArrayIterator $iterator)
{
$iterator->uasort(function ($a, $b) {
return $a->getTime()->getTimestamp() - $b->getTime()->getTimestamp();
});
} | csn |
Add Text Field to Edit Form
@param FormBuilderInterface $builder
@param string $name
@param array $options
@return $this | public function addTextField(FormBuilderInterface $builder, string $name, array $options)
{
$builder->add(
strtolower($name),
TextType::class,
array_merge_recursive(array("required" => false), $options)
);
return $this;
} | csn |
Replaces patterned inputs or targets with activation vectors. | def replacePatterns(self, vector, layer = None):
"""
Replaces patterned inputs or targets with activation vectors.
"""
if not self.patterned: return vector
if type(vector) == str:
return self.replacePatterns(self.lookupPattern(vector, layer), layer)
elif type(... | csn |
Get how schema could change dynamically.
@return array | public function getDynamicSchemaExample(): array
{
$site = Site::instance('1', 'JSON API Samples', []);
$encoder = Encoder::instance([
Site::class => SiteSchema::class,
])->withEncodeOptions(JSON_PRETTY_PRINT);
SiteSchema::$isShowCustomLinks = false;
$noLinksRes... | csn |
// KeyEncrypt encrypts the content encryption key using ECDH-ES | func (kw EcdhesKeyWrapEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) {
kg, err := kw.generator.KeyGenerate()
if err != nil {
return nil, errors.Wrap(err, "failed to create key generator")
}
bwpk, ok := kg.(ByteWithECPrivateKey)
if !ok {
return nil, errors.New("key generator generated invalid key (expecte... | csn |
Given an Accept-Language header, return the best-matching language. | def get_best_language(self, accept_lang):
"""Given an Accept-Language header, return the best-matching language."""
LUM = settings.LANGUAGE_URL_MAP
langs = dict(LUM.items() + settings.CANONICAL_LOCALES.items())
# Add missing short locales to the list. This will automatically map
... | csn |
Utility function to parse a positive integer argument out of a String
array at the given index.
@param args String array containing element to find.
@param index Index of array element to parse integer from.
@return Integer parsed, or -1 if error. | int getInt(String[] args, int index) {
int result = -1;
if(index >= 0 && index < args.length) {
try {
result = Integer.parseInt(args[index]);
}catch(NumberFormatException e) {
result = -1;
}
}
return result;
} | csn |
called by the wrapped value model | public void propertyChange(PropertyChangeEvent evt) {
originalValue = getValue();
if (deliverValueChangeEvents) {
mediatedValueHolder.setValue(originalValue);
updateDirtyState();
}
} | csn |
Create a directory and its parents as needed. | def mkdir(hdfs_path, user=None):
"""
Create a directory and its parents as needed.
"""
host, port, path_ = path.split(hdfs_path, user)
fs = hdfs(host, port, user)
retval = fs.create_directory(path_)
fs.close()
return retval | csn |
Renders the active method selector at the grading method management screen
@param grading_manager $manager
@param moodle_url $targeturl
@return string | public function management_method_selector(grading_manager $manager, moodle_url $targeturl) {
$method = $manager->get_active_method();
$methods = $manager->get_available_methods(false);
$methods['none'] = get_string('gradingmethodnone', 'core_grading');
$selector = new single_select(new... | csn |
Process a character as part of a string token. | def _process_string(self, char):
""" Process a character as part of a string token.
"""
if char in self.QUOTES:
# end of quoted string:
# 1) quote must match original quote
# 2) not escaped quote (e.g. "hey there" vs "hey there\")
# 3) a... | csn |
Remove a single breakpoint | def clear_breakpoint(self, filename, lineno):
"""Remove a single breakpoint"""
clear_breakpoint(filename, lineno)
self.breakpoints_saved.emit()
editorstack = self.get_current_editorstack()
if editorstack is not None:
index = self.is_file_opened(filename)
... | csn |
Appends an Object to an SQL string with the proper escaping, etc. | public static final void appendValueToSql(StringBuilder sql, Object value) {
if (value == null) {
sql.append("NULL");
} else if (value instanceof Boolean) {
Boolean bool = (Boolean)value;
if (bool) {
sql.append('1');
} else {
... | csn |
Get all overviews of a segment
@param int $segmentId
@return array
@throws \InvalidArgumentException | private function generateOverviewsOfSegment($segmentId)
{
/** @var AnalyticsSegmentRepository $segmentRepository */
$segmentRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsSegment');
$segment = $segmentRepository->find($segmentId);
if (!$segment) {
... | csn |
// measurementContainsSets returns true if there are sets cached for the provided measurement. | func (c *TagValueSeriesIDCache) measurementContainsSets(name []byte) bool {
_, ok := c.cache[string(name)]
return ok
} | csn |
// Println calls underlying Logger Println func. | func (n *LevelLogger) Println(v ...interface{}) {
if !n.Enabled() {
return
}
n.mu.RLock()
n.logger.Output(callDepth, fmt.Sprintln(v...))
n.mu.RUnlock()
} | csn |
Create the content of DIDL desc element from a uri.
Args:
uri (str): A uri, eg:
``'x-sonos-http:track%3a3402413.mp3?sid=2&flags=32&sn=4'``
Returns:
str: The content of a desc element for that uri, eg
``'SA_RINCON519_email@example.com'`` | def desc_from_uri(uri):
"""Create the content of DIDL desc element from a uri.
Args:
uri (str): A uri, eg:
``'x-sonos-http:track%3a3402413.mp3?sid=2&flags=32&sn=4'``
Returns:
str: The content of a desc element for that uri, eg
``'SA_RINCON519_email@example.c... | csn |
Return the latest measurement for the given class or None if nothing
has been received from the vehicle. | def get(self, measurement_class):
"""Return the latest measurement for the given class or None if nothing
has been received from the vehicle.
"""
name = Measurement.name_from_class(measurement_class)
return self._construct_measurement(name) | csn |
Insert a child.
@param {Element} element
@param {Element|String} Element or string to be appended. | function(element, child){
if(_.isString(child))
element.innerHTML += child;
else if (_.isElement(child))
element.appendChild(child);
} | csn |
Get an uid for your controller.
:param addr: Address of the controller
:param port: Port of the controller
:type addr: str
:type port: int
:return: Unique id of the controller
:rtype: str | def _new_controller(self, addr, port):
"""
Get an uid for your controller.
:param addr: Address of the controller
:param port: Port of the controller
:type addr: str
:type port: int
:return: Unique id of the controller
:rtype: str
"""
for ... | csn |
Return the indices of all duplicated array elements.
Parameters
----------
arr : array-like object
An array-like object
Returns
-------
idx : NumPy array
An array containing the indices of the duplicated elements
Examples
--------
>>> from root_numpy import dup_idx... | def dup_idx(arr):
"""Return the indices of all duplicated array elements.
Parameters
----------
arr : array-like object
An array-like object
Returns
-------
idx : NumPy array
An array containing the indices of the duplicated elements
Examples
--------
>>> from ... | csn |
Recursively convert an object of data to an array.
@param object $data An object of data to return as an array.
@return array Array representation of the input object. | protected function asArray($data)
{
$array = [];
foreach(get_object_vars((object)$data) as $k => $v){
if ( is_object($v) ){
$array[$k] = $this->asArray($v);
}
else {
$array[$k] = $v;
}
}
return $array;
} | csn |
// appendTextNode creates a text node, appends it as last child
// and returns it. | func (tn *tagNode) appendTextNode(text string) *textNode {
trimmedText := strings.TrimSpace(text)
if trimmedText == "" {
return nil
}
ntn := newTextNode(trimmedText)
tn.appendChild(ntn)
return ntn
} | csn |
// first is a small helper that finds the first record matching a scope, and
// returns the error. | func first(db *gorm.DB, scope scope, v interface{}) error {
return scope.scope(db).First(v).Error
} | csn |
Delete a property in a JSON object and automatically notifies all observers of the change | function (object, property, value) {
if (object[OBSERVER_PROPERTY]) {
var existed = ownProperty.call(object, property), oldVal = object[property];
delete object[property];
if (existed) {
var chgset=[changeDesc(object, property, object[property], oldVal, "dele... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.