benjamintli/modernbert-code-v2
Sentence Similarity • 0.1B • Updated • 240
query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Start the asyncio event loop and runs the application. | def main():
"""Start the asyncio event loop and runs the application."""
# Helper method so that the coroutine exits cleanly if an exception
# happens (which would leave resources dangling)
async def _run_application(loop):
try:
return await cli_handler(loop)
except Keyboard... | csn |
Initialize the pool manager with the number of pools, the entry sizes for each
pool, and the maximum depth of the free pool.
@param bufferEntrySizes the memory sizes of each entry in the pools
@param bufferEntryDepths the maximum number of entries in the free pool | public void initialize(int[] bufferEntrySizes, int[] bufferEntryDepths) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "initialize");
}
// order both lists from smallest to largest, based only on Entry Sizes
int len = bufferEntrySizes.lengt... | csn |
// List lists all of the documents in an index. The documents are returned in
// increasing ID order. | func (x *Index) List(c context.Context, opts *ListOptions) *Iterator {
t := &Iterator{
c: c,
index: x,
count: -1,
listInclusive: true,
more: moreList,
limit: -1,
}
if opts != nil {
t.listStartID = opts.StartID
if opts.Limit > 0 {
t.limit = opts.Limit
... | csn |
Loads the entity that holds the item type data when an Item is loaded.
@param Item $item
@param LifecycleEventArgs $event | public function postLoad(Item $item, LifecycleEventArgs $event)
{
$type = $this->itemDefinitions->getConvertedType($item->getMimeType());
$definition = $this->itemDefinitions->get($type);
$repository = $event
->getEntityManager()
->getRepository($definition->getEntity... | csn |
Extract the normalized text from within an element
@param fromElement
@return extracted Text node (could be null) | protected Text extractText(Element fromElement) {
fromElement.normalize();
NodeList fromNodeList = fromElement.getChildNodes();
Node currentNode;
for (int i=0; i < fromNodeList.getLength(); ++i) {
currentNode = fromNodeList.item(i);
if (currentNode.getNodeType() ... | csn |
// handle processes a request from a Multiwatcher to the storeManager. | func (sm *storeManager) handle(req *request) {
if req.w.stopped {
// The watcher has previously been stopped.
if req.reply != nil {
select {
case req.reply <- false:
case <-sm.tomb.Dying():
}
}
return
}
if req.reply == nil {
// This is a request to stop the watcher.
for req := sm.waiting[req.... | csn |
// Limit returns true if rate was exceeded | func (rl *RateLimiter) Limit() bool {
// Calculate the number of ns that have passed since our last call
now := unixNano()
passed := now - atomic.SwapUint64(&rl.lastCheck, now)
// Add them to our allowance
rate := atomic.LoadUint64(&rl.rate)
current := atomic.AddUint64(&rl.allowance, passed*rate)
// Ensure our... | csn |
Modify to the last occurrence of a given day of the week
in the current quarter. If no day_of_week is provided,
modify to the last day of the quarter. Use the supplied consts
to indicate the desired day_of_week, ex. DateTime.MONDAY.
:type day_of_week: int or None
:rtype: DateTi... | def _last_of_quarter(self, day_of_week=None):
"""
Modify to the last occurrence of a given day of the week
in the current quarter. If no day_of_week is provided,
modify to the last day of the quarter. Use the supplied consts
to indicate the desired day_of_week, ex. DateTime.MONDA... | csn |
Compile Sass content using Leafo's ScssPhp compiler.
@link https://github.com/leafo/scssphp
@param string $content
Content to compile.
@param array $directories
The import directories to make available when compiling.
@return string Compiled Sass content. | private static function compileSassContentWithLeafoScss(string $content, array $directories)
{
if (empty($content)) {
return '';
}
if (self::$sassCompilerInstance == null) {
self::$sassCompilerInstance = self::getLeafoScssInstance();
}
self::u... | csn |
Reset the date to the last day of the decade.
:rtype: Date | def _end_of_decade(self):
"""
Reset the date to the last day of the decade.
:rtype: Date
"""
year = self.year - self.year % YEARS_PER_DECADE + YEARS_PER_DECADE - 1
return self.set(year, 12, 31) | csn |
Puts an archive data row in an index. | private function putRowInIndex(&$index, $metadataNamesToIndexBy, $row, $idSite, $period)
{
$currentLevel = & $index;
foreach ($metadataNamesToIndexBy as $metadataName) {
if ($metadataName == DataTableFactory::TABLE_METADATA_SITE_INDEX) {
$key = $idSite;
} els... | csn |
Is the point near any points in the multi lat lng
@param point point
@param multiLatLng multi lat lng
@param tolerance distance tolerance
@return true if near | public static boolean isPointNearMultiLatLng(LatLng point, MultiLatLng multiLatLng, double tolerance) {
boolean near = false;
for (LatLng multiPoint : multiLatLng.getLatLngs()) {
near = isPointNearPoint(point, multiPoint, tolerance);
if (near) {
break;
... | csn |
Gives support for Rails date_select, datetime_select, time_select helpers. | def process_attributes(attributes = nil)
return attributes if attributes.blank?
multi_parameter_attributes = {}
new_attributes = {}
attributes.each_pair do |key, value|
if key.match(DATE_KEY_REGEX)
match = key.to_s.match(DATE_KEY_REGEX)
found_key = match[1]
... | csn |
read-only
@language=en
Set text CSS font style.
@param {String} font Text CSS font style to set.
@returns {Text} the Text object, chained call supported. | function(font){
var me = this;
if(me.font !== font){
me.font = font;
me._fontHeight = Text.measureFontHeight(font);
}
return me;
} | csn |
Generate a new Key in the NFVO.
@param name the name of the new Key
@return the private Key
@throws SDKException if the request fails | @Help(help = "Generate a new Key in the NFVO")
public String generateKey(String name) throws SDKException {
return (String) requestPost("generate", name);
} | csn |
hack for NS62 bug | function jsUnitFixTop() {
var tempTop = top;
if (!tempTop) {
tempTop = window;
while (tempTop.parent) {
tempTop = tempTop.parent;
if (tempTop.top && tempTop.top.jsUnitTestSuite) {
tempTop = tempTop.top;
break;
}
}
}
... | csn |
Convert a file into a raid file format | public void raidFile(INode sourceINodes[], String source,
RaidCodec codec, short expectedSourceRepl, Block[] parityBlocks)
throws IOException {
waitForReady();
long now = FSNamesystem.now();
unprotectedRaidFile(sourceINodes, source, codec, expectedSourceRepl,
parityBlocks, now);
... | csn |
Checks if an object holding the same name already exists in the index.
If so, it compares their definition order: the lowest definition order
is kept. If definition order equal, an error is risen.Item
The method returns the item that should be added after it has decided
which one shoul... | def manage_conflict(self, item, name):
"""
Checks if an object holding the same name already exists in the index.
If so, it compares their definition order: the lowest definition order
is kept. If definition order equal, an error is risen.Item
The method returns the item that s... | csn |
Convert the alias.
@param string
@return LibBaseTemplateFilterAlias | public function write(&$text)
{
$matches = array();
if (strpos($text, '<html')) {
//add language
$text = str_replace('<html', '<html lang="'.$this->getService('anahita:language')->getTag().'"', $text);
//render the styles
$text = str_replace('</head... | csn |
Create an object URL.
Given a base URL and an object name, create an object URL.
This is useful because object names can contain certain characters
(namely slashes (`/`)) that are normally URLencoded when they appear
inside of path sequences.
@note
Swift does not distinguish between @c %2F and a slash character, so
... | public static function objectUrl($base, $oname) {
if (strpos($oname, '/') === FALSE) {
return $base . '/' . rawurlencode($oname);
}
$oParts = explode('/', $oname);
$buffer = array();
foreach ($oParts as $part) {
$buffer[] = rawurlencode($part);
}
$newname = implode('/', $buffer)... | csn |
get the current input instance
@param CCIn_Instance $set if set the current instance gets updated
@return CCIn_Instance | public static function instance( $set = null )
{
if ( is_null( $set ) )
{
return static::$_instance;
}
if ( !$set instanceof CCIn_Instance )
{
throw new \InvalidArgumentException('CCIn::set() - only CCIn_Instance object can be passed.');
}
static::$_instance = $set;
} | csn |
Print the default values of all cls's Parameters. | def print_param_defaults(self_):
"""Print the default values of all cls's Parameters."""
cls = self_.cls
for key,val in cls.__dict__.items():
if isinstance(val,Parameter):
print(cls.__name__+'.'+key+ '='+ repr(val.default)) | csn |
Perform an ajax request to get comments for a node
and insert the comments into the comments tree. | function getComments(id) {
$.ajax({
type: 'GET',
url: opts.getCommentsURL,
data: {node: id},
success: function(data, textStatus, request) {
var ul = $('#cl' + id);
var speed = 100;
$('#cf' + id)
.find('textarea[name="proposal"]')
.data('source', data.source... | csn |
// lookupReader - return the reader function for the given scheme | func (d *Data) lookupReader(scheme string) (func(*Source, ...string) ([]byte, error), error) {
if d.sourceReaders == nil {
d.registerReaders()
}
r, ok := d.sourceReaders[scheme]
if !ok {
return nil, errors.Errorf("scheme %s not registered", scheme)
}
return r, nil
} | csn |
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray | def get_pij_matrix(t, diag, A, A_inv):
"""
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray
"""
return A.dot(np.diag(np.exp(diag * t))... | csn |
Like tree view mode | def tree(self):
"""Like tree view mode
"""
self.msg.template(78)
print("| Dependencies\n"
"| -- Packages")
self.msg.template(78)
self.data()
for pkg, dep in self.dmap.iteritems():
print("+ {0}{1}{2}".format(self.green, pkg, self.endc))
... | csn |
Payment options.
@return array | public static function getOptions()
{
$options = [];
$options[] = [
'id' => Operation::PRODUCT_VISA,
'label' => "Visa",
];
$options[] = [
'id' => Operation::PRODUCT_MASTERCARD,
'label' => "Mastercard",
];
$options[] = [... | csn |
Load a profile by name
Called by load_user_options | def _load_profile(self, profile_name):
"""Load a profile by name
Called by load_user_options
"""
# find the profile
default_profile = self._profile_list[0]
for profile in self._profile_list:
if profile.get('default', False):
# explicit defaul... | csn |
Wrapper works for conversion.
Args:
- filename -- str, file to be converted | def f2format(filename):
"""Wrapper works for conversion.
Args:
- filename -- str, file to be converted
"""
print('Now converting %r...' % filename)
# fetch encoding
encoding = os.getenv('F2FORMAT_ENCODING', LOCALE_ENCODING)
lineno = dict() # line number -> file offset
conten... | csn |
Teardown button handler. | def exitClient(self):
"""Teardown button handler."""
self.sendRtspRequest(self.TEARDOWN)
#self.handler()
os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video
rate = float(self.counter/self.frameNbr)
print('-'*60 + "\nRTP Packet Loss Rate :" + str(... | csn |
Cancelles an invoice
:param invoice_id: the invoice id
:return Response | def cancel_invoice(self, invoice_id):
"""
Cancelles an invoice
:param invoice_id: the invoice id
:return Response
"""
return self._create_put_request(
resource=INVOICES,
billomat_id=invoice_id,
command=CANCEL,
) | csn |
Initializes a new service. | @SuppressWarnings("unchecked")
private RaftServiceContext initializeService(PrimitiveId primitiveId, PrimitiveType primitiveType, String serviceName, byte[] config) {
RaftServiceContext oldService = raft.getServices().getService(serviceName);
ServiceConfig serviceConfig = config == null ? new ServiceConfig() ... | csn |
// GetSettings retrieves settings from the ArgoCDConfigMap and secret. | func (mgr *SettingsManager) GetSettings() (*ArgoCDSettings, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
if err != nil {
return nil, err
}
argoCDSecret, err := mgr.secrets.Secrets(mgr.namesp... | csn |
Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph | def remove_isolated_nodes_op(graph):
"""Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph
"""
rv = graph.copy()
nodes = list(nx.isolates(rv))
rv.remove_nodes_from(nodes)
return rv | csn |
Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead.
For consistency, gradient functions always return a tupl... | def _create_joint(fwdbwd, func, wrt, input_derivative):
"""Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead... | csn |
Determine whether a given key is filterable
@param string $key
@return bool | public function isFilterable(string $key): bool
{
if ($this->filterable === self::ALLOW_ALL) {
return true;
}
return isset($this->filterable[$key]) && $this->filterable[$key];
} | csn |
Borrow an object from the pool, or create a new object
if no valid objects in the pool
@return {@link Entry} to the pooled object
@throws E exception thrown by initializer | public Entry borrow() throws E {
long now = System.currentTimeMillis();
if (timeout > 0) {
long accessed_ = accessed.get();
if (now > accessed_ + Time.SECOND &&
accessed.compareAndSet(accessed_, now)) {
Entry entry;
while ((entry = deque.pollLast()) != null) {
// inactiveCount.decrem... | csn |
Creates a new Server object. Also creates an HTTP server to start listening
for XML-RPC method calls. Will emit an event with the XML-RPC call's method
name when receiving a method call.
@constructor
@param {Object|String} options - The HTTP server options. Either a URI string
(e.g. 'http://localhost:9090') or an obje... | function Server(options, isSecure, onListening) {
if (false === (this instanceof Server)) {
return new Server(options, isSecure)
}
onListening = onListening || function() {}
var that = this
// If a string URI is passed in, converts to URI fields
if (typeof options === 'string') {
options = url.par... | csn |
Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
def not_exposed(self):
... | def public(self, name=None):
"""Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
... | csn |
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
first_axis : string
An object or changeset key for the collatio... | def _collate_data(collation, first_axis, second_axis):
"""
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
firs... | csn |
Check if sending the given message was enabled by the client.
@param message
the message to check
@return true if the message should be sent, false otherwise (and the message is discarded) | protected boolean checkSendMessageEnabled(RTMPMessage message) {
IRTMPEvent body = message.getBody();
if (!receiveAudio && body instanceof AudioData) {
// The user doesn't want to get audio packets
((IStreamData<?>) body).getData().free();
if (sendBlankAudio) {
... | csn |
Moves the positon based on a direction.
@param int $direction
@return void | public function move($direction)
{
if ($direction === self::DIR_FORWARD) {
return $this->next();
} elseif ($direction === self::DIR_BACKWARD) {
return $this->prev();
}
throw new InvalidArgumentException(sprintf('Unknown direction %s', $direction));
} | csn |
// Build the mount_sample tool if it has not yet been built for this process.
// Return its contents. | func getToolContents() (contents []byte, err error) {
// Get hold of the binary contents, if we haven't yet.
getToolContents_Once.Do(func() {
getToolContents_Contents, getToolContents_Err = getToolContentsImpl()
})
contents, err = getToolContents_Contents, getToolContents_Err
return
} | csn |
Get an instance of a validation class.
@param string $name
@return validator\Validation
@throws exceptions\ValidatorException | private function getValidation(string $name): validator\Validation
{
if (!isset($this->validations[$name])) {
if (isset($this->validationRegister[$name])) {
$class = $this->validationRegister[$name];
} else {
throw new exceptions\ValidatorException("Va... | csn |
// Returns a visualization of the string. | func (s StringObject) String() string {
return fmt.Sprintf("StringObject{Key: %s, Value: '%s'}", DataToString(s.Key), DataToString(s.Value))
} | csn |
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 |
// Dequeue pulls a message off the queue
// If there are no messages, it waits for one.
// If the buffer is closed, it will return immediately. | func (r *messageRing) Dequeue() (*Message, error) {
r.mu.Lock()
for len(r.queue) == 0 && !r.closed {
r.wait.Wait()
}
if r.closed {
r.mu.Unlock()
return nil, errClosed
}
msg := r.queue[0]
r.queue = r.queue[1:]
r.sizeBytes -= int64(len(msg.Line))
r.mu.Unlock()
return msg, nil
} | csn |
Set the current agent's state to Ready on the voice channel.
@param reasons Information on causes for, and results of, actions taken by the user of the current DN. For details about reasons, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Reasons).... | public void setAgentReady(KeyValueCollection reasons, KeyValueCollection extensions) throws WorkspaceApiException {
try {
VoicereadyData readyData = new VoicereadyData();
readyData.setReasons(Util.toKVList(reasons));
readyData.setExtensions(Util.toKVList(extensions));
... | csn |
// CreateForwardingPathList creates a new child ForwardingPathList under the Domain | func (o *Domain) CreateForwardingPathList(child *ForwardingPathList) *bambou.Error {
return bambou.CurrentSession().CreateChild(o, child)
} | csn |
Calculate the vertices that define the position of a graphical object within
the worksheet in EMUs.
The vertices are expressed as English Metric Units (EMUs). There are 12,700
EMUs per point. Therefore, 12,700 * 3 /4 = 9,525 EMUs per pixel. | def position_object_emus(col_start, row_start, x1, y1, width, height, x_dpi = 96, y_dpi = 96) #:nodoc:
col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs =
position_object_pixels(col_start, row_start, x1, y1, width, height)
# Convert the pixel values to EMUs. See above.
x1 ... | csn |
// CropCenter cuts out a rectangular region with the specified size
// from the center of the image and returns the cropped image. | func CropCenter(img image.Image, width, height int) *image.NRGBA {
return CropAnchor(img, width, height, Center)
} | csn |
Disable all benchmarking. | def disable():
"""
Disable all benchmarking.
"""
Benchmark.enable = False
ComparisonBenchmark.enable = False
BenchmarkedFunction.enable = False
BenchmarkedClass.enable = False | csn |
// resetBuffer makes a local pointer to the buffer,
// then resets the buffer by assigning to be a newly-
// made value to clear it out, then sets the buffer
// item count to 0. It returns the copied pointer to
// the original map so the old buffer value can be
// used locally. | func resetBuffer() map[string]interface{} {
bufferMu.Lock()
bufCopy := buffer
buffer = make(map[string]interface{})
bufferItemCount = 0
bufferMu.Unlock()
return bufCopy
} | csn |
Check if a neurite process backtracks to a previous node. Back-tracking takes place
when a daughter of a branching process goes back and either overlaps with a previous point, or
lies inside the cylindrical volume of the latter.
Args:
neurite(Neurite): neurite to operate on
Returns:
Tr... | def is_back_tracking(neurite):
''' Check if a neurite process backtracks to a previous node. Back-tracking takes place
when a daughter of a branching process goes back and either overlaps with a previous point, or
lies inside the cylindrical volume of the latter.
Args:
neurite(Neurite): neurite... | csn |
Helper method for performing requests to the homeserver.
@param method [Symbol] HTTP request method to use. Use only symbols
available as keys in {METHODS}.
@param path [String] The API path to query, relative to the base
API path, eg. `/login`.
@param opts [Hash] Additional request options.
@option opts [H... | def make_request(method, path, opts = {}, &block)
path = (opts[:base] || @base_uri) + URI.encode(path)
options = make_options opts[:params], opts[:content], opts[:headers]
parse_response METHODS[method].call(path, options, &block)
end | csn |
Similar to parse but returns a list of Options objects instead
of the dictionary format. | def parse_options(cls, line, ns={}):
"""
Similar to parse but returns a list of Options objects instead
of the dictionary format.
"""
parsed = cls.parse(line, ns=ns)
options_list = []
for spec in sorted(parsed.keys()):
options = parsed[spec]
... | csn |
Run server with provided command line arguments. | def start(args):
"""Run server with provided command line arguments.
"""
application = tornado.web.Application([(r"/run", run.get_handler(args)),
(r"/status", run.StatusHandler)])
application.runmonitor = RunMonitor()
application.listen(args.port)
torna... | csn |
// GenTLSConfig loads TLS related configuration parameters. | func GenTLSConfig(tc *TLSConfigOpts) (*tls.Config, error) {
// Now load in cert and private key
cert, err := tls.LoadX509KeyPair(tc.CertFile, tc.KeyFile)
if err != nil {
return nil, fmt.Errorf("error parsing X509 certificate/key pair: %v", err)
}
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if e... | csn |
// pruneDeadHolders is used to remove all the dead lock holders | func (s *Semaphore) pruneDeadHolders(lock *semaphoreLock, pairs KVPairs) {
// Gather all the live holders
alive := make(map[string]struct{}, len(pairs))
for _, pair := range pairs {
if pair.Session != "" {
alive[pair.Session] = struct{}{}
}
}
// Remove any holders that are dead
for holder := range lock.Ho... | csn |
Read and return the data from a corpus json file. | def read_corpus(file_name):
"""
Read and return the data from a corpus json file.
"""
with io.open(file_name, encoding='utf-8') as data_file:
return yaml.load(data_file) | csn |
r"""Calculate the matrices omega_ij, gamma_ij, r_pij.
This function calculates the matrices omega_ij, gamma_ij and r_pij given a
list of atomic states. The states can be arbitrarily in their fine,
hyperfine or magnetic detail. | def calculate_matrices(states, Omega=1):
r"""Calculate the matrices omega_ij, gamma_ij, r_pij.
This function calculates the matrices omega_ij, gamma_ij and r_pij given a
list of atomic states. The states can be arbitrarily in their fine,
hyperfine or magnetic detail.
"""
# We check that all sta... | csn |
Get an absolute path to a lock file for a specified file path.
@param string $file The absolute path to get the lock filename for.
@param array $options An array of options for the process.
@return string The absolute path for the lock file | protected function lockFileName($file, array $options = array()) {
$lockDir = $this->getOption('lock_dir', $options, $this->getCachePath() . 'locks' . DIRECTORY_SEPARATOR);
return $lockDir . preg_replace('/\W/', '_', $file) . $this->getOption(xPDO::OPT_LOCKFILE_EXTENSION, $options, '.lock');
} | csn |
// Reads an error out of the HTTP response, or does nothing if
// no error occurred. | func getError(res *http.Response) (*http.Response, error) {
// Do nothing if the response is a successful 2xx
if res.StatusCode/100 == 2 {
return res, nil
}
var apiError ApiError
// ReadAll is usually a bad practice, but here we need to read the response all
// at once because we may attempt to use the data twi... | csn |
Updates the gutter markers for the specified range
@param {!CodeMirror} cm the CodeMirror instance for the active editor
@param {!number} from the starting line for the update
@param {!number} to the ending line for the update | function updateFoldInfo(cm, from, to) {
var minFoldSize = prefs.getSetting("minFoldSize") || 2;
var opts = cm.state.foldGutter.options;
var fade = prefs.getSetting("hideUntilMouseover");
var $gutter = $(cm.getGutterElement());
var i = from;
function clear(m) {
... | csn |
Write the point options of Elements
@return options as JSON object
@throws java.io.IOException If an I/O error occurs | public String encode() throws IOException {
FastStringWriter fsw = new FastStringWriter();
try {
ChartUtils.writeDataValue(fsw, "radius", this.radius, false);
ChartUtils.writeDataValue(fsw, "pointStyle", this.pointStyle, true);
ChartUtils.writeDataValue(fsw, "backgro... | csn |
Initialize the properties of the scene.
800x600 with transparent background and a Region as Parent Node
@return the scene built
@throws CoreException if build fails | protected final Scene buildScene() throws CoreException {
final Scene scene = new Scene(buildRootPane(),
StageParameters.APPLICATION_SCENE_WIDTH.get(),
StageParameters.APPLICATION_SCENE_HEIGHT.get(),
... | csn |
This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course if that fails too, a ValueError is raised. | def _enumload(l: Loader, value, type_) -> Enum:
"""
This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course... | csn |
Handling other not caught exceptions.
@param \OxidEsales\Eshop\Core\Exception\StandardException $exception | protected function _handleBaseException($exception)
{
$this->logException($exception);
if ($this->_isDebugMode()) {
\OxidEsales\Eshop\Core\Registry::getUtilsView()->addErrorToDisplay($exception);
$this->_process('exceptionError', 'displayExceptionError');
}
} | csn |
// SortedKeys returns a slice containing the sorted keys of map m. Argument t
// is the type implementing sort.Interface which is used to sort. | func SortedKeys(m interface{}, t reflect.Type) interface{} {
v := reflect.ValueOf(m)
if v.Kind() != reflect.Map {
panic("wrong type")
}
s := reflect.MakeSlice(reflect.SliceOf(v.Type().Key()), v.Len(), v.Len())
for i, k := range v.MapKeys() {
s.Index(i).Set(k)
}
s = s.Convert(t)
sort.Sort(s.Interface().(so... | csn |
Load refresh token details by token
@param string $refresh_token Refresh token
@return array Refresh token details | public function getRefreshToken($refresh_token)
{
// create refresh token
$token = \Components\Developer\Models\Refreshtoken::oneByToken($refresh_token);
// make sure we have a token
if (!$token->get('id'))
{
return false;
}
// make sure its a published token
if (!$token->isPublished())
{
ret... | csn |
Enqueues markup to be rendered and inserted at a supplied index.
@param {string} parentID ID of the parent component.
@param {string} markup Markup that renders into an element.
@param {number} toIndex Destination index.
@private | function enqueueMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
textContent: null,
fromIndex: null,
toIndex:... | csn |
Builds the item from provided search hit. | private function buildItem(SearchHit $searchHit): Item
{
/** @var \eZ\Publish\API\Repository\Values\Content\Location $location */
$location = $searchHit->valueObject;
/** @var \eZ\Publish\API\Repository\Values\Content\Content $content */
$content = $this->repository->sudo(
... | csn |
Retrieve an indexed element and return it as a Double.
@param index An integer value specifying the offset from the beginning of the array.
@return The element as a Double, or null if the element is not found. | public Double getDouble (int index) {
String string = getString (index);
return (string != null) ? Double.parseDouble (string) : null;
} | csn |
Return the patch | def patch(self):
"""Return the patch"""
resp = self._get(self._api,
headers={'Accept': 'application/vnd.github.patch'})
return resp.content if self._boolean(resp, 200, 404) else None | csn |
Delete my locks.
@return ResultResponse
@Route("/deletemy", name="locks_delete_my") | public function deletemyAction()
{
$uid = $this->getUser()->getId();
$lockManager = $this->get('phlexible_element.element_lock_manager');
$myLocks = $lockManager->findBy(['userId' => $uid]);
foreach ($myLocks as $lock) {
$lockManager->deleteLock($lock);
}
... | csn |
Gets the value of the dispQuoteOrSpeechOrStatement property.
<p>
This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a <CODE>set</CODE> method for the dispQuoteOrSpeechOrStat... | public java.util.List<Object> getDispQuoteOrSpeechOrStatement() {
if (dispQuoteOrSpeechOrStatement == null) {
dispQuoteOrSpeechOrStatement = new ArrayList<Object>();
}
return this.dispQuoteOrSpeechOrStatement;
} | csn |
// Get returns the current merkle root, and the server timestamp of
// that root. To help avoid having too frequent calls into the API
// server, caller can provide a positive tolerance, to accept stale
// LimitBytes and UsageBytes data. If tolerance is 0 or negative, this
// always makes a blocking RPC to bserver and ... | func (ecmr *EventuallyConsistentMerkleRoot) Get(
ctx context.Context, bgTolerance, blockTolerance time.Duration) (
timestamp time.Time, root keybase1.MerkleRootV2,
rootTime time.Time, err error) {
c := ecmr.getCached()
err = ecmr.fetcher.Do(ctx, bgTolerance, blockTolerance, c.timestamp)
if err != nil {
return t... | csn |
Static factory method to create a new client instance.
This method produces a client connected to the supplied addresses.
@param addresses one or more addresses to connect to.
@return a new RiakClient instance.
@throws java.net.UnknownHostException if a supplied hostname cannot be resolved. | public static RiakClient newClient(InetSocketAddress... addresses) throws UnknownHostException
{
final List<String> remoteAddresses = new ArrayList<>(addresses.length);
for (InetSocketAddress addy : addresses)
{
remoteAddresses.add(
String.format("%s:%s", add... | csn |
// openDev find and open an interface. | func openDev(config Config) (ifce *Interface, err error) {
// find the device in registry.
deviceid, err := getdeviceid(config.PlatformSpecificParams.ComponentID, config.PlatformSpecificParams.InterfaceName)
if err != nil {
return nil, err
}
path := "\\\\.\\Global\\" + deviceid + ".tap"
pathp, err := syscall.UT... | csn |
Return the service as a JSON string. | def as_text(self, is_pretty=False):
"""Return the service as a JSON string."""
values = {
'type': self._type,
self.SERVICE_ENDPOINT: self._service_endpoint,
}
if self._consume_endpoint is not None:
values[self.CONSUME_ENDPOINT] = self._consume_endpoint... | csn |
Start capturing and bundling current output.
@param array $options
@return Bundle | public function start(array $options = array())
{
$currentBundleOptions = array(
'docroot' => $this->getDocRoot(),
'bypass' => $this->getBypass()
);
$this->currentBundleOptions = array_merge($currentBundleOptions, $options);
ob_start();
return $this... | csn |
assign a value to a visible Field of a object
@param obj Object to assign value to his property
@param prop name of property
@param value Value to assign
@throws PageException | public static boolean setField(Object obj, String prop, Object value) throws PageException {
Class clazz = value.getClass();
try {
Field[] fields = getFieldsIgnoreCase(obj.getClass(), prop);
// exact comparsion
for (int i = 0; i < fields.length; i++) {
if (toReferenceClass(fields[i].getType()) == cla... | csn |
//GetIndex returns the ActionInterface at the index or nil
//supports negative indexing | func (a *ActDepend) getIndex(ind int) ActionInterface {
ind, ok := a.correctIndex(ind)
if !ok {
return nil
}
return a.waiters[ind]
} | csn |
// Send emits the given message on the 'Out' channel. the send Timesout after 100 ms in order to chaeck of the Pipe has stopped and we've been asked to exit.
// If the Pipe has been stopped, the send will fail and there is no guarantee of either success or failure | func (p *Pipe) Send(msg message.Msg, off offset.Offset) {
p.MessageCount++
for _, ch := range p.Out {
A:
for {
select {
case ch <- TrackedMessage{msg, off}:
break A
}
}
}
} | csn |
// List selects resources in the storage which match to the selector. | func (r *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {
// populate the label selector, defaulting to all
metricSelector := labels.Everything()
if options != nil && options.LabelSelector != nil {
metricSelector = options.LabelSelector
}
namespace := genericap... | csn |
Retrieves all invoices from Xero
Usage : get_invoices
get_invoices(:invoice_id => "297c2dc5-cc47-4afd-8ec8-74990b8761e9")
get_invoices(:invoice_number => "175")
get_invoices(:contact_ids => ["297c2dc5-cc47-4afd-8ec8-74990b8761e9"] )
Note : modified_since is in UTC format (i.e. Brisbane i... | def get_invoices(options = {})
request_params = {}
request_params[:InvoiceID] = options[:invoice_id] if options[:invoice_id]
request_params[:InvoiceNumber] = options[:invoice_number] if options[:invoice_number]
request_params[:order] = options[:order] if options[:order]
re... | csn |
// NewKeyedBlake2B returns a new 512-bit BLAKE2B hash with the given secret key. | func NewKeyedBlake2B(key []byte) hash.Hash {
return New(&Config{Size: 64, Key: key})
} | csn |
Create FC port.
:returns: JSON for FC port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"VirtualAddress":{
"WWNN":{
},
... | def get_json(self):
"""Create FC port.
:returns: JSON for FC port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"VirtualAddress":{
"WWNN":{
... | csn |
Returns first route annotation for method.
@param \ReflectionMethod $reflectionMethod
@return RouteAnnotation[] | private function readRouteAnnotation(\ReflectionMethod $reflectionMethod)
{
$annotations = [];
if ($newAnnotations = $this->readMethodAnnotations($reflectionMethod, 'Route')) {
$annotations = array_merge($annotations, $newAnnotations);
}
return $annotations;
} | csn |
Formats an error message. | def xpatherror(self, file, line, no):
"""Formats an error message. """
libxml2mod.xmlXPatherror(self._o, file, line, no) | csn |
Determine when the next log rotation
should take place.
\param int $currentTime
Current time, as a UNIX timestamp.
\retval int
UNIX timestamp for the next log rotation. | protected function computeRollover($currentTime)
{
if ($this->when == 'MIDNIGHT') {
return strtotime("midnight + 1 day", $currentTime);
}
if (substr($this->when, 0, 1) == 'W') {
return strtotime(
"next " . self::$dayNames[$this->dayOfWeek],
... | csn |
Returns the Config in a format suitable for revealing to users.
@return A ConfigResponse of the current config. Passwords will be encrypted and the default login wil be removed. | @Override
public ConfigResponse<T> getConfigResponse() {
T config = this.config.get();
config = withoutDefaultLogin(config);
if (config instanceof PasswordsConfig<?>) {
config = ((PasswordsConfig<T>) config).withoutPasswords();
}
return new ConfigResponse<>(con... | csn |
Returns the thread context that was captured at the point when the task was submitted.
@param execProps execution properties for the persistent task.
@return the thread context that was captured at the point when the task was submitted.
@throws IOException
@throws ClassNotFoundException | public ThreadContextDescriptor deserializeThreadContext(Map<String, String> execProps) throws IOException, ClassNotFoundException {
return threadContextBytes == null ? null : ThreadContextDeserializer.deserialize(threadContextBytes, execProps);
} | csn |
// NewMockTransactional creates a new mock instance | func NewMockTransactional(ctrl *gomock.Controller) *MockTransactional {
mock := &MockTransactional{ctrl: ctrl}
mock.recorder = &MockTransactionalMockRecorder{mock}
return mock
} | csn |
Sets the tickmark sections of the gauge to the given array of section objects
@param TICKMARK_SECTIONS_ARRAY | public void setTickmarkSections(final Section... TICKMARK_SECTIONS_ARRAY) {
tickmarkSections.clear();
for (Section tickmarkSection : TICKMARK_SECTIONS_ARRAY) {
tickmarkSections.add(new Section(tickmarkSection.getStart(), tickmarkSection.getStop(), tickmarkSection.getColor()));
}
... | csn |
Create shortcuts for this widget. | def create_shortcuts(self):
"""Create shortcuts for this widget."""
# Configurable
copyfig = config_shortcut(self.copy_figure, context='plots',
name='copy', parent=self)
prevfig = config_shortcut(self.go_previous_thumbnail, context='plots',
... | csn |
// ChangeLogLevel changes Envoy log level to correspond to the logrus log level 'level'. | func (e *Envoy) ChangeLogLevel(level logrus.Level) {
e.admin.changeLogLevel(level)
} | csn |
Processes LTI tools element data
@param array|stdClass $data | public function process_enrol_lti_tool($data) {
global $DB;
$data = (object) $data;
// Store the old id.
$oldid = $data->id;
// Change the values before we insert it.
$data->timecreated = time();
$data->timemodified = $data->timecreated;
// Now we can ... | csn |
read all text into memory. | def read_text(self, encoding='utf-8') -> str:
''' read all text into memory. '''
with self.open('r', encoding=encoding) as fp:
return fp.read() | csn |
Generates an empty class.
@param className The classes name.
@param superName The super object, which the class extends from.
@param interfaces The name of the interfaces which this class implements.
@param classModifiers The modifiers to the class.
@return A class writer that will be used to write the remaining inform... | static ClassWriter generateClass(String className, String superName, String[] interfaces, String signature, int classModifiers, String apiName) {
ClassWriter classWriter = new ClassWriter(0);
if (interfaces != null){
for (int i = 0; i < interfaces.length; i++) {
interfaces[i... | csn |