query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Set the value of a preference for this user.
@param string $key
@param mixed $value
@return $this | public function setPreference($key, $value)
{
if (isset(static::$preferences[$key])) {
$preferences = $this->preferences;
if (! is_null($transformer = static::$preferences[$key]['transformer'])) {
$preferences[$key] = call_user_func($transformer, $value);
... | csn |
async def set_name_endpoint(request: web.Request) -> web.Response:
""" Set the name of the robot.
Request with POST /server/name {"name": new_name}
Responds with 200 OK {"hostname": new_name, "prettyname": pretty_name}
or 400 Bad Request
In general, the new pretty name will be the specified name. ... | = await request.json()
if 'name' not in body or not isinstance(body['name'], str):
return build_400('Body has no "name" key with a string')
new_name = await set_name(body['name'])
request.app[DEVICE_NAME_VARNAME] = new_name
return web.json_response(data={'name': new_name},
... | csn_ccr |
Adds a projection that allows the criteria to retrieve the sum of the results of a property
@param propertyName The name of the property
@param alias The alias to use | public org.grails.datastore.mapping.query.api.ProjectionList sum(String propertyName, String alias) {
final AggregateProjection proj = Projections.sum(calculatePropertyName(propertyName));
addProjectionToList(proj, alias);
return this;
} | csn |
protected boolean isValidEventNameForScope(String eventName, Element listenerElement) {
if (eventName != null && eventName.trim().length() > 0) {
if ("start".equals(eventName) || "end".equals(eventName)) {
return true;
} else {
addError("Attribute 'event' must be one of | {start|end}", listenerElement);
}
} else {
addError("Attribute 'event' is mandatory on listener", listenerElement);
}
return false;
} | csn_ccr |
Insert a new field into the message dict and return it.
The new field is:
- 'signature' - the computed GPG message digest of the JSON repr
of the `msg` field. | def sign(message, gpg_home=None, gpg_signing_key=None, **config):
""" Insert a new field into the message dict and return it.
The new field is:
- 'signature' - the computed GPG message digest of the JSON repr
of the `msg` field.
"""
if gpg_home is None or gpg_signing_key is None:
... | csn |
// Register registers new connectionhelper for scheme | func Register(scheme string, fn func(*url.URL) (*ConnectionHelper, error)) {
helpers[scheme] = fn
} | csn |
def add_error(self, error, critical=False):
"""Adds an error to the state.
Args:
error: The text that will be added to the error list.
critical: If set to True and the | error is checked with check_errors, will
dfTimewolf will abort.
"""
self.errors.append((error, critical)) | csn_ccr |
public function get_origin_options() {
$ret = array();
$ret[''] = get_string('allsources', 'report_log');
$ret['cli'] = get_string('cli', 'report_log');
| $ret['restore'] = get_string('restore', 'report_log');
$ret['web'] = get_string('web', 'report_log');
$ret['ws'] = get_string('ws', 'report_log');
$ret['---'] = get_string('other', 'report_log');
return $ret;
} | csn_ccr |
public static final <T> T silenceDeepCopy(T object) {
try {
return deepCopy(object);
} catch (Exception e) {
| e.printStackTrace();
throw new RuntimeException(e);
}
} | csn_ccr |
Turn a byte string from the command line into a unicode string. | def decodeCommandLine(self, cmdline):
"""Turn a byte string from the command line into a unicode string.
"""
codec = getattr(sys.stdin, 'encoding', None) or sys.getdefaultencoding()
return unicode(cmdline, codec) | csn |
function sortAttrs(attrs) {
return attrs.sort(function (a, b) {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else if (a.value < b.value) {
| return -1;
} else if (a.value > b.value) {
return 1;
}
return 0;
});
} | csn_ccr |
def find_point_bin(self, chi_coords):
"""
Given a set of coordinates in the chi parameter space, identify the
indices of the chi1 and chi2 bins that the point occurs in. Returns
these indices.
Parameters
-----------
chi_coords : numpy.array
The positi... | Index of the chi_2 bin.
"""
# Identify bin
chi1_bin = int((chi_coords[0] - self.chi1_min) // self.bin_spacing)
chi2_bin = int((chi_coords[1] - self.chi2_min) // self.bin_spacing)
self.check_bin_existence(chi1_bin, chi2_bin)
return chi1_bin, chi2_bin | csn_ccr |
def multilineplot(args):
"""
%prog multilineplot fastafile chr1
Combine multiple line plots in one vertical stack
Inputs must be BED-formatted.
--lines: traditional line plots, useful for plotting feature freq
"""
p = OptionParser(multilineplot.__doc__)
p.add_option("--lines",
... | shift, mode=opts.mode,
binned=opts.binned, merge=merge)
clen = Sizes(fastafile).mapping[chr]
nbins = get_nbins(clen, shift)
plt.rcParams["xtick.major.size"] = 0
plt.rcParams["ytick.major.size"] = 0
plt.rcParams["figure.figsize"] = iopts.w, iopts.h
fig, axarr = plt... | csn_ccr |
Duplicate a record
@param int $id Model key
@return Symfony\Component\HttpFoundation\Response Redirect to new record | public function duplicate($id)
{
// Find the source item
$src = $this->findOrFail($id);
if (empty($src->cloneable)) {
return App::abort(404);
}
// Duplicate using Bkwld\Cloner
$new = $src->duplicate();
// Don't make duplicates public
if (... | csn |
// SetFormatter sets the logger formatter. | func (logger *Logger) SetFormatter(formatter Formatter) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Formatter = formatter
} | csn |
private void addSubscriptionsToBus(BusGroup group, String busId)
throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "addSubscriptionsToBus", new Object[]{group, busId});
// Get the complete list of Subscriptions from the MatchSpace
// and... |
if (!outputSeenList.contains(oh) &&
oh.neighbourOnDifferentBus(busId))
{
// This won't actually send the subscriptions to the Neighbour
// but generates the list of topics that are to be propagated.
final String topics[] = oh.getTopics();
final SIBUuid12 topic... | csn_ccr |
Returns the current TempURL key, or None if it has not been set.
By default the value returned is cached. To force an API call to get
the current value on the server, pass `cached=False`. | def get_temp_url_key(self, cached=True):
"""
Returns the current TempURL key, or None if it has not been set.
By default the value returned is cached. To force an API call to get
the current value on the server, pass `cached=False`.
"""
meta = self._cached_temp_url_key
... | csn |
Complete the function that takes 3 numbers `x, y and k` (where `x ≤ y`), and returns the number of integers within the range `[x..y]` (both ends included) that are divisible by `k`.
More scientifically: `{ i : x ≤ i ≤ y, i mod k = 0 }`
## Example
Given ```x = 6, y = 11, k = 2``` the function should return `3`, bec... | def divisible_count(x,y,k):
return y//k - (x-1)//k | apps |
public void releaseInstance(ReleaseInstanceRequest request) {
checkNotNull(request, "request should not be null.");
checkStringNotEmpty(request.getInstanceId(), "request instanceId should | not be empty.");
InternalRequest internalRequest = this.createRequest(
request, HttpMethodName.DELETE, INSTANCE_PREFIX, request.getInstanceId());
this.invokeHttpClient(internalRequest, AbstractBceResponse.class);
} | csn_ccr |
protected function getMenuMethods($plugin)
{
//Gets all methods from `$PLUGIN\View\Helper\MenuHelper`
$methods = get_child_methods(sprintf('\%s\View\Helper\MenuHelper', $plugin));
| //Filters invalid name methods and returns
return $methods ? array_values(preg_grep('/^(?!_).+$/', $methods)) : [];
} | csn_ccr |
Adjust the page-numbers of siblings when reordering a page.
@param ReorderEvent $event | public function handleReorder(ReorderEvent $event)
{
$document = $event->getDocument();
if (!$document instanceof PageBehavior) {
return;
}
$propertyName = $this->propertyEncoder->systemName(static::FIELD);
$parentNode = $this->documentInspector->getNode($documen... | csn |
func (gt *GLTriangles) Picture(i int) (pic pixel.Vec, intensity float64) {
tx := gt.data[i*gt.vs.Stride()+6] |
ty := gt.data[i*gt.vs.Stride()+7]
intensity = float64(gt.data[i*gt.vs.Stride()+8])
return pixel.V(float64(tx), float64(ty)), intensity
} | csn_ccr |
public void setFromAddress(final String name, final String fromAddress) {
| fromRecipient = new Recipient(name, fromAddress, null);
} | csn_ccr |
Combine a list of complete nested sampling run dictionaries into a single
ns run.
Input runs must contain any repeated threads.
Parameters
----------
run_list_in: list of dicts
List of nested sampling runs in dict format (see data_processing module
docstring for more details).
... | def combine_ns_runs(run_list_in, **kwargs):
"""
Combine a list of complete nested sampling run dictionaries into a single
ns run.
Input runs must contain any repeated threads.
Parameters
----------
run_list_in: list of dicts
List of nested sampling runs in dict format (see data_pro... | csn |
// SetDeviceSelectionResult sets the DeviceSelectionResult field's value. | func (s *Run) SetDeviceSelectionResult(v *DeviceSelectionResult) *Run {
s.DeviceSelectionResult = v
return s
} | csn |
def generate_pdf(template_id, submission_data, opts = {})
data, _status_code, _headers = | generate_pdf_with_http_info(template_id, submission_data, opts)
data
end | csn_ccr |
Causes the next filter in the chain to be invoked, or, if at the end
of the chain, causes the requested resource to be invoked
@return a String containing the filter name | public void doFilter(ServletRequest request, ServletResponse response) throws ServletException, IOException {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
logger.logp(Level.FINE, CLASS_NAME,"doFilter", "entry");
try {
// if there are ... | csn |
public int getValue(String name, int dflt) {
try {
return Integer.parseInt(getValue(name, Integer.toString(dflt)));
| } catch (Exception e) {
return dflt;
}
} | csn_ccr |
public static function getInstance($database, $anonymous = false)
{
if ($anonymous || !array_key_exists($database, self::$instances)) {
$instance = new Medoo(self::getDatabaseConfig($database));
if ($anonymous) {
return $instance; |
}
self::$instances[$database] = $instance;
}
return self::$instances[$database];
} | csn_ccr |
// Now is part of the Clock interface. | func (t TimeClock) Now() (Interval, error) {
now := time.Now()
return NewInterval(now.Add(-(*uncertainty)), now.Add(*uncertainty))
} | csn |
Tests whether the specified string is a token as defined in RFC 2045
section 5.1.
@param str
string to test.
@return <code>true</code> if the specified string is a RFC 2045 token,
<code>false</code> otherwise. | public static boolean isToken(String str) {
// token := 1*<any (US-ASCII) CHAR except SPACE, CTLs, or tspecials>
// tspecials := "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / "\" /
// <"> / "/" / "[" / "]" / "?" / "="
// CTL := 0.- 31., 127.
final int length = str.length();
if (length == 0)
return fal... | csn |
protected function searchForMetaValue( $meta_key, array $postmeta ) {
if ( empty( $postmeta ) ) {
return '';
}
foreach ( $postmeta as $meta ) {
// prefer this value, if it's set
if ( $meta_key === $meta['key'] | ) {
$meta_val = $meta['value'];
if ( is_serialized( $meta_val ) ) {
$meta_val = unserialize( $meta_val ); // @codingStandardsIgnoreLine
if ( is_object( $meta_val ) ) {
$meta_val = ''; // Hack attempt?
}
}
return $meta_val;
}
}
return '';
} | csn_ccr |
protected void onAfterBackupSession( @Nonnull final MemcachedBackupSession session, final boolean backupWasForced,
@Nonnull final Future<BackupResult> result, @Nonnull final String requestId,
@Nonnull final BackupSessionService backupSessionService ) {
if ( !_sessionIdFormat.isValid( se... | // Details: Now/here we're waiting the whole session backup timeout, even if (perhaps) some time
// was spent before when waiting for session backup result.
// For sync session backup it would be better to set both the session data and
// validity info and afterwards w... | csn_ccr |
public static Debug getInstance(String option, String prefix)
{
if (isOn(option)) {
Debug d = new Debug(prefix); |
return d;
} else {
return null;
}
} | csn_ccr |
public function getTableColumns()
{
$metadata = new MetaData($this->tableGateway->getAdapter()); |
$columns = $metadata->getColumnNames($this->tableGateway->getTable());
return $columns;
} | csn_ccr |
// trysleep for the given duration, or return if Close is called. | func (c *client) trysleep(d time.Duration) {
select {
case <-time.After(d):
case <-c.stop:
}
} | csn |
def calc_extensions(self, extensions=None, Y_agg=None):
""" Calculates the extension and their accounts
For the calculation, y is aggregated across specified y categories
The method calls .calc_system of each extension (or these given in the
extensions parameter)
Parameters
... | The final demand aggregated (one category per country). Can be
used to restrict the calculation of CBA of a specific category
(e.g. households). Default: y is aggregated over all categories
"""
ext_list = list(self.get_extensions(data=False))
extensions = extensio... | csn_ccr |
def getExponentialFormatPrecision(self, result=None):
""" Returns the precision for the Analysis Service and result
provided. Results with a precision value above this exponential
format precision should be formatted as scientific notation.
If the Calculate Precision according to Uncert... | of 4:
Result Uncertainty Returns
5.234 0.22 0
13.5 1.34 1
0.0077 0.008 -3
32092 0.81 4
456021 423 5
For further details, visit https://jira.bikalabs.com/br... | csn_ccr |
protected function _date($date = null) {
if ($date === null || !$date instanceof \DateTimeInterface) {
return '';
}
$datePieces = [];
$datePieces[] = $date->format('Y');
// JavaScript uses 0-indexed months, so we need to subtract 1 month from PHP's output
$datePieces[] = (int)($date->format('m')) - 1;
| $datePieces[] = (int)$date->format('d');
$datePieces[] = (int)$date->format('H');
$datePieces[] = (int)$date->format('i');
$datePieces[] = (int)$date->format('s');
return 'new Date(' . implode(', ', $datePieces) . ')';
} | csn_ccr |
Count the number of bits that overlap between two sets | def count_overlap( bits1, bits2 ):
"""
Count the number of bits that overlap between two sets
"""
b = BitSet( bits1.size )
b |= bits1
b &= bits2
return b.count_range( 0, b.size ) | csn |
protected Element findTag(String tagName, Element element) {
Node result = element.getFirstChild();
while (result != null) {
if (result instanceof Element
&& (tagName.equals(((Element) result).getNodeName()) || tagName
| .equals(((Element) result).getLocalName()))) {
break;
}
result = result.getNextSibling();
}
return (Element) result;
} | csn_ccr |
Creates a token for a service
@param string $identity
@param string $service
@param string $token
@param string $expiresAt
@return mixed | public function create($identity, $service, $token)
{
$params = array(
'service' => $service,
'token' => $token,
);
return $this->_user->post('account/identity/' . $identity . '/token', $params);
} | csn |
def make_startup(notebook_context, config_file, bootstrap_py=PYRAMID_BOOSTRAP, bootstrap_greeting=PYRAMID_GREETING, cwd=""):
"""Populate notebook context with startup.py initialization file skeleton and greeting.
This will set up context ``startup`` and ``greeting`` for their default values.
:param notebo... | config_file = os.path.abspath(config_file)
assert os.path.exists(config_file), "Passed in bad config file: {}".format(config_file)
add_script(nc, bootstrap_py.format(config_uri=config_file, cwd=cwd))
add_greeting(nc, bootstrap_greeting)
add_script(nc, "import datetime")
add_greetin... | csn_ccr |
python stdin nonblock readline | def _read_stdin():
"""
Generator for reading from standard input in nonblocking mode.
Other ways of reading from ``stdin`` in python waits, until the buffer is
big enough, or until EOF character is sent.
This functions yields immediately after each line.
"""
line = sys.stdin.readline()
... | cosqa |
def dispatch_hook(cls, _pkt=None, *args, **kargs):
"""
Returns the right parameter set class.
"""
cls = conf.raw_layer
if _pkt is not None:
ptype | = orb(_pkt[0])
return globals().get(_param_set_cls.get(ptype), conf.raw_layer)
return cls | csn_ccr |
public static Attr[] toAttrArray(Document doc, Object o) throws PageException {
// Node[]
if (o instanceof Node[]) {
Node[] nodes = (Node[]) o;
if (_isAllOfSameType(nodes, Node.ATTRIBUTE_NODE)) return (Attr[]) nodes;
Attr[] attres = new Attr[nodes.length];
for (int i = 0; i < nodes.length; i++) {... |
return attres.toArray(new Attr[attres.size()]);
}
// Node Map and List
Node[] nodes = _toNodeArray(doc, o);
if (nodes != null) return toAttrArray(doc, nodes);
// Single Text Node
try {
return new Attr[] { toAttr(doc, o) };
}
catch (ExpressionException e) {
throw new XMLException("can't cast Obje... | csn_ccr |
Check health.
@return Result | public function check()
{
$healthy = $this->isHealthy();
return $this->makeResult(
$healthy,
$healthy ? '' : $this->target->getErrorMessage()
);
} | csn |
Remove and optionally close the specified help viewer if is the active viewer for the
specified page.
@param page The page owner the help viewer.
@param viewer The viewer to remove.
@param close If true, close the help viewer after removing it. | protected static void removeViewer(Page page, IHelpViewer viewer, boolean close) {
if (viewer != null && viewer == page.getAttribute(VIEWER_ATTRIB)) {
removeViewer(page, close);
}
} | csn |
// MarshalMessageSet encodes the extension map represented by m in the message set wire format.
// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. | func MarshalMessageSet(m map[int32]Extension) ([]byte, error) {
if err := encodeExtensionMap(m); err != nil {
return nil, err
}
// Sort extension IDs to provide a deterministic encoding.
// See also enc_map in encode.go.
ids := make([]int, 0, len(m))
for id := range m {
ids = append(ids, int(id))
}
sort.In... | csn |
Splits a key but allows dots in the key name if they're scaped properly.
Splitting this complex key:
complex_key = ".dont\.splitme.d\.o\. origen.splitme\.dontsplit.splitme."
split_key(complex_key)
results in:
['', 'dont\.splitme', 'd\.o\. origen', 'splitme\.dontsplit', 'splitme', '']
Args:... | def split_key(key, max_keys=0):
"""Splits a key but allows dots in the key name if they're scaped properly.
Splitting this complex key:
complex_key = ".dont\.splitme.d\.o\. origen.splitme\.dontsplit.splitme."
split_key(complex_key)
results in:
['', 'dont\.splitme', 'd\.o\. origen', 'splitme\... | csn |
function( options ){
var script,
url = options.url,
head = document.head ||
document.getElementsByTagName( "head" )[ 0 ] ||
document.documentElement,
jsonpCallback = options.callbackName || 'openseadragon' + $.now... | }
script.src = url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in ... | csn_ccr |
public static function createFromPath(string $path)
{
$createFunctions = [
'image/png' => 'imagecreatefrompng',
'image/jpeg' => 'imagecreatefromjpeg',
'image/gif' => 'imagecreatefromgif',
];
$mimeType = mime_content_type($path);
if (!array_key_ex... | throw new InvalidMimeTypeException(sprintf('The "%s" mime type is not supported.', $mimeType));
}
$resource = $createFunctions[$mimeType]($path);
return new static($resource);
} | csn_ccr |
// SetAlternateValueEncoding sets the AlternateValueEncoding field's value. | func (s *Attribute) SetAlternateValueEncoding(v string) *Attribute {
s.AlternateValueEncoding = &v
return s
} | csn |
Template tag that renders a given menu item, it takes a ``MenuItem``
instance as unique parameter. | def admin_tools_render_menu_item(context, item, index=None):
"""
Template tag that renders a given menu item, it takes a ``MenuItem``
instance as unique parameter.
"""
item.init_with_context(context)
context.update({
'template': item.template,
'item': item,
'index': inde... | csn |
private function interfaceDeclaration() {
$node = new InterfaceNode();
$this->matchDocComment($node);
$this->mustMatch(T_INTERFACE, $node);
$name_node = new NameNode();
$this->mustMatch(T_STRING, $name_node, NULL, TRUE);
$node->addChild($name_node, 'name');
if ($this->tryMatch(T_EXTENDS, $no... |
while ($this->currentType !== NULL && $this->currentType !== '}') {
$this->matchHidden($statement_block);
if ($this->currentType === T_CONST) {
$statement_block->addChild($this->_const());
}
else {
$statement_block->addChild($this->interfaceMethod());
}
}
$this... | csn_ccr |
func (p *MockPeer) BlockHeight() uint64 {
| p.lock.RLock()
defer p.lock.RUnlock()
return p.blockHeight
} | csn_ccr |
// Get the largestDenominator that is a multiple of a basedDenominator
// and fits at least once into a given numerator. | func getLargestDenominator(numerator, multiple, baseDenominator, power int) (int, int) {
if numerator/multiple == 0 {
return 1, power
}
next, nextPower := getLargestDenominator(
numerator, multiple*baseDenominator, baseDenominator, power+1)
if next > multiple {
return next, nextPower
}
return multiple, powe... | csn |
Opens a txt file at the given path where user can add and save notes.
Args:
path (str): Directory where note will be saved.
filename (str): Name of note. Defaults to "note.txt" | def add_note(path, filename="note.txt"):
"""Opens a txt file at the given path where user can add and save notes.
Args:
path (str): Directory where note will be saved.
filename (str): Name of note. Defaults to "note.txt"
"""
path = os.path.expanduser(path)
assert os.path.isdir(path)... | csn |
Return loaded parent
@return \OxidEsales\Eshop\Core\Theme | public function getParent()
{
$sParent = $this->getInfo('parentTheme');
if (!$sParent) {
return null;
}
$oTheme = oxNew(\OxidEsales\Eshop\Core\Theme::class);
if ($oTheme->load($sParent)) {
return $oTheme;
}
return null;
} | csn |
given a shader and pair of uniform names, sets the sampler and dimensions to be used by this texture | function(shader, sampler_name, dimension_name) {
if (this.unit === null)
throw "Trying to use texture not set to a texture unit.";
var gl = this.gl;
gl.useProgram(shader);
// Set the texture buffer to use
gl.uniform1i(gl.getUniformLocation(shader, sampler_name), this.... | csn |
public function addTransactionType($name, $parameters = [])
{
$this->verifyTransactionType($name, $parameters);
$structure = [
'transaction_type' => [
'@attributes' => [
'name' => $name
],
| $parameters
]
];
array_push($this->transaction_types, $structure);
return $this;
} | csn_ccr |
public function fixStringNumericValues(&$input) {
if (!\is_array($input)) {
if (\is_string($input) && \is_numeric($input)) {
$input += 0;
}
return $input;
}
foreach ($input as $k => $v) {
if (\is_array($input[$k])) {
| $input[$k] = $this->fixStringNumericValues($input[$k]);
}
if (\is_string($v) && \is_numeric($v)) {
$v += 0;
}
$input[$k] = $v;
}
return $input;
} | csn_ccr |
Find the region for the current language
@return string | protected function findRegion()
{
if ($this->locale) {
$currentLang = $this->getLanguageFromLocale($this->locale);
$defaultLang = $this->getLanguageFromLocale(static::$default);
if ($currentLang == $defaultLang) {
$region = $this->getRegionFromLocale(stat... | csn |
Resets journal readers to the given head.
@param index The index at which to reset readers. | void resetHead(long index) {
for (SegmentedJournalReader reader : readers) {
if (reader.getNextIndex() < index) {
reader.reset(index);
}
}
} | csn |
// GetMetadata returns required serialization metadata | func (rt *RandomTree) GetMetadata() base.ClassifierMetadataV1 {
return base.ClassifierMetadataV1{
FormatVersion: 1,
ClassifierName: "KNN",
ClassifierVersion: "1.0",
ClassifierMetadata: nil,
}
} | csn |
Given a valid config, create a topic rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.create_topic_rule my_rule "SELECT * FROM 'some/thing'" \\
'[{"lambda":{"fu... | def create_topic_rule(ruleName, sql, actions, description,
ruleDisabled=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create a topic rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not create... | csn |
public function setNodeSegment(NodeInterface $node, string $segment, ?string $previous = null) : void
{
if ($this->isNodeBlacklisted($node)) {
return;
}
if (!$previous) {
$previous = $this->getNodeSegment($node);
}
if (empty($segment)) {
$... | ->database
->merge('ucms_seo_node')
->key(['nid' => $node->id()])
->fields(['alias_segment' => $segment])
->execute()
;
if (empty($segment)) {
$this->onAliasChange([$node->id()]);
} else {
$this->onAliasChange([$node->id(... | csn_ccr |
def to_dict(self, search_fields=None):
"""Builds dict without None object fields"""
fields = self._fields
if search_fields == 'update':
fields = self._search_for_update_fields
elif search_fields == 'all':
fields = self._all_searchable_fields
elif search_fi... | if field in self._updateable_search_fields or
field not in self._search_for_update_fields]
return {field: self.field_to_dict(field) for field in fields
if getattr(self, field, None) is not None} | csn_ccr |
def padding
last = bytes.last
subset = subset_padding
if subset.all?{|e| e == last }
| self.class.new(subset)
else
self.class.new([])
end
end | csn_ccr |
function clonePugOpts(opts, filename) {
return PUGPROPS.reduce((o, p) => {
if (p in opts) {
| o[p] = clone(opts[p]);
}
return o;
}, { filename });
} | csn_ccr |
public function addAnonymousPromise(callable $promise, ?int $priority = null)
{
$priority | = $priority ?? static::DEFAULT_PRIORITY;
$this->pool[] = compact('priority', 'promise');
} | csn_ccr |
func Convert_v1_SignatureIssuer_To_image_SignatureIssuer(in *v1.SignatureIssuer, out *image.SignatureIssuer, s conversion.Scope) error { |
return autoConvert_v1_SignatureIssuer_To_image_SignatureIssuer(in, out, s)
} | csn_ccr |
// identifyUsers identifies the users in the given maps. | func identifyUsers(
ctx context.Context, nug idutil.NormalizedUsernameGetter,
identifier idutil.Identifier,
names map[keybase1.UserOrTeamID]kbname.NormalizedUsername,
t tlf.Type, offline keybase1.OfflineAvailability) error {
eg, ctx := errgroup.WithContext(ctx)
// TODO: limit the number of concurrent identifies?... | csn |
Run everything required for checking this function.
Returns:
A generator of errors.
Raises:
ValidationError: A non-recoverable linting error is found. | def check_all(self) -> Generator[AAAError, None, None]:
"""
Run everything required for checking this function.
Returns:
A generator of errors.
Raises:
ValidationError: A non-recoverable linting error is found.
"""
# Function def
if funct... | csn |
Deploy the apigateway to a particular stage | def deploy_gateway(collector):
"""Deploy the apigateway to a particular stage"""
configuration = collector.configuration
aws_syncr = configuration['aws_syncr']
aws_syncr, amazon, stage, gateway = find_gateway(aws_syncr, configuration)
gateway.deploy(aws_syncr, amazon, stage)
if not configuratio... | csn |
Take a muxed tuple, and treat the first
value as the join key. | public function accumulate($v) {
$this->last_value = null;
$key = $v->value[0];
if(!isset($this->stream[$v->stream][$key])) {
$this->stream[$v->stream][$key] = 0;
}
$this->stream[$v->stream][$key] += 1;
if(isset($this->stream[$v->stream ^ 1][$key])) {
$this->last_value = $v->val... | csn |
def create_hparams_from_json(json_path, hparams=None):
"""Loading hparams from json; can also start from hparams if specified."""
tf.logging.info("Loading hparams from existing json %s" % json_path)
with tf.gfile.Open(json_path, "r") as f:
hparams_values = json.load(f)
# Prevent certain keys from overwrit... | for key in sorted(new_hparams.values().keys()):
if hasattr(hparams, key): # Overlapped keys
value = getattr(hparams, key)
new_value = getattr(new_hparams, key)
if value != new_value: # Different values
tf.logging.info("Overwrite key %s: %s -> %s" % (
... | csn_ccr |
Delete current line | def delete_line(self):
"""Delete current line"""
cursor = self.textCursor()
if self.has_selected_text():
self.extend_selection_to_complete_lines()
start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd()
cursor.setPosition(start_pos)
... | csn |
python image background crop | def _trim(image):
"""Trim a PIL image and remove white space."""
background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))
diff = PIL.ImageChops.difference(image, background)
diff = PIL.ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
image = image.cr... | cosqa |
URL-encodes a given string using ISO-8859-1, which may work better with web pages and umlauts compared to UTF-8.
No UnsupportedEncodingException to handle as it is dealt with in this method. | public static String encodeUrlIso(String stringToEncode) {
try {
return URLEncoder.encode(stringToEncode, "ISO-8859-1");
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
} | csn |
private BindRequest waitForBind(long timeout)
throws IllegalStateException, TimeoutException {
SessionState currentSessionState = getSessionState();
if (currentSessionState.equals(SessionState.OPEN)) {
try {
return bindRequestReceiver.waitForRequest(timeout);
| }
catch (IllegalStateException e) {
throw new IllegalStateException(
"Invocation of waitForBind() has been made", e);
}
catch (TimeoutException e) {
close();
throw e;
}
}
else {
throw new IllegalStateException(
"waitForBind() should ... | csn_ccr |
def has_logged_in(self):
"""Check whether the API has logged in"""
r = self.http.get(CHECKPOINT_URL)
| if r.state is False:
return True
# If logged out, flush cache
self._reset_cache()
return False | csn_ccr |
Connect the socket to a SOCKS 4 proxy and request forwarding to our
remote host.
@param remoteHost
@param remotePort
@param proxyHost
@param proxyPort
@param userId
@return SocksProxyTransport
@throws IOException
@throws UnknownHostException | public static SocksProxyTransport connectViaSocks4Proxy(String remoteHost,
int remotePort, String proxyHost, int proxyPort, String userId)
throws IOException, UnknownHostException {
SocksProxyTransport proxySocket = new SocksProxyTransport(remoteHost,
remotePort, proxyHost, proxyPort, SOCKS4);
proxySocket... | csn |
// The implementation bellow is heavily influenced by go-kit's log context.
// With returns a new error with keyvals context appended to it.
// If the wrapped error is already a contextual error created by With
// keyvals is appended to the existing context, but a new error is returned. | func With(err error, keyvals ...interface{}) error {
if err == nil {
return nil
}
if len(keyvals) == 0 {
return err
}
var kvs []interface{}
// extract context from previous error
if c, ok := err.(*withContext); ok {
err = c.err
kvs = append(kvs, c.keyvals...)
if len(kvs)%2 != 0 {
kvs = append(k... | csn |
protected function initializeElementRegister(ElementRegister $register)
{
$register->set('a', new AnchorElement());
$register->set('admonition', new AdmonitionElement());
$register->set('br', new BreakElement());
$register->set('code', new CodeElement());
$register->set('em',... | $register->set('note', new AdmonitionElement('note'));
$register->set('p', new ParagraphElement());
$register->set('spoiler', new AdmonitionElement('spoiler'));
$register->set('strong', new StrongElement());
$register->set('table', new TableElement());
$register->set('td', ne... | csn_ccr |
Grabs metadata and returns metadata for the given url such as title,
description and thumbnails.
@param url
The URL of the embed
@return The full embed data | public Embed createEmbed(String url) {
return getResourceFactory().getApiResource("/embed/")
.entity(new EmbedCreate(url), MediaType.APPLICATION_JSON_TYPE)
.post(Embed.class);
} | csn |
Issues a request to list the datasets in the project.
Args:
project_id: the project id to use to fetch the results; use None for the default project.
max_results: an optional maximum number of tables to retrieve.
page_token: an optional token to continue the retrieval.
Returns:
A parsed... | def datasets_list(self, project_id=None, max_results=0, page_token=None):
"""Issues a request to list the datasets in the project.
Args:
project_id: the project id to use to fetch the results; use None for the default project.
max_results: an optional maximum number of tables to retrieve.
pag... | csn |
Returns the extended information of the specified manager name.
@param resource_group_name [String] The resource group name
@param manager_name [String] The manager name
@param custom_headers [Hash{String => String}] A hash of custom headers that
will be added to the HTTP request.
@return [ManagerExtendedInfo] o... | def get_extended_info(resource_group_name, manager_name, custom_headers:nil)
response = get_extended_info_async(resource_group_name, manager_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end | csn |
func (om *OAuth2Middleware) GetAccessToken(r *http.Request) string {
authorizationHeader := r.Header.Get("Authorization")
if authorizationHeader == "" {
accessTokenQueryParameter := r.URL.Query().Get("access_token")
return accessTokenQueryParameter
}
if strings.HasPrefix(authorizationHeader, | "bearer ") || strings.HasPrefix(authorizationHeader, "Bearer ") {
return ""
}
accessToken := strings.TrimSpace(strings.TrimPrefix(authorizationHeader, "token"))
return accessToken
} | csn_ccr |
Checks response after request was made.
Checks status of the response, mainly
:param resp:
:return: | def check_response(self, resp):
"""
Checks response after request was made.
Checks status of the response, mainly
:param resp:
:return:
"""
# For successful API call, response code will be 200 (OK)
if resp.ok:
json = resp.json()
s... | csn |
Subclasses should call super implementation in order to set the key and userIp.
@throws IOException I/O exception | public void initialize(AbstractGoogleClientRequest<?> request) throws IOException {
if (key != null) {
request.put("key", key);
}
if (userIp != null) {
request.put("userIp", userIp);
}
} | csn |
protected RaftPartitionServer createServer(PartitionManagementService managementService) {
return new RaftPartitionServer(
this,
config,
managementService.getMembershipService().getLocalMember().id(),
managementService.getMembershipService(),
| managementService.getMessagingService(),
managementService.getPrimitiveTypes(),
threadContextFactory);
} | csn_ccr |
public function remove($property)
{
if (!array_key_exists($property, $this->data)) {
throw new InvalidArgumentException(sprintf('Property %s does not exist', $property));
}
| $value = $this->data[$property];
unset($this->data[$property]);
return $value;
} | csn_ccr |
Close any resources opened by the manager. | public void close() {
if (images != null) {
try {
images.close();
} catch (IOException e) {
}
images = null;
}
if (labels != null) {
try {
labels.close();
} catch (IOException e) {
... | csn |
Init logic for `debug` instances.
Create a new `inspectOpts` object in case `useColors` is set
differently for a particular `debug` instance. | function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
} | csn |
This method will return a byte buffer that can be written to for the amount of data that
needs to be written. If there is no room left in the current byte buffer, a new one will be
created and added to the list.
@param sizeNeeded The amount of data that needs to be written
@return Returns a WsByteBuffer that can be u... | protected WsByteBuffer getCurrentByteBuffer(int sizeNeeded)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getCurrentByteBuffer", Integer.valueOf(sizeNeeded));
WsByteBuffer byteBuffer = null;
// First have a look in the dataList for a buffer.
if (d... | csn |
Checks if the given Path is existent and generates missing folders.
@param string $path the path
@param integer $chmod chmod for new folders
@return boolean true if path is available false if not. | public static function buildDir($path, $chmod = 0775) {
deprecated('mkdir($dir, null, true);');
if (is_dir($path)) {
return true;
}
$dir = DIRECTORY_SEPARATOR;
foreach(explode(DIRECTORY_SEPARATOR, self::unify_slashes($path, DIRECTORY_SEPARATOR, true)) as $f) {
... | csn |
def SetValue(self, row, col, value):
"""
Set value | in the pandas DataFrame
"""
self.dataframe.iloc[row, col] = value | csn_ccr |
private void scanPlatformPath(PackageSymbol p) throws IOException {
fillIn(p, PLATFORM_CLASS_PATH,
list(PLATFORM_CLASS_PATH,
p,
p.fullname.toString(),
allowSigFiles ? | EnumSet.of(JavaFileObject.Kind.CLASS,
JavaFileObject.Kind.OTHER)
: EnumSet.of(JavaFileObject.Kind.CLASS)));
} | csn_ccr |
python k random element from array | def downsample(array, k):
"""Choose k random elements of array."""
length = array.shape[0]
indices = random.sample(xrange(length), k)
return array[indices] | cosqa |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.