query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
def tags_newer(self, versions_file, majors):
"""
Checks this git repo tags for newer versions.
@param versions_file: a common.VersionsFile instance to
check against.
@param majors: a list of major branches to check. E.g. ['6', '7']
@raise RuntimeError: no newer tags w... | found.
@raise MissingMajorException: A new version from a newer major branch is
exists, but hasn't been downloaded due to it not being in majors.
"""
highest = versions_file.highest_version_major(majors)
all = self.tags_get()
newer = _newer_tags_get(highest, all)
... | csn_ccr |
public void calcOffset(Container compAnchor, Point offset)
{
offset.x = 0;
offset.y = 0;
Container parent = this;
while (parent != null)
{
offset.x -= parent.getLocation().x;
offset.y -= parent.getLocation().y;
parent = parent.getParent();
... | if (parent == compAnchor)
return; // Success
}
// Failure - comp not found.
offset.x = 0;
offset.y = 0;
} | csn_ccr |
def add_geometry(self,
geometry,
node_name=None,
geom_name=None,
parent_node_name=None,
transform=None):
"""
Add a geometry to the scene.
If the mesh has multiple transforms defined in its
... | name = geometry.metadata['name']
elif 'file_name' in geometry.metadata:
name = geometry.metadata['file_name']
else:
# try to create a simple name
name = 'geometry_' + str(len(self.geometry))
# if its already taken add a unique random string to it
if ... | csn_ccr |
Construct the context class loader by adding all jars. | private void createClassLoader() {
if (!Utils.isNullOrEmpty(settings.getJarFiles())) {
try {
String[] files = settings.getJarFiles().split(";");
List<URL> urls = newArrayList();
for (String path : files) {
File file = new File(path)... | csn |
Add standard attributes and price data to the collection.
@param ProductCollection $collection Product collection.
@return ProductCollection | public function prepareCollection(ProductCollection $collection)
{
$collection->addAttributeToSelect($this->attributes);
$collection->addPriceData();
return $collection;
} | csn |
public function setIpAllocationPolicy($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Container\V1\IPAllocationPolicy::class);
| $this->ip_allocation_policy = $var;
return $this;
} | csn_ccr |
// PrepareForCreate clears the status of a replication controller before creation. | func (rcStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
controller := obj.(*api.ReplicationController)
controller.Status = api.ReplicationControllerStatus{}
controller.Generation = 1
pod.DropDisabledTemplateFields(controller.Spec.Template, nil)
} | csn |
protected function initOptions()
{
$this->containerOptions = array_merge([
'id' => $this->getId()
| ],$this->containerOptions);
Html::addCssClass($this->containerOptions, 'owl-carousel');
} | csn_ccr |
Sets the values to be inserted. If no params are passed, then it returns
the currently stored values
@deprecated 3.4.0 Use setValues()/getValues() instead.
@param array|null $values Array with values to be inserted.
@return array|$this | public function values($values = null)
{
deprecationWarning(
'ValuesExpression::values() is deprecated. ' .
'Use ValuesExpression::setValues()/getValues() instead.'
);
if ($values !== null) {
return $this->setValues($values);
}
return $thi... | csn |
public EJBObject[] loadEntireCollection() {
EJBObject[] result = null;
try {
result = (EJBObject[]) allRemainingElements();
} catch (NoMoreElementsException e) {
// FFDCFilter.processException(e, CLASS_NAME + ".loadEntireCollection",
// ... | "276", this);
throw new RuntimeException(e.toString());
} catch (RemoteException e) {
// FFDCFilter.processException(e, CLASS_NAME + ".loadEntireCollection",
// "282", this);
throw new RuntimeException(e.toString());
}
... | csn_ccr |
// MySavedComments fetches comments saved by current user using OAuth. | func (o *OAuthSession) MySavedComments(params ListingOptions) ([]*Comment, error) {
me, err := o.Me()
if err != nil {
return nil, err
}
return o.SavedComments(me.Name, params)
} | csn |
func NewExecutionRulesAccepter(rules []imagepolicy.ImageExecutionPolicyRule, integratedRegistryMatcher RegistryMatcher) (Accepter, error) {
mapped := make(mappedAccepter)
for _, rule := range rules {
over, selectors, err := imageConditionInfo(&rule.ImageCondition)
if err != nil {
return nil, err
}
rule.Im... | rule)
}
}
for _, a := range mapped {
byResource := a.(*executionAccepter)
if len(byResource.rules) > 0 {
// if all rules are reject, the default behavior is allow
allReject := true
for _, rule := range byResource.rules {
if !rule.Reject {
allReject = false
break
}
}
byResource... | csn_ccr |
// WriteThroughput returns the write throughput | func (v *Stats) WriteThroughput() uint64 {
intv := toSec(v.IntervalMs)
if intv == 0 {
return 0
}
return (v.WriteBytes) / intv
} | csn |
func linkDir(src, dst string) error {
if err := os.MkdirAll(dst, 0777); err != nil {
return err |
}
return syscall.Mount(src, dst, "", syscall.MS_BIND, "")
} | csn_ccr |
public Node replaceNode(Node n) {
if (parent() == null) {
throw new UnsupportedOperationException("Replacing the root node is not supported");
}
List tail = getTail();
parent().appendNode(n.name(), n.attributes(), n.value());
| parent().children().addAll(tail);
getParentList(parent()).remove(this);
this.setParent(null);
return this;
} | csn_ccr |
Generates conditions for where clause.
@return mixed[] | private function getWhereClause(): array
{
$result = array_merge($this->getOwnerFields(), $this->getBelongTo(), $this->getPermissions());
$result = array_merge($result, $this->getParentPermissions(), $this->getParentJoinsWhereClause());
$result = array_merge_recursive($result, $this->getSupe... | csn |
Returns the calculated average of the current data
@return the calculated average of the current data | public double getAverage() {
if (!DATA_LIST.isEmpty()) {
double sum = 0;
for (DataPoint dataPoint : DATA_LIST) {
sum += dataPoint.getValue();
}
return sum / DATA_LIST.size();
}
return 0;
} | csn |
Apply the transposition to the target iterable.
Parameters
----------
target - iterable
The iterable to transpose. This would be suitable for things
such as a shape as well as a list of ``__getitem__`` keys.
inverse - bool
Whether to map old dimension... | def _apply_axes_mapping(self, target, inverse=False):
"""
Apply the transposition to the target iterable.
Parameters
----------
target - iterable
The iterable to transpose. This would be suitable for things
such as a shape as well as a list of ``__getitem... | csn |
def recursive_delete(path: nil)
raise ArgumentError, "path is a required argument" if path.nil?
result = zk.get_children(path: path)
raise Kazoo::Error, "Failed to list children of #{path} to delete them. Result code: #{result.fetch(:rc)}" if result.fetch(:rc) != Zookeeper::Constants::ZOK
| threads = result.fetch(:children).map do |name|
Thread.new do
Thread.abort_on_exception = true
recursive_delete(path: File.join(path, name))
end
end
threads.each(&:join)
result = zk.delete(path: path)
raise Kazoo::Error, "Failed to delete node #{path}. Re... | csn_ccr |
The code provided is supposed replace all the dots `.` in the specified String `str` with dashes `-`
But it's not working properly.
# Task
Fix the bug so we can all go home early.
# Notes
String `str` will never be null. | def replace_dots(string):
return string.replace('.', '-') | apps |
Deletes message.
@param int $id
@return PodiumResponse
@throws NoMembershipException
@throws ModelNotFoundException | public function removeMessage(int $id): PodiumResponse
{
return $this->getPodium()->message->remove($id, $this->ensureMembership());
} | csn |
public function getMagentoCreditCartType($ccType)
{
$ccTypesMapper = Mage::helper('adyen')->getCcTypesAltData();
if (isset($ccTypesMapper[$ccType])) {
| $ccType = $ccTypesMapper[$ccType]['code'];
}
return $ccType;
} | csn_ccr |
Returns a formatter object that can be reused for similar formatting task
under the same locale and options. This is often a speedier alternative to
using other methods in this class as only one formatter object needs to be
constructed.
### Options
- `locale` - The locale name to use for formatting the number, e.g. f... | public static function formatter($options = [])
{
$locale = isset($options['locale']) ? $options['locale'] : ini_get('intl.default_locale');
if (!$locale) {
$locale = static::DEFAULT_LOCALE;
}
$type = NumberFormatter::DECIMAL;
if (!empty($options['type'])) {
... | csn |
how to add tensorflow to pythonpath after downloading directory | def tfds_dir():
"""Path to tensorflow_datasets directory."""
return os.path.dirname(os.path.dirname(os.path.dirname(__file__))) | cosqa |
def execute(self, limitRequest=350000, limitResMax=-1):
"""Executes the query."""
query = self.getQueries()
query = self.__buildLimit(query, limitResMax)
nbr_results = limitResMax
if (limitResMax == -1):
query.setBaseUrl(self.__url+'/count')
countUrl = qu... | query.setBaseUrl(self.__url+'/records')
url = query.getUrl()
startVal = query._getParameters()['start']
while (nbr_results-startVal)>0 :#Do the job per 300 items till nbr_result is reached
resultTemp = Util.retrieveJsonResponseFromServer(url)
... | csn_ccr |
Use this API to fetch auditsyslogpolicy_csvserver_binding resources of given name . | public static auditsyslogpolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{
auditsyslogpolicy_csvserver_binding obj = new auditsyslogpolicy_csvserver_binding();
obj.set_name(name);
auditsyslogpolicy_csvserver_binding response[] = (auditsyslogpolicy_csvserver_binding[]) obj.get_re... | csn |
Gets image file format.
@param imageFile input image file
@return image file format | public static String getImageFileFormat(File imageFile) {
String imageFileName = imageFile.getName();
String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);
if (imageFormat.matches("(pbm|pgm|ppm)")) {
imageFormat = "pnm";
} else if (imageFormat.matc... | csn |
Output the aggregate block count results. | def finalize(self):
"""Output the aggregate block count results."""
for name, count in sorted(self.blocks.items(), key=lambda x: x[1]):
print('{:3} {}'.format(count, name))
print('{:3} total'.format(sum(self.blocks.values()))) | csn |
Try to guess the encoding of a request without going through the slow chardet process | def guess_encoding(request):
""" Try to guess the encoding of a request without going through the slow chardet process"""
ctype = request.headers.get('content-type')
if not ctype:
# we don't have a content-type, somehow, so...
LOGGER.warning("%s: no content-type; headers are %s",
... | csn |
Get standard belongsToMany reference key name for 'from' and 'to' models
Reversed gives the 'to' key
@param string $relation
@param bool $reversed (default: false)
@return string | public function getCmsReferenceKeyForRelation($relation, $reversed = false)
{
$isParent = ( array_key_exists($relation, $this->relationsConfig)
&& array_key_exists('parent', $this->relationsConfig[$relation])
&& (bool) $this->relationsConfig[$relation]['parent']
... | csn |
Update year in jalali date
@param int $year | private function setYear($year) {
//preventing duplication process
if ($year == $this->year) {
return;
}
$this->year = (int) $year;
$maximumDayAvailable = static::getMonthLength($this->year, $this->month);
if ($this->day > $maximumDayAvailabl... | csn |
// CLEmail implements Client interface. | func (p *implementation) CLEmail(c context.Context, host string, changeNumber int64) (email string, err error) {
defer func() { err = common.TagGRPC(c, err) }()
changeInfo, err := p.clEmailAndProjectNoACLs(c, host, changeNumber)
if err != nil {
return
}
allowed, err := p.acls.IsAllowed(c, host, changeInfo.Projec... | csn |
// Get returns wrapped username and LDAP groups and possibly updates the cache | func (lud *LdapUserData) Get() *querypb.VTGateCallerID {
if int64(time.Since(lud.lastUpdated).Seconds()) > lud.asl.RefreshSeconds {
go lud.update()
}
return &querypb.VTGateCallerID{Username: lud.username, Groups: lud.groups}
} | csn |
public function getDefaultDomain()
{
if ($this->defaultDomain) {
return $this->defaultDomain;
} elseif ($first = $this->getDomains()->first()) {
| return $first->getDomain();
} else {
return null;
}
} | csn_ccr |
Calls a callback with optional args and keyword args lists. This method exists so
we can inspect the `_max_calls` attribute that's set by `_on`. If this value is None,
the callback is considered to have no limit. Otherwise, an integer value is expected
and decremented until there are no remaining calls | def _call(callback, args=[], kwargs={}):
"""
Calls a callback with optional args and keyword args lists. This method exists so
we can inspect the `_max_calls` attribute that's set by `_on`. If this value is None,
the callback is considered to have no limit. Otherwise, an integer value is expected
an... | csn |
// RemoteAddr returns the remote network address. | func (c *Conn) RemoteAddr() net.Addr {
if !c.ok() {
return nil
}
return c.raddr
} | csn |
private function getRelationships(Item $item)
{
if ($include_params = $this->resource->getIncludeParams()) { |
$item->setIncludeParams($include_params);
return $item->getIncluded();
}
return [];
} | csn_ccr |
public InetAddress []
lookupAllHostAddr(String host) throws UnknownHostException {
Name name = null;
try {
name = new Name(host);
}
catch (TextParseException e) {
throw new UnknownHostException(host);
}
Record [] records = null;
if (preferV6)
records = new Lookup(name, Type.AAAA).run();
if (records == n... | = 0; i < records.length; i++) {
Record record = records[i];
if (records[i] instanceof ARecord) {
ARecord a = (ARecord) records[i];
array[i] = a.getAddress();
} else {
AAAARecord aaaa = (AAAARecord) records[i];
array[i] = aaaa.getAddress();
}
}
return array;
} | csn_ccr |
Returns a unicode string for string.
:param string:
The input string.
:type string:
`basestring`
:returns:
A unicode string.
:rtype:
`unicode` | def _ensure_unicode_string(string):
"""Returns a unicode string for string.
:param string:
The input string.
:type string:
`basestring`
:returns:
A unicode string.
:rtype:
`unicode`
"""
if not isinstance(string, si... | csn |
func (r Hardware_SecurityModule750) GetScaleAssets() (resp []datatypes.Scale_Asset, err error) {
err | = r.Session.DoRequest("SoftLayer_Hardware_SecurityModule750", "getScaleAssets", nil, &r.Options, &resp)
return
} | csn_ccr |
python 3 send text message | async def _send_plain_text(self, request: Request, stack: Stack):
"""
Sends plain text using `_send_text()`.
"""
await self._send_text(request, stack, None) | cosqa |
public function removeDir($path)
{
if ($path == 'packages' or $path == '/') {
return false;
}
$files = array_diff(scandir($path), ['.', '..']);
foreach ($files as $file) {
if (is_dir("$path/$file")) {
| $this->removeDir("$path/$file");
} else {
@chmod("$path/$file", 0777);
@unlink("$path/$file");
}
}
return rmdir($path);
} | csn_ccr |
func (i *info) Client() hrpc.RegionClient {
i.m.RLock()
| c := i.client
i.m.RUnlock()
return c
} | csn_ccr |
public OkVolley init(Context context) {
this.mContext = context;
InstanceRequestQueue = newRequestQueue(context);
mUserAgent = generateUserAgent(context);
mRequestHeaders = new HashMap<>();
| mRequestHeaders.put(OkRequest.HEADER_USER_AGENT, mUserAgent);
mRequestHeaders.put(OkRequest.HEADER_ACCEPT_CHARSET, OkRequest.CHARSET_UTF8);
return this;
} | csn_ccr |
Copies vat info from the parent to all children.
In Magento, VAT info on the children may contain a 0 vat rate. To correct
this, we copy the vat information (rate, source, correction info).
@param array $parent
The parent invoice line.
@param array[] $children
The child invoice lines.
@return array[]
The child invoi... | protected function copyVatInfoToChildren(array $parent, array $children)
{
static $vatMetaInfoTags = array(
Meta::VatRateMin,
Meta::VatRateMax,
Meta::VatRateLookup,
Meta::VatRateLookupLabel,
Meta::VatRateLookupSource,
Meta::VatRateLooku... | csn |
protected function blockTable($line, array $block = null)
{
if (! isset($block) or isset($block[ 'type' ]) or isset($block[ 'interrupted' ])) {
return;
}
if (strpos($block[ 'element' ][ 'text' ], '|') !== false and chop($line[ 'text' ], ' -:|') === '') {
$alignments ... | 'style' => 'text-align: ' . $alignment . ';',
];
}
$headerElements[] = $headerElement;
}
$block = [
'alignments' => $alignments,
'identified' => true,
'element' => [
... | csn_ccr |
send http request with authorization python | def auth_request(self, url, headers, body):
"""Perform auth request for token."""
return self.req.post(url, headers, body=body) | cosqa |
Deletes an item from the static acceleration array.
@param string|int $key As given to get|set|delete
@return bool True on success, false otherwise. | protected function static_acceleration_delete($key) {
unset($this->staticaccelerationarray[$key]);
if ($this->staticaccelerationsize !== false && isset($this->staticaccelerationkeys[$key])) {
unset($this->staticaccelerationkeys[$key]);
$this->staticaccelerationcount--;
}
... | csn |
Generates the tags for the HTML head.
@param array $files List of file URLs that should be HTML tags generated for
@param string $filetype Typ of the given files, e.g. 'js' or 'css'
@return string Generated string for inclusion into the HTML head
@throws MW_Jsb2_Exception If the file type is unknown | protected function _createHtml( array $files, $filetype )
{
$html = '';
foreach( $files as $file )
{
switch( $filetype )
{
case 'js':
$html .= '<script type="text/javascript" src="' . $file . '"></script>' . PHP_EOL;
break;
case 'css':
$html .= '<link rel="stylesheet" type="text/css... | csn |
Get an array with the specified length from the pool.
@param {number} length The preferred length of the array.
@return {Array} An array. | function getWithLength(length) {
var arrays = pool[length];
var array;
var i;
// Create the first array for the specified length
if (!arrays) {
array = create(length);
}
// Find an unused array among the created arrays for the specified length
if (!array) {
for (i = arrays.length; i--;) {
... | csn |
@SuppressWarnings("OptionalGetWithoutIsPresent")
public Token<DelegationTokenIdentifier> getBoundOrNewDT(String renewer) throws IOException {
logger.atFine().log("Delegation token requested");
if (isBoundToDT()) {
// the FS was created on startup with a token, so return it.
logger.atFine().log("Re... | // not bound to a token, so create a new one.
// issued DTs are not cached so that long-lived filesystems can
// reliably issue session/role tokens.
return tokenBinding.createDelegationToken(renewer);
} | csn_ccr |
public List<Node> copyDirectory(Node destdir, Filter filter) throws DirectoryNotFoundException, CopyException {
| return new Copy(this, filter).directory(destdir);
} | csn_ccr |
// lambdaWalker returns a walkfunc that applies lambda to every file with extension ext. Ignores all other file types.
// Lambda should take the file path as its parameter. | func lambdaWalker(lambda func(string) error, ext string) filepath.WalkFunc {
walk := func(path string, f os.FileInfo, err error) error {
// if error occurs during traversal to path, exit and crash
if err != nil {
return err
}
// skip anything that is a directory
if f.IsDir() {
return nil
}
if file... | csn |
// reloadConfig and reinitialise phosphor client if necessary
//
// Get Config
// Test hash of config to determine if changed
// If so, update config & reinit | func (p *Phosphor) reloadConfig() error {
c := p.configProvider.Config()
// Skip reloading if the config is the same
h := fmt.Sprintf("%x", deephash.Hash(c))
if p.compareConfigHash(h) {
return nil
}
// keep reference to the old channel so we can drain this in parallel with
// new traces the transport receive... | csn |
Copy a file from source to destination, may be done recursively and may ignore system files
@access public
@author Lionel Lecaque, <lionel@taotesting.com>
@param string source
@param string destination
@param boolean recursive
@param boolean ignoreSystemFiles
@return boolean | static public function copy($source, $destination, $recursive = true, $ignoreSystemFiles = true)
{
if(!is_readable($source)){
return false;
}
$returnValue = (bool) false;
// Check for System File
$basename = basename($source);
if ($basename[0] === '.' &... | csn |
logging python close log file | def close_log(log, verbose=True):
"""Close log
This method closes and active logging.Logger instance.
Parameters
----------
log : logging.Logger
Logging instance
"""
if verbose:
print('Closing log file:', log.name)
# Send closing message.
log.info('The log file h... | cosqa |
Generate a controller with the given name for the given package
@param string $packageKey The package key of the controller's package
@param string $subpackage An optional subpackage name
@param string $controllerName The name of the new controller
@param boolean $overwrite Overwrite any existing files?
@return array ... | public function generateActionController($packageKey, $subpackage, $controllerName, $overwrite = false)
{
list($baseNamespace, $namespaceEntryPath) = $this->getPrimaryNamespaceAndEntryPath($this->packageManager->getPackage($packageKey));
$controllerName = ucfirst($controllerName);
$controlle... | csn |
Publish metrics for a subcontainer and handle filtering on tags | def _update_container_metrics(self, instance, subcontainer, kube_labels):
"""Publish metrics for a subcontainer and handle filtering on tags"""
tags = list(instance.get('tags', [])) # add support for custom tags
if len(subcontainer.get('aliases', [])) >= 1:
# The first alias seems ... | csn |
func (o *Buffer) enc_ref_bool(p *Properties, base structPointer) error {
v := structPointer_RefBool(base, p.field)
if v == nil {
return ErrNil
}
x := 0
| if *v {
x = 1
}
o.buf = append(o.buf, p.tagcode...)
p.valEnc(o, uint64(x))
return nil
} | csn_ccr |
python3 parse a substring to datetime in a string | def parse_date(s):
"""Fast %Y-%m-%d parsing."""
try:
return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10]))
except ValueError: # other accepted format used in one-day data set
return datetime.datetime.strptime(s, '%d %B %Y').date() | cosqa |
Creates a new image of the same type and number of bands
@param imgWidth image width
@param imgHeight image height
@return new image | @Override
public Planar<T> createNew(int imgWidth, int imgHeight) {
return new Planar<>(type, imgWidth, imgHeight, bands.length);
} | csn |
def should_build(self, fpath, meta):
"""
Checks if the file should be built or not
Only skips layouts which are tagged as INCREMENTAL
Rebuilds only those files with mtime changed since previous build
"""
if meta.get('layout', self.default_template) in self.inc_layout:
... | if self.prev_mtime.get(fpath, 0) == os.path.getmtime(fpath):
return False
else:
return True
return True | csn_ccr |
def ip_to_url(ip_addr):
"""
Resolve a hostname based off an IP address.
This is very limited and will
probably not return any results if it is a shared IP address or an
address with improperly setup DNS records.
.. code:: python
reusables.ip_to_url('93.184.216.34') # example.com
... | :param ip_addr: IP address to resolve to hostname
:return: string of hostname or None
"""
try:
return socket.gethostbyaddr(ip_addr)[0]
except (socket.gaierror, socket.herror):
logger.exception("Could not resolve hostname") | csn_ccr |
private FeatureIndex[] createFeatureIndex(int subspaceCount) // throws
// Exception
{
| logger.info("create feature index");
FeatureIndex[] index = new FeatureIndex[subspaceCount];
for (int i = 0; i < subspaceCount; i++)
index[i] = new FeatureIndex(false, 1);
return index;
} | csn_ccr |
Checks if the hub has now activity turned on. This is implemented by checking the hubs current activity. If the
activities id is equal to -1, no activity is on currently.
@returns {Q.Promise} | function isOff () {
debug('check if turned off')
return this.getCurrentActivity()
.then(function (activityId) {
var off = (activityId === '-1')
debug(off ? 'system is currently off' : 'system is currently on with activity ' + activityId)
return off
})
} | csn |
def hdf5(self):
"""Path of output hdf5 folder if relevant, None otherwise."""
if self._rundir['hdf5'] is UNDETERMINED:
h5_folder = self.path / self.par['ioin']['hdf5_output_folder'] |
if (h5_folder / 'Data.xmf').is_file():
self._rundir['hdf5'] = h5_folder
else:
self._rundir['hdf5'] = None
return self._rundir['hdf5'] | csn_ccr |
Copies the input stream to the output stream using a 4K buffer
@param inputStream the stream to copy
@param outputStream the stream to write to
@throws IOException if there is an exception reading or writing | private void copy(final InputStream inputStream, final FileOutputStream outputStream) throws IOException {
final byte[] buffer = new byte[1024*4];
int n;
try {
while (-1 != (n = inputStream.read(buffer))) {
outputStream.write(buffer, 0, n);
}
} fin... | csn |
public static String[] getColumnFamilyList(String path) throws RocksDBException {
List<byte[]> cfList = RocksDB.listColumnFamilies(new Options(), path);
if (cfList == null || cfList.size() == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
List<String> result | = new ArrayList<>(cfList.size());
for (byte[] cf : cfList) {
result.add(new String(cf, StandardCharsets.UTF_8));
}
return result.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
} | csn_ccr |
r"""Purge all pretrained model files in local file store.
Parameters
----------
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters. | def purge(root=os.path.join(base.data_dir(), 'models')):
r"""Purge all pretrained model files in local file store.
Parameters
----------
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
"""
root = os.path.expanduser(root)
files = os.listdir(root)
... | csn |
Returns the String identifying the given cudaLimit
@param n The cudaLimit
@return The String identifying the given cudaLimit | public static String stringFor(int n)
{
switch (n)
{
case cudaLimitStackSize: return "cudaLimitStackSize";
case cudaLimitPrintfFifoSize: return "cudaLimitPrintfFifoSize";
case cudaLimitMallocHeapSize: return "cudaLimitMallocHeapSize";
case cudaL... | csn |
function (column) {
if (isString(column.type) && column.type.match(/string/i) && column.text) {
| delete column["default"];
}
return this._super(arguments, [column]);
} | csn_ccr |
def returnIndexList(self, limit=False):
'''Return a list of integers that are list-index references to the
original list of dictionaries."
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "order": 2},
... {"name": "Larry", "age": 18, ... | :param limit:
A number limiting the quantity of entries to return. Defaults to
False, which means that the full list is returned.
:return:
A list of integers representing the original indices.
'''
if limit==False:
return self.index_track
... | csn_ccr |
Attempt to create a durable subscription on a remote ME.
@param MP The MessageProcessor.
@param subState State describing the subscription to create.
@param remoteME The ME where the subscription should be created. | public static void createRemoteDurableSubscription(
MessageProcessor MP,
ConsumerDispatcherState subState,
SIBUuid8 remoteMEUuid,
SIBUuid12 destinationID)
throws SIDurableSubscriptionAlreadyExistsException,
SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntr... | csn |
Performs a preprocess pass of the table to attempt naive conversions of data and to record
the initial types of each cell. | def preprocess_worksheet(self, table, worksheet):
'''
Performs a preprocess pass of the table to attempt naive conversions of data and to record
the initial types of each cell.
'''
table_conversion = []
flags = {}
units = {}
for rind, row in enumerate(tabl... | csn |
func (b *Backoffer) Backoff(typ backoffType, err error) error {
if strings.Contains(err.Error(), mismatchClusterID) {
logutil.Logger(context.Background()).Fatal("critical error", zap.Error(err))
}
select {
case <-b.ctx.Done():
return errors.Trace(err)
default:
}
typ.Counter().Inc()
// Lazy initialize.
if ... | = append(b.errors, errors.Errorf("%s at %s", err.Error(), time.Now().Format(time.RFC3339Nano)))
if b.maxSleep > 0 && b.totalSleep >= b.maxSleep {
errMsg := fmt.Sprintf("%s backoffer.maxSleep %dms is exceeded, errors:", typ.String(), b.maxSleep)
for i, err := range b.errors {
// Print only last 3 errors for non... | csn_ccr |
Override this method to change the default Route implementation
@param controllerMethod The ControllerMethod
@param parameterNames parameters of the method
@return Route representation | protected Route getRouteStrategy(ControllerMethod controllerMethod, Parameter[] parameterNames) {
return new FixedMethodStrategy(originalUri, controllerMethod, this.supportedMethods, builder.build(), priority, parameterNames);
} | csn |
Calculates the extended gcd
@param {number} a
@param {number} b
@returns {Array} | function(a, b) {
// gcd = a * s + b * t
var s = 0, t = 1, u = 1, v = 0;
while (a !== 0) {
var q = b / a | 0, r = b % a;
var m = s - u * q, n = t - v * q;
b = a;
a = r;
s = u;
t = v;
u = m;
v = n;
}
return [b /* gcd*/, s, t];
} | csn |
Register or render a View. If View is registered this method returns the index number from View
@param string $view
@param array $data
@return int|null | public static function render($view, array $data = array())
{
if (self::$force || App::state() > 2) {
\UtilsSandboxLoader('application/View/' . strtr($view, '.', '/') . '.php', self::$shared + $data);
return $data = null;
}
return array_push(self::$views, array(strt... | csn |
Normalizes a nested array.
@param array $files The nested array
@return array Normalized array | protected static function normalizeNested(array $files)
{
$normalized = [];
foreach (array_keys($files['tmp_name']) as $key) {
$spec = [
'name' => $files['name'][$key],
'tmp_name' => $files['tmp_name'][$key],
'type' => $files['type'... | csn |
calculating the average of a list in python | def mean(inlist):
"""
Returns the arithematic mean of the values in the passed list.
Assumes a '1D' list, but will function on the 1st dim of an array(!).
Usage: lmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + item
return sum / float(len(inlist)) | cosqa |
public static ServerSetup[] verbose(ServerSetup[] serverSetups) {
ServerSetup[] copies = new ServerSetup[serverSetups.length];
for (int i = 0; i < serverSetups.length; i++) {
|
copies[i] = serverSetups[i].createCopy().setVerbose(true);
}
return copies;
} | csn_ccr |
Minimizes the capacity to the actual length of the string.
@return this, to enable chaining | public StrBuilder minimizeCapacity() {
if (buffer.length > length()) {
final char[] old = buffer;
buffer = new char[length()];
System.arraycopy(old, 0, buffer, 0, size);
}
return this;
} | csn |
python asyncio syncio hybrid | def StringIO(*args, **kwargs):
"""StringIO constructor shim for the async wrapper."""
raw = sync_io.StringIO(*args, **kwargs)
return AsyncStringIOWrapper(raw) | cosqa |
Executes SQLSpecialColumns with SQL_BEST_ROWID which creates a
result set of columns that uniquely identify a row | def rowIdColumns(self, table, catalog=None, schema=None, # nopep8
nullable=True):
"""Executes SQLSpecialColumns with SQL_BEST_ROWID which creates a
result set of columns that uniquely identify a row
"""
fut = self._run_operation(self._impl.rowIdColumns, table,
... | csn |
def list_straten(self, gemeente, sort=1):
'''
List all `straten` in a `Gemeente`.
:param gemeente: The :class:`Gemeente` for which the \
`straten` are wanted.
:rtype: A :class:`list` of :class:`Straat`
'''
try:
id = gemeente.id
except Attr... | id,
r.StatusStraatnaam
)for r in res.StraatnaamWithStatusItem
]
except AttributeError:
return []
if self.caches['long'].is_configured:
key = 'ListStraatnamenWithStatusByGemeenteId#%s%s' % (id, sort)
... | csn_ccr |
Add a prepare bridge method to the classfile for the given type.
@param cf file to which to add the prepare bridge
@param leaf leaf class
@param returnClass type returned from generated bridge method
@since 1.2 | private static void definePrepareBridge(ClassFile cf, Class leaf, Class returnClass) {
TypeDesc returnType = TypeDesc.forClass(returnClass);
if (isPublicMethodFinal(leaf, PREPARE_METHOD_NAME, returnType, null)) {
// Cannot override.
return;
}
MethodInfo ... | csn |
Checks if any changed child sockets are in the bucket.
@param int $bucket The bucket to get results in.
@param int $timeout The timeout for changed socket checking (default 0).
@return int|void Returns the number of changed sockets for children workers in $bucket,
or empty array if none. | protected function get_changed_sockets($bucket = self::DEFAULT_BUCKET, $timeout = 0)
{
$write_dummy = null;
$exception_dummy = null;
// grab all the children sockets
$sockets = array();
foreach ($this->forked_children as $pid => $child)
{
if ($child['bucket'] == $bucket)
{
$sockets[$pid] = $chil... | csn |
Triggers entity's fieldAttached callback.
@return void | public function fieldAttached()
{
$handler = $this->get('metadata')->get('handler');
if (class_exists($handler)) {
$handler = new $handler();
return $handler->fieldAttached($this);
}
return true;
} | csn |
Returns permissions from the Role.
@return PermissionInterface[] | public function getPermissions()
{
$mode = \RecursiveIteratorIterator::CHILD_FIRST;
$iterator = $this->createRecursiveIterator($mode);
$permissions = [];
/** @var $child RoleInterface */
foreach ($iterator as $child) {
$permissions = array_replace_recursive(... | csn |
Decode hex string to a byte array
@param encoded
encoded string
@return return array of byte to encode | static public byte[] decode(String encoded) {
if (encoded == null)
return null;
int lengthData = encoded.length();
if (lengthData % 2 != 0)
return null;
char[] binaryData = encoded.toCharArray();
int lengthDecode = lengthData / 2;
byte[] decodedData = new byte[lengthDecode];
byte temp1, temp2;
ch... | csn |
Run configured command
@return string | public function run()
{
$result = $this->getCommand()->run();
if ($result->getExitCode() != 0) {
throw new \RuntimeException(sprintf(
'Command failed. Exit code %d, output %s',
$result->getExitCode(),
$result->getStdErr()));
}
... | csn |
Get a single image
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_get name=image1
salt '*' glanceng.image_get name=0e4febc2a5ab4f2c8f374b054162506d | def image_get(auth=None, **kwargs):
'''
Get a single image
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_get name=image1
salt '*' glanceng.image_get name=0e4febc2a5ab4f2c8f374b054162506d
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
... | csn |
private function raiseIndentationLevel(int $indentationLevel, array $tokensInLine): int
{
$raisingIndentation = [
TokenInterface::TYPE_BRACE_OPEN,
];
if ($this->indentConditions && $this->insideCondition === false) {
$raisingIndentation[] = TokenInterface::TYPE_CONDI... | if (in_array($token->getType(), $raisingIndentation)) {
if ($token->getType() === TokenInterface::TYPE_CONDITION) {
$this->insideCondition = true;
}
return $indentationLevel + 1;
}
}
return $indentationLevel;
} | csn_ccr |
func (r *DatabaseFactory) MustGet(dbName ...string) *DB | {
db, err := r.Get(dbName...)
if err != nil {
panic(err)
}
return db
} | csn_ccr |
Add proper formated variable names, initializers and type names to use in templates | def generate_messages_info(msgs):
"""Add proper formated variable names, initializers and type names to use in templates"""
for msg in msgs:
msg.swift_name = camel_case_from_underscores(msg.name)
msg.formatted_description = ""
if msg.description:
msg.description = " ".join(... | csn |
public static function build_query_string()
{
$params = array();
foreach (func_get_args() as $arg)
{
$arg = is_array($arg) ? $arg : array($arg => '1');
| $params = array_merge($params, $arg);
}
return http_build_query($params);
} | csn_ccr |
def set_by_Id(self, Id, is_added):
"""Update selected_ids with given Id"""
row = self.collection.index_from_id(Id)
if row is None:
| return
self._set_id(Id, is_added, self.index(row, 0)) | csn_ccr |
Create an instance of the oss driver.
@param array $config
@return \yuncms\filesystem\Filesystem
@throws \OSS\Core\OssException
@throws \Exception | public function createOssAdapter(array $config)
{
$root = $config['root'] ?? null;
$oss = new OssClient($config['access_id'], $config['access_secret'], $config['endpoint'],
$config['isCName'] ?? false,
$config['securityToken'] ?? null,
$config['proxy'] ?? null
... | csn |
get a fitting Unmarshaller
@return - the Unmarshaller for the classOfT set
@throws JAXBException | public Unmarshaller getUnmarshaller() throws JAXBException {
JAXBContext context = JAXBContext.newInstance(classOfT);
Unmarshaller u = context.createUnmarshaller();
u.setEventHandler(new ValidationEventHandler() {
@Override
public boolean handleEvent(ValidationEvent event) {
return true;... | csn |
def gettext_lazy(message, domain=DEFAULT_DOMAIN):
"""Mark a message as translatable, but delay the translation until the message is used.
Sometimes, there are some messages that need to be translated, but the translation
can't be done at the point the message itself is written. For example, the names of
... | from zengine.lib.translation import gettext_lazy, InstalledLocale
from pyoko import model, fields
class User(model.Model):
name = fields.String(gettext_lazy('User Name'))
print(User.name.title)
'User Name'
InstalledLocale.install_language('tr')
... | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.