query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Runs the thread.
Args:
self (ThreadReturn): the ``ThreadReturn`` instance
Returns:
``None`` | def run(self):
"""Runs the thread.
Args:
self (ThreadReturn): the ``ThreadReturn`` instance
Returns:
``None``
"""
target = getattr(self, '_Thread__target', getattr(self, '_target', None))
args = getattr(self, '_Thread__args', getattr(self, '_args', None))
kwargs = getattr(self, '_Thread__kwargs', getattr(self, '_kwargs', None))
if target is not None:
self._return = target(*args, **kwargs)
return None | csn |
func (p *PhysicalProperty) Clone() *PhysicalProperty {
prop := &PhysicalProperty{
Items: p.Items,
TaskTp: | p.TaskTp,
ExpectedCnt: p.ExpectedCnt,
}
return prop
} | csn_ccr |
update figures and statistics windows with a new selection of specimen | def update_selection(self):
"""
update figures and statistics windows with a new selection of specimen
"""
# clear all boxes
self.clear_boxes()
self.draw_figure(self.s)
# update temperature list
if self.Data[self.s]['T_or_MW'] == "T":
self.temperatures = np.array(self.Data[self.s]['t_Arai']) - 273.
else:
self.temperatures = np.array(self.Data[self.s]['t_Arai'])
self.T_list = ["%.0f" % T for T in self.temperatures]
self.tmin_box.SetItems(self.T_list)
self.tmax_box.SetItems(self.T_list)
self.tmin_box.SetValue("")
self.tmax_box.SetValue("")
self.Blab_window.SetValue(
"%.0f" % (float(self.Data[self.s]['pars']['lab_dc_field']) * 1e6))
if "saved" in self.Data[self.s]['pars']:
self.pars = self.Data[self.s]['pars']
self.update_GUI_with_new_interpretation()
self.Add_text(self.s)
self.write_sample_box() | csn |
Displays whether 'restart on freeze' is on or off if supported
:return: A string value representing the "restart on freeze" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_restart_freeze | def get_restart_freeze():
'''
Displays whether 'restart on freeze' is on or off if supported
:return: A string value representing the "restart on freeze" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_restart_freeze
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getrestartfreeze')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | csn |
Tries to guess extension for a mimetype.
@param amimetype: name of a mimetype
@time amimetype: string
@return: the extension
@rtype: string | def guess_extension(amimetype, normalize=False):
"""
Tries to guess extension for a mimetype.
@param amimetype: name of a mimetype
@time amimetype: string
@return: the extension
@rtype: string
"""
ext = _mimes.guess_extension(amimetype)
if ext and normalize:
# Normalize some common magic mis-interpreation
ext = {'.asc': '.txt', '.obj': '.bin'}.get(ext, ext)
from invenio.legacy.bibdocfile.api_normalizer import normalize_format
return normalize_format(ext)
return ext | csn |
In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well.
At the end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city's skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example.
What is the maximum total sum that the height of the buildings can be increased?
Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation:
The grid is:
[ [3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0] ]
The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]
The grid after increasing the height of buildings without affecting skylines is:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
Notes:
1 < grid.length = grid[0].length <= 50.
All heights grid[i][j] are in the range [0, 100].
All buildings in grid[i][j] occupy the entire grid cell: that is, they are a 1 x 1 x grid[i][j] rectangular prism. | class Solution:
def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
# Pad with inf to make implementation easier
INF = -10_000
n = len(grid)
total = 0
max_rows = [max(row, default=INF) for row in grid]
# Transpose the grid to make max less cumbersome
max_cols = [max(col, default=INF) for col in zip(*grid)]
for i, best_row in enumerate(max_rows):
for j, best_col in enumerate(max_cols):
new_height = min(best_row, best_col)
total += new_height - grid[i][j]
return total
| apps |
private String decodeAndEscapeSelectors(FacesContext context, UIComponent component, String selector) {
selector = ExpressionResolver.getComponentIDs(context, component, selector); |
selector = BsfUtils.escapeJQuerySpecialCharsInSelector(selector);
return selector;
} | csn_ccr |
public function twitter($entity)
{
$twitterName = Configure::read('Settings.Cms.SEO.Social.twitter_username');
if ($twitterName !== null) {
$twitterName = '@' . $twitterName;
}
$attributes = [
'twitter:card' => 'summary',
'twitter:title' => $this->_getTitle($entity),
'twitter:description' => $entity->attributes['og:description'] ?? $entity->meta_description,
'twitter:image' => $this->_getSocialImage($entity),
| 'twitter:site' => $twitterName,
'twitter:creator' => $twitterName,
];
$out = '';
foreach ($attributes as $property => $content) {
$out .= $this->_render(self::ATTR_NAME, $property, $content);
}
return $out;
} | csn_ccr |
remove leading zeros python | def __remove_trailing_zeros(self, collection):
"""Removes trailing zeroes from indexable collection of numbers"""
index = len(collection) - 1
while index >= 0 and collection[index] == 0:
index -= 1
return collection[:index + 1] | cosqa |
Truncate a collection's data
@return Collection | public function truncate() {
$this->_map = [];
$this->_data = [];
$this->_models = [];
$this->_pointer = 0;
return $this;
} | csn |
Basic parser to deal with date format of the Kp file. | def _parse(yr, mo, day):
"""
Basic parser to deal with date format of the Kp file.
"""
yr = '20'+yr
yr = int(yr)
mo = int(mo)
day = int(day)
return pds.datetime(yr, mo, day) | csn |
Checks if results in cache will satisfy the source before parsing.
@param Event $event Current event emitted by the manager (Reflect class)
@return void | public function onReflectProgress(GenericEvent $event)
{
if ($response = $this->storage->fetch($event)) {
++$this->stats[self::STATS_HITS];
$this->hashUserData = sha1(serialize($response));
$event['notModified'] = $response;
} else {
$this->hashUserData = null;
}
} | csn |
def json_dumps(cls, obj, **kwargs):
"""
A rewrap of json.dumps done for one reason - to inject a custom `cls` kwarg
:param obj:
:param kwargs:
:return:
:rtype: str
| """
if 'cls' not in kwargs:
kwargs['cls'] = cls.json_encoder
return json.dumps(obj, **kwargs) | csn_ccr |
Write a function which outputs the positions of matching bracket pairs. The output should be a dictionary with keys the positions of the open brackets '(' and values the corresponding positions of the closing brackets ')'.
For example: input = "(first)and(second)" should return {0:6, 10:17}
If brackets cannot be paired or if the order is invalid (e.g. ')(') return False. In this kata we care only about the positions of round brackets '()', other types of brackets should be ignored. | def bracket_pairs(string):
brackets = {}
open_brackets = []
for i, c in enumerate(string):
if c == '(':
open_brackets.append(i)
elif c == ')':
if not open_brackets:
return False
brackets[open_brackets.pop()] = i
return False if open_brackets else brackets
| apps |
Get youtube ID
@param {string} url
@returns {string} video id | function getYoutubeID(url) {
let videoID = '';
url = url.replace(/(>|<)/gi, '').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
if (url[2] !== undefined) {
videoID = url[2].split(/[^0-9a-z_\-]/i);
videoID = videoID[0];
} else {
videoID = url;
}
return videoID;
} | csn |
// Base64 reads string from config file then decode using base64 | func (r *Reader) Base64(name string) []byte {
return r.Base64Default(name, []byte{})
} | csn |
protected int interpretInfo(LineParser lp, MessageMgr mm){
String fileName = this.getFileName(lp);
String content = this.getContent(fileName, mm);
if(content==null){
return 1;
}
String[] lines = StringUtils.split(content, "\n");
String info = null;
for(String s : lines){
if(s.startsWith("//**")){
info = StringUtils.substringAfter(s, "//**");
break;
}
}
if(info!=null){
| mm.report(MessageMgr.createInfoMessage("script {} - info: {}", new Object[]{fileName, info}));
// Skb_Console.conInfo("{}: script {} - info: {}", new Object[]{shell.getPromptName(), fileName, info});
}
return 0;
} | csn_ccr |
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).
If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
-----Input-----
The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the elements of the set.
-----Output-----
Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).
-----Examples-----
Input
2
2 3
Output
Alice
Input
2
5 3
Output
Alice
Input
3
5 6 7
Output
Bob
-----Note-----
Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. | def gcd(a, b):
while b > 0:
a, b = b, a % b
return a
n = int(input())
A = list(map(int, input().split()))
GCD = A[0]
for x in A[1:]:
GCD = gcd(GCD, x)
num = max(A) // GCD - n
if num % 2 == 0:
print("Bob")
else:
print("Alice")
| apps |
def _pruning_base(self, axis=None, hs_dims=None):
"""Gets margin if across CAT dimension. Gets counts if across items.
Categorical variables are pruned based on their marginal values. If the
marginal is a 0 or a NaN, the corresponding row/column is pruned. In
case of a subvars (items) dimension, we only prune if all the counts
of the corresponding row/column are zero.
"""
if not self._is_axis_allowed(axis):
# In case we encountered axis that would go across items dimension,
# we need to return at least some result, to prevent explicitly
# checking for this condition, wherever self._margin is used
| return self.as_array(weighted=False, include_transforms_for_dims=hs_dims)
# In case of allowed axis, just return the normal API margin. This call
# would throw an exception when directly invoked with bad axis. This is
# intended, because we want to be as explicit as possible. Margins
# across items are not allowed.
return self.margin(
axis=axis, weighted=False, include_transforms_for_dims=hs_dims
) | csn_ccr |
def _search_for_files(parts):
""" Given a list of parts, return all of the nested file parts. """
file_parts = []
for part in parts:
if isinstance(part, list):
| file_parts.extend(_search_for_files(part))
elif isinstance(part, FileToken):
file_parts.append(part)
return file_parts | csn_ccr |
Renders a hidden form field containing the technical identity of the given object.
@param object $object Object to create the identity field for
@param string $name Name
@return string A hidden field containing the Identity (UUID in Flow) of the given object or NULL if the object is unknown to the persistence framework
@see \Neos\Flow\Mvc\Controller\Argument::setValue() | protected function renderHiddenIdentityField($object, $name)
{
if (!is_object($object) || $this->persistenceManager->isNewObject($object)) {
return '';
}
$identifier = $this->persistenceManager->getIdentifierByObject($object);
if ($identifier === null) {
return chr(10) . '<!-- Object of type ' . get_class($object) . ' is without identity -->' . chr(10);
}
$name = $this->prefixFieldName($name) . '[__identity]';
$this->registerFieldNameForFormTokenGeneration($name);
return chr(10) . '<input type="hidden" name="' . $name . '" value="' . $identifier . '" />' . chr(10);
} | csn |
how to turn bytes string into bytes in python3 | def to_bytes(s, encoding="utf-8"):
"""Convert a string to bytes."""
if isinstance(s, six.binary_type):
return s
if six.PY3:
return bytes(s, encoding)
return s.encode(encoding) | cosqa |
func (t *Template) GetAWSElasticLoadBalancingV2ListenerCertificateWithName(name string) (*resources.AWSElasticLoadBalancingV2ListenerCertificate, error) {
if untyped, ok := t.Resources[name]; ok | {
switch resource := untyped.(type) {
case *resources.AWSElasticLoadBalancingV2ListenerCertificate:
return resource, nil
}
}
return nil, fmt.Errorf("resource %q of type AWSElasticLoadBalancingV2ListenerCertificate not found", name)
} | csn_ccr |
Outputs the mail to a text file according to RFC 4155.
@param \Swift_Mime_SimpleMessage $message The message to send
@param array &$failedRecipients Failed recipients (no failures in this transport)
@return int | public function send(\Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
{
$message->generateId();
// Create a mbox-like header
$mboxFrom = $this->getReversePath($message);
$mboxDate = strftime('%c', $message->getDate()->getTimestamp());
$messageString = sprintf('From %s %s', $mboxFrom, $mboxDate) . chr(10);
// Add the complete mail inclusive headers
$messageString .= $message->toString();
$messageString .= chr(10) . chr(10);
// Write the mbox file
file_put_contents($this->mboxPathAndFilename, $messageString, FILE_APPEND | LOCK_EX);
// Return every recipient as "delivered"
return count((array)$message->getTo()) + count((array)$message->getCc()) + count((array)$message->getBcc());
} | csn |
def _consolidate_classpath(self, targets, classpath_products):
"""Convert loose directories in classpath_products into jars. """
# TODO: find a way to not process classpath entries for valid VTs.
# NB: It is very expensive to call to get entries for each target one at a time.
# For performance reasons we look them all up at once.
entries_map = defaultdict(list)
for (cp, target) in classpath_products.get_product_target_mappings_for_targets(targets, True):
entries_map[target].append(cp)
with self.invalidated(targets=targets, invalidate_dependents=True) as invalidation:
for vt in invalidation.all_vts:
entries = entries_map.get(vt.target, [])
for index, (conf, entry) in enumerate(entries):
if ClasspathUtil.is_dir(entry.path):
jarpath = os.path.join(vt.results_dir, 'output-{}.jar'.format(index))
| # Regenerate artifact for invalid vts.
if not vt.valid:
with self.open_jar(jarpath, overwrite=True, compressed=False) as jar:
jar.write(entry.path)
# Replace directory classpath entry with its jarpath.
classpath_products.remove_for_target(vt.target, [(conf, entry.path)])
classpath_products.add_for_target(vt.target, [(conf, jarpath)]) | csn_ccr |
Returns model table name
@return string | public function getTableName()
{
if (is_null($this->_tableName)) {
$this->_tableName = $this->getDescriptor()->getEntity()
->getTableName();
}
return $this->_tableName;
} | csn |
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
GetField fields = in.readFields();
beginDefaultContext = fields.get(BEGIN_DEFAULT, true);
// Note that further processing is required | in JEEMetadataContextProviderImpl.deserializeThreadContext
// in order to re-establish the thread context based on the metadata identity if not defaulted.
} | csn_ccr |
Generate a linear lookup table.
:param nbits: int
Number of bits to represent a quantized weight value
:param wp: numpy.array
Weight blob to be quantized
Returns
-------
lookup_table: numpy.array
Lookup table of shape (2^nbits, )
qw: numpy.array
Decomposed bit stream as a list of 0/1s of length (len(arr) * 8) | def _get_linear_lookup_table_and_weight(nbits, wp):
"""
Generate a linear lookup table.
:param nbits: int
Number of bits to represent a quantized weight value
:param wp: numpy.array
Weight blob to be quantized
Returns
-------
lookup_table: numpy.array
Lookup table of shape (2^nbits, )
qw: numpy.array
Decomposed bit stream as a list of 0/1s of length (len(arr) * 8)
"""
w = wp.reshape(1, -1)
qw, scales, biases = _quantize_channelwise_linear(w, nbits, axis=0)
indices = _np.array(range(0, 2**nbits))
lookup_table = indices * scales[0] + biases[0]
return lookup_table, qw | csn |
// ResponseHeaders responds with a map of header values | func (h *HTTPBin) ResponseHeaders(w http.ResponseWriter, r *http.Request) {
args := r.URL.Query()
for k, vs := range args {
for _, v := range vs {
w.Header().Add(http.CanonicalHeaderKey(k), v)
}
}
body, _ := json.Marshal(args)
if contentType := w.Header().Get("Content-Type"); contentType == "" {
w.Header().Set("Content-Type", jsonContentType)
}
w.Write(body)
} | csn |
public static List<TracyEvent> getEvents() {
TracyThreadContext ctx = threadContext.get();
List<TracyEvent> events = EMPTY_TRACY_EVENT_LIST;
| if (isValidContext(ctx)) {
events = ctx.getPoppedList();
}
return events;
} | csn_ccr |
Determine if the app has custom exception handler
@return bool | public function hasCustomHandler()
{
if (!class_exists(\App\Exception\Handler::class)) {
return false;
}
if (!in_array(\Pharest\Exception\ExceptionHandler::class, class_implements(\App\Exception\Handler::class))) {
return false;
}
return true;
} | csn |
Stages the models for use by subsequent functions
@param {???} app - loopback application
@param {Array} models - instances of ModelType to populate
with data
@param {callback} cb - callback that handles the error or
successful completion | function stageModels(app, models, cb) {
logger.debug('stageModels entry');
async.forEach(models,
function(model, callback) {
app.dataSources.db.automigrate(
model.name,
function(err) {
callback(err);
}
);
},
function(err) {
logger.debug('stageModels exit');
cb(err);
}
);
} | csn |
function normalizeIdentifier(identifier) {
if (identifier === ".") {
// '.' might be referencing either the root or a locally scoped variable
// called '.'. So try for the locally scoped variable first and then
// default to the root
return "(data['.'] || data)";
}
|
return "data" + identifier.split(".").map(function(property) {
return property ? "['" + property + "']" : "";
}).join("");
} | csn_ccr |
public function slice($start_index, $end_index = NULL) {
if ($start_index < 0) {
$start_index = $this->count() + $start_index;
}
if ($end_index < 0) {
$end_index = $this->count() + $end_index;
}
$last_index = $this->count() - 1;
if ($start_index > $last_index) {
$start_index = $last_index;
}
if ($end_index !== NULL) {
if ($end_index > $last_index) {
$end_index = $last_index;
}
if ($start_index > $end_index) {
$start_index | = $end_index;
}
$length = $end_index - $start_index;
}
else {
$length = $this->count() - $start_index;
}
return new NodeCollection(array_slice($this->nodes, $start_index, $length));
} | csn_ccr |
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
Constraints:
0 <= nums.length <= 100
0 <= nums[i] <= 400 | class Solution:
def rob(self, nums: List[int]) -> int:
if not nums:
return 0
if len(nums) < 3:
return max(nums)
dp = [0] * len(nums)
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i-2] + nums[i], dp[i-1])
return max(dp) | apps |
compute manhattan distance python | def _manhattan_distance(vec_a, vec_b):
"""Return manhattan distance between two lists of numbers."""
if len(vec_a) != len(vec_b):
raise ValueError('len(vec_a) must equal len(vec_b)')
return sum(map(lambda a, b: abs(a - b), vec_a, vec_b)) | cosqa |
Send SOAP message.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request without sending
it to the web service.
* Invoke the web service operation and return its SOAP reply XML.
* Invoke the web service operation, process its results and return
the Python object representing the returned value.
@param soapenv: A SOAP envelope to send.
@type soapenv: L{Document}
@return: SOAP request, SOAP reply or a web service return value.
@rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}|
I{None} | def send(self, soapenv):
"""
Send SOAP message.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request without sending
it to the web service.
* Invoke the web service operation and return its SOAP reply XML.
* Invoke the web service operation, process its results and return
the Python object representing the returned value.
@param soapenv: A SOAP envelope to send.
@type soapenv: L{Document}
@return: SOAP request, SOAP reply or a web service return value.
@rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}|
I{None}
"""
location = self.__location()
log.debug("sending to (%s)\nmessage:\n%s", location, soapenv)
plugins = PluginContainer(self.options.plugins)
plugins.message.marshalled(envelope=soapenv.root())
if self.options.prettyxml:
soapenv = soapenv.str()
else:
soapenv = soapenv.plain()
soapenv = soapenv.encode("utf-8")
ctx = plugins.message.sending(envelope=soapenv)
soapenv = ctx.envelope
if self.options.nosend:
return RequestContext(self.process_reply, soapenv)
request = suds.transport.Request(location, soapenv)
request.headers = self.__headers()
try:
timer = metrics.Timer()
timer.start()
reply = self.options.transport.send(request)
timer.stop()
metrics.log.debug("waited %s on server reply", timer)
except suds.transport.TransportError, e:
content = e.fp and e.fp.read() or ""
return self.process_reply(content, e.httpcode, tostr(e))
return self.process_reply(reply.message, None, None) | csn |
def accuracy(current, predicted):
"""
Computes the accuracy of the TM at time-step t based on the prediction
at time-step t-1 and the current active columns at time-step t.
@param current (array) binary vector containing current active columns
@param predicted (array) binary vector containing predicted active columns
| @return acc (float) prediction accuracy of the TM at time-step t
"""
acc = 0
if np.count_nonzero(predicted) > 0:
acc = float(np.dot(current, predicted))/float(np.count_nonzero(predicted))
return acc | csn_ccr |
Returns the given child index.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.index_of(node_b)
0
>>> node_a.index_of(node_c)
1
:param child: Child node.
:type child: AbstractNode or AbstractCompositeNode or Object
:return: Child index.
:rtype: int | def index_of(self, child):
"""
Returns the given child index.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.index_of(node_b)
0
>>> node_a.index_of(node_c)
1
:param child: Child node.
:type child: AbstractNode or AbstractCompositeNode or Object
:return: Child index.
:rtype: int
"""
for i, item in enumerate(self.__children):
if child is item:
return i | csn |
func PasswordFieldFromInstance(val reflect.Value, t reflect.Type, fieldNo int, name | string) *Field {
ret := PasswordField(name)
ret.SetValue(fmt.Sprintf("%s", val.Field(fieldNo).String()))
return ret
} | csn_ccr |
Use this API to fetch csvserver_cmppolicy_binding resources of given name . | public static csvserver_cmppolicy_binding[] get(nitro_service service, String name) throws Exception{
csvserver_cmppolicy_binding obj = new csvserver_cmppolicy_binding();
obj.set_name(name);
csvserver_cmppolicy_binding response[] = (csvserver_cmppolicy_binding[]) obj.get_resources(service);
return response;
} | csn |
def _deserialize(self, data):
"""
Deserialise from JSON response data.
String items named ``*_at`` are turned into dates.
Filters out:
* attribute names in ``Meta.deserialize_skip``
:param data dict: JSON-style object with instance data.
:return: this instance
"""
if not isinstance(data, dict):
raise ValueError("Need to deserialize from a dict")
try:
skip = set(getattr(self._meta, 'deserialize_skip', []))
| except AttributeError: # _meta not available
skip = []
for key, value in data.items():
if key not in skip:
value = self._deserialize_value(key, value)
setattr(self, key, value)
return self | csn_ccr |
public function mergedWith(Metadata $additionalMetadata): self
{
$values = array_merge($this->values, $additionalMetadata->values);
| if ($values === $this->values) {
return $this;
}
return new static($values);
} | csn_ccr |
Returns a DOM representation of the payment.
@return: Element | def to_xml(self):
'''
Returns a DOM representation of the payment.
@return: Element
'''
for n, v in { "amount": self.amount, "date": self.date,
"method":self.method}.items():
if is_empty_or_none(v):
raise PaymentError("'%s' attribute cannot be empty or " \
"None." % n)
doc = Document()
root = doc.createElement("payment")
super(Payment, self).to_xml(root)
self._create_text_node(root, "amount", self.amount)
self._create_text_node(root, "method", self.method)
self._create_text_node(root, "reference", self.ref, True)
self._create_text_node(root, "date", self.date)
return root | csn |
// NewReader creates a new Reader reading from r.
// NewReader automatically reads in the ar file header, and checks it is valid. | func NewReader(r io.Reader) (*Reader, error) {
ar := &Reader{r: r}
arHeader := make([]byte, arHeaderSize)
_, err := io.ReadFull(ar.r, arHeader)
if err != nil {
return nil, err
}
if string(arHeader) != ArFileHeader {
return nil, errors.New("ar: Invalid ar file")
}
return ar, nil
} | csn |
Writes reversed integer to buffer.
@param out
Buffer
@param value
Integer to write | public static void writeReverseInt(IoBuffer out, int value) {
out.put((byte) (0xFF & value));
out.put((byte) (0xFF & (value >> 8)));
out.put((byte) (0xFF & (value >> 16)));
out.put((byte) (0xFF & (value >> 24)));
} | csn |
Reads a byte string from the gzip file at the current offset.
The function will read a byte string up to the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
bytes: data read.
Raises:
IOError: if the read failed.
OSError: if the read failed. | def read(self, size=None):
"""Reads a byte string from the gzip file at the current offset.
The function will read a byte string up to the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
bytes: data read.
Raises:
IOError: if the read failed.
OSError: if the read failed.
"""
data = b''
while ((size and len(data) < size) and
self._current_offset < self.uncompressed_data_size):
member = self._GetMemberForOffset(self._current_offset)
member_offset = self._current_offset - member.uncompressed_data_offset
data_read = member.ReadAtOffset(member_offset, size)
if data_read:
self._current_offset += len(data_read)
data = b''.join([data, data_read])
return data | csn |
Gets the html of this node, including it's own
tag.
@return string | public function outerHtml()
{
// special handling for root
if ($this->tag->name() == 'root') {
return $this->innerHtml();
}
if ( ! is_null($this->outerHtml)) {
// we already know the results.
return $this->outerHtml;
}
$return = $this->tag->makeOpeningTag();
if ($this->tag->isSelfClosing()) {
// ignore any children... there should not be any though
return $return;
}
// get the inner html
$return .= $this->innerHtml();
// add closing tag
$return .= $this->tag->makeClosingTag();
// remember the results
$this->outerHtml = $return;
return $return;
} | csn |
public function generateUuid() {
if (is_readable(self::UUID_SOURCE)) {
$uuid = trim(file_get_contents(self::UUID_SOURCE));
} elseif (function_exists('mt_rand')) {
/**
* Taken from stackoverflow answer, possibly not the fastest or
* strictly standards compliant
* @link http://stackoverflow.com/a/2040279
*/
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
| // 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
} else {
// chosen by dice roll, guaranteed to be random
$uuid = '4';
}
return $uuid;
} | csn_ccr |
Puts all the child widgets in the correct position. | def _grid_widgets(self):
"""Puts all the child widgets in the correct position."""
self._font_family_header.grid(row=0, column=1, sticky="nswe", padx=5, pady=5)
self._font_label.grid(row=1, column=1, sticky="nswe", padx=5, pady=(0, 5))
self._font_family_list.grid(row=2, rowspan=3, column=1, sticky="nswe", padx=5, pady=(0, 5))
self._font_properties_header.grid(row=0, column=2, sticky="nswe", padx=5, pady=5)
self._font_properties_frame.grid(row=1, rowspan=2, column=2, sticky="we", padx=5, pady=5)
self._font_size_header.grid(row=3, column=2, sticky="we", padx=5, pady=5)
self._size_dropdown.grid(row=4, column=2, sticky="we", padx=5, pady=5)
self._example_label.grid(row=5, column=1, columnspan=2, sticky="nswe", padx=5, pady=5)
self._ok_button.grid(row=6, column=2, sticky="nswe", padx=5, pady=5)
self._cancel_button.grid(row=6, column=1, sticky="nswe", padx=5, pady=5) | csn |
Returns a list of Encodings that belong to a Profile.
@param id_or_name Id or name of a Profile.
@param factory_id Id of a Factory.
@param [Hash] opts the optional parameters
@return [PaginatedEncodingsCollection] | def profile_encodings(id_or_name, factory_id, opts = {})
data, _status_code, _headers = profile_encodings_with_http_info(id_or_name, factory_id, opts)
return data
end | csn |
Convert hours, minutes, seconds, and microseconds to fractional days.
Parameters
----------
hour : int, optional
Hour number. Defaults to 0.
min : int, optional
Minute number. Defaults to 0.
sec : int, optional
Second number. Defaults to 0.
micro : int, optional
Microsecond number. Defaults to 0.
Returns
-------
days : float
Fractional days.
Examples
--------
>>> hmsm_to_days(hour=6)
0.25 | def hmsm_to_days(hour=0,min=0,sec=0,micro=0):
"""
Convert hours, minutes, seconds, and microseconds to fractional days.
Parameters
----------
hour : int, optional
Hour number. Defaults to 0.
min : int, optional
Minute number. Defaults to 0.
sec : int, optional
Second number. Defaults to 0.
micro : int, optional
Microsecond number. Defaults to 0.
Returns
-------
days : float
Fractional days.
Examples
--------
>>> hmsm_to_days(hour=6)
0.25
"""
days = sec + (micro / 1.e6)
days = min + (days / 60.)
days = hour + (days / 60.)
return days / 24. | csn |
protected String properties(TQProperty<?>... props) {
StringBuilder selectProps = new StringBuilder(50);
for (int i = 0; i < props.length; i++) {
if (i > 0) {
selectProps.append(",");
}
| selectProps.append(props[i].propertyName());
}
return selectProps.toString();
} | csn_ccr |
Attach a URL to a sheet.
The URL can be a normal URL (attachmentType "URL"), a Google Drive URL (attachmentType "GOOGLE_DRIVE") or a
Box.com URL (attachmentType "BOX_COM").
It mirrors to the following Smartsheet REST API method: POST /sheets/{sheetId}/attachments
@param sheetId the sheet id
@param attachment the attachment object
@return the attachment object
@throws IllegalArgumentException if any argument is null or empty string
@throws InvalidRequestException if there is any problem with the REST API request
@throws AuthorizationException if there is any problem with the REST API authorization (access token)
@throws ResourceNotFoundException if the resource cannot be found
@throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
@throws SmartsheetException if there is any other error during the operation | public Attachment attachUrl(long sheetId, Attachment attachment) throws SmartsheetException
{
return this.createResource("sheets/" + sheetId + "/attachments", Attachment.class, attachment);
} | csn |
Adds a case clause to this switch statement. | public SwitchBuilder addCase(Expression caseLabel, Statement body) {
clauses.add(new Switch.CaseClause(ImmutableList.of(caseLabel), body));
return this;
} | csn |
func newLoadBalancerController(cfg *loadBalancerConfig, kubeClient *unversioned.Client, namespace string, tcpServices map[string]int) *loadBalancerController {
lbc := loadBalancerController{
cfg: cfg,
client: kubeClient,
queue: workqueue.New(),
reloadRateLimiter: util.NewTokenBucketRateLimiter(
reloadQPS, int(reloadQPS)),
targetService: *targetService,
forwardServices: *forwardServices,
httpPort: *httpPort,
tcpServices: tcpServices,
}
enqueue := func(obj interface{}) {
key, err := keyFunc(obj)
if err != nil {
glog.Infof("Couldn't get key for object %+v: %v", obj, err)
return
}
lbc.queue.Add(key)
}
eventHandlers := framework.ResourceEventHandlerFuncs{
AddFunc: enqueue,
DeleteFunc: enqueue,
UpdateFunc: func(old, cur interface{}) {
if !reflect.DeepEqual(old, cur) {
enqueue(cur)
}
| },
}
lbc.svcLister.Store, lbc.svcController = framework.NewInformer(
cache.NewListWatchFromClient(
lbc.client, "services", namespace, fields.Everything()),
&api.Service{}, resyncPeriod, eventHandlers)
lbc.epLister.Store, lbc.epController = framework.NewInformer(
cache.NewListWatchFromClient(
lbc.client, "endpoints", namespace, fields.Everything()),
&api.Endpoints{}, resyncPeriod, eventHandlers)
return &lbc
} | csn_ccr |
def update(self, settings):
"""Recursively merge the given settings into the current settings."""
self.settings.cache_clear()
self._settings = settings
| log.info("Updated settings to %s", self._settings)
self._update_disabled_plugins() | csn_ccr |
// extractSwaggerOptionFromFileDescriptor extracts the message of type
// swagger_options.Swagger from a given proto method's descriptor. | func extractSwaggerOptionFromFileDescriptor(file *pbdescriptor.FileDescriptorProto) (*swagger_options.Swagger, error) {
if file.Options == nil {
return nil, nil
}
if !proto.HasExtension(file.Options, swagger_options.E_Openapiv2Swagger) {
return nil, nil
}
ext, err := proto.GetExtension(file.Options, swagger_options.E_Openapiv2Swagger)
if err != nil {
return nil, err
}
opts, ok := ext.(*swagger_options.Swagger)
if !ok {
return nil, fmt.Errorf("extension is %T; want a Swagger object", ext)
}
return opts, nil
} | csn |
func TypeToMySQL(typ querypb.Type) (mysqlType, flags int64) {
| val := typeToMySQL[typ]
return val.typ, val.flags
} | csn_ccr |
Return output with specified encoding. | def wrap_output(output, encoding):
"""Return output with specified encoding."""
return codecs.getwriter(encoding)(output.buffer
if hasattr(output, 'buffer')
else output) | csn |
def join(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]:
"""Block until all items in the queue are processed.
Returns an awaitable, which raises | `tornado.util.TimeoutError` after a
timeout.
"""
return self._finished.wait(timeout) | csn_ccr |
protected function createExtensionSelector()
{
$this->getAndSaveSelectedTestableKey();
/** @var \Tx_Phpunit_ViewHelpers_ExtensionSelectorViewHelper $extensionSelectorViewHelper */
$extensionSelectorViewHelper =
GeneralUtility::makeInstance(\Tx_Phpunit_ViewHelpers_ExtensionSelectorViewHelper::class);
$extensionSelectorViewHelper->injectOutputService($this->outputService);
$extensionSelectorViewHelper->injectUserSettingService($this->userSettingsService); |
$extensionSelectorViewHelper->injectTestFinder($this->testFinder);
$extensionSelectorViewHelper->setAction(BackendUtility::getModuleUrl('tools_txphpunitbeM1'));
$extensionSelectorViewHelper->render();
} | csn_ccr |
Trim values at input thresholds using pandas function | def clip(self, lower=None, upper=None):
'''
Trim values at input thresholds using pandas function
'''
df = self.export_df()
df = df.clip(lower=lower, upper=upper)
self.load_df(df) | csn |
Returns the IDs of related objects. | public Map<String, String> getLinks() {
if (links == null) {
return ImmutableMap.of();
}
return ImmutableMap.copyOf(links);
} | csn |
Returns the array of attachments set in the instance variable.
@param bool $reset (optional, default is false)
@since 5.5.0
@return array|null | function getBookMedia( $reset = false ) {
// Cheap cache
static $book_media = null;
if ( $reset || $book_media === null ) {
$book_media = [];
$args = [
'post_type' => 'attachment',
'posts_per_page' => -1, // @codingStandardsIgnoreLine
'post_status' => 'inherit',
'no_found_rows' => true,
];
$attached_media = get_posts( $args );
foreach ( $attached_media as $media ) {
$book_media[ $media->ID ] = $media->guid;
}
}
return $book_media;
} | csn |
def convertPossibleValues(val, possibleValues, invalidDefault, emptyValue=''):
'''
convertPossibleValues - Convert input value to one of several possible values,
with a default for invalid entries
@param val <None/str> - The input value
@param possibleValues list<str> - A list of possible values
@param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None
and "val" is not in #possibleValues
If instantiated Exception (like ValueError('blah')): Raise this exception
If an Exception type ( like ValueError ) - Instantiate and raise this exception type
Otherwise, use this raw value
@param emptyValue Default '', used for an empty value (empty string or None)
'''
from .utils import tostr
# If null, retain null
| if val is None:
if emptyValue is EMPTY_IS_INVALID:
return _handleInvalid(invalidDefault)
return emptyValue
# Convert to a string
val = tostr(val).lower()
# If empty string, same as null
if val == '':
if emptyValue is EMPTY_IS_INVALID:
return _handleInvalid(invalidDefault)
return emptyValue
# Check if this is a valid value
if val not in possibleValues:
return _handleInvalid(invalidDefault)
return val | csn_ccr |
Add the IFRAME tag for the frame that lists all classes.
@param contentTree the content tree to which the information will be added | private void addAllClassesFrameTag(Content contentTree) {
HtmlTree frame = HtmlTree.IFRAME(DocPaths.ALLCLASSES_FRAME.getPath(),
"packageFrame", configuration.getText("doclet.All_classes_and_interfaces"));
HtmlTree leftBottom = HtmlTree.DIV(HtmlStyle.leftBottom, frame);
contentTree.addContent(leftBottom);
} | csn |
def receive(self, request, wait=True, timeout=None):
"""
Polls the message buffer of the TCP connection and waits until a valid
message is received based on the message_id passed in.
:param request: The Request object to wait get the response for
:param wait: Wait for the final response in the case of a
STATUS_PENDING response, the pending response is returned in the
case of wait=False
:param timeout: Set a timeout used while waiting for a response from
the server
:return: SMB2HeaderResponse of the received message
"""
start_time = time.time()
# check if we have received a response
while True:
self._flush_message_buffer()
status = request.response['status'].get_value() if \
request.response else None
if status is not None and (wait and
status != NtStatus.STATUS_PENDING):
break
current_time = time.time() - start_time
if timeout | and (current_time > timeout):
error_msg = "Connection timeout of %d seconds exceeded while" \
" waiting for a response from the server" \
% timeout
raise smbprotocol.exceptions.SMBException(error_msg)
response = request.response
status = response['status'].get_value()
if status not in [NtStatus.STATUS_SUCCESS, NtStatus.STATUS_PENDING]:
raise smbprotocol.exceptions.SMBResponseException(response, status)
# now we have a retrieval request for the response, we can delete
# the request from the outstanding requests
message_id = request.message['message_id'].get_value()
del self.outstanding_requests[message_id]
return response | csn_ccr |
Acquires the canonical File for the supplied file.
@param file A non-null File for which the canonical File should be retrieved.
@return The canonical File of the supplied file. | public static File getCanonicalFile(final File file) {
// Check sanity
Validate.notNull(file, "file");
// All done
try {
return file.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException("Could not acquire the canonical file for ["
+ file.getAbsolutePath() + "]", e);
}
} | csn |
Total power used. | def total_power(self):
"""Total power used.
"""
power = self.average_current * self.voltage
return round(power, self.sr) | csn |
public boolean checkAndMaybeUpdate() throws IOException {
try {
File nativeLibDir = soSource.soDirectory;
Context updatedContext =
applicationContext.createPackageContext(applicationContext.getPackageName(), 0);
File updatedNativeLibDir = new File(updatedContext.getApplicationInfo().nativeLibraryDir);
if (!nativeLibDir.equals(updatedNativeLibDir)) {
Log.d(
SoLoader.TAG,
"Native library directory updated from " + nativeLibDir + " to " + updatedNativeLibDir);
// update flags to resolve dependencies since the system does not properly resolve
// dependencies when the location has moved
| flags |= DirectorySoSource.RESOLVE_DEPENDENCIES;
soSource = new DirectorySoSource(updatedNativeLibDir, flags);
soSource.prepare(flags);
applicationContext = updatedContext;
return true;
}
return false;
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(e);
}
} | csn_ccr |
def members_from_rank_range(self, starting_rank, ending_rank, **options):
'''
Retrieve members from the leaderboard within a given rank range.
@param starting_rank [int] Starting rank (inclusive).
@param ending_rank [int] Ending rank (inclusive).
@param options [Hash] Options to be used when retrieving the data from the leaderboard.
@return members | from the leaderboard that fall within the given rank range.
'''
return self.members_from_rank_range_in(
self.leaderboard_name, starting_rank, ending_rank, **options) | csn_ccr |
def _check_and_flip(arr):
"""Transpose array or list of arrays if they are 2D."""
if hasattr(arr, 'ndim'):
if arr.ndim >= 2:
return arr.T
else:
| return arr
elif not is_string_like(arr) and iterable(arr):
return tuple(_check_and_flip(a) for a in arr)
else:
return arr | csn_ccr |
private void addField(int fieldIndex, XmlSchemaObjectBase xsdSchemaObject,
Map < String, Object > fields, RootCompositeType compositeTypes) {
if (xsdSchemaObject instanceof XmlSchemaElement) {
XmlSchemaElement xsdElement = (XmlSchemaElement) xsdSchemaObject;
| fields.put(getFieldName(xsdElement),
getProps(fieldIndex, xsdElement, compositeTypes));
} else if (xsdSchemaObject instanceof XmlSchemaChoice) {
XmlSchemaChoice xsdChoice = (XmlSchemaChoice) xsdSchemaObject;
fields.put(getFieldName(xsdChoice),
getProps(fieldIndex, xsdChoice, compositeTypes));
}
// TODO Add Groups
} | csn_ccr |
public function findByHost($hostname, $onlyActive = false)
{
$domains = $onlyActive === true ? $this->findByActive(true)->toArray() : $this->findAll()->toArray();
| return $this->domainMatchingStrategy->getSortedMatches($hostname, $domains);
} | csn_ccr |
func determineBlockHeights(blocksMap map[chainhash.Hash]*blockChainContext) error {
queue := list.New()
// The genesis block is included in blocksMap as a child of the zero hash
// because that is the value of the PrevBlock field in the genesis header.
preGenesisContext, exists := blocksMap[zeroHash]
if !exists || len(preGenesisContext.children) == 0 {
return fmt.Errorf("Unable to find genesis block")
}
for _, genesisHash := range preGenesisContext.children {
blocksMap[*genesisHash].height = 0
queue.PushBack(genesisHash)
}
for e := queue.Front(); e != nil; e = | queue.Front() {
queue.Remove(e)
hash := e.Value.(*chainhash.Hash)
height := blocksMap[*hash].height
// For each block with this one as a parent, assign it a height and
// push to queue for future processing.
for _, childHash := range blocksMap[*hash].children {
blocksMap[*childHash].height = height + 1
queue.PushBack(childHash)
}
}
return nil
} | csn_ccr |
Get the full url to the original video.
@param MediaInterface $media
@return string | public function getUrl(MediaInterface $media)
{
$metadata = $media->getMetaData();
return sprintf('%s?v=%s', self::WATCH_URL, $metadata['id']);
} | csn |
Creates a new JavaLoggerProxy and redirects the platform logger to it | private void redirectToJavaLoggerProxy() {
DefaultLoggerProxy lp = DefaultLoggerProxy.class.cast(this.loggerProxy);
JavaLoggerProxy jlp = new JavaLoggerProxy(lp.name, lp.level);
// the order of assignments is important
this.javaLoggerProxy = jlp; // isLoggable checks javaLoggerProxy if set
this.loggerProxy = jlp;
} | csn |
Set the attributes of the hint of the form element object
@param array $attribs
@return AbstractElement | public function setHintAttributes(array $attribs)
{
foreach ($attribs as $a => $v) {
$this->setHintAttribute($a, $v);
}
return $this;
} | csn |
// UpdateOrganization updates an organization in the organizations store | func (s *Service) UpdateOrganization(w http.ResponseWriter, r *http.Request) {
var req organizationRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
invalidJSON(w, s.Logger)
return
}
if err := req.ValidUpdate(); err != nil {
invalidData(w, err, s.Logger)
return
}
ctx := r.Context()
id := httprouter.GetParamFromContext(ctx, "oid")
org, err := s.Store.Organizations(ctx).Get(ctx, chronograf.OrganizationQuery{ID: &id})
if err != nil {
Error(w, http.StatusBadRequest, err.Error(), s.Logger)
return
}
if req.Name != "" {
org.Name = req.Name
}
if req.DefaultRole != "" {
org.DefaultRole = req.DefaultRole
}
err = s.Store.Organizations(ctx).Update(ctx, org)
if err != nil {
Error(w, http.StatusBadRequest, err.Error(), s.Logger)
return
}
res := newOrganizationResponse(org)
location(w, res.Links.Self)
encodeJSON(w, http.StatusOK, res, s.Logger)
} | csn |
def compress(data,
mode=DEFAULT_MODE,
quality=lib.BROTLI_DEFAULT_QUALITY,
lgwin=lib.BROTLI_DEFAULT_WINDOW,
lgblock=0,
dictionary=b''):
"""
Compress a string using Brotli.
.. versionchanged:: 0.5.0
Added ``mode``, ``quality``, `lgwin``, ``lgblock``, and ``dictionary``
parameters.
:param data: A bytestring containing the data to compress.
:type data: ``bytes``
:param mode: The encoder mode.
:type mode: :class:`BrotliEncoderMode` or ``int``
:param quality: Controls the compression-speed vs compression-density
tradeoffs. The higher the quality, the slower the compression. The
range of this value is 0 to 11.
:type quality: ``int``
:param lgwin: The base-2 logarithm of the sliding window size. The range of
this value is 10 to 24.
:type lgwin: ``int``
:param lgblock: The base-2 logarithm of the maximum input block size. The
range of this value is 16 to 24. If set to 0, the value will be set
based on ``quality``.
:type lgblock: ``int``
:param dictionary: A pre-set dictionary for LZ77. Please use this with
caution: if a dictionary is used for compression, the same dictionary
**must** be used for decompression!
:type dictionary: ``bytes``
:returns: The compressed bytestring.
:rtype: ``bytes``
"""
| # This method uses private variables on the Compressor object, and
# generally does a whole lot of stuff that's not supported by the public
# API. The goal here is to minimise the number of allocations and copies
# we have to do. Users should prefer this method over the Compressor if
# they know they have single-shot data.
compressor = Compressor(
mode=mode,
quality=quality,
lgwin=lgwin,
lgblock=lgblock,
dictionary=dictionary
)
compressed_data = compressor._compress(data, lib.BROTLI_OPERATION_FINISH)
assert lib.BrotliEncoderIsFinished(compressor._encoder) == lib.BROTLI_TRUE
assert (
lib.BrotliEncoderHasMoreOutput(compressor._encoder) == lib.BROTLI_FALSE
)
return compressed_data | csn_ccr |
public function getValues()
{
$attrs = array();
foreach ($this->_attributes as $attr => $value) {
$attrs[$attr] | = $this->getValue($attr);
}
return $attrs;
} | csn_ccr |
state insertion on mouse click
:param widget:
:param Gdk.Event event: mouse click event | def on_mouse_click(self, widget, event):
"""state insertion on mouse click
:param widget:
:param Gdk.Event event: mouse click event
"""
import rafcon.gui.helpers.state_machine as gui_helper_state_machine
if self.view.get_path_at_pos(int(event.x), int(event.y)) is not None \
and len(self.view.get_selected_items()) > 0:
return gui_helper_state_machine.insert_state_into_selected_state(self._get_state(), False) | csn |
Finds an HTML element by class and the text value and clicks it.
@param string $text Text value of the element
@param string $selector CSS selector of the element
@param string $textSelector Extra CSS selector for text of the element
@param string $baseElement Element in which the search is based | public function clickElementByText($text, $selector, $textSelector = null, $baseElement = null)
{
$element = $this->getElementByText($text, $selector, $textSelector, $baseElement);
if ($element && $element->isVisible()) {
$element->click();
} elseif ($element) {
throw new \Exception("Can't click '$text' element: not visible");
} else {
throw new \Exception("Can't click '$text' element: not Found");
}
} | csn |
Builds a Datetime object given a jd and utc offset. | def fromJD(jd, utcoffset):
""" Builds a Datetime object given a jd and utc offset. """
if not isinstance(utcoffset, Time):
utcoffset = Time(utcoffset)
localJD = jd + utcoffset.value / 24.0
date = Date(round(localJD))
time = Time((localJD + 0.5 - date.jdn) * 24)
return Datetime(date, time, utcoffset) | csn |
A package-private method that supports all kinds of profile modification,
including renaming or deleting one or more profiles.
@param modifications
Use null key value to indicate a profile that is to be
deleted. | static void modifyProfiles(File destination, Map<String, Profile> modifications) {
final boolean inPlaceModify = destination.exists();
File stashLocation = null;
// Stash the original file, before we apply the changes
if (inPlaceModify) {
boolean stashed = false;
try {
// We can't use File.createTempFile, since it will always create
// that file no matter what, and File.reNameTo does not allow
// the destination to be an existing file
stashLocation = new File(destination.getParentFile(),
destination.getName() + ".bak."
+ UUID.randomUUID().toString());
stashed = destination.renameTo(stashLocation);
if (LOG.isDebugEnabled()) {
LOG.debug(String
.format("The original credentials file is stashed to loaction (%s).",
stashLocation.getAbsolutePath()));
}
} finally {
if (!stashed) {
throw new SdkClientException(
"Failed to stash the existing credentials file " +
"before applying the changes.");
}
}
}
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(destination), StringUtils.UTF8);
ProfilesConfigFileWriterHelper writerHelper = new ProfilesConfigFileWriterHelper(writer, modifications);
if (inPlaceModify) {
Scanner existingContent = new Scanner(stashLocation, StringUtils.UTF8.name());
writerHelper.writeWithExistingContent(existingContent);
} else {
writerHelper.writeWithoutExistingContent();
}
// Make sure the output is valid and can be loaded by the loader
new ProfilesConfigFile(destination);
if ( inPlaceModify && !stashLocation.delete() ) {
if (LOG.isDebugEnabled()) {
LOG.debug(String
.format("Successfully modified the credentials file. But failed to " +
"delete the stashed copy of the original file (%s).",
stashLocation.getAbsolutePath()));
}
}
} catch (Exception e) {
// Restore the stashed file
if (inPlaceModify) {
boolean restored = false;
try {
// We don't really care about what destination.delete()
// returns, since the file might not have been created when
// the error occurred.
if ( !destination.delete() ) {
LOG.debug("Unable to remove the credentials file "
+ "before restoring the original one.");
}
restored = stashLocation.renameTo(destination);
} finally {
if (!restored) {
throw new SdkClientException(
"Unable to restore the original credentials file. " +
"File content stashed in " + stashLocation.getAbsolutePath());
}
}
}
throw new SdkClientException(
"Unable to modify the credentials file. " +
"(The original file has been restored.)",
e);
} finally {
try {
if (writer != null) writer.close();
} catch (IOException e) {}
}
} | csn |
Backs up the specified storage account.
Requests that a backup of the specified storage account be downloaded to the
client. This operation requires the storage/backup permission.
@param vault_base_url [String] The vault name, for example
https://myvault.vault.azure.net.
@param storage_account_name [String] The name of the storage account.
@param custom_headers [Hash{String => String}] A hash of custom headers that
will be added to the HTTP request.
@return [BackupStorageResult] operation results. | def backup_storage_account(vault_base_url, storage_account_name, custom_headers:nil)
response = backup_storage_account_async(vault_base_url, storage_account_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end | csn |
final public function animate($sel, Array $keyframes, Array $opts)
{
if (! array_key_exists('animate', $this->response)) {
$this->response['animate'] = [];
| }
$this->response['animate'][$sel] = ['keyframes' => $keyframes, 'opts' => $opts];
return $this;
} | csn_ccr |
updatating plot object inline python juypter | def _push_render(self):
"""Render the plot with bokeh.io and push to notebook.
"""
bokeh.io.push_notebook(handle=self.handle)
self.last_update = time.time() | cosqa |
public function traverse()
{
if (self::$ignoreAjax or ! $this->validate()) {
return;
}
$request = app('antares.request');
$module = $request->getModule();
$controller = $request->getController();
$action = $request->getAction();
| $insert = [
'type_id' => $this->getLogTypeByName($module),
'owner_type' => $request->getControllerClass(),
'priority_id' => $this->logPrioriotyId('low'),
'name' => strtoupper(implode('_', [$module, $controller, $action])),
'type' => 'viewed'
];
return Logs::insert(array_merge($this->prepare(), $insert));
} | csn_ccr |
Computes the union of this +Directory+ with another +Directory+. If the
two directories have a file path in common, the file in the +other+
+Directory+ takes precedence. If the two directories have a sub-directory
path in common, the union's sub-directory path will be the union of those
two sub-directories.
@raise [ArgumentError] if the +other+ parameter is not a +Directory+
@param other [Directory]
@return [Directory] | def |(other)
if !other.is_a?(Directory)
raise ArgumentError, "#{other} is not a Directory"
end
dup.tap do |directory|
other.files.each do |file|
directory.add_file(file.dup)
end
other.directories.each do |new_directory|
existing_directory = @directories[new_directory.name]
if existing_directory.nil?
directory.add_directory(new_directory.dup)
else
directory.add_directory(new_directory | existing_directory)
end
end
end
end | csn |
Custom renders the table page summary.
@return string the rendering result.
@throws \yii\base\InvalidConfigException | public function renderPageSummary()
{
$content = parent::renderPageSummary();
if ($this->showCustomPageSummary) {
if (!$content) {
$content = "<tfoot></tfoot>";
}
if ($this->beforeSummary) {
foreach ($this->beforeSummary as &$row) {
if (!isset($row['options'])) {
$row['options'] = $this->pageSummaryRowOptions;
}
}
}
if ($this->afterSummary) {
foreach ($this->afterSummary as &$row) {
if (!isset($row['options'])) {
$row['options'] = $this->pageSummaryRowOptions;
}
}
}
return strtr(
$content,
[
'<tfoot>' => "<tfoot>\n" . parent::generateRows($this->beforeSummary),
'</tfoot>' => parent::generateRows($this->afterSummary) . "\n</tfoot>",
]
);
}
return $content;
} | csn |
Sets the localized value of this cp definition specification option value in the language.
@param value the localized value of this cp definition specification option value
@param locale the locale of the language | @Override
public void setValue(String value, java.util.Locale locale) {
_cpDefinitionSpecificationOptionValue.setValue(value, locale);
} | csn |
Send a message through the udp socket.
:type message: Message
:param message: the message to send | def send_datagram(self, message):
"""
Send a message through the udp socket.
:type message: Message
:param message: the message to send
"""
if not self.stopped.isSet():
host, port = message.destination
logger.debug("send_datagram - " + str(message))
serializer = Serializer()
message = serializer.serialize(message)
self._socket.sendto(message, (host, port)) | csn |
func (r *Router) Add(meth, path string, hand HandlerFunc) {
route := &Route{
Path: path,
Method: meth,
Handler: hand,
}
// Rank the route
route.Rank = route.rank()
// Add the route to the tree
| r.routes[meth] = append(r.routes[meth], route)
// Sort the routes according to rank
sort.Sort(ranker(r.routes[meth]))
} | csn_ccr |
func NewBridge(info Info) *Bridge {
acc := Bridge{}
acc.Accessory = | New(info, TypeBridge)
return &acc
} | csn_ccr |
Once we have entered a turn we can keep executing propagations without waiting for another tick. Start a trampoline to process the current queue. | function enterTurn() {
var snapshot;
while ((snapshot = queue).length) {
queue = [];
trampoline(snapshot);
}
queue = null;
} | csn |
A storage which keeps configuration settings for attachments | def storage(self):
"""A storage which keeps configuration settings for attachments
"""
annotation = self.get_annotation()
if annotation.get(ATTACHMENTS_STORAGE) is None:
annotation[ATTACHMENTS_STORAGE] = OOBTree()
return annotation[ATTACHMENTS_STORAGE] | csn |
Returns all the widgets. | public static function get()
{
$widgets = [];
foreach (Packages::all() as $package) {
$dir = __DIR__.'/../../'.$package.'/src';
$files = is_dir($dir) ? scandir($dir) : [];
foreach ($files as $file) {
if ($file == 'Widgets.json') {
$file_r = file_get_contents($dir.'/'.$file);
foreach (json_decode($file_r, true) as $w) {
$w['package'] = $package;
array_push($widgets, $w);
}
break;
}
}
}
$widgets = static::orderByPreference($widgets);
return $widgets;
} | csn |
Return whether or not the provided subject ends with suffix.
@param string $subject
@param string $suffix
@param null|string $encoding
@return bool
@throws InvalidArgumentException | public static function endsWith($subject, $suffix, $encoding = null)
{
return Rope::of($subject, $encoding)->endsWith($suffix);
} | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.