comment stringlengths 16 255 | code stringlengths 52 3.87M |
|---|---|
Gets the list of <em>instances</em> associated to a virtual host name.
@param virtualHostName
the virtual hostname for which the instances need to be
returned.
@return list of <em>instances</em>. | public List<InstanceInfo> getInstancesByVirtualHostName(String virtualHostName) {
return Optional.ofNullable(this.virtualHostNameAppMap.get(virtualHostName.toUpperCase(Locale.ROOT)))
.map(VipIndexSupport::getVipList)
.map(AtomicReference::get)
.orElseGet(Collections::emptyLis... |
Handle the deleted event for the Ban model.
@param \Cog\Contracts\Ban\Ban $ban
@return void | public function deleted(BanContract $ban): void
{
$bannable = $ban->bannable()->withBanned()->first();
if ($bannable->bans->count() === 0) {
$bannable->unsetBannedFlag()->save();
event(new ModelWasUnbanned($bannable));
}
} |
Clear sequence numbers in column 1-6 and anything beyond column 72.
@param line the line of code
@return a line of code without sequence numbers | public String cleanFixedLine(final String line) {
StringBuilder cleanedLine = new StringBuilder();
int length = line.length();
/* Clear sequence numbering */
for (int i = 0; i < _startColumn - 1; i++) {
cleanedLine.append(" ");
}
/* Trim anything beyond end... |
// DisableVanityNameServers Vanity Name Servers for the given domain
//
// See https://developer.dnsimple.com/v2/vanity/#disable | func (s *VanityNameServersService) DisableVanityNameServers(accountID string, domainIdentifier string) (*vanityNameServerResponse, error) {
path := versioned(vanityNameServerPath(accountID, domainIdentifier))
vanityNameServerResponse := &vanityNameServerResponse{}
resp, err := s.client.delete(path, nil, nil)
if er... |
/* eslint-disable | function adaptor(prompt) {
prompt = { ...prompt }
switch (prompt.type) {
case 'confirm':
prompt.type = 'checkbox'
prompt.transformType = 'confirm'
prompt.value = [prompt.value]
prompt.choices = [
{ label: 'Yes?', value: true }
]
break
case 'list':
prompt.typ... |
Create new array
<p>Stack: ..., count => ..., arrayref
@param name
@param aClass
@param size
@throws IOException | public void addNewArray(String name, Class<?> aClass, int size) throws IOException
{
addNewArray(name, Typ.getTypeFor(aClass), size);
} |
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated | @Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case SimpleAntlrPackage.OPTIONS__OPTION_VALUES:
return ((InternalEList<?>)getOptionValues()).basicRemove(otherEnd, msgs);
}
return super.eInverseRem... |
// IsValidOsArch checks if a OS-architecture combination is valid given a map
// of valid OS-architectures | func IsValidOSArch(labels map[ACIdentifier]string, validOSArch map[string][]string) error {
if os, ok := labels["os"]; ok {
if validArchs, ok := validOSArch[os]; !ok {
// Not a whitelisted OS. TODO: how to warn rather than fail?
validOses := make([]string, 0, len(validOSArch))
for validOs := range validOSAr... |
// ListEmailForwards lists the email forwards for a domain.
//
// See https://developer.dnsimple.com/v2/domains/email-forwards/#list | func (s *DomainsService) ListEmailForwards(accountID string, domainIdentifier string, options *ListOptions) (*emailForwardsResponse, error) {
path := versioned(emailForwardPath(accountID, domainIdentifier, 0))
forwardsResponse := &emailForwardsResponse{}
path, err := addURLQueryOptions(path, options)
if err != nil... |
// RoundDown will round tp down to next "full" d. | func RoundDown(t time.Time, d TimeDelta) time.Time {
td := d.RoundDown(t)
DebugLogger.Printf("RoundDown( %s, %s ) --> %s", t.Format("2006-01-02 15:04:05 (Mon)"), d.String(),
td.Format("2006-01-02 15:04:05 (Mon)"))
return td
} |
Add method info.
@param methodInfoList
the method info list
@param classNameToClassInfo
the map from class name to class info | void addMethodInfo(final MethodInfoList methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) {
for (final MethodInfo mi : methodInfoList) {
// Index method annotations
addFieldOrMethodAnnotationInfo(mi.annotationInfo, /* isField = */ false, classNameToClassInfo);
... |
send the transaction using the API
@param string|array $signed
@param string[] $paths
@param bool $checkFee
@return string the complete raw transaction
@throws \Exception | protected function sendTransaction($signed, $paths, $checkFee = false) {
return $this->sdk->sendTransaction($this->identifier, $signed, $paths, $checkFee);
} |
Register application provider
Workaround for BC break in https://github.com/laravel/framework/pull/25028
@param string $providerName
@param bool $force | protected function appRegister($providerName, $force = false)
{
if (!$this->appRegisterParameters) {
$method = new \ReflectionMethod(get_class($this->app), 'register');
$this->appRegisterParameters = count($method->getParameters());
}
if ($this->appRegisterParameters... |
Sets or resets the order of the existing schemas in the current search path of the user.
This is a PostgreSQL only function.
@return void | public function determineExistingSchemaSearchPaths()
{
$names = $this->getSchemaNames();
$paths = $this->getSchemaSearchPaths();
$this->existingSchemaPaths = array_filter($paths, static function ($v) use ($names) {
return in_array($v, $names);
});
} |
/*
(non-Javadoc)
@see javax.security.enterprise.authentication.mechanism.http.HttpMessageContext#forward(java.lang.String) | @Override
public AuthenticationStatus forward(String path) {
try {
RequestDispatcher requestDispatcher = request.getRequestDispatcher(path);
requestDispatcher.forward(request, response);
} catch (Exception e) {
// TODO: Add serviceability message
}
... |
@param Shopgate_Model_XmlResultObject $itemNode
@return Shopgate_Model_XmlResultObject | public function asXml(Shopgate_Model_XmlResultObject $itemNode)
{
/**
* @var Shopgate_Model_XmlResultObject $stockNode
*/
$identifierNode = $itemNode->addChildWithCDATA('identifier', $this->getValue());
$identifierNode->addAttribute('uid', $this->getUid());
$identif... |
创建BeanCopier
@param <T> 目标Bean类型
@param source 来源对象,可以是Bean或者Map
@param dest 目标Bean对象
@param copyOptions 拷贝属性选项
@return BeanCopier | public static <T> BeanCopier<T> create(Object source, T dest, CopyOptions copyOptions) {
return create(source, dest, dest.getClass(), copyOptions);
} |
// SetCertificate sets the Certificate field's value. | func (s *SslConfiguration) SetCertificate(v string) *SslConfiguration {
s.Certificate = &v
return s
} |
/* (non-Javadoc)
@see org.joml.Matrix4x3fc#rotateX(float, org.joml.Matrix4x3f) | public Matrix4x3f rotateX(float ang, Matrix4x3f dest) {
if ((properties & PROPERTY_IDENTITY) != 0)
return dest.rotationX(ang);
float sin, cos;
if (ang == (float) Math.PI || ang == -(float) Math.PI) {
cos = -1.0f;
sin = 0.0f;
} else if (ang == (float) ... |
get the activity that is started by the first instruction, if exists;
return null if the first instruction is a start-transition instruction | protected ActivityImpl determineFirstActivity(ProcessDefinitionImpl processDefinition,
ProcessInstanceModificationBuilderImpl modificationBuilder) {
AbstractProcessInstanceModificationCommand firstInstruction = modificationBuilder.getModificationOperations().get(0);
if (firstInstruction instanceof Abstra... |
生成文件
@param template 模板
@param context 模板上下文
@param destPath 目标路径(绝对) | public static void toFile(Template template, VelocityContext context, String destPath) {
PrintWriter writer = null;
try {
writer = FileUtil.getPrintWriter(destPath, Velocity.getProperty(Velocity.INPUT_ENCODING).toString(), false);
merge(template, context, writer);
} catch (IORuntimeException e) {
t... |
Read cookie data from the request's cookie data.
@param string $key The key you want to read.
@return null|string Either the cookie value, or null if the value doesn't exist.
@deprecated 3.4.0 Use getCookie() instead. | public function cookie($key)
{
deprecationWarning(
'ServerRequest::cookie() is deprecated. ' .
'Use getCookie() instead.'
);
if (isset($this->cookies[$key])) {
return $this->cookies[$key];
}
return null;
} |
Command line interface | def main():
parser = argparse.ArgumentParser(
description='Extract the raw gps communication from an ULog file')
parser.add_argument('filename', metavar='file.ulg', help='ULog input file')
def is_valid_directory(parser, arg):
"""Check if valid directory"""
if not os.path.isdir(... |
Write the extension to the OutputStream.
@param out the OutputStream to write the extension to
@exception IOException on encoding errors | public void encode(OutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
if (extensionValue == null) {
extensionId = PKIXExtensions.CertificateIssuer_Id;
critical = true;
encodeThis();
}
super.encode(tmp);
out.wri... |
Expires the given session. | private void expireSession(RaftSession session) {
if (expiring.add(session.sessionId())) {
log.debug("Expiring session due to heartbeat failure: {}", session);
appendAndCompact(new CloseSessionEntry(raft.getTerm(), System.currentTimeMillis(), session.sessionId().id(), true, false))
.whenComple... |
Unserializes in instance from an ASCII safe string representation produced by __toString.
@param string $string String representation
@return BloomFilter Unserialized instance | public static function unserializeFromStringRepresentation($string)
{
if (!preg_match('~k:(?P<k>\d+)/m:(?P<m>\d+)\((?P<bitfield>[0-9a-zA-Z+/=]+)\)~', $string, $matches)) {
throw new InvalidArgumentException('Invalid string representation');
}
$bf = new self((int) $matches['m'], (... |
{@inheritDoc}
@see \rocket\ei\manage\gui\GuiFieldEditable::createMag($propertyName) | public function getMag(): Mag {
$this->contentItemMag = new ContentItemMag($this->label, $this->panelConfigs,
$this->targetReadEiFrame, $this->targetEditEiFrame);
$this->contentItemMag->setNewMappingFormUrl($this->newMappingFormUrl);
$this->contentItemMag->setValue($this->toManyEiField->getValue());
$t... |
Convert a string to a byte array, no encoding is used. String must only contain characters <256. | public static byte[] str2bytes(String str) throws IOException {
byte[] b=new byte[str.length()];
for(int i=0; i<str.length(); ++i) {
char c=str.charAt(i);
if(c>255) throw new UnsupportedEncodingException("string contained a char > 255, cannot convert to bytes");
b[i]=(byte)c;
}
return b;
} |
Convenient Method for the vibrato effekt
@param aktMemo | protected void doVibratoEffekt(ChannelMemory aktMemo)
{
int periodAdd;
switch (aktMemo.vibratoType & 0x03)
{
case 1: periodAdd = (Helpers.ModRampDownTable[aktMemo.vibratoTablePos]); // Sawtooth
break;
case 2: periodAdd = (Helpers.ModSquareTable [aktMemo.vibratoTablePos]); // Squarewave
break;
... |
Get the value of a cookie.
@param $name
@param null $default
@return null|string | public static function get($name, $default = null)
{
if (isset(static::$jar[$name])) {
return static::parse(static::$jar[$name]['value']);
}
$cookie = Request::$cookieData;
if (!is_null($value = $cookie->get($name))) {
return static::parse($value);
}... |
Rails controller stuff
======================== | def setup
set_descriptor :default
get_mxit_info
@_mxit = descriptor
@_mxit_validated = true
@_mxit_validation_types = []
@_mxit_validation_messages = []
@_mxit_emulator = request.headers['X-Mxit-UserId-R'].nil?
clean_session
# Tidy multi-select if needed
... |
@param \Spryker\Yves\Kernel\Container $container
@return \Spryker\Yves\Kernel\Container | public function provideDependencies(Container $container)
{
$container[self::CLIENT_PAYONE] = function (Container $container) {
return $container->getLocator()->payone()->client();
};
$container[self::CLIENT_CUSTOMER] = function (Container $container) {
return new Pa... |
State for handling dateto:foo constructs. Potentially emits a token. | function indateto($content){
if (strlen($content) < 8) { // State exit or missing parameter.
return true;
}
// Strip off the dateto: part and add the reminder to the parsed token array
$param = trim(substr($content,7));
$this->tokens[] = new search_token(TOKEN_DATETO,... |
// WithAnnotations appends or replaces the annotations on the spec with the
// provided annotations | func WithAnnotations(annotations map[string]string) SpecOpts {
return func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error {
if s.Annotations == nil {
s.Annotations = make(map[string]string)
}
for k, v := range annotations {
s.Annotations[k] = v
}
return nil
}
} |
Array to mapper criteria
@param array $values
@param boolean $qmMode force question mark placeholder
@return string | public static function buildCriteria(array $values, $qmMode = false)
{
reset($values);
$qmMode = $qmMode ?: is_numeric(key($values));
if ($qmMode) {
$result = array_values($values);
array_unshift($result, str_repeat('?,', count($values)-1).'?');
return $... |
// NewKey returns a new key that can be used to encrypt and decrypt messages. | func NewKey() (*[SecretKeyLength]byte, error) {
// get 32-bytes of random from /dev/urandom
bytes, err := randomProvider.Bytes(SecretKeyLength)
if err != nil {
return nil, fmt.Errorf("unable to generate random: %v", err)
}
return KeySliceToArray(bytes)
} |
Write data to the connection
@param string $data | protected function write(string $data)
{
$this->clearTimeout();
$this->conn->write($data . static::NEW_LINE);
$this->log('<-' . $data);
$this->setTimeout();
} |
Drops the user into an interactive Python session with the ``sess`` variable
set to the current session instance. If keyword arguments are supplied, these
names will also be available within the session. | def interact(self, **local):
import code
code.interact(local=dict(sess=self, **local)) |
Set a new state to the underlying object
@param string $state
@throws SMException | protected function setState($state)
{
if (!in_array($state, $this->config['states'])) {
throw new SMException(sprintf(
'Cannot set the state to "%s" to object "%s" with graph %s because it is not pre-defined.',
$state,
get_class($this->object),
... |
EVENTS
Event handler for a touch start event.
Stops the default click event from triggering and stores where we touched
@inner
@param {object} jqEvent The normalised jQuery event object. | function touchStart(jqEvent) {
//If we already in a touch event (a finger already in use) then ignore subsequent ones..
if( getTouchInProgress() )
return;
//Check if this element matches any in the excluded elements selectors, or its parent is excluded, if so, DON'T swipe
if( $(jqEvent.target).clos... |
// SetTagList sets the TagList field's value. | func (s *TagListMessage) SetTagList(v []*Tag) *TagListMessage {
s.TagList = v
return s
} |
// 修改默认或者说全局 appname(应用名) | func (l *Live) SetAppName(appname string) *Live {
l.liveReq.AppName = appname
return l
} |
/*[deutsch]
<p>Rollt dieses zyklische Jahr um den angegebenen Betrag. </p>
@param amount determines how many years/units this instance should be rolled
@return changed copy of this instance | public CyclicYear roll(int amount) {
if (amount == 0) {
return this;
}
return CyclicYear.of(MathUtils.floorModulo(MathUtils.safeAdd(this.year - 1, amount), 60) + 1);
} |
Add a task to the executor, it is expected that this method is
called on the ResultReceiver thread. | public void addTask (ExecutorTask task)
{
for (int ii=0, nn=_queue.size(); ii < nn; ii++) {
ExecutorTask taskOnQueue = _queue.get(ii);
if (taskOnQueue.merge(task)) {
return;
}
}
// otherwise, add it on
_queue.add(task);
//... |
// List lists the buildclient using the OpenShift client. | func (c *ClientBuildConfigLister) List(label labels.Selector) ([]*buildv1.BuildConfig, error) {
list, err := c.client.BuildConfigs(metav1.NamespaceAll).List(metav1.ListOptions{LabelSelector: label.String()})
return buildConfigListToPointerArray(list), err
} |
Return True if the media type is a valid form media type. | def is_form_media_type(media_type):
base_media_type, params = parse_header(media_type.encode(HTTP_HEADER_ENCODING))
return (base_media_type == 'application/x-www-form-urlencoded' or
base_media_type == 'multipart/form-data') |
Saves relation between optimizer and search container
@param \Magento\Framework\Model\AbstractModel $object Optimizer to save
@return void | private function saveSearchContainerRelation(\Magento\Framework\Model\AbstractModel $object)
{
$searchContainers = $object->getSearchContainer();
if (is_array($searchContainers) && (count($searchContainers) > 0)) {
$searchContainerLinks = [];
$deleteCondition = OptimizerInte... |
// SetProcessingConfiguration sets the ProcessingConfiguration field's value. | func (s *ExtendedS3DestinationUpdate) SetProcessingConfiguration(v *ProcessingConfiguration) *ExtendedS3DestinationUpdate {
s.ProcessingConfiguration = v
return s
} |
Pass through to provider CommentLookupSession.use_federated_book_view | def use_federated_book_view(self):
""""""
self._book_view = FEDERATED
# self._get_provider_session('comment_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
try:
session.use_federated_book_view()
... |
/*JWTBearerInterface | public function getClientKey($client_id, $subject)
{
if (isset($this->jwt[$client_id])) {
$jwt = $this->jwt[$client_id];
if ($jwt) {
if ($jwt["subject"] == $subject) {
return $jwt["key"];
}
}
}
return fa... |
Return URL string of Atom link element under parent element. Link with no rel attribute is
considered to be rel="alternate"
@param parent Consider only children of this parent element
@param rel Consider only links with this relationship | private String findAtomLink(final Element parent, final String rel) {
String ret = null;
final List<Element> linksList = parent.getChildren("link", ATOM_10_NS);
if (linksList != null) {
for (final Element element : linksList) {
final Element link = element;
... |
Render page with assessment(s) result.
@throws \common_exception_Error
@throws \common_exception_MissingParameter
@throws \oat\oatbox\service\ServiceNotFoundException | public function printReport()
{
if (!$this->hasRequestParameter('id')) {
throw new \common_exception_MissingParameter('id');
}
$idList = $this->getRequestParameter('id');
$context = $this->getRequestParameter('context');
if (!is_array($idList)) {
$idLi... |
// Provide returns the result of executing the constructor with argument values resolved from a dependency graph | func (p provider) Provide(g Graph) reflect.Value {
fnType := reflect.TypeOf(p.constructor)
argCount := fnType.NumIn()
if fnType.IsVariadic() {
argCount = len(p.argPtrs)
}
args := make([]reflect.Value, argCount, argCount)
var inType reflect.Type
for i := 0; i < argCount; i++ {
arg := g.Resolve(p.argPtrs[i])... |
@param Request $request
@param integer $id
@return \Symfony\Component\HttpFoundation\JsonResponse
@throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException | public function updateAction(Request $request, $id)
{
$this->checkCsrf();
$transUnit = $this->get('lexik_translation.data_grid.request_handler')->updateFromRequest($id, $request);
return $this->get('lexik_translation.data_grid.formatter')->createSingleResponse($transUnit);
} |
// Ensure the directory exists or create it if needed. | func EnsureDir(dir string, mode os.FileMode) error {
if fileOptions, err := os.Stat(dir); os.IsNotExist(err) {
if errMake := os.MkdirAll(dir, mode); errMake != nil {
return fmt.Errorf("Could not create directory %s. %v", dir, err)
}
} else if err != nil {
return fmt.Errorf("Error asserting directory %s: %v",... |
Update the given MySQL User.
@param array $data
@return MysqlUser | public function update(array $data)
{
return $this->forge->updateMysqlUser($this->serverId, $this->id, $data);
} |
// SetActivityFailedEventDetails sets the ActivityFailedEventDetails field's value. | func (s *HistoryEvent) SetActivityFailedEventDetails(v *ActivityFailedEventDetails) *HistoryEvent {
s.ActivityFailedEventDetails = v
return s
} |
Flushes the data buffers to disk.
@param force force a synchronous flush (otherwise if the environment has
the MDB_NOSYNC flag set the flushes will be omitted, and with
MDB_MAPASYNC they will be asynchronous) | public void sync(final boolean force) {
if (closed) {
throw new AlreadyClosedException();
}
final int f = force ? 1 : 0;
checkRc(LIB.mdb_env_sync(ptr, f));
} |
Handle the command.
@var string | public function handle()
{
$indexConfigurator = $this->getIndexConfigurator();
if ($indexConfigurator && ! $this->alreadyExists($indexConfigurator)) {
$this->call('make:index-configurator', [
'name' => $indexConfigurator,
]);
}
$searchRule = ... |
Performs a search and returns the match, or null if no match was found
or more than one match was found.
@since 1.527 | public static SuggestedItem find(SearchIndex index, String query, SearchableModelObject searchContext) {
List<SuggestedItem> r = find(Mode.FIND, index, query, searchContext);
if(r.isEmpty()){
return null;
}
else if(1==r.size()){
return r.get(0);
}
... |
r"""
Initialize the solution vector (self.petsc_x), which is a dense
matrix (1D vector) and defines the rhs vector (self.petsc_b) from
the existing data. | def _initialize_b_x(self):
"""
# Get vector(s) compatible with the matrix,
# i.e., with the same parallel layout.
self.petsc_x, self.petsc_b = self.petsc_A.getVecs()
# Set the solution vector to zeros.
self.petsc_x.set(0)
# Define the petsc rhs vector ... |
Handles the creating or updating of a stack in CloudFormation.
Also makes sure that we don't try to create or update a stack while
it is already updating or creating. | def _launch_stack(self, stack, **kwargs):
old_status = kwargs.get("status")
wait_time = 0 if old_status is PENDING else STACK_POLL_TIME
if self.cancel.wait(wait_time):
return INTERRUPTED
if not should_submit(stack):
return NotSubmittedStatus()
p... |
Convert to EEML. Optional parameter describes the version of EEML to generate.
Default (and currently only version implemented) is version 5. | def to_eeml(version = nil)
if version.nil? || version == 5
# Check that we have some data items
if size < 1
raise EEML::NoData.new('EEML requires at least one data item')
end
# Create EEML
eeml = Builder::XmlMarkup.new
eeml.instruct!
eeml_options =... |
Returns the calculated age the time of event.
@param int $age The age from the database record
@return string | private function calculateAge(int $age): string
{
if ((int) ($age / 365.25) > 0) {
$result = (int) ($age / 365.25) . 'y';
} elseif ((int) ($age / 30.4375) > 0) {
$result = (int) ($age / 30.4375) . 'm';
} else {
$result = $age . 'd';
}
retu... |
Option for the user to revert the changes made since it was last published | public function revert() {
if ($this->data()->IsModifiedOnStage) {
$this->data()->doRevertToLive();
}
return $this->redirect($this->data()->Link() . '?stage=Live');
} |
// SetOperation sets the Operation field's value. | func (s *DynamoDBAction) SetOperation(v string) *DynamoDBAction {
s.Operation = &v
return s
} |
Queue an "event" to be run on the GL rendering thread.
@param r
the runnable to be run on the GL rendering thread. | public void queueEvent(Runnable r) {
synchronized (this) {
mEventQueue.add(r);
synchronized (sGLThreadManager) {
mEventsWaiting = true;
sGLThreadManager.notifyAll();
}
... |
path doesnt handle ~ resolution, fallback to env variables, solution taken from https://github.com/nodejs/node-v0.x-archive/issues/2857 | function tilda(cwd) {
if (cwd.substring(0, 1) === '~') {
cwd = (process.env.HOME || process.env.HOMEPATH || process.env.HOMEDIR || process.cwd()) + cwd.substr(1);
}
return path.resolve(cwd);
} |
This method finds the first parent class which is within the buildbot namespace
it prepends the name with as many ">" as the class is subclassed | def getName(obj):
# elastic search does not like '.' in dict keys, so we replace by /
def sanitize(name):
return name.replace(".", "/")
if isinstance(obj, _BuildStepFactory):
klass = obj.factory
else:
klass = type(obj)
name = ""
klasses = (klass, ) + inspect.getmro(k... |
Returns "a mark" to the current position of this node Cassandra log.
This is for use with the from_mark parameter of watch_log_for_* methods,
allowing to watch the log from the position when this method was called. | def mark_log(self, filename='system.log'):
log_file = os.path.join(self.get_path(), 'logs', filename)
if not os.path.exists(log_file):
return 0
with open(log_file) as f:
f.seek(0, os.SEEK_END)
return f.tell() |
A safe function for creating a directory tree. | def safe_makedirs(path):
""""""
try:
os.makedirs(path)
except OSError as err:
if err.errno == errno.EEXIST:
if not os.path.isdir(path):
raise
else:
raise |
It's kind of redundant to have the server return the foreign
keys corresponding to the belongs_to associations (since they'll
be in the URL anyway), so we'll try to inject them based on the
attributes of the object we just used. | def load(attributes, remove_root=false)
attributes = attributes ? attributes.stringify_keys : {}
self.class.belongs_to_with_parents.each do |belongs_to_param|
attributes["#{belongs_to_param}_id"] ||= prefix_options["#{belongs_to_param}_id".intern]
# also set prefix attributes as real attrib... |
Count records of model.
@param string $alias Optional alias of count result
@return int | public function count($alias = null)
{
if ($this->controller && $this->controller->hasMethod('count')) {
return $this->controller->count($this, $alias);
}
throw $this->exception('The controller doesn\'t support count', 'NotImplemented')
->addMoreInfo('controller', $th... |
Sets the StructTypeInfo that declares the total schema of the file in the configuration | public static void setSchemaTypeInfo(Configuration conf, StructTypeInfo schemaTypeInfo) {
if (schemaTypeInfo != null) {
conf.set(SCHEMA_TYPE_INFO, schemaTypeInfo.getTypeName());
LOG.debug("Set schema typeInfo on conf: {}", schemaTypeInfo);
}
} |
where 语法见 @see WhereRule
@param array|string|callable|null $conditions
@param string $_
@return \PhpBoot\DB\rules\select\WhereRule | public function findWhere($conditions=null, $_=null)
{
$query = $this->db->select($this->getColumns())
->from($this->entity->getTable());
$query->context->resultHandler = function ($result){
foreach ($result as &$i){
$i = $this->entity->make($i, false);
... |
Source configuration file. | def source_file(pymux, variables):
filename = os.path.expanduser(variables['<filename>'])
try:
with open(filename, 'rb') as f:
for line in f:
line = line.decode('utf-8')
handle_command(pymux, line)
except IOError as e:
raise CommandException('... |
Modifies the result of each promise from a scalar value to a object containing its fieldname | function wrap(fieldName, promise, args) {
return promise(args).then((result) => ({
[fieldName]: result,
}));
} |
Send `post_dict` to the :attr:`.ALEPH_EXPORT_URL`.
Args:
post_dict (dict): dictionary from :class:`PostData.get_POST_data()`
Returns:
str: Reponse from webform. | def _sendPostDict(post_dict):
downer = Downloader()
downer.headers["Referer"] = settings.EDEPOSIT_EXPORT_REFERER
data = downer.download(settings.ALEPH_EXPORT_URL, post=post_dict)
rheaders = downer.response_headers
error_msg = rheaders.get("aleph-info", "").lower().strip()
if "aleph-info" i... |
// buildKubeletConfig is responsible for creating the kubelet configuration | func (b *KubeletBuilder) buildKubeletConfig() (*kops.KubeletConfigSpec, error) {
if b.InstanceGroup == nil {
glog.Fatalf("InstanceGroup was not set")
}
kubeletConfigSpec, err := b.buildKubeletConfigSpec()
if err != nil {
return nil, fmt.Errorf("error building kubelet config: %v", err)
}
// TODO: Memoize if ... |
Verify credentials | def login(self, request):
try:
user = authenticate(request)
if not user:
raise AuthenticationFailed("User not authenticated.")
if not user.is_active:
raise AuthenticationFailed("This user has been disabled.")
login(reque... |
Removes a key by adding a remove entry to the row.
The remove is represented as a delta entry so checkpoints can be
written asynchronously.
@return false if the new record cannot fit into the block. | boolean remove(RowCursor cursor)
{
int rowHead = _rowHead;
int blobTail = _blobTail;
rowHead -= cursor.removeLength();
if (rowHead < blobTail) {
return false;
}
byte []buffer = _buffer;
// buffer[rowHead] = REMOVE;
cursor.getRemove(buffer, rowHead);
// cu... |
Retrieve model for route model binding
@param mixed $value
@return \Illuminate\Database\Eloquent\Model|null | public function resolveRouteBinding($value)
{
if (! (ctype_digit($value) || is_int($value))) {
return null;
}
try {
$value = App::make('fakeid')->decode((int) $value);
} catch (Exception $e) {
return null;
}
return $this->where($t... |
// NewGrip takes the name for a logging instance and creates a new
// Grip instance with configured with a local, standard output logging.
// The default level is "Notice" and the threshold level is "info." | func NewGrip(name string) *Grip {
sender, _ := send.NewNativeLogger(name,
send.LevelInfo{
Threshold: level.Trace,
Default: level.Trace,
})
return &Grip{impl: sender}
} |
Set the state of the BFD session. | def _set_state(self, new_state, diag=None):
old_state = self._session_state
LOG.info("[BFD][%s][STATE] State changed from %s to %s.",
hex(self._local_discr),
bfd.BFD_STATE_NAME[old_state],
bfd.BFD_STATE_NAME[new_state])
self._session_s... |
/*
TODO: Too general; this should be split into overloaded methods.
Is that possible? | XmlNode.QName toNodeQName(Context cx, Object nameValue, boolean attribute) {
if (nameValue instanceof XMLName) {
return ((XMLName)nameValue).toQname();
} else if (nameValue instanceof QName) {
QName qname = (QName)nameValue;
return qname.getDelegate();
} else ... |
Check whether order is cancelled.
$param boolean $strict
@return boolean | public function isCancelled( $strict = true ) {
if( $strict ) {
return $this->status == self::STATUS_CANCELLED;
}
return $this->status >= self::STATUS_CANCELLED;
} |
Internally called to reallocate the indexes. This method should be called when the filtered model changes its
element size | protected void reallocateIndexes() {
if (this.indexes == null || this.indexes.length != getFilteredModel().getSize()) {
this.indexes = new int[getFilteredModel().getSize()];
}
applyConstraint();
} |
Convenience method, calls {@link #view(String, Object)} internally.
The keys in the map are converted to String values.
@param values map with values to pass to view. | protected void view(Map<String, Object> values){
for(String key:values.keySet() ){
view(key, values.get(key));
}
} |
handle commands from user | def process_stdin(line):
''''''
if line is None:
sys.exit(0)
line = line.strip()
if not line:
return
args = shlex.split(line)
cmd = args[0]
if cmd == 'help':
k = command_map.keys()
k.sort()
for cmd in k:
(fn, help) = command_map[cmd]
... |
List all active quotes on an account | def cli(env):
""""""
table = formatting.Table([
'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id'
])
table.align['Name'] = 'l'
table.align['Package Name'] = 'r'
table.align['Package Id'] = 'l'
manager = ordering.OrderingManager(env.client)
items = man... |
/* Check if reduced-form input >= 2^255-19 | private static final boolean is_overflow(long10 x) {
return (
((x._0 > P26-19)) &&
((x._1 & x._3 & x._5 & x._7 & x._9) == P25) &&
((x._2 & x._4 & x._6 & x._8) == P26)
) || (x._9 > P25);
} |
put
@param key
@param value
@return V | public V put(K key, V value) {
if (isHighPrioEnabled) {
return highPrioMap.put(key, value);
} else {
return lowPrioMap.put(key, value);
}
} |
////////////////////////////////////////////////// Converts a single value into its Postgres format. | function formatValue(value, fm, cc) {
if (typeof value === 'function') {
return formatValue(resolveFunc(value, cc), fm, cc);
}
const ctf = getCTF(value); // Custom Type Formatting
if (ctf) {
fm |= ctf.rawType ? fmFlags.raw : 0;
return formatValue(resolveFunc(ctf.toPostgres, val... |
Парсит элемент и извлекает из него аргументы
@param DOMElement $element
@return void | protected function parseArgs(DOMElement $element)
{
$args = XmlUtil::getChildElements($element, 'arg');
foreach ($args as $arg) {
$name = XmlUtil::getRequiredAttributeValue($arg, 'name');
$this->args[$name] = XmlUtil::getText($arg);
}
} |
Returns a line formatted as comment.
@param string $text
@param array $style
@return string | public function error(string $text, array $style = []): string
{
return $this->line($text, ['fg' => static::RED] + $style);
} |
Returns the current paths unique ID.
@return string|null | public function getId()
{
if ($output = $this->execute('fsutil file queryfileid', $this->path)) {
if ((bool) preg_match('/(\d{1}[x].*)/', $output[0], $matches)) {
return $matches[0];
}
}
} |
Register a new model (models) | def post(self):
""""""
self.set_header("Content-Type", "application/json")
key = uuid.uuid4().hex
metadata = json.loads(self.request.body.decode())
metadata["uuid"] = key
self.database[key] = metadata
result = json.dumps({"uuid": key})
self.write(result) |
// SetName sets the Name field's value. | func (s *CreateRemoteAccessSessionInput) SetName(v string) *CreateRemoteAccessSessionInput {
s.Name = &v
return s
} |
// Metadata returns meta data about the overlay driver such as
// LowerDir, UpperDir, WorkDir and MergeDir used to store data. | func (d *Driver) Metadata(id string) (map[string]string, error) {
dir := d.dir(id)
if _, err := os.Stat(dir); err != nil {
return nil, err
}
metadata := map[string]string{
"WorkDir": path.Join(dir, "work"),
"MergedDir": path.Join(dir, "merged"),
"UpperDir": path.Join(dir, "diff"),
}
lowerDirs, err :=... |
@param WKBBuffer $buffer
@param int $srid
@return Geometry
@throws GeometryIOException | protected function readGeometry(WKBBuffer $buffer, int $srid) : Geometry
{
$buffer->readByteOrder();
$this->readGeometryHeader($buffer, $geometryType, $hasZ, $hasM, $srid);
$cs = new CoordinateSystem($hasZ, $hasM, $srid);
switch ($geometryType) {
case Geometry::POINT:
... |
Subsets and Splits
SQL Console for sentence-transformers/codesearchnet
Identifies examples where both requests.get() and beautifulsoup libraries are used together in code comments, revealing common web scraping patterns in the training data.
Golang Code and Comments
Retrieves all entries containing the term 'golang' in either the comment or code, providing a basic filter for data related to the Go programming language.