query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
function customJaroWinkler(options, a, b) {
options = options || {};
const {
boostThreshold = 0.7,
scalingFactor = 0.1
} = options;
if (scalingFactor > 0.25)
throw Error('talisman/metrics/distance/jaro-winkler: the scaling factor should not exceed 0.25.');
if (boostThreshold < 0 || boostThresho... | const dj = jaro(a, b);
if (dj < boostThreshold)
return dj;
const p = scalingFactor;
let l = 0;
const prefixLimit = Math.min(a.length, b.length, 4);
// Common prefix (up to 4 characters)
for (let i = 0; i < prefixLimit; i++) {
if (a[i] === b[i])
l++;
else
break;
}
return d... | csn_ccr |
// Returns the inspect container response, the sandbox metadata, and network namespace mode | func (ds *dockerService) getPodSandboxDetails(podSandboxID string) (*dockertypes.ContainerJSON, *runtimeapi.PodSandboxMetadata, error) {
resp, err := ds.client.InspectContainer(podSandboxID)
if err != nil {
return nil, nil, err
}
metadata, err := parseSandboxName(resp.Name)
if err != nil {
return nil, nil, er... | csn |
func SetAppInfo(info *AppInfo) {
if info != nil && info.Name == "" {
panic(fmt.Errorf("App info name cannot be empty"))
}
appInfo = info
// This is run in init, but | we need to reinitialize it now that we have
// some app info.
initUserAgent()
} | csn_ccr |
// Deserialize decodes a block header from r into the receiver using a format
// that is suitable for long-term storage such as a database while respecting
// the Version field. | func (h *BlockHeader) Deserialize(r io.Reader) error {
// At the current time, there is no difference between the wire encoding
// at protocol version 0 and the stable long-term storage format. As
// a result, make use of readBlockHeader.
return readBlockHeader(r, 0, h)
} | csn |
Handle LTI requests of type `content-item`
@return void | public function onContentItem()
{
$this->initSession();
/* blindly copied from Vickers' Rating demo app */
$_SESSION[__CLASS__] = [
'consumer_key' => $this->consumer->getKey(),
'resource_id' => getGuid(),
'resource_id_created' => false,
'user_c... | csn |
// DeriveAvailabilityZones mocks base method | func (m *MockZonedEnviron) DeriveAvailabilityZones(arg0 context.ProviderCallContext, arg1 environs.StartInstanceParams) ([]string, error) {
ret := m.ctrl.Call(m, "DeriveAvailabilityZones", arg0, arg1)
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
} | csn |
public void setIncludeRoot(File includeroot) {
this.includeroot = includeroot;
if (!includeroot.exists()) {
throw new BuildException("includeroot doesn't exist: "
+ includeroot);
}
| if (!includeroot.isDirectory()) {
throw new BuildException("includeroot must be a directory: "
+ includeroot);
}
} | csn_ccr |
Updates the background and segments it at the same time. In some implementations this can be
significantly faster than doing it with separate function calls. Segmentation is performed using the model
which it has prior to the update. | public void updateBackground( T frame , GrayU8 segment ) {
updateBackground(frame);
segment(frame,segment);
} | csn |
Return all docopt lines for the 'Usage' section | def docopt_usage
doc = ["\nUsage:"];
@actions.each do |_name, action|
doc << " run #{action.usage}" unless action.usage == false
end
basic_flags = @version ? "(-h|--help|--version)" : "(-h|--help)"
if @superspace
doc << " run #{@superspace} #{basic_flags}\n"
else
... | csn |
Processing a collection's data
@param Closure $callback callback
@return Collection | public function walk(Closure $callback) {
foreach($this->_data as &$data) {
$data = $callback($data);
}
unset($data);
return $this;
} | csn |
def _render_relationships(self, resource):
"""Render the resource's relationships."""
relationships = {}
related_models = resource.__mapper__.relationships.keys()
primary_key_val = getattr(resource, self.primary_key)
if self.dasherize:
mapped_relationships = {
... | 'self': '/{}/{}/relationships/{}'.format(
resource.__tablename__,
primary_key_val,
mapped_relationships[model]),
'related': '/{}/{}/{}'.format(
resource.__tablename__,
primary_key... | csn_ccr |
Start gRPC server. | @Override
protected void startUp() throws Exception {
long traceId = LoggerHelpers.traceEnterWithContext(log, this.objectId, "startUp");
try {
log.info("Starting gRPC server listening on port: {}", this.config.getPort());
this.server.start();
} finally {
L... | csn |
private function guessTrackClass(string $uri): string
{
$classes = [
Spotify::class,
Google::class,
GoogleUnlimited::class,
Deezer::class,
Stream::class,
];
| foreach ($classes as $class) {
if (substr($uri, 0, strlen($class::PREFIX)) === $class::PREFIX) {
return $class;
}
}
return Track::class;
} | csn_ccr |
func (t *T) ExpectErrorMessage(err error, msg string, desc ...string) {
prefix := ""
if len(desc) > 0 {
prefix = strings.Join(desc, " ") + ": "
}
if err == nil {
| t.Fatalf("%sExpected error was not returned.", prefix)
} else if !strings.Contains(err.Error(), msg) {
t.Fatalf("%sError message didn't contain the expected message:\n"+
"Error message=%s\nExpected string=%s", prefix, err.Error(), msg)
}
} | csn_ccr |
function AbstractAdapter(valueOrBuffer, pos) {
this.pos = pos != null ? pos : 0;
this.data = null;
if (Buffer.isBuffer(valueOrBuffer)) {
this.value | = this.getValue(valueOrBuffer);
} else {
this.loadData(valueOrBuffer);
}
} | csn_ccr |
public static void read(Swagger swagger, Set<Class<?>> classes) {
final SwaggerAnnotationsReader reader = new SwaggerAnnotationsReader(swagger);
for (Class<?> cls : classes) {
final ReaderContext | context = new ReaderContext(swagger, cls, "", null, false, new ArrayList<>(),
new ArrayList<>(), new ArrayList<>(), new ArrayList<>());
reader.read(context);
}
} | csn_ccr |
public function flush($max = 10, $options = [])
{
$defaults = [
'selectTimeout' => 1.0
];
$options += $defaults;
do {
$this->select($options['selectTimeout']);
$this->process($max);
| } while ($this->_running > 0);
$results = $this->_results;
$this->_results = [];
return $results;
} | csn_ccr |
def print_param_defaults(self_):
"""Print the default values of all cls's Parameters."""
cls = self_.cls
for key,val in cls.__dict__.items():
| if isinstance(val,Parameter):
print(cls.__name__+'.'+key+ '='+ repr(val.default)) | csn_ccr |
def _tolog(self,level):
""" log with different level """
def wrapper(msg):
if self.log_colors:
color = self.log_colors[level.upper()]
getattr(self.logger, level.lower())(coloring("- | {}".format(msg), color))
else:
getattr(self.logger, level.lower())(msg)
return wrapper | csn_ccr |
Computes the output for the table structure array
@return string | protected function renderDataTable()
{
$html = "<table " . ($this->tableId ? "id=\"{$this->tableId}\" " : "") . "border=\"1\">\n<thead>\n\t<tr>\n";
foreach ($this->allColumns as $name => $toDisplay) {
if ($toDisplay !== false) {
if ($name === 0) {
$na... | csn |
def sim_combi(self):
""" Simulate data to model combi regulation.
"""
n_samples = 500
sigma_glob = 1.8
X = np.zeros((n_samples,3))
X[:,0] = np.random.uniform(-sigma_glob,sigma_glob,n_samples)
X[:,1] = np.random.uniform(-sigma_glob,sigma_glob,n_samples)
... | # XOR type
# X[:,2] = (func(X[:,0])*sp.stats.norm.pdf(X[:,1],0,0.2)
# + func(X[:,1])*sp.stats.norm.pdf(X[:,0],0,0.2))
# AND type / diagonal
# X[:,2] = (func(X[:,0]+X[:,1])*sp.stats.norm.pdf(X[:,1]-X[:,0],0,0.2))
# AND type / horizontal
X[:,2] = (func(X[:,0... | csn_ccr |
import tensorflow as tf
from d2l import tensorflow as d2l
def batch_norm(X, gamma, beta, moving_mean, moving_var, eps):
inv = tf.cast(tf.math.rsqrt(moving_var + eps), X.dtype)
inv *= gamma
Y = X * inv + (beta - moving_mean * inv)
return Y
class BatchNorm(tf.keras.layers.Layer):
def __init__(self, **... | import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import paddle
import paddle.nn as nn
def batch_norm(X, gamma, beta, moving_mean, moving_var, eps, momentum, is_training=True):
if not is_training:
X_hat = (X - moving_mean) / (moving_var + eps) ** 0.5
else:
assert le... | codetrans_dl |
def iiif_info_handler(prefix=None, identifier=None,
config=None, klass=None, auth=None, **args):
"""Handler for IIIF Image Information requests."""
if (not auth or degraded_request(identifier) or auth.info_authz()):
# go ahead with request as made
if (auth):
log... | # authn but not authz -> 401
abort(401)
else:
# redirect to degraded
response = redirect(host_port_prefix(
config.host, config.port, prefix) + '/' + identifier + '-deg/info.json')
response.headers['Access-control-allow-origin'] = '*'
return response | csn_ccr |
def run_sim(morphology='patdemo/cells/j4a.hoc',
cell_rotation=dict(x=4.99, y=-4.33, z=3.14),
closest_idx=dict(x=-200., y=0., z=800.)):
'''set up simple cell simulation with LFPs in the plane'''
# Create cell
cell = LFPy.Cell(morphology=morphology, **cell_parameters)
# Align cell... | 'tau' : 0.5, # synaptic time constant
'weight' : 0.0878, # synaptic weight
'record_current' : True, # record synapse current
}
# Create synapse and set time of synaptic input
synapse = LFPy.Synapse(cell, **synapse_parameters)
synapse.set_spike_time... | csn_ccr |
Set the parameters, using groups
@param array $parameters name => value of parameters | public function set(array $parameters)
{
foreach ($parameters as $name => $value)
{
$this->group_for_name($name)->set($name, $value);
}
return $this;
} | csn |
def get_all_parts(self, max_parts=None, part_number_marker=None):
"""
Return the uploaded parts of this MultiPart Upload. This is
a lower-level method that requires you to manually page through
results. To simplify this process, you can just use the
object itself as an iterator... | response = self.bucket.connection.make_request('GET', self.bucket.name,
self.key_name,
query_args=query_args)
body = response.read()
if response.status == 200:
h = handler.XmlHand... | csn_ccr |
Set if payment slip has a bank specified
Resets the bank data when disabling.
@param bool $withBank True for yes, false for no
@return $this The current instance for a fluent interface. | public function setWithBank($withBank = true)
{
$this->isBool($withBank, 'withBank');
$this->withBank = $withBank;
if ($withBank === false) {
$this->bankName = '';
$this->bankCity = '';
}
return $this;
} | csn |
Find assignment by name.
@param $name
@return null | protected function findAssignmentByName($name)
{
$assignmentFound = collect($this->assignments)->filter(function ($assignment) use ($name) {
return $assignment->name == $name;
})->first();
if ($assignmentFound) return $assignmentFound;
return null;
} | csn |
function trimWhitespace(line) {
let whitespaceIndicies = [];
let allWhitespace = true;
let seenAnyTag = false;
let newLine = new Array(line.length);
for (let i = 0; i < line.length; i++) {
let obj = line[i];
newLine[i] = obj;
if (typeof obj === 'string') {
if (!nonWhitespace.test(obj)) {
... | line consists of:
// - only whitespace text
// - no Interpolators or Unescaped Interpolators
// - at least one Mustache tag
if (allWhitespace && seenAnyTag) {
for (let i = 0; i < whitespaceIndicies.length; i++) {
let index = whitespaceIndicies[i];
let obj = newLine[index];
newLine[inde... | csn_ccr |
def get_properties(self):
"""
Add property to variables in XMLBIF
Return
------
dict: dict of type {variable: property tag}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_property()
{'light-on': <Element PROPERTY at 0x7... |
for var in sorted(variables):
properties = self.model.node[var]
property_tag[var] = etree.SubElement(self.variables[var], "PROPERTY")
for prop, val in properties.items():
property_tag[var].text = str(prop) + " = " + str(val)
return property_tag | csn_ccr |
function(keyDownFn, keyUpFn) {
var g_keyState = {};
var g_oldKeyState = {};
var updateKey = function(keyCode, state) {
g_keyState[keyCode] = state;
if (g_oldKeyState !== g_keyState) {
g_oldKeyState = state;
if (state) {
keyDownFn(keyCode);
} else {
ke... |
};
var keyDown = function(event) {
updateKey(event.keyCode, true);
};
window.addEventListener("keyup", keyUp, false);
window.addEventListener("keydown", keyDown, false);
} | csn_ccr |
// SetJSONMappingParameters sets the JSONMappingParameters field's value. | func (s *MappingParameters) SetJSONMappingParameters(v *JSONMappingParameters) *MappingParameters {
s.JSONMappingParameters = v
return s
} | csn |
public function set($name, $value = null)
{
if (is_string($name)) {
$name = $this->cleanAttributeName($name);
if ($value === null && isset($this->props[$name])) {
unset($this->props[$name]);
} elseif | ($value !== null) {
$this->props[$name] = $value;
}
}
return $this;
} | csn_ccr |
Copy remote file to local hardrive
@param {string} url url of the remote file
@param {string} dest destination where to copy file
@param {Function} cb callback when file is copied
@return {void} | function(url, dest, cb) {
var get = request(url);
get.on('response', function (res) {
res.pipe(fs.createWriteStream(dest));
res.on('end', function () {
cb();
});
res.on('error', function (err) {
cb(err);
});
});
} | csn |
Request succeeded, process the reply
@param binding: The binding to be used to process the reply.
@type binding: L{bindings.binding.Binding}
@param reply: The raw reply text.
@type reply: str
@return: The method result.
@rtype: I{builtin}, L{Object}
@raise WebFaul... | def succeeded(self, binding, reply):
"""
Request succeeded, process the reply
@param binding: The binding to be used to process the reply.
@type binding: L{bindings.binding.Binding}
@param reply: The raw reply text.
@type reply: str
@return: The method result.
... | csn |
func IsLAN(ip net.IP) bool {
if ip.IsLoopback() {
return true
}
if v4 := ip.To4(); v4 != | nil {
return lan4.Contains(v4)
}
return lan6.Contains(ip)
} | csn_ccr |
Return an array with key weight pairs
@return array | public function getKeyValuesByWeight()
{
if(empty($this->keysByWeight)) {
$weightPerToken = $this->getWeightPerToken();
//make a copy of the array
$keyValuesByWeight = $this->keyValues;
array_walk($keyValuesByWeight, function(&$value, $key, $weightPerToken) {
... | csn |
protected function addButton($builder, $name, $config)
{
$options = isset($config['options']) ? $config['options'] : [];
if (!in_array($config['type'], $this->allowedTypes)) {
throw new \LogicException(sprintf(
'Allowed button types : | "%s", given "%s".',
implode('", "', $this->allowedTypes),
$config['type']
));
}
return $builder->add($name, $config['type'], $options);
} | csn_ccr |
Helper method for creating new traversals. | public static <NODE, EDGE> FixedPointGraphTraversal<NODE, EDGE> newTraversal(
EdgeCallback<NODE, EDGE> callback) {
return new FixedPointGraphTraversal<>(callback);
} | csn |
// createMux initializes the main router the server uses. | func (s *Server) createMux() *mux.Router {
m := mux.NewRouter()
logrus.Debug("Registering routers")
for _, apiRouter := range s.routers {
for _, r := range apiRouter.Routes() {
f := s.makeHTTPHandler(r.Handler())
logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
m.Path(versionMatcher + r.Path())... | csn |
Create the tag that matches current regexp
@param string $tagName
@param string $template
@return Tag | protected function createTag($tagName, $template)
{
$tag = new Tag;
foreach ($this->captures as $key => $capture)
{
if (!isset($capture['name']))
{
continue;
}
$attrName = $capture['name'];
if (isset($tag->attributes[$attrName]))
{
continue;
}
$this->addAttribute($tag, $attrName... | csn |
Binds the RTP and RTCP components to a suitable address and port.
@param isLocal
Whether the binding address is in local range.
@param rtcpMux
Whether RTCP multiplexing is supported.<br>
If so, both RTP and RTCP components will be merged into one
channel only. Otherwise, the RTCP component will be bound to
the odd por... | public void bind(boolean isLocal, boolean rtcpMux) throws IOException, IllegalStateException {
this.rtpChannel.bind(isLocal, rtcpMux);
if(!rtcpMux) {
this.rtcpChannel.bind(isLocal, this.rtpChannel.getLocalPort() + 1);
}
this.rtcpMux = rtcpMux;
if(logger.isDebugEnabled()) {
logger.debug(this.mediaType... | csn |
def inspect_file(self, commit, path):
"""
Returns info about a specific file.
Params:
* commit: A tuple, string, or Commit object representing the commit. |
* path: Path to file.
"""
req = proto.InspectFileRequest(file=proto.File(commit=commit_from(commit), path=path))
res = self.stub.InspectFile(req, metadata=self.metadata)
return res | csn_ccr |
@Override
public DataSet vectorize(InputStream is, String label) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = "";
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {... | builder.append(line);
}
return vectorize(builder.toString(), label);
} catch (Exception e) {
throw new RuntimeException(e);
}
} | csn_ccr |
// CreateUserAndRole creates user and role and assignes role to a user, used in tests | func CreateUserAndRole(clt clt, username string, allowedLogins []string) (services.User, services.Role, error) {
user, err := services.NewUser(username)
if err != nil {
return nil, nil, trace.Wrap(err)
}
role := services.RoleForUser(user)
role.SetLogins(services.Allow, []string{user.GetName()})
err = clt.Upsert... | csn |
Saves the layout as a property value using the specified identifier.
@param layoutId Layout identifier
@return True if operation succeeded. | public boolean saveToProperty(LayoutIdentifier layoutId) {
setName(layoutId.name);
try {
LayoutUtil.saveLayout(layoutId, toString());
} catch (Exception e) {
log.error("Error saving application layout.", e);
return false;
}
return true;
} | csn |
public function autoload($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
| $className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, dirname(__FILE__). DIRECTORY_SEPARATOR . $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
if(file_exists($fileName))
req... | csn_ccr |
public void setSettings(DatePickerSettings datePickerSettings) {
// If no settings were supplied, then create a default settings instance.
if (datePickerSettings == null) {
datePickerSettings = new DatePickerSettings();
}
// Save the settings.
this.settings = datePick... | }
// Apply the border properties settings.
// This is applied regardless of whether the calendar panel was created by a date picker,
// or as an independent calendar panel.
zApplyBorderPropertiesList();
// Set the label indicators to their default states.
zSetAllLabe... | csn_ccr |
public void setGroupCertificateAuthorities(java.util.Collection<GroupCertificateAuthorityProperties> groupCertificateAuthorities) {
if (groupCertificateAuthorities == null) {
this.groupCertificateAuthorities = null;
return;
| }
this.groupCertificateAuthorities = new java.util.ArrayList<GroupCertificateAuthorityProperties>(groupCertificateAuthorities);
} | csn_ccr |
The wrapper around a job that will be executed in the thread pool.
It is especially in charge of logging, changing the job status
and checking for the next job to be executed.
@param jobToRun the job to execute | private void runJob(Job jobToRun) {
long startExecutionTime = timeProvider.currentTime();
long timeBeforeNextExecution = jobToRun.nextExecutionTimeInMillis() - startExecutionTime;
if(timeBeforeNextExecution < 0) {
logger.debug("Job '{}' execution is {}ms late", jobToRun.name(), -timeBeforeNextExecution);
}
... | csn |
def getrange(self):
"""Retrieve the dataset min and max values.
Args::
no argument
Returns::
(min, max) tuple (attribute 'valid_range')
Note that those are the values as stored
by the 'setrange' method. 'getrange' does *NOT* compute the
min ... | _array_to_str
elif data_type in [SDC.UCHAR8, SDC.UINT8]:
buf1 = _C.array_byte(n_values)
buf2 = _C.array_byte(n_values)
elif data_type == SDC.INT8:
buf1 = _C.array_int8(n_values)
buf2 = _C.array_int8(n_values)
elif data_type == SDC.INT16:
... | csn_ccr |
def readpipe(self, chunk=None):
""" Return iterator that iterates over STDIN line by line
If ``chunk`` is set to a positive non-zero integer value, then the
reads are performed in chunks of that many lines, and returned as a
list. Otherwise the lines are returned one by one.
"""... | if read:
yield read
return
return
if not chunk:
yield l
else:
read.append(l)
if len(read) == chunk:
yield read | csn_ccr |
Special HTML encoding check. | def header_check(self, content):
"""Special HTML encoding check."""
encode = None
# Look for meta charset
m = RE_HTML_ENCODE.search(content)
if m:
enc = m.group(1).decode('ascii')
try:
codecs.getencoder(enc)
encode = enc
... | csn |
Implements hook "user.role.permissions"
@param array $permissions | public function hookUserRolePermissions(array &$permissions)
{
$permissions['module_file_manager'] = gplcart_text('File manager: access');
foreach ($this->getHandlers() as $command_id => $command) {
$permissions["module_file_manager_$command_id"] = gplcart_text('File manager: perform co... | csn |
def key_exists(key_id, region=None, key=None, keyid=None, profile=None):
'''
Check for the existence of a key.
CLI example::
salt myminion boto_kms.key_exists 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key = conn.de... | to context cache
r['result'] = True
except boto.exception.BotoServerError as e:
if isinstance(e, boto.kms.exceptions.NotFoundException):
r['result'] = False
return r
r['error'] = __utils__['boto.get_error'](e)
return r | csn_ccr |
Attempt to ascertain the gzip status of a file based on the "magic signatures" of the file.
This was taken from the stack overflow post
http://stackoverflow.com/questions/13044562/python-mechanism-to-identify-compressed-file-type\
-and-uncompress
:param str filename: A path to a file
:return: ... | def is_gzipfile(filename):
"""
Attempt to ascertain the gzip status of a file based on the "magic signatures" of the file.
This was taken from the stack overflow post
http://stackoverflow.com/questions/13044562/python-mechanism-to-identify-compressed-file-type\
-and-uncompress
:param str f... | csn |
Return a new |Selection| object with the given name and copies
of the handles |Nodes| and |Elements| objects based on method
|Devices.copy|. | def copy(self, name: str) -> 'Selection':
"""Return a new |Selection| object with the given name and copies
of the handles |Nodes| and |Elements| objects based on method
|Devices.copy|."""
return type(self)(name, copy.copy(self.nodes), copy.copy(self.elements)) | csn |
Get an onion layer function.
This function will get the object from a previous layer and pass it inwards
@param LayerInterface $nextLayer
@param LayerInterface $layer
@return Closure | private function createLayer($nextLayer, $layer)
{
return function($object) use($nextLayer, $layer){
return $layer->peel($object, $nextLayer);
};
} | csn |
Determines if a specified certificate type indicates a GSI-3 proxy
certificate.
@param certType the certificate type to check.
@return true if certType is a GSI-3 proxy, false otherwise. | public static boolean isGsi3Proxy(GSIConstants.CertificateType certType) {
return certType == GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY
|| certType == GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY
|| certType == GSIConstants.CertificateType.GSI_3_RESTRICTED_PR... | csn |
WebSocket to execute command | function (command, id) {
id = id || '';
if (id) {
this.queue.push(id);
}
SocketService.emit('execute', {
command: command,
id: id
});
} | csn |
protected function isCallable($arg, $method = null)
{
if (is_callable($arg) | || is_callable([$arg, $method]) || $this->isClass($arg)) {
return true;
}
return false;
} | csn_ccr |
Encrypts audio data using RbNaCl
@param header [String] The header of the packet, to be used as the nonce
@param buf [String] The encoded audio data to be encrypted
@return [String] the audio data, encrypted | def encrypt_audio(header, buf)
raise 'No secret key found, despite encryption being enabled!' unless @secret_key
box = RbNaCl::SecretBox.new(@secret_key)
# The nonce is the header of the voice packet with 12 null bytes appended
nonce = header + ([0] * 12).pack('C*')
box.encrypt(nonce, b... | csn |
def del_row(self, row_index):
"""Delete a row to the table
Arguments:
row_index - The index of the row you want to delete. Indexing | starts at 0."""
if row_index > len(self._rows)-1:
raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
del self._rows[row_index] | csn_ccr |
Returns the value of an option as an integer, or -1 if not defined. | public static int
intValue(String option) {
String s = value(option);
if (s != null) {
try {
int val = Integer.parseInt(s);
if (val > 0)
return (val);
}
catch (NumberFormatException e) {
}
}
return (-1);
} | csn |
func (r *Reader) ReadAll() (records [][]string, err error) {
for {
record, err := r.Read()
if err == io.EOF {
return records, nil
}
| if err != nil {
return nil, err
}
records = append(records, record)
}
} | csn_ccr |
protected function prepareContainer(Container $container)
{
foreach ($this->getKernelParameters() as $key => $value) {
$container[$key] = $value;
}
$container->set('kernel', $this);
$container->set('configuration', $this->configuration);
| $container->set('request', $this->request);
$container->set('request_stack', $this->requestStack);
$container->set('session', $this->session);
} | csn_ccr |
Calculates area of a polygon. Ported from d3.js
@param poly Object
@returns {number} square units inside the polygon | function area(poly) {
var i = -1,
n = poly.length,
a,
b = poly[n - 1],
area = 0;
while (++i < n) {
a = b;
b = poly[i];
area += a.y * b.x - a.x * b.y;
}
return Math.abs(area * 0.5);
} | csn |
private void closeCursor() {
if (mCursor != null) {
int count = mCursor.getCount();
mCursor.close();
mCursor = null;
| notifyItemRangeRemoved(0, count);
}
updateCursorObserver();
} | csn_ccr |
Detect the group from the content type using cURL.
@return null|string | protected function detectGroupFromContentType()
{
if (extension_loaded('curl'))
{
$this->getLogger()->warning('Attempting to determine asset group using cURL. This may have a considerable effect on application speed.');
$handler = curl_init($this->absolutePath);
... | csn |
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
... | def gte(name, value):
'''
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func:... | csn |
see if a msg is from our primary vehicle | def is_primary_vehicle(self, msg):
'''see if a msg is from our primary vehicle'''
sysid = msg.get_srcSystem()
if self.target_system == 0 or self.target_system == sysid:
return True
return False | csn |
Save the abbreviations into a file.
@param fileName The file name.
@throws FileNotFoundException
@throws UnsupportedEncodingException | public void save(String fileName)
throws FileNotFoundException, UnsupportedEncodingException {
try (PrintWriter writer = new PrintWriter(fileName, "UTF-8")) {
for (Map.Entry<String, Integer> entry : data.entrySet()) {
writer.println(String.format("%d;%s", entry.getValue(), entry.getKey()));
... | csn |
Get "NEXT PROFILE" link in the navigation bar.
@return a content tree for the next link | public Content getNavLinkNext() {
Content li;
if (nextProfile == null) {
li = HtmlTree.LI(nextprofileLabel);
} else {
li = HtmlTree.LI(getHyperLink(pathToRoot.resolve(DocPaths.profileSummary(
nextProfile.name)), nextprofileLabel, "", ""));
}
... | csn |
public function now($type = 'datetime')
{
if ($type === 'datetime') {
return $this->_build('NOW')->setReturnType('datetime');
}
if ($type === 'date') {
return $this->_build('CURRENT_DATE')->setReturnType('date');
} |
if ($type === 'time') {
return $this->_build('CURRENT_TIME')->setReturnType('time');
}
} | csn_ccr |
python validate email regular expression | def is_valid_email(email):
"""
Check if email is valid
"""
pattern = re.compile(r'[\w\.-]+@[\w\.-]+[.]\w+')
return bool(pattern.match(email)) | cosqa |
func (r Range) IsEmpty() bool {
if r.Start == nil || r.End == nil {
return | false
}
return !r.Start.Less(r.End)
} | csn_ccr |
def add_z(bookings)
data3 = '0256'
data3 += 'Z'
sum = 0
bookings.each do |b|
sum += b.value.divmod(100)[0]
end
data3 += '%015i' % sum
data3 += '%015i' % bookings.count
data3 += '%0221s' | % ''
raise "DTAUS: Längenfehler Z (#{data3.size} <> 256)\n" if data3.size != 256
dta_string << data3
end | csn_ccr |
Add a SKIP clause
@see http://neo4j.com/docs/stable/query-skip.html#skip-skip-first-from-expression
@param string $cypher Of type string as it may contain operations
@return self | public function skip(string $cypher): self
{
$query = new self;
$query->clauses = $this->clauses->add(
new Clause\SkipClause($cypher)
);
return $query;
} | csn |
Return a pandas DataFrame with the DataFrame data. | def toPandas(self):
"""
Return a pandas DataFrame with the DataFrame data.
"""
assert pd is not None
nindices = self.getNumIndices()
headers = self.getHeaders()
columns = {
header: list(self.getColumn(header))
for header in headers[nindices... | csn |
def load_config(cls, opts, path=None, profile=None):
"""Load a configuration file into an options object."""
if path and os.path.exists(path):
if os.path.isdir(path):
cls.config_searchpath.insert(0, path)
else:
cls.config_files.insert(0, path)
... | config = cls.read_config()
values = config.get("default", {})
cls._load_values_into_opts(opts, values)
if profile and profile != "default":
values = config.get("profile:%s" % profile, {})
cls._load_values_into_opts(opts, values)
return values | csn_ccr |
Add a client to the pool.
@param ClientInterface|HttpAsyncClient|HttpClientPoolItem $client | public function addHttpClient($client): void
{
if (!$client instanceof HttpClientPoolItem) {
$client = new HttpClientPoolItem($client);
}
$this->clientPool[] = $client;
} | csn |
def _fetch_router_info(self, router_ids=None, device_ids=None,
all_routers=False):
"""Fetch router dict from the routing plugin.
:param router_ids: List of router_ids of routers to fetch
:param device_ids: List of device_ids whose routers to fetch
:param all_r... | 'inoperable',
self.sync_routers_chunk_size)
raise
except oslo_messaging.MessagingException:
LOG.exception("RPC Error in fetching routers from plugin")
self.fullsync = True
raise n_exc.AbortSyncRouters()
... | csn_ccr |
Reduce the cyclomatic complexity of parse
Process quantification char
@param {String} char
@return {Number}
@private | function (char) {
var
parsedItem = this._lastItem();
if ("*" === char) {
parsedItem._min = 0;
parsedItem._max = 0;
} else if ("+" === char) {
parsedItem._max = 0;
} else if ("?... | csn |
def get_instance(self, payload):
"""
Build an instance of TranscriptionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance
| :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance
"""
return TranscriptionInstance(
self._version,
payload,
account_sid=self._solution['account_sid'],
recording_sid=self._solution['recording_sid'],
) | csn_ccr |
python turn self into list | def as_list(self):
"""Return all child objects in nested lists of strings."""
return [self.name, self.value, [x.as_list for x in self.children]] | cosqa |
def translate_text(
self,
contents,
target_language_code,
mime_type=None,
source_language_code=None,
parent=None,
model=None,
glossary_config=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAU... | message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amo... | csn_ccr |
def _set_query_data_fast_2(self, page):
"""
set less expensive action=query response data PART 2
"""
self.data['pageid'] = page.get('pageid')
redirects = page.get('redirects')
if redirects:
self.data['redirects'] = redirects
terms = page.get('terms')... | None)
if terms.get('label'):
self.data['label'] = next(iter(terms['label']), None)
title = page.get('title')
self.data['title'] = title
if not self.params.get('title'):
self.params['title'] = title
watchers = page.get('watchers')
... | csn_ccr |
// parseFramerErr takes an error and returns an error. The error will
// potentially change if it was caused by the connection being closed. | func parseFramerErr(err error) error {
if err == nil {
return nil
}
errMsg := err.Error()
if strings.Contains(errMsg, io.ErrClosedPipe.Error()) {
// The pipe check is for tests
return syscall.EPIPE
}
// The connection was closed by our peer
if strings.Contains(errMsg, syscall.EPIPE.Error()) || strings.C... | csn |
Adds or updates a header file if neccessary.
@param string $header_name Original name of header.
@param string $content
@param string $subdir | public function AddHeader($header_name, &$content, $subdir="includes")
{
if($subdir)
{
$subdir = trim($subdir, "\\/") . "/";
if(!file_exists($this->output_path . $subdir))
\Peg\Lib\Utilities\FileSystem::MakeDir(
$this->output_p... | csn |
private function getConnectionType(array $config)
{
$isGrpcExtensionLoaded = $this->isGrpcLoaded();
$defaultTransport = $isGrpcExtensionLoaded ? 'grpc' : 'rest';
$transport = isset($config['transport'])
? strtolower($config['transport'])
: $defaultTransport;
... | 'gRPC support has been requested but required dependencies ' .
'have not been found. ' . $this->getGrpcInstallationMessage()
);
}
}
return $transport;
} | csn_ccr |
Prepares the list of items for displaying. | public function prepare_items() {
// Define Columns
$columns = $this->get_columns();
$hidden = [];
$sortable = $this->get_sortable_columns();
$this->_column_headers = [ $columns, $hidden, $sortable ];
// Data
$data = $this->getLatestExports();
// Pagination
$per_page = $this->get_items_per_page( 'p... | csn |
Indices of sentences when enumerating data set from batches.
Useful when retrieving the correct order of sentences
Returns
-------
list
List of ids ranging from 0 to #sent -1 | def idx_sequence(self):
"""Indices of sentences when enumerating data set from batches.
Useful when retrieving the correct order of sentences
Returns
-------
list
List of ids ranging from 0 to #sent -1
"""
return [x[1] for x in sorted(zip(self._record... | csn |
Given the current exchange rate between the USD and the EUR is 1.1363636 write a function that will accept the Curency type to be returned and a list of the amounts that need to be converted.
Don't forget this is a currency so the result will need to be rounded to the second decimal.
'USD' Return format should be `'... | def solution(to,lst):
dolSym, eurSym, power = ('', '€', -1) if to=='EUR' else ('$','', 1)
return [f"{ dolSym }{ v*1.1363636**power :,.2f}{ eurSym }" for v in lst] | apps |
Scans for a JCAssign node with a LHS matching a given
symbol, and returns its RHS. Does not scan nested JCAnnotations. | private JCExpression scanForAssign(final MethodSymbol sym,
final JCTree tree) {
class TS extends TreeScanner {
JCExpression result = null;
public void scan(JCTree t) {
if (t != null && result == null)
t.accept(thi... | csn |
# Task
Yesterday you found some shoes in your room. Each shoe is described by two values:
```
type indicates if it's a left or a right shoe;
size is the size of the shoe.
```
Your task is to check whether it is possible to pair the shoes you found in such a way that each pair consists of a right and a left shoe of an... | def pair_of_shoes(a):
return sorted(s for lr, s in a if lr == 1) == sorted(s for lr, s in a if lr == 0) | apps |
function () {
if (this._enableIEpolling) {
this._hashPollCallback = ariaCoreTimer.addCallback({
fn : this._hashPoll,
scope : this,
delay : this.ie7PollDelay
});
var documentHash = this.getHashString(... | this._currentHashString = iframeHash;
this.setHash(iframeHash);
this._internalCallback();
} else if (documentHash != this._currentHashString) {// no back or forward
this._addIframeHistoryEntry(documentHash);
thi... | csn_ccr |
func (c *CMSketch) MergeCMSketch(rc *CMSketch) error {
if c.depth != rc.depth || c.width != rc.width {
return errors.New("Dimensions of Count-Min Sketch should be the same")
}
if c.topN != nil || rc.topN != nil {
return errors.New("CMSketch with | Top-N does not support merge")
}
c.count += rc.count
for i := range c.table {
for j := range c.table[i] {
c.table[i][j] += rc.table[i][j]
}
}
return nil
} | csn_ccr |
def render_css(self, fn=None, text=None, margin='', indent='\t'):
"""output css using the Sass processor"""
fn = fn or os.path.splitext(self.fn)[0]+'.css'
if not os.path.exists(os.path.dirname(fn)):
os.makedirs(os.path.dirname(fn))
curdir = os.path.abspath(os.curdir)
... | # needed in order for scss to relative @import
text = text or self.render_styles()
if text != '': text = sass.compile(string=text)
os.chdir(curdir)
return CSS(fn=fn, text=text) | csn_ccr |
Consider a pyramid made up of blocks. Each layer of the pyramid is a rectangle of blocks, and the dimensions of these rectangles increment as you descend the pyramid. So, if a layer is a `3x6` rectangle of blocks, then the next layer will be a `4x7` rectangle of blocks. A `1x10` layer will be on top of a `2x11` layer o... | def num_blocks(w, l, h):
return w*l*h + (w+l)*h*(h-1)/2 + h*(h-1)*(2*h-1)/6 | apps |
def stream=(stream)
logger = Logger.new(stream)
logger.level = @logger.level
logger.formatter | = @logger.formatter
@logger = logger
end | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.