query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
protected Response upload(String name, File fileToUpload, String mediaTypeString, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
| return (upload(name, fileToUpload, mediaTypeString, null, url));
} | csn_ccr |
def _mmComputeSequenceRepresentationData(self):
"""
Calculates values for the overlap distance matrix, stability within a
sequence, and distinctness between sequences. These values are cached so
that they do need to be recomputed for calls to each of several accessor
methods that use these values.
... | []
for i in xrange(n):
for j in xrange(i+1):
overlapUnionSDR = len(unionSDRTrace.data[i] & unionSDRTrace.data[j])
overlapMatrix[i][j] = overlapUnionSDR
overlapMatrix[j][i] = overlapUnionSDR
if (i != j and
sequenceLabelsTrace.data[i] is not None and
n... | csn_ccr |
public String getResults(long totalErrors) {
Object[] info = { fileCount, doneTasks.get(COMPILED).get(),
startedTasks.get(COMPILED).get(),
doneTasks.get(ANNOTATION).get(),
startedTasks.get(ANNOTATION).get(), doneTasks.get(XML).get(),
| startedTasks.get(XML).get(), doneTasks.get(DEP).get(),
startedTasks.get(DEP).get(), totalErrors, buildTime,
convertToMB(heapUsed.get()), convertToMB(heapTotal.get()),
convertToMB(nonHeapUsed.get()), convertToMB(nonHeapTotal.get()) };
return MessageUtils.format(MSG_STATISTICS_TEMPLATE, info);
} | csn_ccr |
// Wait on specified services to be in the given state | func (s *Server) WaitService(request *WaitServiceRequest, throwaway *string) error {
err := s.f.WaitService(s.context(), request.State, request.Timeout, request.Recursive, request.ServiceIDs...)
return err
} | csn |
public static void fillCircle(Graphics g, int centerX, int centerY, int diam){
| g.fillOval((int) (centerX-diam/2), (int) (centerY-diam/2), diam, diam);
} | csn_ccr |
gets the property value for items | def items(self):
'''gets the property value for items'''
self.__init()
items = []
for item in self._items:
items.append(
UserItem(url="%s/items/%s" % (self.location, item['id']),
securityHandler=self._securityHandler,
... | csn |
// Encode a reference to int32 pointer. | func (o *Buffer) enc_ref_int32(p *Properties, base structPointer) error {
v := structPointer_RefWord32(base, p.field)
if refWord32_IsNil(v) {
return ErrNil
}
x := refWord32_Get(v)
o.buf = append(o.buf, p.tagcode...)
p.valEnc(o, uint64(x))
return nil
} | csn |
protected final Definition bean(Class<?> clazz) {
Definition def = new Definition(clazz.getName(), | clazz, Scope.SINGLETON.toString());
def.beanName = clazz.getName() + "#" + Math.abs(System.identityHashCode(def));
return def;
} | csn_ccr |
Register external services used in this package.
Currently this consists of:
- PragmaRX\Google2FA
- Laravel\Socialite
- Yajra\Datatables | public function register_services()
{
// Register the Socialite Factory.
// From: Laravel\Socialite\SocialiteServiceProvider
$this->app->singleton('Laravel\Socialite\Contracts\Factory', function ($app) {
return new SocialiteManager($app);
});
// Slap in the Eve... | csn |
def list_instances(self, machine_state):
"""Returns the list of the instances in the Cloud.
in machine_state of type :class:`CloudMachineState`
out return_names of type str
VM names.
return return_ids of type str
VM ids.
"""
if | not isinstance(machine_state, CloudMachineState):
raise TypeError("machine_state can only be an instance of type CloudMachineState")
(return_ids, return_names) = self._call("listInstances",
in_p=[machine_state])
return (return_ids, return_names) | csn_ccr |
def update(self, command=None, **kwargs):
"""update data, which is usually passed in ArgumentParser initialization
e.g. command.update(prog="foo")
"""
if command is None:
argparser = self.argparser |
else:
argparser = self[command]
for k,v in kwargs.items():
setattr(argparser, k, v) | csn_ccr |
def reorder(things, ids)
ordered_things = []
ids.each do |id|
thing = | things.find{ |t| t.id.to_s == id.to_s }
ordered_things |= [thing] if thing
end
ordered_things
end | csn_ccr |
def _install_wrappers(self):
"""
Install our PluginLoader monkey patches and update global variables
with references to the real functions.
"""
global action_loader__get
action_loader__get = ansible_mitogen.loaders.action_loader.get
ansible_mitogen.loaders.action_... |
global connection_loader__get
connection_loader__get = ansible_mitogen.loaders.connection_loader.get
ansible_mitogen.loaders.connection_loader.get = wrap_connection_loader__get
global worker__run
worker__run = ansible.executor.process.worker.WorkerProcess.run
ansible.e... | csn_ccr |
Which mapper sent this key sum?
@param key Key to check
@param numReducers Number of reducers
@param maxKeySpace Max key space
@return Mapper that send this key sum | private static int getMapperId(long key, int numReducers, int maxKeySpace) {
key = key - getFirstSumKey(numReducers, maxKeySpace);
return (int) (key / numReducers);
} | csn |
protected function unload()
{
foreach ($this->ial as $entry) {
if (isset($entry['TIMER'])) {
| $this->removeTimer($entry['TIMER']);
}
}
} | csn_ccr |
public function getFilePath(User $receiver)
{
$basePath = $this->getOption(self::CONFIG_FILEPATH);
if (is_null($basePath) || !file_exists($basePath)) {
throw new \common_exception_InconsistentData('Missing path '.self::CONFIG_FILEPATH.' for '.__CLASS__);
}
| $path = $basePath.\tao_helpers_File::getSafeFileName($receiver->getIdentifier()).DIRECTORY_SEPARATOR;
if (!file_exists($path)) {
mkdir($path);
}
return $path.\tao_helpers_File::getSafeFileName('message.html', $path);
} | csn_ccr |
Cycles among the arguments with the current loop index. | def cycle(self, *args):
"""Cycles among the arguments with the current loop index."""
if not args:
raise TypeError('no items for cycling given')
return args[self.index0 % len(args)] | csn |
Write a function named `first_non_repeating_letter` that takes a string input, and returns the first character that is not repeated anywhere in the string.
For example, if given the input `'stress'`, the function should return `'t'`, since the letter *t* only occurs once in the string, and occurs first in the string.
... | def first_non_repeating_letter(string):
string_lower = string.lower()
for i, letter in enumerate(string_lower):
if string_lower.count(letter) == 1:
return string[i]
return "" | apps |
text type and size in shell for python | def _size_36():
""" returns the rows, columns of terminal """
from shutil import get_terminal_size
dim = get_terminal_size()
if isinstance(dim, list):
return dim[0], dim[1]
return dim.lines, dim.columns | cosqa |
Appends a range to the tracker. The range has to be after the last DrId
of the tracker.
@param startDrId
@param endDrId
@param spUniqueId
@param mpUniqueId | public void append(long startDrId, long endDrId, long spUniqueId, long mpUniqueId) {
assert(startDrId <= endDrId && (m_map.isEmpty() || startDrId > end(m_map.span())));
addRange(startDrId, endDrId, spUniqueId, mpUniqueId);
} | csn |
public function deleteDirs()
{
$dirs = $this->files->directories($this->basePath);
foreach ($dirs as $dir) {
| $this->files->deleteDirectory($dir);
}
$this->info('Subdirectories deleted');
} | csn_ccr |
public function getSortableDirection($direction = null)
{
if ( ! is_null($direction))
{
| return $this->validateSortableDirection($direction);
}
return $this->getDefaultSortableDirection();
} | csn_ccr |
public static function fromResponse(Response $response)
{
$header = $response->headers->get('Link');
if (is_array($header)) {
| implode(',', $header);
}
return self::fromString($header);
} | csn_ccr |
Populates associative array of iOS versions.
@throws \Exception | private static function populate() {
$arr = array();
$epoch = 0;
if (!isset(self::$BuildVer) || !is_array(self::$BuildVer)) {
require __DIR__ .'/data.php';
if (empty($arr) || !is_array($arr) || empty($epoch)) {
throw new \Exception('Error fetching file data.php');
}
self::$Da... | csn |
def button(request):
"""If the user is logged in, returns the logout button, otherwise returns the login button""" |
if not authenticated_userid(request):
return markupsafe.Markup(SIGNIN_HTML)
else:
return markupsafe.Markup(SIGNOUT_HTML) | csn_ccr |
Updates the completer model.
:param words: Words to update the completer with.
:type words: tuple or list
:return: Method success.
:rtype: bool | def update_model(self, words):
"""
Updates the completer model.
:param words: Words to update the completer with.
:type words: tuple or list
:return: Method success.
:rtype: bool
"""
extended_words = DefaultCompleter._DefaultCompleter__tokens[self.__lang... | csn |
func ListenAndServe(handler Handler) error {
l, err := net.ListenPacket("udp4", ":67")
if err != nil {
| return err
}
defer l.Close()
return Serve(l, handler)
} | csn_ccr |
def _bg_combine(self, bgs):
"""Combine several background amplitude images"""
out = | np.ones(self.h5["raw"].shape, dtype=float)
# bg is an h5py.DataSet
for bg in bgs:
out *= bg[:]
return out | csn_ccr |
public static function getDrafts(Site $site)
{
$db = Database::connection();
$nc = self::getDraftsParentPage($site);
$r = $db->executeQuery('select Pages.cID from Pages inner join Collections c on Pages.cID = c.cID where cParentID = ? order by cDateAdded desc', [$nc->getCollectionID()]);
... | {
$entry = self::getByID($row['cID']);
if (is_object($entry)) {
$pages[] = $entry;
}
}
return $pages;
} | csn_ccr |
Get following people for pinner.
@param string $username
@param int $limit
@return Pagination | public function followingPeople($username, $limit = Pagination::DEFAULT_LIMIT)
{
return $this->following($username, UrlBuilder::FOLLOWING_PEOPLE, $limit);
} | csn |
Return the custom annotations declared in the configuration. | public List<String> getAnnotations() {
if (attribute.getColumnConfig().getCustomAnnotations() == null) {
return newArrayList();
}
AnnotationBuilder builder = new AnnotationBuilder();
for (CustomAnnotation ca : attribute.getColumnConfig().getCustomAnnotations()) {
... | csn |
def crossover(cross):
"""Return an inspyred crossover function based on the given function.
This function generator takes a function that operates on only
two parent candidates to produce an iterable sequence of offspring
(typically two). The generator handles the pairing of selected
parents and co... | This function is most commonly used as a function decorator with
the following usage::
@crossover
def cross(random, mom, dad, args):
# Implementation of paired crossing
pass
The generated function also contains an attribute named
``single_crossover`` which holds th... | csn_ccr |
Check parameter and return types for pre and post command hooks. | def _validate_prepostcmd_hook(cls, func: Callable, data_type: Type) -> None:
"""Check parameter and return types for pre and post command hooks."""
signature = inspect.signature(func)
# validate that the callable has the right number of parameters
cls._validate_callable_param_count(func,... | csn |
public function get($email, $default = null)
{
$this->setFormat('php');
$data = unserialize(
| file_get_contents($this->getUrl($email))
);
return (is_array($data) && isset($data['entry']))
? $data
: $default;
} | csn_ccr |
function (timeout, hash, uuid) {
var deferred = Q.defer();
this.events.emit('driver:message', {key: 'wait', timeout: timeout, | uuid: uuid, hash: hash, value: timeout + ' ms'});
setTimeout(function () {
deferred.resolve();
}.bind(this), timeout);
return deferred.promise;
} | csn_ccr |
def seek_to(topic, partition, offset)
@processed_offsets[topic] ||= {}
@processed_offsets[topic][partition] = | offset
@fetcher.seek(topic, partition, offset)
end | csn_ccr |
// globalFactor returns the current value of the global cost factor | func (ct *costTracker) globalFactor() float64 {
ct.gfLock.RLock()
defer ct.gfLock.RUnlock()
return ct.gf
} | csn |
public function valid()
{
// Check the current position.
if (!is_scalar($this->current) | || !isset($this->objects[$this->current]))
{
return false;
}
return true;
} | csn_ccr |
Object containers have string keys. The string key is composed of two parts.
The key has a 1-byte integer size and a variable length string value with no null-terminator.
@param type $key | protected function makeKeyString($key): string {
//convert numbers to strings.
$stringValue = (string)$key;
$length = strlen( $stringValue );
if( $length == 0 ){
throw new \Exception("Key values must be string values of at least 1 character. Empty strings cannot be used as in... | csn |
func (s *CopyDBParameterGroupInput) SetTargetDBParameterGroupIdentifier(v string) *CopyDBParameterGroupInput {
| s.TargetDBParameterGroupIdentifier = &v
return s
} | csn_ccr |
public function addMiddleware(string $middleware, bool $inner = true): int |
{
return $inner ? $this->onion->addInnerLayer($middleware) : $this->onion->addOuterLayer($middleware);
} | csn_ccr |
Returns a GraphNode representing the requested resources in an empty Graph
@param request
@return a GraphNode representing the resource | static GraphNode getServiceNode(HttpServletRequest request) {
final IRI serviceUri = new IRI(getFullRequestUrl(request));
final Graph resultGraph = new SimpleGraph();
return new GraphNode(serviceUri, resultGraph);
} | csn |
def restoreWCS(self,prepend=None):
""" Resets the WCS values to the original values stored in
the backup keywords recorded in self.backup.
"""
# Open header for image
image = self.rootname
if prepend: _prepend = prepend
elif self.prepend: _prepend = self.prep... | for key in self.wcstrans.keys():
# Get new keyword name based on old keyname
# and prepend string
if key != 'pixel scale':
_okey = self._buildNewKeyname(key,_prepend)
if _okey in _extn.header:
_extn.hea... | csn_ccr |
public static DesignContextMenu create() {
return PageUtil.createPage(DesignConstants.RESOURCE_PREFIX + "designContextMenu.fsp", ExecutionContext.getPage())
| .get(0).getAttribute("controller", DesignContextMenu.class);
} | csn_ccr |
def html_to_tags(code):
"""
Convert HTML code to tags.
``code`` is a string containing HTML code. The return value is a
list of corresponding instances of ``TagBase``.
"""
| code = ('<div>' + code + '</div>').encode('utf8')
el = ET.fromstring(code)
return [tag_from_element(c) for c in el] | csn_ccr |
public void clear() throws IOException {
try {
zooKeeper.setData(fullyQualifiedZNode, null, expectedZNodeVersion.get());
} catch (KeeperException.BadVersionException e) {
LOG.error(fullyQualifiedZNode + " has been updated by another process",
e);
throw new StaleVersionException(fully... | process!");
} catch (KeeperException e) {
keeperException("Unrecoverable ZooKeeper error clearing " +
fullyQualifiedZNode, e);
} catch (InterruptedException e) {
interruptedException("Interrupted clearing " + fullyQualifiedZNode, e);
}
} | csn_ccr |
calculates the unit signature vector used by unit_signature
@return [Array]
@raise [ArgumentError] when exponent associated with a unit is > 20 or < -20 | def unit_signature_vector
return to_base.unit_signature_vector unless base?
vector = Array.new(SIGNATURE_VECTOR.size, 0)
# it's possible to have a kind that misses the array... kinds like :counting
# are more like prefixes, so don't use them to calculate the vector
@numerator.map { |elemen... | csn |
Create SNS lambda event from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): Trigger rules from the settings | def create_sns_event(app_name, env, region, rules):
"""Create SNS lambda event from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): Trigger rules from the set... | csn |
def to_python(value, seen=None):
"""Reify values to their Python equivalents.
Does recursion detection, failing when that happens.
"""
seen = seen or set()
if isinstance(value, framework.TupleLike):
if value.ident in seen:
raise RecursionException('to_python: infinite recursion while evaluating %r'... | return {k: to_python(value[k], seen=new_seen) for k in value.exportable_keys()}
if isinstance(value, dict):
return {k: to_python(value[k], seen=seen) for k in value.keys()}
if isinstance(value, list):
return [to_python(x, seen=seen) for x in value]
return value | csn_ccr |
Add authentication information to the connection. This will be used to identify the user and check access to
nodes protected by ACLs
@param scheme
@param auth | public void addAuthInfo(final String scheme, final byte[] auth) {
retryUntilConnected(new Callable<Object>() {
@Override
public Object call() throws Exception {
_connection.addAuthInfo(scheme, auth);
return null;
}
});
} | csn |
def remove(self, index):
'''
Delete one or more relationship, by index, from the extent
index - either a single index or a list of indices
'''
raise NotImplementedError
if hasattr(index, '__iter__'):
ind = set(index)
else:
| ind = [index]
# Rebuild relationships, excluding the provided indices
self._relationships = [r for i, r in enumerate(self._relationships) if i not in ind] | csn_ccr |
protected function locateSelfMedia() {
$url = esc_url( wp_get_attachment_url( $this->post_id ) );
$mime = get_post_mime_type( $this->post_id );
list( $type, $subtype ) = false !== strpos( $mime, '/' ) ? explode( '/', $mime ) : [ $mime, | '' ];
return in_array( $type, [ 'audio', 'video' ] )
? call_user_func( "wp_{$type}_shortcode", [ 'src' => $url ] )
: '';
} | csn_ccr |
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list.
Of course... | from itertools import combinations
def area(t):
(a,b),(c,d),(e,f) = t
return abs(a*d+b*e+c*f-d*e-a*f-b*c)/2
def find_biggTriang(lst):
tris = list(combinations(lst,3))
areas = list(map(area,tris))
m = max(areas)
mTris = [list(map(list,t)) for t,v in zip(tris,areas) if v==m]
return [ le... | apps |
libtcodpy style callback, needs to preserve the old userData issue. | def _pycall_path_old(x1: int, y1: int, x2: int, y2: int, handle: Any) -> float:
"""libtcodpy style callback, needs to preserve the old userData issue."""
func, userData = ffi.from_handle(handle)
return func(x1, y1, x2, y2, userData) | csn |
zend implementation overridden to avoid pathInfo getting modified even if route didn't match | public function match($request, $partial = null)
{
$path = trim($request->getPathInfo(), self::URI_DELIMITER);
$subPath = $path;
$values = array();
$numRoutes = count($this->_routes);
$matchedPath = null;
foreach ($this->_routes as $key => $route) {... | csn |
func BackendError(b ServiceBackend, zone string, rcode int, state request.Request, err error, opt Options) (int, error) {
m := new(dns.Msg)
m.SetRcode(state.Req, rcode)
m.Authoritative, m.RecursionAvailable, m.Compress = true, true, true
m.Ns, _ = SOA(b, zone, state, opt)
| state.SizeAndDo(m)
state.W.WriteMsg(m)
// Return success as the rcode to signal we have written to the client.
return dns.RcodeSuccess, err
} | csn_ccr |
returns a Dispatcher instance.
@return dispatcher instance | public Dispatcher getInstance() {
try {
return (Dispatcher) Class.forName(dispatcherImpl)
.getConstructor(Configuration.class).newInstance(conf);
} catch (InstantiationException e) {
throw new AssertionError(e);
} catch (IllegalAccessException e) {
... | csn |
func findNextInitContainerToRun(pod *v1.Pod, podStatus *kubecontainer.PodStatus) (status *kubecontainer.ContainerStatus, next *v1.Container, done bool) {
if len(pod.Spec.InitContainers) == 0 {
return nil, nil, true
}
// If there are failed containers, return the status of the last failed one.
for i := len(pod.Sp... | == kubecontainer.ContainerStateRunning {
return nil, nil, false
}
if status.State == kubecontainer.ContainerStateExited {
// all init containers successful
if i == (len(pod.Spec.InitContainers) - 1) {
return nil, nil, true
}
// all containers up to i successful, go to i+1
return nil, &pod.S... | csn_ccr |
Display a message in console.
@param $message
@param string $type | public function message($message, $type = 'line')
{
if (! is_null($this->command)) {
$this->command->{$type}($message);
}
} | csn |
public RestoreObjectRequest withTier(Tier tier) {
this.tier = tier == null ? | null : tier.toString();
return this;
} | csn_ccr |
// WriteChainConfig writes the chain config settings to the database. | func WriteChainConfig(db ethdb.Writer, hash common.Hash, cfg *params.ChainConfig) {
if cfg == nil {
return
}
data, err := json.Marshal(cfg)
if err != nil {
log.Crit("Failed to JSON encode chain config", "err", err)
}
if err := db.Put(configKey(hash), data); err != nil {
log.Crit("Failed to store chain confi... | csn |
public static Validator validCharset(String... charsets) {
if (null == charsets || | charsets.length == 0) {
return new ValidCharset();
} else {
return new ValidCharset(charsets);
}
} | csn_ccr |
public function base32_decode($hash)
{
$lookup = $this->getLookup();
if (preg_match('/^['.implode('', array_keys($lookup)).']+$/', $hash) == false) {
throw new \InvalidArgumentException('Invalid base32 hash!');
}
$hash = strtoupper($hash);
$buffer = 0;
$... | $buffer += $lookup[$hash[$i]];
$length += 5;
if ($length >= 8) {
$length -= 8;
$binary .= chr(($buffer & (0xFF << $length)) >> $length);
}
}
return $binary;
} | csn_ccr |
Will parse attributes.
@param string $html
@return string Remaining HTML. | private function parseAttribute(string $html) : string
{
$remainingHtml = ltrim($html);
try {
// Will match the first entire name/value attribute pair.
preg_match(
"/((([a-z0-9\-_]+:)?[a-z0-9\-_]+)(\s*=\s*)?)/i",
$remainingHtml,
... | csn |
public static function fix_revision_values(array $versions) {
$byrev = [];
foreach ($versions as $version) {
if ($version->revision === '') {
$version->revision = userdate($version->timecreated, get_string('strftimedate', 'core_langconfig'));
}
$byre... | foreach ($versions as $version) {
if ($version->id == $versionid) {
$version->revision = $version->revision.' - v'.$cnt;
$cnt--;
break;
}
}
... | csn_ccr |
Checks if the path is actually on the file system and performs
any syscalls if necessary. | def match(dirname, basename)
# Potential `entries` syscall
matches = @entries[dirname]
pattern = @patterns[basename]
matches = matches.select { |m| m =~ pattern }
sort_matches(matches, basename).each do |path|
filename = File.join(dirname, path)
# Potential... | csn |
private boolean isFirstRequestProcessed()
{
FacesContext context = FacesContext.getCurrentInstance();
//if firstRequestProcessed is not set, check the application map
if(!_firstRequestProcessed && context != null
&& Boolean.TRUE.equals(context.getExternalContext().g... | .containsKey(LifecycleImpl.FIRST_REQUEST_PROCESSED_PARAM)))
{
_firstRequestProcessed = true;
}
return _firstRequestProcessed;
} | csn_ccr |
// GlobalLexicalScopeNames invokes the Runtime method. Returns all let, const
// and class variables from global scope. | func (d *domainClient) GlobalLexicalScopeNames(ctx context.Context, args *GlobalLexicalScopeNamesArgs) (reply *GlobalLexicalScopeNamesReply, err error) {
reply = new(GlobalLexicalScopeNamesReply)
if args != nil {
err = rpcc.Invoke(ctx, "Runtime.globalLexicalScopeNames", args, reply, d.conn)
} else {
err = rpcc.I... | csn |
def _symlink_or_copy_grabix(in_file, out_file, data):
"""We cannot symlink in CWL, but may be able to use inputs or copy
"""
if cwlutils.is_cwl_run(data):
# Has grabix indexes, we're okay to go
if utils.file_exists(in_file + ".gbi"):
out_file | = in_file
else:
utils.copy_plus(in_file, out_file)
else:
utils.symlink_plus(in_file, out_file)
return out_file | csn_ccr |
public function write($data)
{
return $this->stream->write(
$this->splitter->writePacket(
| $this->protocol->serializeVariantPacket($data)
)
);
} | csn_ccr |
Verify inteceptor meta
@param element Interceptor taw type
@return verify result | private boolean verify(Element element) {
Interceptor interceptor = element.getAnnotation(Interceptor.class);
// It must be implement the interface IInterceptor and marked with annotation Interceptor.
return null != interceptor && ((TypeElement) element).getInterfaces().contains(iInterceptor);
... | csn |
Adds a MenuItem to this Menu.
@param MenuItem $menuItem The MenuItem to add.
@param int $position The position in the menu the MenuItem should have.
If not set, it is appended to the end.
@return $this | public function addMenuItem(MenuItem $menuItem, $position = -1) {
if (!is_int($position)) {
throw new InvalidArgumentException('position should be of type int.');
}
if ($position < 0) {
$position = count($this->menuItems);
}
$menuItem->setOrder($position... | csn |
def to_matrix(self, index_regs=None, index_meta=None,
columns_regs=None, columns_meta=None,
values_regs=None, values_meta=None, **kwargs):
""" Transforms the GDataframe to a pivot matrix having as index and columns the
ones specified. This function is a wrapper around... | values_regs = values_regs if values_regs is not None else []
values_meta = values_meta if values_meta is not None else []
index_meta_s = set(index_meta)
columns_meta_s = set(columns_meta)
values_meta_s = set(values_meta)
meta_to_project = list(index_meta_s.union(columns... | csn_ccr |
In some ranking people collects points. The challenge is sort by points and calulate position for every person. But remember if two or more persons have same number of points, they should have same position number and sorted by name (name is unique).
For example:
Input structure:
Output should be: | def ranking(a):
a.sort(key=lambda x: (-x["points"], x["name"]))
for i, x in enumerate(a):
x["position"] = i + 1 if not i or x["points"] < a[i-1]["points"] else a[i-1]["position"]
return a | apps |
for testing, simply shows a list details | def show(title, lst, full=-1):
"""
for testing, simply shows a list details
"""
txt = title + ' (' + str(len(lst)) + ') items :\n '
num = 0
for i in lst:
if full == -1 or num < full:
if type(i) is str:
txt = txt + i + ',\n '
else:
t... | csn |
Returns the already created ZipArchive instance or
creates one if none exists.
@return \ZipArchive | protected function createOrGetZip()
{
if (!isset($this->zip)) {
$this->zip = new \ZipArchive();
$zipFilePath = $this->getZipFilePath();
$this->zip->open($zipFilePath, \ZipArchive::CREATE|\ZipArchive::OVERWRITE);
}
return $this->zip;
} | csn |
// Finds the Endpoint Url of "type" from the v2AuthResponse using the
// Region if set or defaulting to the first one if not
//
// Returns "" if not found | func (auth *v2Auth) endpointUrl(Type string, endpointType EndpointType) string {
for _, catalog := range auth.Auth.Access.ServiceCatalog {
if catalog.Type == Type {
for _, endpoint := range catalog.Endpoints {
if auth.Region == "" || (auth.Region == endpoint.Region) {
switch endpointType {
case Endp... | csn |
public function getInfo($ip = null)
{
if ($ip == null) {
$ip = $this->getIpAdress();
}
$url = str_replace('{IP}', $ip, $this->api_adress);
$hex = $this->ipToHex($ip);
$me = $this;
// Check if the IP is | in the cache
if (Cache::has($hex)) {
$this->isCached = true;
}
// Use the IP info stored in cache or store it
$ipInfo = Cache::remember($hex, 10080, function () use ($me, $url) {
return $me->fetchInfo($url);
});
$ipInfo->geoplugin_cached = $this-... | csn_ccr |
Default p-norm implementation. | def _pnorm_default(x, p):
"""Default p-norm implementation."""
return np.linalg.norm(x.data.ravel(), ord=p) | csn |
public function commands($commands)
{
$commands = is_array($commands) ? $commands : func_get_args();
// To register the commands with FlyConsole, we will grab each of the arguments
// passed into the method and listen for FlyConsole "start" event which will
// give us the FlyConsole console instance | which we will give commands to.
$events = $this->app['events'];
$events->listen('flyconsole.start', function($flyconsole) use ($commands)
{
$flyconsole->resolveCommands($commands);
});
} | csn_ccr |
Push Criteria for filter the query
@param $criteria
@return $this
@throws \Prettus\Repository\Exceptions\RepositoryException | public function pushCriteria($criteria)
{
if (is_string($criteria)) {
$criteria = new $criteria;
}
if (!$criteria instanceof CriteriaInterface) {
throw new RepositoryException("Class " . get_class($criteria) . " must be an instance of Prettus\\Repository\\Contracts\\C... | csn |
public function validate0101(MessageInterface $message, &$reason = "")
{
// 1.1 incorporates 1.0 validation standar
if (!$this->validate0100($message, $reason)) {
return false;
}
foreach ($message->getAllAdditionals() as $key => $value) {
if (!preg_match('#^[... | $reason = sprintf(
"additional key '%s' contains invalid characters",
$key
);
return false;
}
}
return true;
} | csn_ccr |
how do i recognize python as an internal or external command | def IPYTHON_MAIN():
"""Decide if the Ipython command line is running code."""
import pkg_resources
runner_frame = inspect.getouterframes(inspect.currentframe())[-2]
return (
getattr(runner_frame, "function", None)
== pkg_resources.load_entry_point("ipython", "console_scripts", "ipython"... | cosqa |
def get_cousins_treepos(self, treepos):
"""Given a treeposition, return the treeposition of its siblings."""
cousins_pos = []
mother_pos = self.get_parent_treepos(treepos)
if mother_pos is not None:
aunts_pos = self.get_siblings_treepos(mother_pos)
| for aunt_pos in aunts_pos:
cousins_pos.extend( self.get_children_treepos(aunt_pos) )
return cousins_pos | csn_ccr |
Construct and return a filename for this tile. | def generate_filename(self, directory=os.getcwd(), prefix='tile',
format='png', path=True):
"""Construct and return a filename for this tile."""
filename = prefix + '_{col:02d}_{row:02d}.{ext}'.format(
col=self.column, row=self.row, ext=format.lower().repl... | csn |
Simple wrapper around SimpleCliTool. Simple. | def call_simple_cli(command, cwd=None, universal_newlines=False, redirect_stderr=False):
""" Simple wrapper around SimpleCliTool. Simple. """
return SimpleCliTool()._call_cli(command, cwd, universal_newlines, redirect_stderr) | csn |
function getApparentTypeOfTypeParameter(type) {
if (!type.resolvedApparentType) {
var constraintType = getConstraintOfTypeParameter(type);
while (constraintType && constraintType.flags & 16384 /* TypeParameter */) {
constraintType = getConstraintOfTypePara... | }
type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type);
}
return type.resolvedApparentType;
} | csn_ccr |
def compute_wed(self):
"""
Computes weight error derivative for all connections in
self.connections starting with the last connection.
"""
if len(self.cacheConnections) != 0:
changeConnections = self.cacheConnections
else:
changeConnections = self.... | connect.toLayer.delta)
if len(self.cacheLayers) != 0:
changeLayers = self.cacheLayers
else:
changeLayers = self.layers
for layer in changeLayers:
if layer.active:
layer.wed = layer.wed + layer.delta | csn_ccr |
Load a Module
@param string The name of the Module
@param array Array of options to apply to the Module (see above).
@return \ChickenWire\Module The created Module instance | public static function load($name, $options = array()) {
// Module already loaded?
if (array_key_exists($name, self::$_modules)) {
throw new \Exception("A module with the name $name has already been loaded.", 1);
}
// Create and add
$module = new Module($name, $options);
self::$_modules[$name] =... | csn |
def count_delayed_jobs(cls, names):
"""
Return the number of all delayed jobs in queues with the given names
"""
| return sum([queue.delayed.zcard() for queue in cls.get_all(names)]) | csn_ccr |
From Craft's native saveField, which doesn't really support Ajax... | public function actionSaveField()
{
$this->requirePostRequest();
$fieldsService = Craft::$app->getFields();
$request = Craft::$app->getRequest();
$type = $request->getRequiredBodyParam('type');
$field = $fieldsService->createField([
'type' => $ty... | csn |
Convert the EPW to a dictionary. | def to_json(self):
"""Convert the EPW to a dictionary."""
# load data if it's not loaded
if not self.is_data_loaded:
self._import_data()
def jsonify_dict(base_dict):
new_dict = {}
for key, val in base_dict.items():
new_dict[key] = val.... | csn |
func (c *Client) GetIncidents() (IncidentsResponse, error) { |
i := IncidentsResponse{}
err := c.request("api/v2/incidents.json", &i)
return i, err
} | csn_ccr |
def _pmap(self, func, items, keys, pool, bookkeeping_dict=None):
"""Efficiently map func over all items.
Calls func only once for duplicate items.
Item duplicates are detected by corresponding keys.
Unless keys is None.
Serial if pool is None, but still skips duplicates... | Add bookkeeping
if bookkeeping_dict is not None:
bookkeeping_dict['key_indices'] = key_indices
# Combine duplicates back into list
all_results = [None] * len(items)
for indices, result in zip(key_indices, results):
for j, i in enumerate(indices):
... | csn_ccr |
def process_affinity(affinity=None):
"""Get or set the CPU affinity set for the current process.
This will affect all future threads spawned by this process. It is
implementation-defined whether it | will also affect previously-spawned
threads.
"""
if affinity is not None:
affinity = CPUSet(affinity)
if not affinity.issubset(system_affinity()):
raise ValueError("unknown cpus: %s" % affinity)
return system_affinity() | csn_ccr |
Change the sub-screen.
@param parent
@param baseScreen
@param strCommandToPush
@param options
@return | public boolean changeSubScreen(Container parent, JBasePanel baseScreen, String strCommandToPush, int options)
{
if ((parent == null) || (parent == this))
parent = m_parent;
boolean bScreenChange = false;
if (!this.checkSecurity(baseScreen))
{
baseScreen.free()... | csn |
Get package build time, if possible.
:param name:
:return: | def _get_pkg_build_time(name):
'''
Get package build time, if possible.
:param name:
:return:
'''
iso_time = iso_time_t = None
changelog_dir = os.path.join('/usr/share/doc', name)
if os.path.exists(changelog_dir):
for fname in os.listdir(changelog_dir):
try:
... | csn |
def save(self):
"""
Attempts to move the node using the selected target and
position.
If an invalid move is attempted, the related error message will
be added to the form's non-field errors and the error will be
re-raised. Callers should attempt to catch ``InvalidNode`` ... | try:
self.node.move_to(self.cleaned_data['target'],
self.cleaned_data['position'])
return self.node
except InvalidMove, e:
self.errors[NON_FIELD_ERRORS] = ErrorList(e)
raise | csn_ccr |
python load json from a json formatted string | def from_json_str(cls, json_str):
"""Convert json string representation into class instance.
Args:
json_str: json representation as string.
Returns:
New instance of the class with data loaded from json string.
"""
return cls.from_json(json.loads(json_str, cls=JsonDecoder)) | cosqa |
public function view($viewname, $data = '')
{
if (in_array($viewname, $this->viewset) === false) {
$this->viewset[] = array($viewname, | $data);
$view = new View(Base::getInstance());
$this->loaderHooks($view,'pre_view',$class='',$method_name='',$data=array());
return $view;
}
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.