query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
update a record via table api, kparams being the dict of PUT params to update.
returns a SnowRecord obj. | def update(self,table, sys_id, **kparams):
"""
update a record via table api, kparams being the dict of PUT params to update.
returns a SnowRecord obj.
"""
record = self.api.update(table, sys_id, **kparams)
return record | csn |
private void dumpMEtoMEConversations(final IncidentStream is)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "dumpMEtoMEConversations", is);
final ServerConnectionManager scm = ServerConnectionManager.getRef();
final List obc = scm.getActiveOutbound... | followed by its conversations
for (final Iterator<Entry<Object,LinkedList<Conversation>>>i = connectionToConversationMap.entrySet().iterator(); i.hasNext();)
{
final Entry<Object, LinkedList<Conversation>>entry = i.next();
is.writeLine("\nOutbound connection:", entry.getKey())... | csn_ccr |
Calculates the maximum depth of the program tree. | def _depth(self):
"""Calculates the maximum depth of the program tree."""
terminals = [0]
depth = 1
for node in self.program:
if isinstance(node, _Function):
terminals.append(node.arity)
depth = max(len(terminals), depth)
else:
... | csn |
def lock(self, session):
"""Lock the connection, ensuring that it is not busy and storing
a weakref for the session.
:param queries.Session session: The session to lock the connection with
:raises: ConnectionBusyError
"""
if self.busy:
| raise ConnectionBusyError(self)
with self._lock:
self.used_by = weakref.ref(session)
LOGGER.debug('Connection %s locked', self.id) | csn_ccr |
private function getModelId(EnvironmentInterface $environment)
{
$inputProvider = $environment->getInputProvider();
if ($inputProvider->hasParameter('id') && $inputProvider->getParameter('id')) {
$modelId = ModelId::fromSerialized($inputProvider->getParameter('id'));
}
... |
&& ($environment->getDataDefinition()->getName() === $modelId->getDataProviderName()))
) {
return null;
}
return $modelId;
} | csn_ccr |
tieBreak method which will kick in when the comparator list generated an equality result for
both sides. the tieBreak method will try best to make sure a stable result is returned. | protected boolean tieBreak(final T object1, final T object2) {
if (null == object2) {
return true;
}
if (null == object1) {
return false;
}
return object1.hashCode() >= object2.hashCode();
} | csn |
func signalReorg(d ReorgData) {
if nodeClient == nil {
log.Errorf("The daemon RPC client for signalReorg is not configured!")
return
}
// Determine the common ancestor of the two chains, and get the full
// list of blocks in each chain back to but not including the common
// ancestor.
ancestor, newChain, old... | default:
d.WG.Done()
}
// Send reorg data to blockdata's monitor.
d.WG.Add(1)
select {
case NtfnChans.ReorgChanBlockData <- fullData:
default:
d.WG.Done()
}
// Send reorg data to ChainDB's monitor.
d.WG.Add(1)
select {
case NtfnChans.ReorgChanDcrpgDB <- fullData:
default:
d.WG.Done()
}
d.WG.Wait(... | csn_ccr |
Return a sound playback callback.
Parameters
----------
resampler
The resampler from which samples are read.
samplerate : float
The sample rate.
params : dict
Parameters for FM generation. | def get_playback_callback(resampler, samplerate, params):
"""Return a sound playback callback.
Parameters
----------
resampler
The resampler from which samples are read.
samplerate : float
The sample rate.
params : dict
Parameters for FM generation.
"""
def call... | csn |
def store_groups_in_session(sender, user, request, **kwargs):
"""
When a user logs in, fetch its groups and store them in the users session.
This is required by ws4redis, since fetching groups accesses the database, which is a blocking
operation and thus not | allowed from within the websocket loop.
"""
if hasattr(user, 'groups'):
request.session['ws4redis:memberof'] = [g.name for g in user.groups.all()] | csn_ccr |
private ServletHandler configureHandler(String servletClassName) {
ServletHandler handler = new ServletHandler();
| handler.addServletWithMapping(servletClassName, "/*");
return handler;
} | csn_ccr |
Reserves the given number of bytes to spill. If more than the maximum, throws an exception.
@throws ExceededSpillLimitException | public synchronized ListenableFuture<?> reserve(long bytes)
{
checkArgument(bytes >= 0, "bytes is negative");
if ((currentBytes + bytes) >= maxBytes) {
throw exceededLocalLimit(succinctBytes(maxBytes));
}
currentBytes += bytes;
return NOT_BLOCKED;
} | csn |
Stateless intermediate ops from LongStream | @Override
public final DoubleStream asDoubleStream() {
return new DoublePipeline.StatelessOp<Long>(this, StreamShape.LONG_VALUE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
@Override
public Sink<Long> opWrapSink(int flags... | csn |
def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t):
X,Y = t.shape
pt = np.zeros((X,Y))
"omp parallel for"
for i in range(X):
for j in range(Y):
for k in t:
tmp = 6368.* np.arccos( | np.cos(xmin+step*i)*np.cos( k[0] ) * np.cos((ymin+step*j)-k[1])+ np.sin(xmin+step*i)*np.sin(k[0]))
if tmp < range_:
pt[i][j]+=k[2] / (1+tmp)
return pt | csn_ccr |
def merged(self, other):
"""Returns the merged result of two requirements.
Two requirements can be in conflict and if so, this function returns
None. For example, requests for "foo-4" and "foo-6" are in conflict,
since both cannot be satisfied with a single version of foo.
Some... | else:
r = _r(other)
r.range_ = range_
return r
elif other.conflict:
range_ = self.range_ - other.range_
if range_ is None:
return None
else:
r = _r(self)
r.... | csn_ccr |
// MakeRequest initiates a request to the remote host, returning a response and
// possible error. | func (c Client) MakeRequest(req Request) (Response, error) {
if req.AcceptableStatusCodes == nil {
panic("acceptable status codes for this request were not set")
}
request, err := c.buildRequest(req)
if err != nil {
return Response{}, err
}
var resp *http.Response
transport := buildTransport(c.config.SkipV... | csn |
public static String resolveFunction(String functionString, TestContext context) {
String functionExpression = VariableUtils.cutOffVariablesPrefix(functionString);
if (!functionExpression.contains("(") || !functionExpression.endsWith(")") || !functionExpression.contains(":")) {
throw new In... | FunctionLibrary library = context.getFunctionRegistry().getLibraryForPrefix(functionPrefix);
parameterString = VariableUtils.replaceVariablesInString(parameterString, context, false);
parameterString = replaceFunctionsInString(parameterString, context);
String value = library.getFunction... | csn_ccr |
public function groups()
{
if ($this->groups === null) {
$ident = $this->ident();
$metadata = $this->adminSecondaryMenu();
$this->groups = [];
if (isset($metadata[$ident]['groups'])) {
$groups = $metadata[$ident]['groups']; |
if (is_array($groups)) {
$this->setGroups($groups);
}
}
}
return $this->groups;
} | csn_ccr |
protected function _compile($part, ValueBinder $generator)
{
if ($part instanceof ExpressionInterface) {
$part = $part->sql($generator);
} elseif (is_array($part)) {
$placeholder = $generator->placeholder('param');
| $generator->bind($placeholder, $part['value'], $part['type']);
$part = $placeholder;
}
return $part;
} | csn_ccr |
public JBBPTextWriter Byte(final byte[] array, int off, int len) throws IOException {
ensureValueMode();
| while (len-- > 0) {
Byte(array[off++]);
}
return this;
} | csn_ccr |
Parses all settings form the main configuration file.
@param root The root element of the configuration. | private final void parseSettings (final Element root) {
if (root == null) { throw new NullPointerException(); }
clear();
parseGlobalSettings(root);
parseTargetSpecificSettings(root);
} | csn |
Initialmethode, wird aufgerufen um den internen Zustand des Objektes zu setzten.
@param fld Function Libraries zum validieren der Funktionen
@param cfml CFML Code der transfomiert werden soll. | protected Data init(Data data) {
if (JSON_ARRAY == null) JSON_ARRAY = getFLF(data, "_literalArray");
if (JSON_STRUCT == null) JSON_STRUCT = getFLF(data, "_literalStruct");
if (GET_STATIC_SCOPE == null) GET_STATIC_SCOPE = getFLF(data, "_getStaticScope");
if (GET_SUPER_STATIC_SCOPE == null) GET_SUPER_STATIC_SCOPE = g... | csn |
please add timezone info to timestamps python | def parse_timestamp(timestamp):
"""Parse ISO8601 timestamps given by github API."""
dt = dateutil.parser.parse(timestamp)
return dt.astimezone(dateutil.tz.tzutc()) | cosqa |
// arePodVolumesBound returns true if all volumes are fully bound | func (b *volumeBinder) arePodVolumesBound(pod *v1.Pod) bool {
for _, vol := range pod.Spec.Volumes {
if isBound, _, _ := b.isVolumeBound(pod.Namespace, &vol); !isBound {
// Pod has at least one PVC that needs binding
return false
}
}
return true
} | csn |
// signMessage signs the given message with the private key for the given
// address | func signMessage(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.SignMessageCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
privKey, err := w.PrivKeyForAddress(addr)
if err != nil {
return nil, err
}
var buf bytes.Buffer
wi... | csn |
Sets configuration options from raw DirectAdmin data.
@param UserContext $context Owning user context
@param array $config An array of settings | private function setConfig(UserContext $context, array $config)
{
$this->domainName = $config['domain'];
// Determine owner
if ($config['username'] === $context->getUsername()) {
$this->owner = $context->getContextUser();
} else {
throw new DirectAdminExcepti... | csn |
public Geometry createGeometry(Geometry geometry) {
if (geometry instanceof Point) {
return createPoint(geometry.getCoordinate());
} else if (geometry instanceof LinearRing) {
return createLinearRing(geometry.getCoordinates());
} else if (geometry instanceof LineString) {
return createLineString(geometry... | LineString[] clones = new LineString[geometry.getNumGeometries()];
for (int n = 0; n < geometry.getNumGeometries(); n++) {
clones[n] = createLineString(geometry.getGeometryN(n).getCoordinates());
}
return new MultiLineString(srid, precision, clones);
} else if (geometry instanceof MultiPolygon) {
Po... | csn_ccr |
// startListening on the network addresses | func startListening(host p2phost.Host, cfg *config.Config) error {
listenAddrs, err := listenAddresses(cfg)
if err != nil {
return err
}
// Actually start listening:
if err := host.Network().Listen(listenAddrs...); err != nil {
return err
}
// list out our addresses
addrs, err := host.Network().InterfaceL... | csn |
Reads a single byte from the input stream. | private int read() {
int curByte = 0;
try {
curByte = rawData.get() & 0xFF;
} catch (Exception e) {
header.status = GifDecoder.STATUS_FORMAT_ERROR;
}
return curByte;
} | csn |
Resolve services, factories, callables by given token
@param string $name
@return mixed | public function tokenResolve($name)
{
if(strpos($name, 'self.callable') === 0)
$name = str_replace('self.callable.', 'callable.', $name);
if(strpos($name, 'self.factory') === 0)
$name = str_replace('self.factory.', 'factory.', $name);
switch($name)
{
... | csn |
This is a private message handler method.
It is a message handler for analog messages.
:param data: message data
:returns: None - but saves the data in the pins structure | async def _analog_message(self, data):
"""
This is a private message handler method.
It is a message handler for analog messages.
:param data: message data
:returns: None - but saves the data in the pins structure
"""
pin = data[0]
value = (data[PrivateC... | csn |
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain posi... | n=int(input())
q=[]
for i in range(max(0,n-100),n+1):
j=i
res=i
while j:
res+=j%10
j//=10
if res==n:
q.append(i)
print(len(q))
for i in q:
print(i) | apps |
Show device model. | def get_device_model(self) -> str:
'''Show device model.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'getprop', 'ro.product.model')
return output.strip() | csn |
public void writeit(String strTemp)
{
String strTabs = "";
int i = 0;
for (i = 0; i < m_iTabs; i++)
{
strTabs += "\t";
}
if (m_bTabOnNextLine) if ((strTemp.length() > 0) && (strTemp.charAt(0) != '\n'))
strTemp = strTabs + strTemp;
m_bTa... | iIndex = -1;
}
iIndex = 0;
while (iIndex != -1)
{
iIndex = strTemp.indexOf('\r', iIndex);
if (iIndex != -1)
strTemp = strTemp.substring(0, iIndex) + strTemp.substring(iIndex + 1, strTemp.length());
}
strTemp = this.ta... | csn_ccr |
function getPropertyValue(obj, path, useGetter) {
// if (arguments.length < 3) {
// useGetter = false;
// }
path = path.trim();
if (path === undefined || path.length === 0) {
throw new Error("Invalid field path: '" + path + "'");
}
// if (obj === undefined || obj === null) {
... |
if (useGetter === true && m !== null) {
obj = m.call(obj);
} else {
obj = obj[p];
}
} else {
return undefined;
}
}
} else if (path === '*') {
var res = {};
for (va... | csn_ccr |
public void setSelectionType(MaterialDatePickerType selectionType) {
this.selectionType = selectionType;
switch (selectionType) {
case MONTH_DAY:
options.selectMonths = true;
break;
case YEAR_MONTH_DAY:
options.selectYears = yearsTo... | break;
case YEAR:
options.selectYears = yearsToDisplay;
options.selectMonths = false;
break;
}
} | csn_ccr |
// CloseDevTools closes the dev tools | func (w *Window) CloseDevTools() (err error) {
if err = w.isActionable(); err != nil {
return
}
return w.w.write(Event{Name: EventNameWindowCmdWebContentsCloseDevTools, TargetID: w.id})
} | csn |
public static String encodeECC200(String codewords, SymbolInfo symbolInfo) {
if (codewords.length() != symbolInfo.getDataCapacity()) {
throw new IllegalArgumentException(
"The number of codewords does not match the selected symbol");
}
StringBuilder sb = new StringBuilder(symbolInfo.getDataC... |
for (int block = 0; block < blockCount; block++) {
StringBuilder temp = new StringBuilder(dataSizes[block]);
for (int d = block; d < symbolInfo.getDataCapacity(); d += blockCount) {
temp.append(codewords.charAt(d));
}
String ecc = createECCBlock(temp.toString(), errorSiz... | csn_ccr |
public static ImageRequestBuilder fromRequest(ImageRequest imageRequest) {
return ImageRequestBuilder.newBuilderWithSource(imageRequest.getSourceUri())
.setImageDecodeOptions(imageRequest.getImageDecodeOptions())
.setBytesRange(imageRequest.getBytesRange())
.setCacheChoice(imageRequest.getCa... | .setLowestPermittedRequestLevel(imageRequest.getLowestPermittedRequestLevel())
.setPostprocessor(imageRequest.getPostprocessor())
.setProgressiveRenderingEnabled(imageRequest.getProgressiveRenderingEnabled())
.setRequestPriority(imageRequest.getPriority())
.setResizeOptions(imageR... | csn_ccr |
Populate data from this array as if it was in local file data.
@param data an array of bytes
@param offset the start offset
@param length the number of bytes in the array from offset
@since 1.1
@throws ZipException on error | public void parseFromLocalFileData(byte[] data, int offset, int length)
throws ZipException {
long givenChecksum = ZipLong.getValue(data, offset);
byte[] tmp = new byte[length - WORD];
System.arraycopy(data, offset + WORD, tmp, 0, length - WORD);
crc.reset();
crc.update(tmp);
long realChe... | csn |
private function okToDelete(PhingFile $d)
{
$list = $d->listDir();
if ($list === null) {
return false; // maybe io error?
}
foreach ($list as $s) {
| $f = new PhingFile($d, $s);
if ($f->isDirectory()) {
if (!$this->okToDelete($f)) {
return false;
}
} else {
// found a file
return false;
}
}
return true;
} | csn_ccr |
def update_feature_value(host_name, client_name, client_pass, user_twitter_id, feature_name, feature_score):
"""
Updates a single topic score, for a single user.
Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted.
- client_name: The PServer ... | request.
request = construct_request(model_type="pers",
client_name=client_name,
client_pass=client_pass,
command="setusr",
values=values)
# Send request.
send_request(host_name,... | csn_ccr |
function normalizeOptions(options, include) {
_.forEach(options, function (v,k) {
if(!_.contains(include, k))
| delete options[k];
});
return options;
} | csn_ccr |
"I don't have any fancy quotes." - vijju123
Chef was reading some quotes by great people. Now, he is interested in classifying all the fancy quotes he knows. He thinks that all fancy quotes which contain the word "not" are Real Fancy; quotes that do not contain it are regularly fancy.
You are given some quotes. For eac... | # cook your dish here
import re
t=int(input())
while(t>0):
s=list(input().split(' '))
if("not" in s):
print("Real Fancy")
else:
print("regularly fancy")
t=t-1 | apps |
public function get_admin_config() {
if ($this->adminconfig) {
return $this->adminconfig;
}
| $this->adminconfig = get_config('assign');
return $this->adminconfig;
} | csn_ccr |
public static function get($refundId)
{
$api = new Api\Info();
$api->setRefundId($refundId);
$result = $api->doRequest();
| $result['refundId'] = $refundId;
return new Result\Refund($result);
} | csn_ccr |
def on(cls, event, handler_func=None):
"""
Registers a handler function whenever an instance of the model
emits the given event.
This method can either called directly, passing a function reference:
MyModel.on('did_save', my_function)
...or as a decorator of the fu... | """
if handler_func:
cls.handler_registrar().register(event, handler_func)
return
def register(fn):
cls.handler_registrar().register(event, fn)
return fn
return register | csn_ccr |
2) Returns CredentialEmailModel
@param Request $request
@return CredentialEmailModel | public function getCredentials(Request $request)
{
$post = json_decode($request->getContent(), true);
return new CredentialEmailModel($post[self::EMAIL_FIELD], $post[self::PASSWORD_FIELD]);
} | csn |
// AllowMissingKeys allows a caller to specify whether they want an error if a field or map key
// cannot be located, or simply an empty result. The receiver is returned for chaining. | func (j *JSONPath) AllowMissingKeys(allow bool) *JSONPath {
j.allowMissingKeys = allow
return j
} | csn |
channel user prefixes | def _parse_PREFIX(value):
"channel user prefixes"
channel_modes, channel_chars = value.split(')')
channel_modes = channel_modes[1:]
return collections.OrderedDict(zip(channel_chars, channel_modes)) | csn |
Sets and prepares the rows. The rows are stored in groups in a dictionary. A group is a list of rows with the
same pseudo key. The key in the dictionary is a tuple with the values of the pseudo key.
:param list[dict] rows: The rows | def prepare_data(self, rows):
"""
Sets and prepares the rows. The rows are stored in groups in a dictionary. A group is a list of rows with the
same pseudo key. The key in the dictionary is a tuple with the values of the pseudo key.
:param list[dict] rows: The rows
"""
s... | csn |
func pushCommit(ref *github.Reference, tree *github.Tree) (err error) {
// Get the parent commit to attach the commit to.
parent, _, err := client.Repositories.GetCommit(ctx, *sourceOwner, *sourceRepo, *ref.Object.SHA)
if err != nil {
return err
}
// This is not always populated, but is needed.
parent.Commit.SH... | tree.
date := time.Now()
author := &github.CommitAuthor{Date: &date, Name: authorName, Email: authorEmail}
commit := &github.Commit{Author: author, Message: commitMessage, Tree: tree, Parents: []github.Commit{*parent.Commit}}
newCommit, _, err := client.Git.CreateCommit(ctx, *sourceOwner, *sourceRepo, commit)
if ... | csn_ccr |
function createErrorHandler(opts, transform) {
return err => {
if ('emit' === opts.error) {
transform.emit('error', err)
}
else if ('function' === typeof opts.error) {
opts.error(err)
}
else {
const message = colors.red(err.name) + '\n' + err.toString()
| .replace(/(ParseError.*)/, colors.red('$1'))
log(message)
}
transform.emit('end')
if (opts.callback) {
opts.callback(through2())
}
}
} | csn_ccr |
// UpdateIngressStatus updates an Ingress with a provided status. | func (c *clientWrapper) UpdateIngressStatus(namespace, name, ip, hostname string) error {
if !c.isWatchedNamespace(namespace) {
return fmt.Errorf("failed to get ingress %s/%s: namespace is not within watched namespaces", namespace, name)
}
ing, err := c.factoriesKube[c.lookupNamespace(namespace)].Extensions().V1b... | csn |
// LogURIs returns the URIs of all logs currently in the logCache | func (c *logCache) LogURIs() []string {
c.RLock()
defer c.RUnlock()
var uris []string
for _, l := range c.logs {
uris = append(uris, l.uri)
}
return uris
} | csn |
Compute a set of summary metrics from the input value expression
Parameters
----------
arg : value expression
exact_nunique : boolean, default False
Compute the exact number of distinct values (slower)
prefix : string, default None
String prefix for metric names
Returns
-------... | def _generic_summary(arg, exact_nunique=False, prefix=None):
"""
Compute a set of summary metrics from the input value expression
Parameters
----------
arg : value expression
exact_nunique : boolean, default False
Compute the exact number of distinct values (slower)
prefix : string, d... | csn |
public function prevUrl()
{
$prev = $this->current() - | 1;
return ($prev > 0 && $prev < $this->pages()) ? $this->parseUrl($prev) : "";
} | csn_ccr |
func (b byTime) Less(i, j int) bool {
if b[i].Next.IsZero() {
return false
}
if b[j].Next.IsZero() { |
return true
}
return b[i].Next.Before(b[j].Next)
} | csn_ccr |
function drawTurnInfo(pdata) {
var my_game = $.cookie("game");
var my_player = pdata[$.cookie("player")];
$(PIECES).empty();
$(ADDPIECE).show();
// allow player to end his turn
if (my_player.has_turn) {
$(ENDTURN).removeAttr('disabled');
$(TURN).html("It's your turn! You have "... | getPlayers();
/* Typically we let HAVETURN get updated from the server
* in onGetPlayers(), but if there is only one player this
* doesn't work very well (the player has to refresh manually).
* So we force it to false here in this special c... | csn_ccr |
func Col(text string, colType ColumnType) Column {
return | Column{Text: text, Type: colType}
} | csn_ccr |
@SuppressWarnings("unchecked")
public <T> T convertElement(ConversionContext context, Object source,
TypeReference<T> destinationType) throws ConverterException {
| return (T) elementConverter.convert(context, source, destinationType);
} | csn_ccr |
Call `load` method with `centerings` filtered to keys in `self.filter_`. | def load(self, df, centerings):
"""Call `load` method with `centerings` filtered to keys in `self.filter_`."""
return super().load(
df,
{key: value
for key, value in centerings.items()
if key in self.filter_}
) | csn |
def register_on_medium_changed(self, callback):
"""Set the callback function to consume on medium changed events.
Callback receives a IMediumChangedEvent | object.
Returns the callback_id
"""
event_type = library.VBoxEventType.on_medium_changed
return self.event_source.register_callback(callback, event_type) | csn_ccr |
python compress leading whitespace | def clean_whitespace(string, compact=False):
"""Return string with compressed whitespace."""
for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'),
('\t', ' '), (' ', ' ')):
string = string.replace(a, b)
if compact:
for a, b in (('\n', ' '), ('[ ', '['),
... | cosqa |
Serialize additionalProperties to JSON
@param JsonSerializationVisitor $visitor Visitor
@param SchemaAdditionalProperties $additionalProperties properties
@param array $type Type
@param Context $context Context
@return string|null | public function serializeSchemaAdditionalPropertiesToJson(
JsonSerializationVisitor $visitor,
SchemaAdditionalProperties $additionalProperties,
array $type,
Context $context
) {
$properties = $additionalProperties->getProperties();
// case for v4 schema
if (... | csn |
// Release implements util.Releaser.
// It also close the file if it is an io.Closer. | func (r *Reader) Release() {
r.mu.Lock()
defer r.mu.Unlock()
if closer, ok := r.reader.(io.Closer); ok {
closer.Close()
}
if r.indexBlock != nil {
r.indexBlock.Release()
r.indexBlock = nil
}
if r.filterBlock != nil {
r.filterBlock.Release()
r.filterBlock = nil
}
r.reader = nil
r.cache = nil
r.bpoo... | csn |
public static void store(Explanation<OWLAxiom> explanation, OutputStream os) throws IOException {
try {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.createOntology(explanation.getAxioms());
OWLDataFactory df = manager.getO... | BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(os);
OWLXMLDocumentFormat justificationOntologyFormat = new OWLXMLDocumentFormat();
manager.saveOntology(ontology, justificationOntologyFormat, bufferedOutputStream);
}
catch (OWLOntologyStorageExcept... | csn_ccr |
def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
"""Helper for _issubclass_Union.
"""
# this function is partly based on code from typing module 3.5.2.2
super_args = get_Union_params(superclass)
if... | return True
if subclass.__constraints__:
return _issubclass(Union[subclass.__constraints__],
superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check)
return False
else:
return any(_i... | csn_ccr |
Get a ResponsiveImageClass by it's name
@param string $classname
@return ResponsiveImageClass | public function getClass($classname)
{
if ((string) $classname == '' || !array_key_exists($classname, $this->classes)) {
throw new ImageClassNotRegisteredException($classname);
}
return $this->classes[$classname];
} | csn |
An helper method to build and throw a SQL Exception when a property cannot be set.
@param cause the cause
@param theType the type of the property
@param value the value of the property
@throws SQLException the SQL Exception | public static void throwSQLException(Exception cause, String theType, String value)
throws SQLException {
throw new SQLException("Invalid " + theType + " value: " + value, cause);
} | csn |
Your company, [Congo Pizza](http://interesting-africa-facts.com/Africa-Landforms/Congo-Rainforest-Facts.html), is the second-largest online frozen pizza retailer. You own a number of international warehouses that you use to store your frozen pizzas, and you need to figure out how many crates of pizzas you can store at ... | def box_capacity(length, width, height):
return (length * 12 // 16) * (width * 12 // 16) * (height * 12 // 16)
| apps |
Synchronize between the file in the file system and the field record | def sync(self, force=None):
"""Synchronize between the file in the file system and the field record"""
try:
if force:
sd = force
else:
sd = self.sync_dir()
if sd == self.SYNC_DIR.FILE_TO_RECORD:
if force and not self.... | csn |
protected function getDividend($row)
{
$currentValue = $row->getColumn($this->columnValueToRead);
// if the site this is for doesn't support ecommerce & this is for the revenue_evolution column,
// we don't add the new column
if ($currentValue === false
&& $this->isReven... | $this->getPastRowFromCurrent($row);
if ($pastRow) {
$pastValue = $pastRow->getColumn($this->columnValueToRead);
} else {
$pastValue = 0;
}
return $currentValue - $pastValue;
} | csn_ccr |
computing distance matrix in python | def get_distance_matrix(x):
"""Get distance matrix given a matrix. Used in testing."""
square = nd.sum(x ** 2.0, axis=1, keepdims=True)
distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))
return nd.sqrt(distance_square) | cosqa |
Loads all data for zones that belong to provided layout. | public function loadLayoutZonesData(Layout $layout): array
{
$query = $this->getZoneSelectQuery();
$query->where(
$query->expr()->eq('layout_id', ':layout_id')
)
->setParameter('layout_id', $layout->id, Type::INTEGER)
->orderBy('identifier', 'ASC');
$this... | csn |
func (c *Chunk) NumRows() int {
if c.NumCols() == 0 {
| return c.numVirtualRows
}
return c.columns[0].length
} | csn_ccr |
int size() {
int res = m_subscriptions.size();
for (TreeNode child : m_children) {
res | += child.size();
}
return res;
} | csn_ccr |
func (_class PBDClass) GetSR(sessionID SessionRef, self PBDRef) (_retval SRRef, _err error) {
_method := "PBD.get_SR"
_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
if | _err != nil {
return
}
_selfArg, _err := convertPBDRefToXen(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 = convertSRRefToGo(_method + " -> ", _result.Value)
return
... | csn_ccr |
Asks for a single choice out of multiple items.
Given those items, and a prompt to ask the user with | def get_choice(prompt, choices):
"""
Asks for a single choice out of multiple items.
Given those items, and a prompt to ask the user with
"""
print()
checker = []
for offset, choice in enumerate(choices):
number = offset + 1
print("\t{}): '{}'\n".format(number, choice))
... | csn |
func (c *Client) FromString(targetPath, content string) (resource.Resource, error) {
return c.rs.ResourceCache.GetOrCreate(resources.CACHE_OTHER, targetPath, func() (resource.Resource, error) {
return c.rs.NewForFs(
c.rs.FileCaches.AssetsCache().Fs,
resources.ResourceSourceDescriptor{
LazyPublish: true,
... | OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) {
return hugio.NewReadSeekerNoOpCloserFromString(content), nil
},
RelTargetFilename: filepath.Clean(targetPath)})
})
} | csn_ccr |
private function selectRestVersion($channelXml, $supportedVersions)
{
$channelXml->registerXPathNamespace('ns', self::CHANNEL_NS);
foreach ($supportedVersions as $version) {
$xpathTest = "ns:servers/ns:primary/ns:rest/ns:baseurl[@type='{$version}']";
$testResult = $channelXm... | if (count($testResult) > 0) {
return array('version' => $version, 'baseUrl' => (string) $testResult[0]);
}
}
return null;
} | csn_ccr |
Runs Sonar.
@throws IOException
@return the json file containing the results. | public File run() throws IOException {
Map<String, String> props = loadBaseProperties();
setAdditionalProperties(props);
sonarEmbeddedScanner.addGlobalProperties(props);
log.info("Sonar configuration: {}", props.toString());
sonarEmbeddedScanner.start();
sonarEmbeddedS... | csn |
Calculate reasonable canvas height and width for tree given N tips | def get_dims_from_tree_size(self):
"Calculate reasonable canvas height and width for tree given N tips"
ntips = len(self.ttree)
if self.style.orient in ("right", "left"):
# height is long tip-wise dimension
if not self.style.height:
self.style.height = ma... | csn |
Set the hotspots that define the choices that are to be ordered by the candidate.
@param \qtism\data\content\interactions\HotspotChoiceCollection $hotspotChoices A collection of HotspotChoice objects.
@throws \InvalidArgumentException If the given $hotspotChoices collection is empty. | public function setHotspotChoices(HotspotChoiceCollection $hotspotChoices)
{
if (count($hotspotChoices) > 0) {
$this->hotspotChoices = $hotspotChoices;
} else {
$msg = "A GraphicOrderInteraction must contain at least 1 hotspotChoice object. None given.";
throw new... | csn |
def add_color(self, name, model, description):
r"""Add a color that can be used throughout the document.
Args
----
name: str
Name to set for the color
model: str
The color model to use when defining the color
description: str
The value... | self.color = True
self.preamble.append(Command("definecolor", arguments=[name,
model,
description])) | csn_ccr |
def create(self, name, url, description=None, extra=None, is_public=None,
is_protected=None):
"""Create a Job Binary.
:param dict extra: authentication info needed for some job binaries,
containing the keys `user` and `password` for job binary in Swift
or the keys... | name,
"url": url
}
self._copy_if_defined(data, description=description, extra=extra,
is_public=is_public, is_protected=is_protected)
return self._create('/job-binaries', data, 'job_binary') | csn_ccr |
Explain the libxml errors encountered.
@param string $filename The name of the file to which the errors are related.
@return string[] | public static function explainLibXmlErrors($filename = '')
{
$errors = libxml_get_errors();
$result = array();
if (empty($errors)) {
$result[] = 'Unknown libxml error';
} else {
foreach ($errors as $error) {
switch ($error->level) {
... | csn |
matrix csv write python | def csv_matrix_print(classes, table):
"""
Return matrix as csv data.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return:
"""
result = ""
classes.sort()
for i in classes:
for j in classes:
result += str(table[i][j]... | cosqa |
Classes annotated with DBObject gain persistence methods. | def DBObject(table_name, versioning=VersioningTypes.NONE):
"""Classes annotated with DBObject gain persistence methods."""
def wrapped(cls):
field_names = set()
all_fields = []
for name in dir(cls):
fld = getattr(cls, name)
if fld and isinstance(fld, Field):
... | csn |
public static <T extends Field> ImmutableMap<String, T> getFieldsForType(
Descriptor descriptor, Set<FieldDescriptor> extensions, Factory<T> factory) {
ImmutableMap.Builder<String, T> fields = ImmutableMap.builder();
for (FieldDescriptor fieldDescriptor : descriptor.getFields()) {
if (ProtoUtils.sho... | fields.put(fieldName, Iterables.getOnlyElement(ambiguousFields));
} else {
T value = factory.createAmbiguousFieldSet(ambiguousFields);
logger.severe(
"Proto "
+ descriptor.getFullName()
+ " has multiple extensions with the name \""
+... | csn_ccr |
Set a default Acl of this group.
@param int Acl ID. | public function setDefaultAcl($aclId) {
// set no default to siblings
Database::run('UPDATE `acl` SET `is_default` = 0 WHERE `group_id` = ? AND `id` <> ?', [$this->id, $aclId]);
// set default to this
Database::run('UPDATE `acl` SET `is_default` = 1 WHERE `group_id` = ? AND `id` = ?', [$this->id, $aclId]);
... | csn |
Handle log level request
=== Parameters
options(Hash):: Command line options
=== Return
true:: Always return true | def manage(options)
# Initialize configuration directory setting
AgentConfig.cfg_dir = options[:cfg_dir]
# Determine command
level = options[:level]
command = { :name => (level ? 'set_log_level' : 'get_log_level') }
command[:level] = level.to_sym if level
# Determine candidat... | csn |
func Pty() (*os.File, *os.File, error) {
ptm, err := open_pty_master()
if err != nil {
return nil, nil, err
}
sname, err := Ptsname(ptm)
if err != nil {
return nil, nil, err
}
err = grantpt(ptm)
if err != nil {
return nil, nil, err
}
err = unlockpt(ptm)
if err != nil {
return nil, nil, err
} |
pts, err := open_device(sname)
if err != nil {
return nil, nil, err
}
return os.NewFile(uintptr(ptm), "ptm"), os.NewFile(uintptr(pts), sname), nil
} | csn_ccr |
In computer science and discrete mathematics, an [inversion](https://en.wikipedia.org/wiki/Inversion_%28discrete_mathematics%29) is a pair of places in a sequence where the elements in these places are out of their natural order. So, if we use ascending order for a group of numbers, then an inversion is when larger num... | def count_inversion(nums):
return sum(a > b for i, a in enumerate(nums) for b in nums[i + 1:])
| apps |
def watch_command(context, backend, config, poll):
"""
Watch for change on your Sass project sources then compile them to CSS.
Watched events are:
\b
* Create: when a new source file is created;
* Change: when a source is changed;
* Delete: when a source is deleted;
* Move: When a sour... | 'ignore_patterns': ['*.part'],
'ignore_directories': False,
'case_sensitive': True,
}
# Init inspector instance shared through all handlers
inspector = ScssInspector()
if not poll:
logger.debug(u"Using Watchdog native platform observer")
observer = Observer()
e... | csn_ccr |
Doctrine table data loader
@param int $page
@param int $limit
@return SimpleTableData | public function dataLoader($page, $limit)
{
if ($limit > 0) {
$this->getQueryBuilder()->setMaxResults($limit);
$this->getQueryBuilder()->setFirstResult(($page - 1) * $limit);
}
$paginator = new Paginator($this->getQueryBuilder());
$tableData = new SimpleTable... | csn |
func (bb *Builder) SetSigner(signer blob.Ref) | *Builder {
bb.m["camliSigner"] = signer.String()
return bb
} | csn_ccr |
def convert_from_gps_time(gps_time, gps_week=None):
""" Convert gps time in ticks to standard time. """
converted_gps_time = None
gps_timestamp = float(gps_time)
if gps_week != None:
# image date
converted_gps_time = GPS_START + datetime.timedelta(seconds=int(gps_week) *
... | gps_time_as_tai = gps_time_as_gps + \
datetime.timedelta(seconds=19)
tai_epoch_as_tai = datetime.datetime(1970, 1, 1, 0, 0, 10)
# by definition
tai_timestamp = (gps_time_as_tai - tai_epoch_as_tai).total_seconds()
converted_gps_time = (
datetime.datetime.utcfro... | csn_ccr |
public function publish(Message $message): ChannelInformation
{
$response = $this->client->post(
new Request(
$this->channelUrl,
[
'Accept' => 'application/json',
'Content-Type' => $message->contentType()... | throw new NchanException(
sprintf(
'Unable to publish to channel. Maybe the channel does not exists. HTTP status code was %s.',
$response->statusCode()
)
);
}
return ChannelInformation::fromJson($response->b... | csn_ccr |
Given a 2MASS position, look up the epoch when it was observed.
This function uses the CDS Vizier web service to look up information in
the 2MASS point source database. Arguments are:
tmra
The source's J2000 right ascension, in radians.
tmdec
The source's J2000 declination, in radians.
... | def get_2mass_epoch (tmra, tmdec, debug=False):
"""Given a 2MASS position, look up the epoch when it was observed.
This function uses the CDS Vizier web service to look up information in
the 2MASS point source database. Arguments are:
tmra
The source's J2000 right ascension, in radians.
tmde... | csn |
Returns all the database columns in SHOW COLUMN format
@return array | public function columns()
{
if (!isset($this->_columns)) {
$this->_columns = array();
foreach ($this->_connection->execute("SHOW COLUMNS FROM ".$this->_name->quoted()) as $c) {
$column = $c['Field'];
unset($c['Field']);
$this->_columns... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.