query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Return the path of the document in relation to the content root.
TODO: We need a better solution for retrieving webspace paths (the existing
"session manager" is not a good solution).
@param PathBehavior $document
@return string | public function getContentPath(PathBehavior $document)
{
$path = $this->getPath($document);
$webspaceKey = $this->getWebspace($document);
return str_replace(
sprintf(
'/%s/%s/%s',
$this->pathSegmentRegistry->getPathSegment('base'),
... | csn |
Returns the IP address and port of the remote end of the UDP connection, or null if this connection is not connected. | public InetSocketAddress getRemoteAddressUDP () {
InetSocketAddress connectedAddress = udp.connectedAddress;
if (connectedAddress != null) return connectedAddress;
return udpRemoteAddress;
} | csn |
Retrieves any config value found in the Blog's config.yml file.
@param string $key The config array key whose value you would like to retrieve. For every arg you include we will keep working our way up the config array to find just what you are looking for.
@return mixed The config key(s) value, or null if not found... | public function config($key = null)
{
$args = func_get_args(); // In PHP7, func_get_args() are changed by the time we use them, so we call it now
if (is_null($this->config)) {
$file = $this->folder.'config.yml';
$this->config = (is_file($file)) ? (array) Yaml::parse(file_get_... | csn |
def json_options_to_metadata(options, add_brackets=True):
"""Read metadata from its json representation"""
try:
options = loads('{' + options | + '}' if add_brackets else options)
return options
except ValueError:
return {} | csn_ccr |
Get action groups
@return array | protected function _getActionGroups()
{
$action = $this->_action();
$groups = $action->getConfig('scaffold.action_groups') ?: [];
$groupedActions = [];
foreach ($groups as $group) {
$groupedActions[] = array_keys(Hash::normalize($group));
}
// add "prima... | csn |
Do query.
@param string $query
@param array|null $queryParams
@return Oppa\Batch\BatchInterface | public final function doQuery(string $query, array $queryParams = null): BatchInterface
{
return $this->queue($query, $queryParams)->do();
} | csn |
func (ph *peerHeap) Swap(i, j int) {
p1 := ph.peers[i]
p2 := ph.peers[j]
ph.peers[i], | ph.peers[j] = ph.peers[j], ph.peers[i]
p1.idx = j
p2.idx = i
} | csn_ccr |
Save the found matches to the cache.
@return void | public function savePolicyCache()
{
$tags = ['Neos_Flow_Aop'];
if (!$this->methodPermissionCache->has('methodPermission')) {
$this->methodPermissionCache->set('methodPermission', $this->methodPermissions, $tags);
}
} | csn |
Send close stream to server.
@param pos write outputStream | public static void send(final PacketOutputStream pos) {
try {
pos.startPacket(0);
pos.write(Packet.COM_QUIT);
pos.flush();
} catch (IOException ioe) {
//eat
}
} | csn |
Check if two rectangles intersect | def intersect(a, b):
"""
Check if two rectangles intersect
"""
if a[x0] == a[x1] or a[y0] == a[y1]:
return False
if b[x0] == b[x1] or b[y0] == b[y1]:
return False
return a[x0] <= b[x1] and b[x0] <= a[x1] and a[y0] <= b[y1] and b[y0] <= a[y1] | csn |
def _CheckDatabaseEncoding(cursor):
"""Enforces a sane UTF-8 encoding for the database."""
cur_character_set = _ReadVariable("character_set_database", cursor)
if cur_character_set != CHARACTER_SET:
| raise EncodingEnforcementError(
"Require MySQL character_set_database of {}, got {}."
" To create your database, use: {}".format(CHARACTER_SET,
cur_character_set,
CREATE_DATABASE_QUERY)) | csn_ccr |
Convert input to process stdout
implementation | function _initConverter(){
var csvConverter = new Converter_1();
var started = false;
var writeStream = process.stdout;
csvConverter.on("record_parsed",function(rowJSON){
if (started){
writeStream.write(",\n");
... | csn |
A helper function to return the Sequence for a chain. If use_seqres_sequences_if_possible then we return the SEQRES
Sequence if it exists. We return a tuple of values, the first identifying which sequence was returned. | def get_annotated_chain_sequence_string(self, chain_id, use_seqres_sequences_if_possible, raise_Exception_if_not_found = True):
'''A helper function to return the Sequence for a chain. If use_seqres_sequences_if_possible then we return the SEQRES
Sequence if it exists. We return a tuple of values, th... | csn |
Makes a request to the URL and returns a response.
@param [type] $url
@return [type] | protected function makeRequest($resource)
{
$url = "{$this->api_url}/{$resource}";
$response = $this->guzzle->get($url, $this->getHeaders())->getBody();
return json_decode($response, true);
} | csn |
def authenticate(self, transport, account_name, password):
"""
Authenticates account, if no password given tries to pre-authenticate.
@param transport: transport to use for method calls
@param account_name: account name
@param password: account password
@return: AuthToken... | authentication fails
"""
if not isinstance(transport, ZimbraClientTransport):
raise ZimbraClientException('Invalid transport')
if util.empty(account_name):
raise AuthException('Empty account name') | csn_ccr |
def validate_registry_uri_version(query: str) -> None:
"""
Raise an exception if the version param is malformed.
"""
| query_dict = parse.parse_qs(query, keep_blank_values=True)
if "version" not in query_dict:
raise ValidationError(f"{query} is not a correctly formatted version param.") | csn_ccr |
public AnimaQuery<? extends Model> set(String column, Object value) {
| return query.set(column, value);
} | csn_ccr |
Retrieve a registered rule by it's ID
@param {String} id
@param {Function} callback( error, result )
@return {Request} | function( id, callback ) {
var self = this
return this.client._clientRequest({
url: '/alerts/rest/v1/json/get/' + id,
}, function( error, data ) {
callback.call( self.client, error, data )
})
} | csn |
from __future__ import print_function
def getDifference(b1, b2):
r = (b2 - b1) % 360.0
if r >= 180.0:
r -= 360.0
return r
if __name__ == "__main__":
print ("Input in -180 to +180 range")
print (getDifference(20.0, 45.0))
print (getDifference(-45.0, 45.0))
print (getDifference(-85.0, 90.0))
print (getD... | #include <cmath>
#include <iostream>
using namespace std;
double getDifference(double b1, double b2) {
double r = fmod(b2 - b1, 360.0);
if (r < -180.0)
r += 360.0;
if (r >= 180.0)
r -= 360.0;
return r;
}
int main()
{
cout << "Input in -180 to +180 range" << endl;
cout << getDifference(20.0, 45.0) << endl;
... | codetrans_contest |
Create a new driver instance for the given connection.
@param string $name
@param array $config
@return mixed | protected function createForConnection($name, array $config = [])
{
if (isset($this->customCreators[$name])) {
return $this->callCustom($name, compact('config'));
}
} | csn |
protected function recompileProvider(string $provider): array
{
$instance = $this->app->resolveProvider($provider);
$type = $instance->isDeferred() ? 'Deferred' : 'Eager';
|
return $this->{"register{$type}ServiceProvider"}($provider, $instance);
} | csn_ccr |
Set up arguments for each FieldDescriptor in an array. | protected void addArguments(FieldDescriptor field[])
{
for (int i = 0; i < field.length; i++)
{
ArgumentDescriptor arg = new ArgumentDescriptor(this);
arg.setValue(field[i].getAttributeName(), false);
this.addArgument(arg);
}
} | csn |
public function insertTagEntry($tag, $uri = null)
{
if ($uri instanceof Zend_Gdata_Photos_PhotoEntry) {
$uri = $uri->getLink(self::FEED_LINK_PATH)->href;
}
if ($uri === null) {
require_once 'Zend/Gdata/App/InvalidArgumentException.php';
throw new Zend_Gdat... | 'URI must not be null');
}
$newEntry = $this->insertEntry($tag, $uri, 'Zend_Gdata_Photos_TagEntry');
return $newEntry;
} | csn_ccr |
Let's say that in a hypothetical platform that resembles Codewars there is a clan with 2 warriors. The 2nd one in ranking (lets call him **D**) wants to at least reach the honor score of his ally (lets call her **M**).
*(Let's say that there is no antagonism here, he just wants to prove his ally that she should be pro... | def get_honor_path(honor, target):
return dict(list(zip(["1kyus", "2kyus"], divmod(target - honor, 2)))) if target > honor else {}
| apps |
// stepsFor245 returns upgrade steps for Juju 2.4.5 | func stepsFor245() []Step {
return []Step{
&upgradeStep{
description: "update exec.start.sh log path if incorrect",
targets: []Target{AllMachines},
run: correctServiceFileLogPath,
},
}
} | csn |
// ScanProofs creates a ScanProofsEngine and runs it. | func (h *ScanProofsHandler) ScanProofs(ctx context.Context, arg keybase1.ScanProofsArg) error {
uis := libkb.UIs{
LogUI: h.getLogUI(arg.SessionID),
SessionID: arg.SessionID,
}
eng := engine.NewScanProofsEngine(arg.Infile, arg.Indices, arg.Sigid, arg.Ratelimit, arg.Cachefile, arg.Ignorefile, h.G())
m := libk... | csn |
python see if char is ready for reading | def _stdin_ready_posix():
"""Return True if there's something to read on stdin (posix version)."""
infds, outfds, erfds = select.select([sys.stdin],[],[],0)
return bool(infds) | cosqa |
Forward events from the scaffold instance to the `Scaffold` constructor | function foward(app, options) {
if (typeof options.name === 'string') {
app.name = options.name;
delete options.name;
}
Scaffold.emit('scaffold', app);
emit('target', app, Scaffold);
emit('files', app, Scaffold);
} | csn |
r"""Defines command line options
Args:
**kwargs:
key: A name for the option.
value : Default value or a tuple of (default value, description).
Returns:
None
For example,
```
# Either of the following two lines will define `--n_epoch` command line argument and set its ... | def sg_arg_def(**kwargs):
r"""Defines command line options
Args:
**kwargs:
key: A name for the option.
value : Default value or a tuple of (default value, description).
Returns:
None
For example,
```
# Either of the following two lines will define `--n_epoch` comm... | csn |
Single account
Returns a single account
@param budget_id The id of the budget (\"last-used\" can also be used to specify the last used budget)
@param account_id The id of the account
@param [Hash] opts the optional parameters
@return [AccountResponse] | def get_account_by_id(budget_id, account_id, opts = {})
data, _status_code, _headers = get_account_by_id_with_http_info(budget_id, account_id, opts)
data
end | csn |
Sends generated file for download
@param string $sOutputKey Output key. | public function downloadResultFile($sOutputKey = null)
{
$sCurrentKey = (empty($sOutputKey)) ? $this->_sOutputKey : $sOutputKey;
$this->_oUtils = \OxidEsales\Eshop\Core\Registry::getUtils();
$iFileSize = filesize($this->_oUtils->getCacheFilePath($sCurrentKey));
$this->_oUtils->setH... | csn |
func FromStringAndExt(t, ext string) (Type, error) {
tp, err := fromString(t)
| if err != nil {
return tp, err
}
tp.Suffixes = []string{strings.TrimPrefix(ext, ".")}
return tp, nil
} | csn_ccr |
Return a processor by an identifier if it exists
@param string $name The processor identifier
@return mixed The processor if it exists | public function getProcessor($name)
{
return isset($this->processors[$name]) ? $this->processors[$name] : false;
} | csn |
// ToTLFWriterKeyBundleV3 converts a TLFWriterKeyGenerationsV2 to a TLFWriterKeyBundleV3. | func (wkg TLFWriterKeyGenerationsV2) ToTLFWriterKeyBundleV3(
codec kbfscodec.Codec,
tlfCryptKeyGetter func() ([]kbfscrypto.TLFCryptKey, error)) (
TLFWriterKeyBundleV2, TLFWriterKeyBundleV3, error) {
keyGen := wkg.LatestKeyGeneration()
if keyGen < FirstValidKeyGen {
return TLFWriterKeyBundleV2{}, TLFWriterKeyBund... | csn |
Execute a SQL file in the database.
This will scan the file for statements, skipping comment-only lines.
Occurences of %PREFIX% will be replaced with the configured table
prefix. YOU ARE STRONGLY ADVISED TO ENCLOSE ALL TABLE REFERENCES
WITH IDENTIFIER QUOTES. For MySQL use backticks, for PostgreSQL
use double quotes.... | public function executeSQL(string $filename)
{
$fh = @fopen($filename, "r");
if ($fh === false)
throw new IOException("Unable to open file '$filename'");
$prefix = $this->driver->getTablePrefix();
$statement = '';
while (!feof($fh))
{
... | csn |
def parse_block(self, contents, parent, module, depth):
"""Extracts all executable definitions from the specified string and adds
them to the specified parent."""
for anexec in self.RE_EXEC.finditer(contents):
x = self._process_execs(anexec, parent, module)
parent.executa... | if "\n" in contents[rem[0]+1:rem[1]]:
signature = contents[rem[0]+1:rem[1]].index("\n") + 2
keep = contents[cur_end:rem[0] + signature]
cur_end = rem[1]
retain.append(keep)
#Now we have a string of documentation s... | csn_ccr |
func MinimumAPIVersionCheck(current string, minimum string) error {
if minimum == "" {
return nil
}
currentSemver, err := semver.Make(current)
if err != nil {
return err
}
minimumSemver, err := semver.Make(minimum)
if err != nil {
return | err
}
if currentSemver.Compare(minimumSemver) == -1 {
return ccerror.MinimumAPIVersionNotMetError{
CurrentVersion: current,
MinimumVersion: minimum,
}
}
return nil
} | csn_ccr |
// WaitTimeSeconds controls the length of long polling for available messages | func WaitTimeSeconds(seconds int64) broker.SubscribeOption {
return func(o *broker.SubscribeOptions) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, waitTimeSecondsKey{}, seconds)
}
} | csn |
def is_dockerized(flag_name: str = 'DOCKERIZED', strict: bool = False):
"""
Reads env ``DOCKERIZED`` variable as a boolean.
:param flag_name: environment variable name
:param strict: raise a ``ValueError`` if variable does not look like a | normal boolean
:return: ``True`` if has truthy ``DOCKERIZED`` env, ``False`` otherwise
"""
return env_bool_flag(flag_name, strict=strict) | csn_ccr |
Load icon images, return css string. | function iconStyle (files, useIcons) {
if (!useIcons) return '';
var className;
var i;
var iconName;
var list = [];
var rules = {};
var selector;
var selectors = {};
var style = '';
for (i = 0; i < files.length; i++) {
var file = files[i];
var isDir = '..' == file.name || (file.stat && fil... | csn |
def _setint(self, int_, length=None):
"""Reset the bitstring to have given signed int interpretation."""
# If no length given, and we've previously been given a length, use it.
if length is None and hasattr(self, 'len') and self.len != 0:
length = self.len
if length is None o... | # TODO: We should decide whether to just use the _setuint, or to do the bit flipping,
# based upon which will be quicker. If the -ive number is less than half the maximum
# possible then it's probably quicker to do the bit flipping...
# Do the 2's complement thing. Add one, set to minus n... | csn_ccr |
Richik$Richik$ has just completed his engineering and has got a job in one of the firms at Sabrina$Sabrina$ which is ranked among the top seven islands in the world in terms of the pay scale.
Since Richik$Richik$ has to travel a lot to reach the firm, the owner assigns him a number X$X$, and asks him to come to work o... | t=int(input())
for i in range(t):
x,n=[int(g) for g in input().split()]
sal=0
day=x
while day<n:
sal=sal+day
day+=x
print(sal)
| apps |
protected function massAssign($data = [])
{
if (is_array($data)) {
/**
* Check if the passed in array contains a sub customer array.
* If a matching array is found, it is passed to the set customer method.
* ['customer' => [ 'name' => 'Victor Ariama', 'ema... | channel key and value.
* If a matching key and value is found, assign the channel that was passed in
* to the token on the instance.
*
* ['channel' => 'mtn-gh']
*/
if (array_key_exists('channel', $data)) {
$this->setChannel($d... | csn_ccr |
Returns all users who belong to
a group.
@param \Cartalyst\Sentry\Groups\GroupInterface $group
@return array | public function findAllInGroup(GroupInterface $group)
{
return array_filter($this->findAll(), function($user) use ($group)
{
return $user->inGroup($group);
});
} | csn |
Gets a single byte return or -1 if no data is available. | public synchronized int get() {
if (available == 0) {
return -1;
}
byte value = buffer[idxGet];
idxGet = (idxGet + 1) % capacity;
available--;
return value;
} | csn |
def docelement(self):
"""Returns the instance of the element whose body owns the docstring
in the current operation.
"""
#This is needed since the decorating documentation
#for types and executables is in the body of the module, but when they
#get edited, the edit belongs... | else:
ichar = self.element.module.charindex(self.icached[0], 1)
if (ichar > self.element.docstart and ichar <= self.element.docend):
self._docelement = self.element.parent
else:
self._docelement = self.element
return self.... | csn_ccr |
func Convert_v1beta1_LocalEtcd_To_kubeadm_LocalEtcd(in *LocalEtcd, out *kubeadm.LocalEtcd, s conversion.Scope) error { |
return autoConvert_v1beta1_LocalEtcd_To_kubeadm_LocalEtcd(in, out, s)
} | csn_ccr |
Factory to create a row associated with this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_table_row]
:end-before: [END bigtable_table_row]
.. warning::
At most one of ``filter_`` and ``append`` can be used in a
... | def row(self, row_key, filter_=None, append=False):
"""Factory to create a row associated with this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_table_row]
:end-before: [END bigtable_table_row]
.. warning::
... | csn |
Adjusts the image's brightness.
```php
$img = new bbn\file\image("/home/data/test/image.jpg");
$img->brightness();
$img->brightness("-");
```
@param string $val The value "+" (default) increases the brightness, the value ("-") reduces it.
@return image | public function brightness($val='+')
{
if ( $this->test() )
{
if ( class_exists('\\Imagick') )
{
$p = ( $val == '-' ) ? 90 : 110;
if ( !$this->img->modulateImage($p,100,100) ){
$this->error = \defined('BBN_THERE_HAS_BEEN_A_PROBLEM') ?
BBN_THERE_HAS_BEEN_A_PROBLEM : 'There has been a proble... | csn |
Sets the MaximumLength value.
@param int $maximumLength
@return $this
@throws \Xloit\Bridge\Zend\Validator\Exception\InvalidArgumentException | public function setMaximumLength($maximumLength)
{
if ($maximumLength <= $this->minimalLength) {
throw new Exception\InvalidArgumentException('Maximum length must be larger than minimal length.');
}
$this->maximumLength = $maximumLength;
return $this;
} | csn |
round to significant figures in python | def round_figures(x, n):
"""Returns x rounded to n significant figures."""
return round(x, int(n - math.ceil(math.log10(abs(x))))) | cosqa |
public function addByArray(array $services = [])
{
if (!empty($services)) {
foreach ($services as $name => $methods) {
if (!$this->has($name)) {
$service = new Service();
foreach ($methods as $method => $value) {
if (method_exists($service, $method)) {
... | } else {
throw new ServiceMethodNotExists(sprintf(
"Method '%s' does not exists on the %s service.",
$method,
$name
));
}
}
$this->services[$name] = $service;
continue;
}
... | csn_ccr |
def __prepare_body(self, search_value, search_type='url'):
"""
Prepares the http body for querying safebrowsing api. Maybe the list need to get adjusted.
:param search_value: value to search for
:type search_value: str
:param search_type: 'url' or 'ip'
:type search_type:... | data = {
'threatTypes': ['MALWARE'],
'platformTypes': ['WINDOWS', 'LINUX', 'OSX'],
'threatEntryTypes': ['IP_RANGE']
}
else:
raise SearchTypeNotSupportedError('Currently supported search types are \'url\' and \'ip\'.')
# TODO: ... | csn_ccr |
def validate_dynamic_argspec(callback, kdims, streams):
"""
Utility used by DynamicMap to ensure the supplied callback has an
appropriate signature.
If validation succeeds, returns a list of strings to be zipped with
the positional arguments i.e kdim values. The zipped values can then
be merged... | positional kdim arguments only allowed at '
'the start of the signature of {name!r}'.format(name=name))
return posargs
elif argspec.varargs: # Posargs missing, passed to Callable directly
return None
elif set(posargs) - set(kdims):
raise KeyError('... | csn_ccr |
def _create_selector(int_type, func, trait, **kwargs):
"""Create a selector of the specified type.
Also attaches the function `func` as an `on_trait_change` listener
for the trait `trait` of the selector.
This is an internal function which should not be called by the user.
Parameters
--------... | The name of the Selector trait whose change triggers the
call back function `func`.
"""
interaction = _add_interaction(int_type, **kwargs)
if func is not None:
interaction.on_trait_change(func, trait)
return interaction | csn_ccr |
def _sortAttributeValue(self, offset):
"""
return the value of the sort attribute for the item at
'offset' in the results of the last query, otherwise None.
"""
if self._currentResults:
pageStart = (self._currentResults[offset][
self.currentSortColumn.... |
self._currentResults[offset][
'__item__'].storeID)
else:
pageStart = None
return pageStart | csn_ccr |
Rollback and close a transaction
@param bool $throw
@return bool
@throws Exception
@test equals false,(false),'transaction is not open' | public function rollback($throw=true)
{
if (!$this->transactionOpen && $throw) $this->throwError("Transaction not open to rollback()","");
if (!$this->isOpen) { $this->throwError("It's not connected to the database",""); return false; }
$this->transactionOpen = false;
return @$this->conn1->rollback();
} | csn |
Determine if 'path' is an key or property of another object
@param {NodePath} path
@returns {Boolean} | function isPropertyOrKey(path) {
return path.parentPath.get('key') === path || path.parentPath.get('property') === path;
} | csn |
public function parent($key):self
{
$breadcrumb = BreadcrumbFacade::get($key); |
$this->parents->put($key, $breadcrumb);
return $this;
} | csn_ccr |
Inserts object data into DB, returns true on success.
@return bool | protected function _insert()
{
// set oxinsert value
$this->oxpricealarm__oxinsert = new \OxidEsales\Eshop\Core\Field(date('Y-m-d', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime()));
return parent::_insert();
} | csn |
Normalize the values array. | protected function normalizeValues(array $values, string $property): ?array
{
foreach ($values as $key => $value) {
if (!\is_int($key) || !\is_string($value)) {
unset($values[$key]);
}
}
if (empty($values)) {
$this->getLogger()->notice('In... | csn |
Add a global header which will be appended to every HTTP request.
The headers defined per request will override this headers.
@param name The name of the header
@param value The value of the header
@return a reference to this so multiple method calls can be chained together | public RestClientOptions putGlobalHeader(String name, String value) {
globalHeaders.add(name, value);
return this;
} | csn |
Get the current carpet cleaning settings.
@return The current carpet cleaning settings.
@throws CommandExecutionException When there has been a error during the communication or the response was invalid. | public JSONObject getCarpetModeState() throws CommandExecutionException {
JSONArray ret = sendToArray("get_carpet_mode");
if (ret == null) return null;
return ret.optJSONObject(0);
} | csn |
def add_album_art(file_name, album_art):
"""
Add album_art in .mp3's tags
"""
img = requests.get(album_art, stream=True) # Gets album art from url
img = img.raw
audio = EasyMP3(file_name, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
... | type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
return album_art | csn_ccr |
private function initializePlugin($pluginId) {
$configData = $this->config->plugins[$pluginId];
// load class file
$class = str_replace('/', '\\', $configData['class']);
$file = $this->rootPath . 'src/' . $configData['classPath'] . $class . '.php';
if(!file_exists($file)) {
throw new ApplicationExce... |
// set parameters
if(!empty($configData['parameters'])) {
if(!method_exists($plugin, 'setParameters')) {
throw new ApplicationException(sprintf("Plugin '%s' (class %s) does not provide a 'setParameters' method but has parameters configured.", $pluginId, $class));
}
$plugin->setParameters($conf... | csn_ccr |
Returns the CA file for validating certificates for encrypted
connections to the RADIUS server, as configured in
guacamole.properties.
@return
The file name for the CA file for validating
RADIUS server certificates
@throws GuacamoleException
If guacamole.properties cannot be parsed. | public File getRadiusCAFile() throws GuacamoleException {
return environment.getProperty(
RadiusGuacamoleProperties.RADIUS_CA_FILE,
new File(environment.getGuacamoleHome(), "ca.crt")
);
} | csn |
func recoverFromReorg(chain *blockchain.BlockChain, minBlock, maxBlock int32,
lastBlock *chainhash.Hash) ([]chainhash.Hash, error) {
hashList, err := chain.HeightRange(minBlock, maxBlock)
if err != nil {
rpcsLog.Errorf("Error looking up block range: %v", err)
return nil, &btcjson.RPCError{
Code: btcjson.E... | chain.BlockByHash(&hashList[0])
if err != nil {
rpcsLog.Errorf("Error looking up possibly reorged block: %v",
err)
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCDatabase,
Message: "Database error: " + err.Error(),
}
}
jsonErr := descendantBlock(lastBlock, blk)
if jsonErr != nil {
return ni... | csn_ccr |
public static String leftStr(String str, int length) {
return | str.substring(0, Math.min(str.length(), length));
} | csn_ccr |
Put spans with null endpoints first, so that their data can be attached to the first span with
the same ID and endpoint. It is possible that a server can get the same request on a different
port. Not addressing this. | static int compareEndpoint(Endpoint left, Endpoint right) {
if (left == null) { // nulls first
return (right == null) ? 0 : -1;
} else if (right == null) {
return 1;
}
int byService = nullSafeCompareTo(left.serviceName(), right.serviceName(), false);
if (byService != 0) return byService;... | csn |
func Register(name string, factory acl.Factory) {
mu.Lock()
defer mu.Unlock()
if _, ok := acls[name]; ok {
| panic(fmt.Sprintf("register a registered key: %s", name))
}
acls[name] = factory
} | csn_ccr |
protected static function build(array $file)
{
if (is_array($file['tmp_name'])) {
return static::normalizeNested($file);
}
return new UploadedFile(
$file['name'],
| $file['tmp_name'],
$file['type'],
$file['size'],
$file['error']
);
} | csn_ccr |
public static function fromFloat($float, $tolerance=1e-7)
{
if (is_string($float) && preg_match('~^\-?\d+([,|.]\d+)?$~', $float)) {
$float = floatval(str_replace(',','.',$float));
}
if ($float == 0.0) {
return new Rational(0,1);
}
$negative = ($float ... | $aux = $den1;
$den1 = $floor * $den1 + $den2;
$den2 = $aux;
$oneOver = $oneOver - $floor;
} while (abs($float - $num1 / $den1) > $float * $tolerance);
if ($negative) {
$num1 *= -1;
}
return new Rational(intval($num1), intval($den1));... | csn_ccr |
Given an array of indexes
return the number of new axis elements
in teh array
@param axes the indexes to get the number
of new axes for
@return the number of new axis elements in the given array | public static int numNewAxis(INDArrayIndex... axes) {
int ret = 0;
for (INDArrayIndex index : axes)
if (index instanceof NewAxis)
ret++;
return ret;
} | csn |
public function &getAccessControlConfig()
{
if (!isset($this->_accessControlConfigCache)) {
$this->_accessControlConfigCache = new CKFinder_Connector_Core_AccessControlConfig(isset($GLOBALS['config']['AccessControl']) ? | $GLOBALS['config']['AccessControl'] : array());
}
return $this->_accessControlConfigCache;
} | csn_ccr |
Entry point for event that were not delegated
@param {HTMLEvent} event HTML Event
@param {String} delegateId Id of the delegated callback
@param {Boolean} wrapTarget, if true, wrap target into DomEventWrapper
@param {HTMLElement} container HTML Element on which the listener is attached
@return {Object} Return value of ... | function (event, delegateId, wrapTarget, container) {
this.$assert(286, this.__delegateMapping);
var eventWrapper = this.__wrapEvent(event, wrapTarget), result;
var callback = this.__delegateMapping[delegateId];
if (callback) {
result = callback.call(event... | csn |
def start(self):
'''
Listen to auth requests and send the AES key.
Each client connection starts a new thread.
'''
# Start suicide polling thread
log.debug('Starting the auth process')
self.verify_cert()
self._create_skt()
log.debug('The auth proce... | wrapped_auth_skt = ssl.wrap_socket(clientsocket,
server_side=True,
certfile=self.certificate,
keyfile=self.keyfile)
except ssl.SSLError:
... | csn_ccr |
Update the table server side filter action.
It is done based on the current filter. The filter info may be stored
in the session and this will restore it. | def update_server_filter_action(self, request, table=None):
"""Update the table server side filter action.
It is done based on the current filter. The filter info may be stored
in the session and this will restore it.
"""
if not table:
table = self.get_table()
... | csn |
Add primary layer to the map. | private void addPrimaryLayer() {
LineLayer primary = TrafficLayer.getLineLayer(
Primary.BASE_LAYER_ID,
Primary.ZOOM_LEVEL,
Primary.FILTER,
Primary.FUNCTION_LINE_COLOR,
Primary.FUNCTION_LINE_WIDTH,
Primary.FUNCTION_LINE_OFFSET
);
LineLayer primaryCase = TrafficLayer.getLi... | csn |
Calculates the signature for the given request data. | def calculate_signature(key, data, timestamp=None):
"""
Calculates the signature for the given request data.
"""
# Create a timestamp if one was not given
if timestamp is None:
timestamp = int(time.time())
# Construct the message from the timestamp and the data in the request
messag... | csn |
private boolean setValue(String propertyName, String value, boolean sync) throws NullPointerException
{
gatekeeper.signIn();
try
{
ChangeStack<String> stack = properties.get(propertyName);
if (stack == null)
{
ChangeStack<String> newStack =... | sync);
stack = properties.putIfAbsent(propertyName, newStack);
if (stack == null)
{
return true;
}
}
return sync ? stack.sync(value) : stack.push(value);
}
finally
{
gateke... | csn_ccr |
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 |
// New initializes an empty infrastructure | func New() *Infrastructure {
return &Infrastructure{
Lock: new(sync.RWMutex),
Services: make(map[string]*Service),
UpdateTimestamp: time.Now().UnixNano(),
}
} | csn |
Terminate execution immediately - use it when there's no other way of recovering from error, usually
in boot procedure, when exceptions are not loaded yet and etc.
Some parts of framework use this method, that's why it's public. You should never get into case when
using this method would be recommended.
@param string... | public static function terminateWithError(string $message, int $errorCode = 503): void
{
http_response_code($errorCode);
header('Retry-After: 300'); // 300 seconds / 5 minutes
print $message;
exit(1);
} | csn |
function chrootSpawn(command, argv, opts, callback)
{
argv = [opts.uid, opts.gid, command].concat(argv)
const options =
{
cwd: opts.cwd,
env: opts.env, |
stdio: 'inherit'
}
proc.spawn(`${__dirname}/chrootSpawn`, argv, options).on('exit', callback)
} | csn_ccr |
public function AddOverload(\Peg\Lib\Definitions\Element\Overload $overload)
{
$overload->function =& $this;
| $this->overloads[] = $overload;
return $this;
} | csn_ccr |
Send a SECTOR_SELECT command to switch the 1K address sector.
The command is only send to the tag if the *sector* number is
different from the currently selected sector number (set to 0
when the tag instance is created). If the command was
successful, the currently selected sector numbe... | def sector_select(self, sector):
"""Send a SECTOR_SELECT command to switch the 1K address sector.
The command is only send to the tag if the *sector* number is
different from the currently selected sector number (set to 0
when the tag instance is created). If the command was
suc... | csn |
def scatter2d(data, **kwargs):
"""Create a 2D scatter plot
Builds upon `matplotlib.pyplot.scatter` with nice defaults
and handles categorical colors / legends better.
Parameters
----------
data : array-like, shape=[n_samples, n_features]
Input data. Only the first two components will b... | and label_prefix is None, no label is set.
zlabel : str or None (default : None)
Label for the z axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
Only used for 3D plots.
title : str or None (default: None)
axis title. ... | csn_ccr |
Takes as input an ArrayList of double arrays which contains the set of local descriptors of an image.
Returns the multiVLAD representation of the image using the codebooks supplied in the constructor.
@param descriptors
@return the multiVLAD vector
@throws Exception | public double[] aggregate(ArrayList<double[]> descriptors) throws Exception {
double[] multiVlad = new double[vectorLength];
int vectorShift = 0;
for (int i = 0; i < vladAggregators.length; i++) {
double[] subVlad = vladAggregators[i].aggregate(descriptors);
if (normalizationsOn) {
Normalization.n... | csn |
Returns the current status of this parameter server
updater
@return | @Override
public Map<String, Number> status() {
Map<String, Number> ret = new HashMap<>();
ret.put("workers", workers);
ret.put("accumulatedUpdates", numUpdates());
return ret;
} | csn |
func hapiAdminsUpdate(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ABOT_ENV") != "test" {
if !isAdmin(w, r) {
return
}
if !isLoggedIn(w, r) {
return
}
if !isValidCSRF(w, r) {
return
}
}
var req struct {
ID uint64
Email string
Admin bool
}
if err := json.NewDecoder(r.Body).D... | if err != nil {
writeErrorInternal(w, err)
return
}
var user struct {
ID uint64
Email string
Name string
}
q = `SELECT id, email, name FROM users WHERE id=$1`
if err = db.Get(&user, q, req.ID); err != nil {
writeErrorInternal(w, err)
return
}
byt, err := json.Marshal(user)
if err != nil {
w... | csn_ccr |
public Metric<G> merge(final Metric with) {
this.description = with.description;
this.domain = with.domain;
this.enabled = with.enabled;
this.qualitative = with.qualitative;
this.worstValue = with.worstValue;
this.bestValue = with.bestValue; |
this.optimizedBestValue = with.optimizedBestValue;
this.direction = with.direction;
this.key = with.key;
this.type = with.type;
this.name = with.name;
this.userManaged = with.userManaged;
this.hidden = with.hidden;
this.deleteHistoricalData = with.deleteHistoricalData;
return this;
... | csn_ccr |
kwargs inside contructor python | def updateFromKwargs(self, properties, kwargs, collector, **unused):
"""Primary entry point to turn 'kwargs' into 'properties'"""
properties[self.name] = self.getFromKwargs(kwargs) | cosqa |
Sets the value of an ISE project property. | def set_property(name, value, mark_non_default=true)
#Set the node's property, as specified.
node = get_property_node(name)
node.attribute("value").value = value
#If the mark non-default option is set, mark the state is not a default value.
node.attribute("valueState").value = 'non-defa... | csn |
def main():
"""
NAME
update_measurements.py
DESCRIPTION
update the magic_measurements table with new orientation info
SYNTAX
update_measurements.py [command line options]
OPTIONS
-h prints help message and quits
-f MFILE, specify magic_measurements file; ... | break
if rec['er_sample_name'].lower() not in sampnames:
sampnames.append(rec['er_sample_name'].lower())
sflag=1
SampRec={}
for key in list(samps[0].keys()):SampRec[key]=""
SampRec['er_sample_name']=rec['er_sample_name']
SampRec['er... | csn_ccr |
Unset all keys.
@return void | public function delete()
{
foreach (array_keys($this->data) as $key) {
unset($this->data[$key]);
}
foreach (array_keys($this->flash) as $key) {
unset($this->flash[$key]);
}
} | csn |
private function normalizeDriverOptions(array $connection)
{
$driverOptions = $connection['driverOptions'] ?? [];
$driverOptions['typeMap'] = DocumentManager::CLIENT_TYPEMAP;
if (isset($driverOptions['context'])) {
| $driverOptions['context'] = new Reference($driverOptions['context']);
}
return $driverOptions;
} | csn_ccr |
Create an Accept-Datetime header object from a string
@param value the header value
@return an AcceptDatetime object or null if the value is not parseable | public static AcceptDatetime valueOf(final String value) {
final Optional<Instant> datetime = parseDatetime(value);
if (datetime.isPresent()) {
return new AcceptDatetime(datetime.get());
}
return null;
} | csn |
public function revokePermission($permission, $user_id)
{
$user = \App\User::findorfail($user_id);
| $user->revokePermissionTo(str_slug($permission, ' '));
return redirect('scaffold-users/edit/'.$user_id);
} | csn_ccr |
public function getCompiledInsert(string $table, bool $reset=TRUE): string
{
| return $this->_getCompile('insert', $table, $reset);
} | csn_ccr |
public Waiter<DescribeVaultRequest> vaultNotExists() {
return new WaiterBuilder<DescribeVaultRequest, DescribeVaultResult>().withSdkFunction(new DescribeVaultFunction(client))
.withAcceptors(new HttpSuccessStatusAcceptor(WaiterState.RETRY), new VaultNotExists.IsResourceNotFoundExceptionMatcher(... | .withDefaultPollingStrategy(new PollingStrategy(new MaxAttemptsRetryStrategy(15), new FixedDelayStrategy(3)))
.withExecutorService(executorService).build();
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.