query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
def cli(yamlfile, format, classes, directory):
""" Generate a UML representation of a biolink model """
| print(YumlGenerator(yamlfile, format).serialize(classes=classes, directory=directory), end="") | csn_ccr |
public function eval($script, $numberOfKeys, ...$arguments)
{
| return $this->client->eval($script, $arguments, $numberOfKeys);
} | csn_ccr |
public static function scopes()
{
return collect(static::$scopes)->map(function ($description, | $id) {
return new Scope($id, $description);
})->values();
} | csn_ccr |
func (_class VIFClass) GetNetwork(sessionID SessionRef, self VIFRef) (_retval NetworkRef, _err error) {
_method := "VIF.get_network"
_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
| if _err != nil {
return
}
_selfArg, _err := convertVIFRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
if _err != nil {
return
}
_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
if _err != nil {
return
}
_retval, _err = convertNetworkRefToGo(_method + " -> ", _result.Value)
... | csn_ccr |
def unit_signature_vector
return to_base.unit_signature_vector unless base?
vector = Array.new(SIGNATURE_VECTOR.size, 0)
# it's possible to have a kind that misses the array... kinds like :counting
# are more like prefixes, so don't use them to calculate the vector
@numerator.map { |elemen... | @denominator.map { |element| RubyUnits::Unit.definition(element) }.each do |definition|
index = SIGNATURE_VECTOR.index(definition.kind)
vector[index] -= 1 if index
end
raise ArgumentError, 'Power out of range (-20 < net power of a unit < 20)' if vector.any? { |x| x.abs >= 20 }
vec... | csn_ccr |
how do i time the amount of time it takes to run an operation in python | def timeit(output):
"""
If output is string, then print the string and also time used
"""
b = time.time()
yield
print output, 'time used: %.3fs' % (time.time()-b) | cosqa |
Draw the manifold embedding for the specified algorithm | def plot_manifold_embedding(self, algorithm="lle", path="images"):
"""
Draw the manifold embedding for the specified algorithm
"""
_, ax = plt.subplots(figsize=(9,6))
path = self._make_path(path, "s_curve_{}_manifold.png".format(algorithm))
oz = Manifold(
ax=... | csn |
func New(config *Config) (SecretService, error) {
var err error
var keyBytes *[SecretKeyLength]byte
var metricsClient metrics.Client
// Read in key from KeyPath or if not given, try getting them from KeyBytes.
if config.KeyPath != "" {
if keyBytes, err = ReadKeyFromDisk(config.KeyPath); err != nil {
return n... | // build metrics client
hostport := fmt.Sprintf("%v:%v", config.StatsdHost, config.StatsdPort)
metricsClient, err = metrics.NewWithOptions(hostport, prefix, metrics.Options{UseBuffering: true})
if err != nil {
return nil, err
}
} else {
// if you don't want to emit stats, use the nop client
metricsClie... | csn_ccr |
def get_related_entry_admin_url(entry):
"""
Returns admin URL for specified entry instance.
:param entry: the entry instance.
:return: str.
"""
namespaces = {
Document: 'wagtaildocs:edit',
Link: 'wagtaillinks:edit',
Page: 'wagtailadmin_pages:edit',
| }
for cls, url in namespaces.iteritems():
if issubclass(entry.content_type.model_class(), cls):
return urlresolvers.reverse(url, args=(entry.object_id,))
return '' | csn_ccr |
def organize_noalign(data):
"""CWL target to skip alignment and organize input data.
"""
data = utils.to_single_data(data[0])
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "align", dd.get_sample_name(data)))
work_bam = os.path.join(work_dir, "%s-input.bam" % dd.get_sample_name(da... | else:
assert data["files"][0].endswith(".bam"), data["files"][0]
utils.copy_plus(data["files"][0], work_bam)
bam.index(work_bam, data["config"])
else:
work_bam = None
data["align_bam"] = work_bam
return data | csn_ccr |
func (f *LogFile) Stat() (int64, time.Time) {
f.mu.RLock()
size, modTime := | f.size, f.modTime
f.mu.RUnlock()
return size, modTime
} | csn_ccr |
// Handle registers a function has handler for the specified key. | func (w *Handler) Handle(key string, h func(eventtypes.Message)) {
w.mu.Lock()
w.handlers[key] = h
w.mu.Unlock()
} | csn |
@Override
public int getConnectedSingleElectronsCount(IAtom atom) {
int count = 0;
for (int i = 0; i < singleElectronCount; i++) {
| if (singleElectrons[i].contains(atom)) ++count;
}
return count;
} | csn_ccr |
python color not in tuple | def rgba_bytes_tuple(self, x):
"""Provides the color corresponding to value `x` in the
form of a tuple (R,G,B,A) with int values between 0 and 255.
"""
return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x)) | cosqa |
Set material uniform
@example
mat.setUniform('color', [1, 1, 1, 1]);
@param {string} symbol
@param {number|array|clay.Texture|ArrayBufferView} value | function (symbol, value) {
if (value === undefined) {
console.warn('Uniform value "' + symbol + '" is undefined');
}
var uniform = this.uniforms[symbol];
if (uniform) {
if (typeof value === 'string') {
// Try to parse as a color. Invalid color str... | csn |
func (fs *FileSorter) Less(i, j int) bool {
l := fs.buf[i].key
r := fs.buf[j].key |
ret, err := lessThan(fs.sc, l, r, fs.byDesc)
if fs.err == nil {
fs.err = err
}
return ret
} | csn_ccr |
function pushToEditUrl(sSegment) {
if (sSegment.includes("($uid=")) | {
prepareKeyPredicate(stripPredicate(sSegment));
} else {
aEditUrl.push(sSegment);
}
} | csn_ccr |
public function executePartition(PartitionInterface $partition, array $options = [])
{
if ($partition instanceof QueryPartition) {
return $this->executeQuery($partition);
} elseif ($partition instanceof ReadPartition) {
| return $this->executeRead($partition);
}
throw new \BadMethodCallException('Unsupported partition type.');
} | csn_ccr |
private static function rewriteParameterAndType(array $parameters, array $types, $index)
{
// The parameter value according.
$parameterValue = $parameters[$index];
// The parameter count.
$parameterCount = count($parameterValue);
// Extract the fridge type.
$type = ... | } elseif (isset($types[$newPosition])) {
unset($types[$newPosition]);
}
}
// Rewrite parameters and types according to the parameter count.
for ($newPlaceholderIndex = 0; $newPlaceholderIndex < $parameterCount; $newPlaceholderIndex++) {
// De... | csn_ccr |
def _capture_variable(iterator, parameters):
"""
return the replacement string.
this assumes the preceeding {{ has already been
popped off.
"""
key = ""
next_c = next(iterator)
while next_c != "}":
| key += next_c
next_c = next(iterator)
# remove the final "}"
next(iterator)
return parameters[key] | csn_ccr |
private KeyScope cascadeChildKeys(final KeyScope rootScope) {
final Map<String, KeyDef> res = new HashMap<>(rootScope.keyDefinition);
cascadeChildKeys(rootScope, res, "");
| return new KeyScope(rootScope.id, rootScope.name, res, new ArrayList<>(rootScope.childScopes));
} | csn_ccr |
def read(self, num_bytes=None):
"""Read and return the specified bytes from the buffer."""
| res = self.get_next(num_bytes)
self.skip(len(res))
return res | csn_ccr |
public static String qualifier(String qualifiedName) {
int loc = qualifiedName.lastIndexOf('.');
if (loc < 0)
| return "";
return qualifiedName.substring(0, loc);
} | csn_ccr |
public function setValues($values, array $files = array())
{
foreach ($this->getFields() as $name => $field) {
$name = $field->getBaseName();
$index = $field->getIndex();
if ($index === null) {
if ($present = isset($values[$name])) {
... | $value = array();
}
$field->setValues($value, (isset($files[$name])?$files[$name]:array()));
} else {
if ($present) {
$field->setValue($value, $files);
} else {
if ($field instanceof Fields\Fil... | csn_ccr |
function (orig, response) {
if (!orig.id) {
console.log("[Brackets LiveDev] Trying to send a response for a message with no ID");
return;
| }
response.id = orig.id;
this.send(response);
} | csn_ccr |
// GetStreamManager returns a StreamManager based on the db headers, or nil if the type is unsupported
// Can be used to lock only certain entries instead of calling | func (db *Database) GetStreamManager() (*StreamManager, error) {
if db.Header.FileHeaders != nil {
if db.Header.IsKdbx4() {
return NewStreamManager(
db.Content.InnerHeader.InnerRandomStreamID,
db.Content.InnerHeader.InnerRandomStreamKey,
)
}
return NewStreamManager(
db.Header.FileHeaders.InnerR... | csn |
Method findAndReplaceSimpleLists.
@param counter
@param childName
@param parentName
@param list
@param parent | protected Element findAndReplaceSimpleLists(Counter counter, Element parent, java.util.Collection list,
String parentName, String childName)
{
boolean shouldExist = (list != null) && (list.size() > 0);
Element element = updateElement(counter, parent, parentName, shouldExist);
if (should... | csn |
Make a connection to the database.
@param logger
This is here so we can use the right logger associated with the sub-class. | @SuppressWarnings("resource")
protected DatabaseConnection makeConnection(Logger logger) throws SQLException {
Properties properties = new Properties();
if (username != null) {
properties.setProperty("user", username);
}
if (password != null) {
properties.setProperty("password", password);
}
Database... | csn |
Get ContentKeyAuthorizationPolicy linked Options.
@param ContentKeyAuthorizationPolicy|string $policy ContentKeyAuthorizationPolicy data or
ContentKeyAuthorizationPolicy Id
@return ContentKeyAuthorizationPolicyOption[] | public function getContentKeyAuthorizationPolicyLinkedOptions($policy)
{
$policyId = Utilities::getEntityId(
$policy,
'WindowsAzure\MediaServices\Models\ContentKeyAuthorizationPolicy'
);
$propertyList = $this->_getEntityList("ContentKeyAuthorizationPolicies('{$policy... | csn |
protected function hydrateBuyerData(HpsBuyerData $buyer)
{
return array(
'BillingAddress1' => $buyer->address->address,
'BillingCity' => $buyer->address->city,
'BillingCountryCode' => $buyer->countryCode,
'BillingFirstName' => $buyer->firstName,
... | 'BillingMiddleName' => $buyer->middleName,
'BillingPhone' => $buyer->phoneNumber,
'BillingPostalCode' => $buyer->address->zip,
'BillingState' => $buyer->address->state,
);
} | csn_ccr |
// User gets current user id from access token.
//
// Returns error if access token is not set or invalid.
//
// It's a standard way to validate a facebook access token. | func (session *Session) User() (id string, err error) {
if session.id != "" {
id = session.id
return
}
if session.accessToken == "" && session.HttpClient == nil {
err = fmt.Errorf("access token is not set")
return
}
var result Result
result, err = session.Api("/me", GET, Params{"fields": "id"})
if err... | csn |
Prompts the user for a value that represents a fixed number of options.
All options are strings.
@param options The first array has an entry for each option. Each entry is either a String[1] that is both the display value
and actual value, or a String[2] whose first element is the display value and second element is t... | static public Value optionValue (String name, final String currentValue, final String[][] options, final String description) {
return new DefaultValue(name, currentValue.toString()) {
public void showDialog () {
int selectedIndex = -1;
DefaultComboBoxModel model = new DefaultComboBoxModel();
for (... | csn |
Return config record information about the most recent bundle accesses and operations | def edit_history(self):
"""Return config record information about the most recent bundle accesses and operations"""
ret = self._db.session\
.query(Config)\
.filter(Config.type == 'buildstate')\
.filter(Config.group == 'access')\
.filter(Config.key == 'las... | csn |
Parses the value of a column by an operation
@param CDataColumn $column
@param integer $row the current row number
@return string | protected function parseColumnValue($column, $row)
{
ob_start();
$column->renderDataCell($row);
$value = ob_get_clean();
if ($column instanceof CDataColumn && array_key_exists($column->name, $this->extendedSummary['columns'])) {
// lets get the configuration
... | csn |
Sends messages for all the methods in the first block in _outstandingMethodBlocks. | function() {
var self = this;
if (_.isEmpty(self._outstandingMethodBlocks))
return;
_.each(self._outstandingMethodBlocks[0].methods, function (m) {
m.sendMessage();
});
} | csn |
Returns the biddable ad group criterion with by specifying the product
partition and bid amount.
@param int $adGroupId the ID of ad group that this ad group criterion is
created under
@param ProductPartition $productPartition the product partition to create
an ad group criterion
@param null|$bidAmount the bid for the ... | public static function asBiddableAdGroupCriterion(
$adGroupId,
ProductPartition $productPartition,
$bidAmount = null
) {
$criterion = new BiddableAdGroupCriterion();
if ($bidAmount !== null && $bidAmount > 0) {
$biddingStrategyConfiguration = new BiddingStrategyC... | csn |
Gets the negative query.
@param index the index
@return the negative query | public MtasSpanQuery getNegativeQuery(int index) {
if ((index >= 0) && (index < negativeQueryList.size())) {
return negativeQueryList.get(index);
} else {
return null;
}
} | csn |
public function getLog(string $logger = 'default'): LoggerInterface
{
if (!isset($this->loggers[$logger])) {
if ($logger === 'default') {
if (!isset($this->implicit['logger'])) {
| throw new \RuntimeException('The default logger was not set');
}
$this->loggers[$logger] = $this->implicit['logger'];
} else {
$this->loggers[$logger] = $this->getCollector()->getLogger($logger);
}
}
return $this->loggers[... | csn_ccr |
how to show type in python | def getTypeStr(_type):
r"""Gets the string representation of the given type.
"""
if isinstance(_type, CustomType):
return str(_type)
if hasattr(_type, '__name__'):
return _type.__name__
return '' | cosqa |
protected function _getSnippetModel() {
$snippetModel = new Model_Snippet();
if ($snippetModel->getObserver('Translatable')) {
$i18nModelFactory = new Garp_I18n_ModelFactory();
| $snippetModel = $i18nModelFactory->getModel($snippetModel);
}
return $snippetModel;
} | csn_ccr |
private static StackLine getStackLine(SrcTree srcTree,
String classQualifiedName, String methodSimpleName, int line) {
StackLine rootStackLine = getStackLine(
srcTree.getRootMethodTable(), classQualifiedName, methodSimpleName, line);
| if (rootStackLine != null) {
return rootStackLine;
}
StackLine subStackLine = getStackLine(
srcTree.getSubMethodTable(), classQualifiedName, methodSimpleName, line);
if (subStackLine != null) {
return subStackLine;
}
return null;
... | csn_ccr |
public static function make($name, array $options = []): self
{
$class = new ReflectionClass($options['class'] ?? static::class);
/* @var static $instance */
| $instance = $class->newInstanceWithoutConstructor();
$instance->setName($name);
$instance->setOptions($options);
return $instance;
} | csn_ccr |
def update_metatab(self, doc, resources):
"""Add documentation entries for resources"""
if not 'Documentation' in doc:
doc.new_section("Documentation")
ds = doc['Documentation']
if not 'Name' in ds.args:
ds.add_arg('Name', prepend=True)
# This is the ... | ds.new_term('Root.Documentation', 'docs/' + name, name=name, title='Primary Documentation (HTML)')
elif name == 'html_basic_body.html':
pass
elif name.endswith('.html'):
ds.new_term('Root.Documentation', 'docs/' + name, name=name, title='Documentat... | csn_ccr |
// addElement adds a child element based on the current token. | func (p *parser) addElement() {
p.addChild(&Node{
Type: ElementNode,
DataAtom: p.tok.DataAtom,
Data: p.tok.Data,
Attr: p.tok.Attr,
})
} | csn |
Gets a 201 response with the specified data.
:param data: The content value.
:param schema: The schema to serialize the data.
:param envelope: The key used to envelope the data.
:return: A Flask response object. | def created(self, data, schema=None, envelope=None):
"""
Gets a 201 response with the specified data.
:param data: The content value.
:param schema: The schema to serialize the data.
:param envelope: The key used to envelope the data.
:return: A Flask response object.
... | csn |
Convert annotations into nanopub_bel annotations format | def process_set(line, annotations):
"""Convert annotations into nanopub_bel annotations format"""
matches = re.match('SET\s+(\w+)\s*=\s*"?(.*?)"?\s*$', line)
key = None
if matches:
key = matches.group(1)
val = matches.group(2)
if key == "STATEMENT_GROUP":
annotations["stat... | csn |
Create a Network proxy for the given proxy settings. | def _create_proxy(proxy_setting):
"""Create a Network proxy for the given proxy settings."""
proxy = QNetworkProxy()
proxy_scheme = proxy_setting['scheme']
proxy_host = proxy_setting['host']
proxy_port = proxy_setting['port']
proxy_username = proxy_setting['username']
... | csn |
private function applyMultiSort(array $data, array $sortArguments)
{
$args = [];
foreach ($sortArguments as $values) {
$remain = count($values) % 3;
if ($remain != 0) {
throw new \InvalidArgumentException(
'The parameter count for each sort... |
$args[] = $values[2]; // sort type
}
$args[] = $data;
//possible 5.3.3 fix?
$sortArgs = [];
foreach ($args as $key => &$value) {
$sortArgs[$key] = &$value;
}
call_user_func_array('array_multisort', $sortArgs);
return end($args)... | csn_ccr |
def _update_user_roles_names_from_roles_id(self, user, users_roles,
roles_list):
"""Add roles names to user.roles, based on users_roles.
:param user: user to update
:param users_roles: list of roles ID
:param roles_list: list of roles obtai... | user_roles_names = [role.name for role in roles_list
if role.id in users_roles]
current_user_roles_names = set(getattr(user, "roles", []))
user.roles = list(current_user_roles_names.union(user_roles_names)) | csn_ccr |
def authenticate_eauth(self, load):
'''
Authenticate a user by the external auth module specified in load.
Return True on success or False on failure.
'''
if 'eauth' not in load:
log.warning('Authentication failure of type "eauth" occurred.')
return False
... | if load['eauth'] not in self.opts['external_auth']:
log.warning('The eauth system "%s" is not enabled', load['eauth'])
log.warning('Authentication failure of type "eauth" occurred.')
return False
# Perform the actual authentication. If we fail here, do not
# contin... | csn_ccr |
handle yaml files in python | def load_yaml(file):
"""If pyyaml > 5.1 use full_load to avoid warning"""
if hasattr(yaml, "full_load"):
return yaml.full_load(file)
else:
return yaml.load(file) | cosqa |
def setup_lookup_table( self, hamiltonian='nearest-neighbour' ):
"""
Create a jump-probability look-up table corresponding to the appropriate Hamiltonian.
Args:
hamiltonian (Str, optional): String specifying the simulation Hamiltonian.
| valid values are 'nearest-neighbour' (default) and 'coordination_number'.
Returns:
None
"""
expected_hamiltonian_values = [ 'nearest-neighbour', 'coordination_number' ]
if hamiltonian not in expected_hamiltonian_values:
raise ValueError
self.... | csn_ccr |
Load a YAML file.
@param $filePath
@return $this | public function loadYamlFile($filePath)
{
if (file_exists($filePath)) {
$this->loadYaml(file_get_contents($filePath));
return $this;
}
return $this;
} | csn |
func askToTrustHost(addr, algo, fingerprint string) bool {
var ans string
fmt.Fprintf(os.Stderr, promptToTrustHost, addr, algo, fingerprint)
fmt.Scanf("%s\n", &ans)
ans | = strings.ToLower(ans)
if ans != "yes" && ans != "y" {
return false
}
return true
} | csn_ccr |
def load_data(infile, workdir=None):
"""Load python data structure from either a YAML or numpy file. """
infile = resolve_path(infile, workdir=workdir)
infile, ext = os.path.splitext(infile)
if os.path.isfile(infile + '.npy'):
infile += '.npy'
elif os.path.isfile(infile + '.yaml'):
... | file does not exist.')
ext = os.path.splitext(infile)[1]
if ext == '.npy':
return infile, load_npy(infile)
elif ext == '.yaml':
return infile, load_yaml(infile)
else:
raise Exception('Unrecognized extension.') | csn_ccr |
Count how many tasks should preempt for the starving pools
@return The number of tasks should kill | private int countTasksShouldPreempt() {
int tasksToPreempt = 0;
long now = ClusterManager.clock.getTime();
for (PoolGroupSchedulable poolGroup : poolGroupManager.getPoolGroups()) {
for (PoolSchedulable pool : poolGroup.getPools()) {
if (pool.isStarving(now)) {
tasksToPreempt +=
... | csn |
func (r *Store) Move(ctx context.Context, from, to string) error | {
return r.move(ctx, from, to, true)
} | csn_ccr |
Deploy a signature fole | def deploy_signature(source, dest, user=None, group=None):
"""Deploy a signature fole"""
move(source, dest)
os.chmod(dest, 0644)
if user and group:
try:
uid = pwd.getpwnam(user).pw_uid
gid = grp.getgrnam(group).gr_gid
os.chown(dest, uid, gid)
except (K... | csn |
def set_exception(self, exc_info):
"""
This method allows you to set an exception in the future without requring
that exception to be raised from the futures worker. This method can be
called on an unbound future.
:param exc_info: Either an exception info tuple or an exception value.
In the l... | was actually raised by the caller? (Not sure if possible)
raise exc_info
except:
exc_info = sys.exc_info()
exc_info = (exc_info[0], exc_info[1], exc_info[2])
with self._lock:
if self._enqueued:
raise RuntimeError('can not set exception of enqueued Future')
se... | csn_ccr |
private function build( $pString ) {
for ( $i=0; $i < strlen( $pString ); $i++ ) {
| $this->addChar( $pString[$i] );
}
} | csn_ccr |
// Type returns a new multiplexer who matches an HTTP response
// Content-Type header field based on the given type string. | func Type(kind string) *Mux {
return Match(func(ctx *c.Context) bool {
if ctx.GetString("$phase") != "response" {
return false
}
if value, ok := types.Types[kind]; ok {
kind = value
}
return strings.Contains(ctx.Response.Header.Get("Content-Type"), kind)
})
} | csn |
Given an array, find the duplicates in that array, and return a new array of those duplicates. The elements of the returned array should appear in the order when they first appeared as duplicates.
__*Note*__: numbers and their corresponding string representations should not be treated as duplicates (i.e., `"1" != 1`).... | def duplicates(array):
seen = []
dups = []
for char in array:
if char not in seen:
seen.append(char)
elif char not in dups:
dups.append(char)
return dups
| apps |
public function writeString(&$string)
{
$len = strlen($string);
if(!$len){
$this->writeInteger(0x01);
return $this;
}
$ref = array_key_exists($string, $this->_referenceStrings)
? $this->_referenceStrings[$string]
: false;
| if ($ref === false){
$this->_referenceStrings[$string] = count($this->_referenceStrings);
$this->writeBinaryString($string);
} else {
$ref <<= 1;
$this->writeInteger($ref);
}
return $this;
} | csn_ccr |
func (c *ContentSpec) truncateWordsToWholeSentenceOld(content string) (string, bool) {
words := strings.Fields(content)
if c.summaryLength >= len(words) {
return strings.Join(words, " "), false
}
for counter, word := range words[c.summaryLength:] {
if strings.HasSuffix(word, ".") ||
strings.HasSuffix(word,... | ".\"") ||
strings.HasSuffix(word, "!") {
upper := c.summaryLength + counter + 1
return strings.Join(words[:upper], " "), (upper < len(words))
}
}
return strings.Join(words[:c.summaryLength], " "), true
} | csn_ccr |
Set table data | def set_data(self, data):
"""Set table data"""
if data is not None:
self.model.set_data(data, self.dictfilter)
self.sortByColumn(0, Qt.AscendingOrder) | csn |
private ProcessInfo executeProcess(boolean background,ProcessBuilder pb)
{
try
{
pb.directory(workingDirectory);
pb.redirectErrorStream(false);
if(log != null)
pb.redirectOutput(Redirect.appendTo(log));
pb.environment().putAll(envMap);
Process p = pb.start();
String out = null... |
if(background)
{
out = IO.readText(p.getInputStream(),true,defaultBackgroundReadSize);
error = IO.readText(p.getErrorStream(),true,20);
}
else
{
out = IO.readText(p.getInputStream(),true);
error = IO.readText(p.getErrorStream(),true);
}
if(background)
... | csn_ccr |
public Optional<Object> getContextForToken(String key, String token) {
Object context | = validateTokenAndGetContext(key, token).second();
return null != context ? Optional.of(context) : Optional.absent();
} | csn_ccr |
function runSync(context, func, callback)
{
var result
, requiresContext = isArrowFunction(func)
;
try
{
if (requiresContext)
{
result = func.call(null, context);
}
else
{
result = func.call(context);
}
}
| catch (ex)
{
// pass error as error-first callback
callback(ex);
return;
}
// everything went well
callback(null, result);
} | csn_ccr |
Do its goddam job.
@param $os | public function work($os)
{
switch ($os) {
case 'linux':
$this->_fetchPciIdsLinux();
$this->_fetchUsbIdsLinux();
break;
case 'freebsd':
case 'dragonfly':
$this->_fetchPciIdsPciConf();
break;
... | csn |
public function rtrim($str, $charlist = null)
{
return | isset($charlist) ? rtrim($str, $charlist) : rtrim($str);
} | csn_ccr |
public function signXML($data)
{
$xml = new DOMDocument;
$xml->preserveWhiteSpace = false;
$xml->loadXML($data);
$sig = new DOMDocument;
$sig->preserveWhiteSpace = false;
$sig->loadXML(
'<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
... | $sig = $xml->importNode($sig->documentElement, true);
$xml->documentElement->appendChild($sig);
// calculate digest
$xpath = $this->getXPath($xml);
$digestValue = $xpath->query('ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestValue')->item(0);
$digestValue->nodeValue = $... | csn_ccr |
Init a new \Beluga\IO\FolderAccessError for folder write mode.
@param string $package
@param string $folder The folder where reading fails.
@param string $message The optional error message.
@param integer $code A optional error code (Defaults to \E_USER_ERROR)
@param \Throwable $previous A ... | public static function Write(
string $package, string $folder, string $message = null, int $code = \E_USER_ERROR, \Throwable $previous = null )
: FolderAccessError
{
return new FolderAccessError(
$package,
$folder,
static::ACCESS_WRITE,
$message,
$code,
... | csn |
Generate detach logic for calls.
<p>Calls are a little different due to a desire to minimize the cost of detaches. We assume
that if a given call site detaches once, it is more likely to detach multiple times. So we
generate code that looks like:
<pre>{@code
RenderResult initialResult = template.render(appendable, re... | Statement detachForCall(final Expression callRender) {
checkArgument(callRender.resultType().equals(RENDER_RESULT_TYPE));
final Label reattachRender = new Label();
final SaveRestoreState saveRestoreState = variables.saveRestoreState();
// We pass NULL statement for the restore logic since we handle that... | csn |
public static String SITInfo( EnumMap<SIT, EnumMap<CIT, Boolean>> shp ){
StringBuilder result = new StringBuilder();
for( SIT key: shp.keySet() ){
| result.append("\t"+key.toString()+":"+CITInfo( shp.get(key))+"\n");
}
return result.toString();
} | csn_ccr |
private boolean selectACollection()
{
if (!cfm.comparator.hasCollections())
return false;
for (ColumnDefinition def : selection.getColumns())
{
| if (def.type.isCollection() && def.type.isMultiCell())
return true;
}
return false;
} | csn_ccr |
Compares the state of the current object to that of the last fork,
returning the untagged responses that reflect any changes. A new copy
of the object is also returned, ready for the next command.
Args:
command: The command that was finished. | def fork(self, command: Command) \
-> Tuple['SelectedMailbox', Iterable[Response]]:
"""Compares the state of the current object to that of the last fork,
returning the untagged responses that reflect any changes. A new copy
of the object is also returned, ready for the next command.
... | csn |
Transform for calls to module members in code. | def transform_dot(self, node, results):
"""Transform for calls to module members in code."""
module_dot = results.get("bare_with_attr")
member = results.get("member")
new_name = None
if isinstance(member, list):
member = member[0]
for change in MAPPING[module_... | csn |
func (s *Sling) BodyProvider(body BodyProvider) *Sling {
if body == nil {
return s
}
s.bodyProvider = body
| ct := body.ContentType()
if ct != "" {
s.Set(contentType, ct)
}
return s
} | csn_ccr |
public function createForm()
{
$form = '
<form action="'.$this->_setEnvironment.'" method="post" id="'.$this->_setIdForm.'" name="'.$this->_setNameForm.'" >
<input type="hidden" name="Ds_MerchantParameters" value="'.$this->generateMerchantParameters().'"/>
<input ... | <input type="submit" name="'.$this->_setNameSubmit.'" id="'.$this->_setIdSubmit.'" value="'.$this->_setValueSubmit.'" '.($this->_setStyleSubmit != '' ? ' style="'.$this->_setStyleSubmit.'"' : '').' '.($this->_setClassSubmit != '' ? ' class="'.$this->_setClassSubmit.'"' : '').'>
</form>
';
... | csn_ccr |
Adding fields group with hostnames | protected function addgroup_hostnames(){
$this->registerGroup(BLang::_('ADMIN_CONFIG_GENERAL_HOSTNAMES'),'hostnames',array(
new BConfigFieldString(
'BHOSTNAME',
BLang::_('ADMIN_CONFIG_GENERAL_BHOSTNAME'),
'vidido.ua'),
new BConfigFieldString(
'BHOSTNAME_STATIC',
BLang::_('ADMIN_CONFIG_GENERA... | csn |
public R setFields(String... fields) {
if (fields.length == 1 && fields[0] == null){
mQueryMap.remove(QUERY_FIELDS);
return (R) this;
}
if (fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append(fields[0]);
| for (int i = 1; i < fields.length; ++i) {
sb.append(String.format(Locale.ENGLISH, ",%s", fields[i]));
}
mQueryMap.put(QUERY_FIELDS, sb.toString());
}
return (R) this;
} | csn_ccr |
Creates new aggregating maps.
@param map1
@param map2
@param <K>
@param <V>
@return | public static <K, V> Map<K, V> aggregate(Map<K, V> map1, Map<K, V> map2) {
return new AggregatingMap<K, V>(map1, map2);
} | csn |
Retrieve the next occurrence in the series.
@return {ICAL.Time} | function() {
var iter;
var ruleOfDay;
var next;
var compare;
var maxTries = 500;
var currentTry = 0;
while (true) {
if (currentTry++ > maxTries) {
throw new Error(
'max tries have occured, rule may be impossible to forfill.'
);
... | csn |
func (c *cacher) clear() {
c.lock.Lock()
defer c.lock.Unlock()
c.cache | = make(map[string]*futures.Future, 10)
} | csn_ccr |
Create a keyspace in Cassandra.
@param keyspace | public void createKeyspace(String keyspace) {
Map<String, String> replicationSimpleOneExtra = new HashMap<>();
replicationSimpleOneExtra.put("'class'", "'SimpleStrategy'");
replicationSimpleOneExtra.put("'replication_factor'", "1");
String query = this.cassandraqueryUtils.createKeyspaceQ... | csn |
handle an incoming mavlink packet from the master vehicle. Relay it to the tracker
if it is a GLOBAL_POSITION_INT | def mavlink_packet(self, m):
'''handle an incoming mavlink packet from the master vehicle. Relay it to the tracker
if it is a GLOBAL_POSITION_INT'''
if m.get_type() in ['GLOBAL_POSITION_INT', 'SCALED_PRESSURE']:
connection = self.find_connection()
if not connection:
... | csn |
public synchronized int getPartitionStoreCount() {
int count = 0;
for (String store : storeToPartitionIds.keySet()) {
count += | storeToPartitionIds.get(store).size();
}
return count;
} | csn_ccr |
def absolute_url(self):
"""Get the absolute url of ``self``.
Returns:
str: the absolute url.
| """
if self.is_root():
return utils.concat_urls(self.url)
return utils.concat_urls(self.parent.absolute_url, self.url) | csn_ccr |
protected function conditionalSet($key, $value)
{
if (!$this->has($key)) {
| $this->set($key, $value);
}
} | csn_ccr |
public function setLink($sLink)
{
$iLang = $this->getLanguage();
if (\OxidEsales\Eshop\Core\Registry::getUtils()->seoIsActive()) { |
$this->_aSeoUrls[$iLang] = $sLink;
} else {
$this->_aStdUrls[$iLang] = $sLink;
}
} | csn_ccr |
how to validate a regex in python3 | def is_valid_regex(string):
"""
Checks whether the re module can compile the given regular expression.
Parameters
----------
string: str
Returns
-------
boolean
"""
try:
re.compile(string)
is_valid = True
except re.error:
is_valid = False
return ... | cosqa |
def clean_tenant_url(url_string):
"""
Removes the TENANT_TOKEN from a particular string
"""
if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF'):
if (settings.PUBLIC_SCHEMA_URLCONF and
| url_string.startswith(settings.PUBLIC_SCHEMA_URLCONF)):
url_string = url_string[len(settings.PUBLIC_SCHEMA_URLCONF):]
return url_string | csn_ccr |
def _make_indices(self, Ns):
''' makes indices for cross validation '''
N_new = int(Ns * self.n_splits)
test = [np.full(N_new, False) for i in range(self.n_splits)]
for i in range(self.n_splits):
test[i][np.arange(Ns * i, Ns * (i + 1))] = True
train = [np.logical_not... | range(self.n_splits)]
test = [np.arange(N_new)[test[i]] for i in range(self.n_splits)]
train = [np.arange(N_new)[train[i]] for i in range(self.n_splits)]
cv = list(zip(train, test))
return cv | csn_ccr |
def copy_foreign_keys(self, event):
"""Copies possible foreign key values from the object into the Event,
skipping common keys like modified and created.
Args:
event (Event): The Event instance to copy the FKs into
obj (fleaker.db.Model): The object to pull the values fr... | it
# exists. If this conflicts with desired behavior, handle this in the
# respective callback. This does rely on the FK matching the lower case
# version of the class name and that the event isn't trying to delete
# the current record, becuase that ends badly.
possible_key = se... | csn_ccr |
This method sets the desired JPEG quality.
@param q the quality (between
{@link V4L4JConstants#MIN_JPEG_QUALITY} and
{@link V4L4JConstants#MAX_JPEG_QUALITY} inclusive)
@throws StateException if this
<code>FrameGrabber</code> has been already released, and therefore must
not be used anymore. | public void setJPGQuality(int q){
state.checkReleased();
if(q<V4L4JConstants.MIN_JPEG_QUALITY)
q =V4L4JConstants.MIN_JPEG_QUALITY;
if(q>V4L4JConstants.MAX_JPEG_QUALITY)
q = V4L4JConstants.MAX_JPEG_QUALITY;
setQuality(object, q);
quality = q;
} | csn |
Replies if the given object is locally assigned.
<p>An object is locally assigned when it is the left operand of an assignment operation.
@param target the object to test.
@param containerToFindUsage the container in which the usages should be find.
@return {@code true} if the given object is assigned.
@since 0.7 | protected boolean isLocallyAssigned(EObject target, EObject containerToFindUsage) {
if (this.readAndWriteTracking.isAssigned(target)) {
return true;
}
final Collection<Setting> usages = XbaseUsageCrossReferencer.find(target, containerToFindUsage);
// field are assigned when they are not used as the left oper... | csn |
public static IAtomContainerSet partitionIntoMolecules(IAtomContainer container) {
ConnectedComponents | cc = new ConnectedComponents(GraphUtil.toAdjList(container));
return partitionIntoMolecules(container, cc.components());
} | csn_ccr |
Removes serialVersionUID field. | @Override
public boolean visit(FieldDeclaration node) {
if (isSerializationField(node.getFragment(0).getVariableElement())) {
node.remove();
}
return false;
} | csn |
func List(root string, includePatterns []string, excludePatterns []string) ([]string, error) {
root = filepath.FromSlash(root)
newincludes, bases := baseDirs(root, includePatterns)
ret := []string{}
for _, b := range bases {
err := filepath.Walk(
b,
func(p string, fi os.FileInfo, err error) error {
if e... | only if it's explicitly excluded
if err != nil && !m {
return filepath.SkipDir
}
} else if cleanpath != "" {
ret = append(ret, cleanpath)
}
return nil
},
)
if err != nil {
return nil, err
}
}
return normPaths(root, ret)
} | csn_ccr |
func New(minValue, maxValue int64, sigfigs int) *Histogram {
if sigfigs < 1 || 5 < sigfigs {
panic(fmt.Errorf("sigfigs must be [1,5] (was %d)", sigfigs))
}
largestValueWithSingleUnitResolution := 2 * math.Pow10(sigfigs)
subBucketCountMagnitude := int32(math.Ceil(math.Log2(float64(largestValueWithSingleUnitResolu... | lowestTrackableValue: minValue,
highestTrackableValue: maxValue,
unitMagnitude: int64(unitMagnitude),
significantFigures: int64(sigfigs),
subBucketHalfCountMagnitude: subBucketHalfCountMagnitude,
subBucketHalfCount: subBucketHalfCount,
subBucketMask: ... | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.