comment stringlengths 16 255 | code stringlengths 52 3.87M |
|---|---|
Bootstrap the application services. | public function boot()
{
if ( ! $this->app->routesAreCached()) {
require __DIR__ . '/routes.php';
}
$this->publishes([
__DIR__ . '/../config/config.php' => config_path('laravelimage.php'),
]);
$this->registerBladeExtensions();
} |
Retrieve related objects.
@param key {string} The relation key to fetch models for.
@param options {object} Options for 'Backbone.Model.fetch' and 'Backbone.sync'.
@return {xhr} An array or request objects | function( key, options ) {
options || ( options = {} );
var rel = this.getRelation( key ),
keyContents = rel && rel.keyContents,
toFetch = keyContents && _.select( _.isArray( keyContents ) ? keyContents : [ keyContents ], function( item ) {
var id = _.isString( item ) || _.isNumber( item ) ? item : ... |
Parse, extract and load assets from the stylesheet content
@param string $css the stylesheet content | private function loadStyleSheetAsset($css){
$imageRe = "/url\\s*\\(['|\"]?([^)]*\.(png|jpg|jpeg|gif|svg))['|\"]?\\)/mi";
$importRe = "/@import\\s*(url\\s*\\()?['\"]?([^;]*)['\"]/mi";
$fontFaceRe = "/@font-face\\s*\\{(.*)?\\}/mi";
$fontRe = "/url\\s*\\(['|\"]?([^)'|\"]*)['|\"]?\\)/i";
... |
Function executed when running the script with the -install switch | def install():
""""""
# Create Spyder start menu folder
# Don't use CSIDL_COMMON_PROGRAMS because it requres admin rights
# This is consistent with use of CSIDL_DESKTOPDIRECTORY below
# CSIDL_COMMON_PROGRAMS =
# C:\ProgramData\Microsoft\Windows\Start Menu\Programs
# CSIDL_PROGRAMS =
... |
Get the min and max values for a response body group
@param string $group The name of the group
@throws InvalidArgumentException
@return array An array with two keys, min and max, which represents the min and max values
for $group | protected function getResponseCodeGroupRange($group) {
switch ($group) {
case 'informational':
$min = 100;
$max = 199;
break;
case 'success':
$min = 200;
$max = 299;
break;
case 'r... |
Check if a piece of text is in the list of countries | def is_country(self, text):
""""""
ct_list = self._just_cts.keys()
if text in ct_list:
return True
else:
return False |
Handle the drag end. Apply the correct positioning to the draggable element | function () {
var element = this.getElement();
// This is to handle if there is a scroll
element.onselectstart = Aria.returnTrue;
if (this.overlay) {
// remove overlay here
this.overlay.$dispose();
... |
// Field is the field to be used for random number generation.
// This parameter is compulsory when a Seed is set and ignored
// otherwise. Note that documents that have the same value for a
// field will get the same score. | func (fn *RandomFunction) Field(field string) *RandomFunction {
fn.field = field
return fn
} |
Expects an exception with an authorization_paramaters field in its raw_json | def session_hook(exception):
safeprint(
"The resource you are trying to access requires you to "
"re-authenticate with specific identities."
)
params = exception.raw_json["authorization_parameters"]
message = params.get("session_message")
if message:
safeprint("message:... |
Adds a value to a writer if value is not <code>null</code>.
@param writer
writer to add object to.
@param field
field name to set.
@param value
field value.
@throws JSONException
if io error occurs. | public static void addIfNotNull(JSONWriter writer, String field,
Boolean value) throws JSONException {
if (value == null)
return;
writer.key(field);
writer.value(value);
} |
Read a duration.
@param units duration units
@param duration duration value
@return Duration instance | private Duration getDuration(TimeUnit units, Double duration)
{
Duration result = null;
if (duration != null)
{
double durationValue = duration.doubleValue() * 100.0;
switch (units)
{
case MINUTES:
{
durationValue *= MINUTES_PER_DAY... |
Initializes the found DFU device so that we can program it. | def init():
""""""
global __dev, __cfg_descr
devices = get_dfu_devices(idVendor=__VID, idProduct=__PID)
if not devices:
raise ValueError('No DFU device found')
if len(devices) > 1:
raise ValueError("Multiple DFU devices found")
__dev = devices[0]
__dev.set_configuration()
... |
Executes the command
@param InputInterface $input Command input
@param OutputInterface $output Command output | protected function execute( InputInterface $input, OutputInterface $output ) {
Log::instance()->setOutput( $output );
$repository = RepositoryManager::instance()->setup( $input->getArgument( 'repository' ) );
if ( ! $repository ) {
Log::instance()->write( 'Repository not configured. Before creating the repos... |
Generate the final CSS string | def create_css(self, rules):
style = rules[0].legacy_compiler_options.get(
'style', self.compiler.output_style)
debug_info = self.compiler.generate_source_map
if style == 'legacy':
sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg = True, ' ', ' ', False, '', '\n', '\n'... |
Stores the members of the set resulting from the intersection
of all the given sets. | function sinterstore(destination /* key-1, key-N, req*/) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length - 1] === 'object'
? args[args.length - 1] : null;
var list = this.sinter.apply(this, args);
if(list.length) {
this.setKey(
destination, new Set(list), undefined, undef... |
Adds a header entry value to the header. For example use this to set the source RPM package
name on your RPM
@param tag the header tag to set
@param value the value to set the header entry with | public void addHeaderEntry( final Tag tag, final String value) {
format.getHeader().createEntry(tag, value);
} |
to join the data that does not fit into memory.
@param masterLabels label of master data
@param masterColumns master column's
@param dataColumns data column's
@param masterPath master data HDFS path
@return this
@throws DataFormatException | public SimpleJob setBigJoin(String[] masterLabels, String[] masterColumns,
String[] dataColumns, String masterPath) throws DataFormatException {
String separator = conf.get(SEPARATOR);
return setBigJoin(masterLabels, masterColumns, dataColumns, masterPath, separator);
... |
Gets information from the #WINDOWS file.
Checks the #WINDOWS file to see if it has any info that was
not found in #SYSTEM (topics, index or default page. | def GetWindowsInfo(self):
'''
'''
result, ui = chmlib.chm_resolve_object(self.file, '/#WINDOWS')
if (result != chmlib.CHM_RESOLVE_SUCCESS):
return -1
size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, 8)
if (size < 8):
return -2
b... |
Search and load every installed plugin through entry points. | def load_installed_plugins():
""""""
providers = {}
checkers = {}
for entry_point in pkg_resources.iter_entry_points(group='archan'):
obj = entry_point.load()
if issubclass(obj, Provider):
providers[entry_point.name] = obj
elif issubcla... |
Parse the request command input.
Input:
Request Handle
Output:
Request Handle updated with parsed input.
Return code - 0: ok, non-zero: error | def parseCmdline(rh):
rh.printSysLog("Enter powerVM.parseCmdline")
if rh.totalParms >= 2:
rh.userid = rh.request[1].upper()
else:
# Userid is missing.
msg = msgs.msg['0010'][1] % modId
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0010'][0])
rh.print... |
Set or retrieve an attribute ``name`` from thread ``ct``.
If ``ct`` is not given used the current thread. If ``value``
is None, it will get the value otherwise it will set the value. | def thread_data(name, value=NOTHING, ct=None):
'''
'''
ct = ct or current_thread()
if is_mainthread(ct):
loc = process_data()
elif not hasattr(ct, '_pulsar_local'):
ct._pulsar_local = loc = {}
else:
loc = ct._pulsar_local
if value is not NOTHING:
if name in lo... |
// SetNextToken sets the NextToken field's value. | func (s *ListRobotApplicationsInput) SetNextToken(v string) *ListRobotApplicationsInput {
s.NextToken = &v
return s
} |
-- delete ------------------------ | @Override
public boolean delete(Object bean) throws OptimisticLockException {
methodCalls.add(MethodCall.of("bean").with("bean", bean));
capturedBeans.addDeleted(bean);
if (persistDeletes) {
return delete.delete(bean, null);
}
return true;
} |
// Next returns true if there are any values remaining in the iterator. | func (k *tsmBatchKeyIterator) Next() bool {
RETRY:
// Any merged blocks pending?
if len(k.merged) > 0 {
k.merged = k.merged[1:]
if len(k.merged) > 0 {
return true
}
}
// Any merged values pending?
if k.hasMergedValues() {
k.merge()
if len(k.merged) > 0 || k.hasMergedValues() {
return true
}
}
... |
Determines if a file is dirty
@private
@param {!File} file - file to test
@return {boolean} true if the file is dirty, false otherwise | function _isOpenAndDirty(file) {
// working set item might never have been opened; if so, then it's definitely not dirty
var docIfOpen = DocumentManager.getOpenDocumentForPath(file.fullPath);
return (docIfOpen && docIfOpen.isDirty);
} |
Get this object properties
REST: GET /hosting/web/{serviceName}/envVar/{key}
@param serviceName [required] The internal name of your hosting
@param key [required] Name of the variable | public OvhEnvVar serviceName_envVar_key_GET(String serviceName, String key) throws IOException {
String qPath = "/hosting/web/{serviceName}/envVar/{key}";
StringBuilder sb = path(qPath, serviceName, key);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhEnvVar.class);
} |
Send the given notification immediately.
@param \Illuminate\Support\Collection|array|mixed $notifiables
@param mixed $notification
@param array|null $channels
@return void | public function sendNow($notifiables, $notification, array $channels = null)
{
$notifiables = $this->formatNotifiables($notifiables);
$original = clone $notification;
foreach ($notifiables as $notifiable) {
if (empty($viaChannels = $channels ?: $notification->via($notifiable)))... |
// NewPrefixV0 returns a CIDv0 prefix with the specified multihash type.
// DEPRECATED: Use V0Builder | func NewPrefixV0(mhType uint64) Prefix {
return Prefix{
MhType: mhType,
MhLength: mh.DefaultLengths[mhType],
Version: 0,
Codec: DagProtobuf,
}
} |
This method is intended for internal use only. Returns the marshaled request configured with additional
parameters to enable operation dry-run. | @Override
public Request<DescribeSecurityGroupsRequest> getDryRunRequest() {
Request<DescribeSecurityGroupsRequest> request = new DescribeSecurityGroupsRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
} |
This will fail if there are duplicate beans in the Spring context. Beans
that are configured in the bootstrap context will not be considered
duplicate beans. | public void assertUniqueBeans(Set<String> ignoredDuplicateBeanNames) {
for (BeanohBeanFactoryMethodInterceptor callback : callbacks) {
Map<String, List<BeanDefinition>> beanDefinitionMap = callback
.getBeanDefinitionMap();
for (String key : beanDefinitionMap.keySet()) {
if (!ignoredDuplicateBeanNames.c... |
测试是否以数字开头,负数也是数字,但是不支持科学表达式模型
@return if matches a digit character | public boolean matchesDigit() {
return !isEmpty() && (Character.isDigit(queue.charAt(pos))
|| queue.charAt(pos) == '-' && remainingLength() >= 2 && Character.isDigit(queue.charAt(pos + 1)));
} |
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled. | func (c *ServerGetBotConfigCall) Context(ctx context.Context) *ServerGetBotConfigCall {
c.ctx_ = ctx
return c
} |
Checks the selector value.
@param $value
@return bool | public function checkValue(&$value)
{
if (is_string($value)) {
$value = Placeholder::replaceStringsAndComments($value);
$value = Placeholder::removeCommentPlaceholders($value, true);
$value = preg_replace('/[ ]+/', ' ', $value);
$value = Placeholder::replaceSt... |
Cleans the text from mentions, by providing a context message.
@param \CharlotteDunois\Yasmin\Models\Message $message
@param string $text
@return string | static function cleanContent(\CharlotteDunois\Yasmin\Models\Message $message, string $text) {
/** @var \CharlotteDunois\Yasmin\Interfaces\ChannelInterface $channel */
foreach($message->mentions->channels as $channel) {
$text = \str_replace('<#'.$channel->getId().'>', '#'.$channel->name, $te... |
Iterates over (valid) attributes of a class.
Args:
cls (object): the class to iterate over
Yields:
(str, obj) tuples: the class-level attributes. | def iterclass(cls):
for field in dir(cls):
if hasattr(cls, field):
value = getattr(cls, field)
yield field, value |
Convert datetime.datetime to timestamp
:param obj: value to (possibly) convert | def json_encode_default(obj):
'''
'''
if isinstance(obj, (datetime, date)):
result = dt2ts(obj)
else:
result = json_encoder.default(obj)
return to_encoding(result) |
Attempt to immediately acquire a shared read lock.
@param locker object which might be write or upgrade lock owner
@return true if acquired | public final boolean tryLockForRead(L locker) {
int state = mState;
if (state >= 0) { // no write lock is held
if (isReadWriteFirst() || isReadLockHeld(locker)) {
do {
if (incrementReadLocks(state)) {
adjustReadLockCount(locke... |
Get a specific attribute for this tag.
@param string @attribute
@return string|null | public function getAttribute($attribute)
{
return !empty($this->attributes[$attribute]) ? $this->attributes[$attribute] : null;
} |
Initialize JSON structure.
@return Path
@deprecated | public function initializeStructure()
{
$structure = [
'id' => $this->getId(),
'name' => $this->getName(),
'description' => $this->getDescription(),
'manualProgressionAllowed' => $this->manualProgressionAllowed,
'steps' => [],
];
$... |
Emits the record clicked signal for the given item, provided the
signals are not currently blocked.
:param item | <QTreeWidgetItem> | def emitRecordMiddleClicked(self, item):
# emit that the record has been double clicked
if isinstance(item, XOrbRecordItem) and not self.signalsBlocked():
self.recordMiddleClicked.emit(item.record()) |
// ReturnSubs returns substitutions to the pool. USE WITH CAUTION. | func ReturnSubs(sub Subs) {
switch s := sub.(type) {
case mSubs:
for k := range s {
delete(s, k)
}
mSubPool.Put(sub)
case *sSubs:
size := cap(s.s) - 2
if size > 0 && size < poolSize+1 {
// reset to empty
for i := range s.s {
s.s[i] = Substitution{}
}
s.s = s.s[:size]
sSubPool[size-1]... |
Converts the RP Record to a String | String
rrToString() {
StringBuffer sb = new StringBuffer();
sb.append(mailbox);
sb.append(" ");
sb.append(textDomain);
return sb.toString();
} |
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. | func (in *TopologySpec) DeepCopyInto(out *TopologySpec) {
*out = *in
if in.Bastion != nil {
in, out := &in.Bastion, &out.Bastion
*out = new(BastionSpec)
(*in).DeepCopyInto(*out)
}
if in.DNS != nil {
in, out := &in.DNS, &out.DNS
*out = new(DNSSpec)
**out = **in
}
return
} |
Returns the shipment state label.
@param string|ShipmentInterface $stateOrShipment
@return string | public function getShipmentStateLabel($stateOrShipment)
{
$state = $stateOrShipment instanceof ShipmentInterface ? $stateOrShipment->getState() : $stateOrShipment;
return $this->translator->trans(ShipmentStates::getLabel($state));
} |
print header row
allows user to override | def print_header_row r, c, len, value, color, attr
#acolor = $promptcolor
@graphic.printstring r, c+@left_margin, "%-*s" % [len-@left_margin ,value], color, attr
end |
Ensure that datetime fields are correctly formatted.
@param string $type
@param string $value
@return string|FragmentInterface|\DateTime
@throws DefaultValueException | protected function formatDatetime(string $type, $value)
{
if ($value === 'current_timestamp()') {
$value = self::DATETIME_NOW;
}
return parent::formatDatetime($type, $value);
} |
// SetTrainingStartTime sets the TrainingStartTime field's value. | func (s *TrainingJob) SetTrainingStartTime(v time.Time) *TrainingJob {
s.TrainingStartTime = &v
return s
} |
Maps this exception to a response object.
@return Response this exception maps to. | public static Response toResponse(Response.Status status, String wwwAuthHeader) {
Response.ResponseBuilder rb = Response.status(status);
if (wwwAuthHeader != null) {
rb.header("WWW-Authenticate", wwwAuthHeader);
}
return rb.build();
} |
Calls the post init hubs
:param dict parser_result: Dictionary with the parsed arguments | def post_setup_plugins(parser_result):
if not isinstance(parser_result, dict):
parser_result = vars(parser_result)
plugins.run_post_inits(parser_result) |
// Convert_kops_LyftVPCNetworkingSpec_To_v1alpha1_LyftVPCNetworkingSpec is an autogenerated conversion function. | func Convert_kops_LyftVPCNetworkingSpec_To_v1alpha1_LyftVPCNetworkingSpec(in *kops.LyftVPCNetworkingSpec, out *LyftVPCNetworkingSpec, s conversion.Scope) error {
return autoConvert_kops_LyftVPCNetworkingSpec_To_v1alpha1_LyftVPCNetworkingSpec(in, out, s)
} |
Application booted, let's dispatch the routes.
@return callable | protected function dispatchToRouter() : Closure
{
return function ($request) {
return $this->router->setContainer($this->container)->dispatch($request);
};
} |
// SetOutputArtifactDetails sets the OutputArtifactDetails field's value. | func (s *ActionType) SetOutputArtifactDetails(v *ArtifactDetails) *ActionType {
s.OutputArtifactDetails = v
return s
} |
Calls a JavaScript method on the object.
@param method The name of the method.
@param returnType The return type.
@param args Method arguments.
@param <T> Java type for the return value.
@return A return value. | @Nullable
protected final <T> T jsiiCall(final String method, final Class<T> returnType, @Nullable final Object... args) {
return JsiiObjectMapper.treeToValue(JsiiObject.engine.getClient()
.callMethod(this.objRef,
... |
Relay chat messages to and from clients. | def chat(ws):
lag_tolerance_secs = float(request.args.get("tolerance", 0.1))
client = Client(ws, lag_tolerance_secs=lag_tolerance_secs)
client.subscribe(request.args.get("channel"))
gevent.spawn(client.heartbeat)
client.publish() |
call api, handle error, return response
@param Message $req
@param String $method
@param String $uri
@param function $handler function($response, $bizerror, $common) create response oject or throw biz error exception
@return Message $result | public function callApi(Message $req, $method, $uri, $handler)
{
// check handler, php before 5.4 doesn't support Type Hinting of callable
if (!is_callable($handler)) {
throw new GeneralException("Can not find response handler.");
}
$data = [
'json' => (objec... |
Execute an Http GET request.
@param $path
@param array $parameters
@return mixed | protected function get($path, array $parameters = array())
{
if (count($parameters) > 0) {
$path .= '?' . http_build_query($parameters);
}
$response = $this->client->getHttpClient()->get($path);
return $this->parseResponse($response);
} |
Deletes the expired contexts.
@return int[] The number of deleted contexts. | public function process_approved_deletions() : array {
$this->trace->output('Checking requirements');
if (!$this->check_requirements()) {
$this->trace->output('Requirements not met. Cannot process expired retentions.', 1);
return [0, 0];
}
$this->trace->output('F... |
Sets id
@param string $id id
@return $this | public function setId($id)
{
if (!is_null($id) && (!preg_match("/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/", $id))) {
throw new \InvalidArgumentException("invalid value for $id when calling StackService., must conform to the pattern /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0... |
Set the Trigger's {@link JobDataMap}, adding any values to it that were
already set on this TriggerBuilder using any of the other 'usingJobData'
methods.
@return the updated TriggerBuilder
@see ITrigger#getJobDataMap() | @Nonnull
public TriggerBuilder <T> usingJobData (final JobDataMap newJobDataMap)
{
// add any existing data to this new map
newJobDataMap.putAll (m_aJobDataMap);
m_aJobDataMap = newJobDataMap; // set new map as the map to use
return this;
} |
// SetFlow sets the Flow field's value. | func (s *CreateFlowOutput) SetFlow(v *Flow) *CreateFlowOutput {
s.Flow = v
return s
} |
<pre>
Performs generic data validation for the operation to be performed
</pre> | protected void validate(String operationType) throws Exception
{
super.validate(operationType);
MPSString id_validator = new MPSString();
id_validator.setConstraintIsReq(MPSConstants.DELETE_CONSTRAINT, true);
id_validator.setConstraintIsReq(MPSConstants.MODIFY_CONSTRAINT, true);
id_validator.validate... |
return quality score format -
might return several if ambiguous. | def guessFormat(self):
''''''
c = [ord(x) for x in self.quals]
mi, ma = min(c), max(c)
r = []
for entry_format, v in iteritems(RANGES):
m1, m2 = v
if mi >= m1 and ma < m2:
r.append(entry_format)
return r |
Bail to send new saved data back to our modal handler.
@param int $item_id Item ID.
@param string $item_title Item title.
@param object $field_args Field arguments. | public function admin_modal_bail( $item_id, $item_title, $field_args ) {
$model_data = $this->build_dfv_field_item_data_recurse_item( $item_id, $item_title, $field_args );
?>
<script type="text/javascript">
window.parent.jQuery( window.parent ).trigger(
'dfv:modal:update',
<?php echo wp_json_encod... |
Is the given line a diff header line.
diff --git a/some/file b/some/file
@param string $line
@return bool | private function isHeaderLine(string $line): bool
{
$matches = [];
if (preg_match('#^diff --git [a|b|c|i|w|o]/(.*) [a|b|c|i|w|o]/(.*)#', $line, $matches)) {
$this->appendCollectedFileAndChanges();
$this->currentOperation = File::OP_MODIFIED;
$this->currentFileName... |
// SetTimeoutSeconds sets the TimeoutSeconds field's value. | func (s *SendCommandInput) SetTimeoutSeconds(v int64) *SendCommandInput {
s.TimeoutSeconds = &v
return s
} |
Returns a route definition by the name of the route.
@param string $name The name of the route
@return RouteDefinition The route definition with the given name | public function getRouteDefinitionByName(string $name): RouteDefinition
{
if (!isset($this->routesByName[$name])) {
throw new \InvalidArgumentException("Invalid route name '$name'");
}
return $this->getRouteDefinition($this->routesByName[$name]);
} |
// NewRegexpWithLimit creates a new Regular Expression automaton with
// the specified expression. The size of the compiled finite state
// automaton exceeds the user specified size, ErrCompiledTooBig will be
// returned. | func NewWithLimit(expr string, size uint) (*Regexp, error) {
parsed, err := syntax.Parse(expr, syntax.Perl)
if err != nil {
return nil, err
}
return NewParsedWithLimit(expr, parsed, size)
} |
Returns the GA4GH protocol representation of this read group's
ReadStats. | def getStats(self):
stats = protocol.ReadStats()
stats.aligned_read_count = self.getNumAlignedReads()
stats.unaligned_read_count = self.getNumUnalignedReads()
# TODO base_count requires iterating through all reads
return stats |
// PubSubHandler is a webhook that stores the builds coming in from pubsub. | func PubSubHandler(ctx *router.Context) {
statusCode := pubSubHandlerImpl(ctx.Context, ctx.Request)
ctx.Writer.WriteHeader(statusCode)
} |
Returns the WKB representation of this geometry.
@noproxy
@return string | public function asBinary() : string
{
static $wkbWriter;
if ($wkbWriter === null) {
$wkbWriter = new WKBWriter();
}
return $wkbWriter->write($this);
} |
Returns all the values joined together.
:return <int> | def all(self):
out = 0
for key, value in self.items():
out |= value
return out |
// ReadLine awaits a single line from the client. | func (c *Conn) ReadLine() (text string, ok bool) {
ok = c.RwcScanner.Scan()
return c.RwcScanner.Text(), ok
} |
Given a value of type <code>A</code>, produced an instance of this tuple with each slot set to that value.
@param a the value to fill the tuple with
@param <A> the value type
@return the filled tuple
@see Tuple2#fill | public static <A> Tuple7<A, A, A, A, A, A, A> fill(A a) {
return tuple(a, a, a, a, a, a, a);
} |
@param string $id
@param array $data
@param array $headers
@throws Exception
@return array|string | public function reactivate(string $id, array $data, array $headers = [])
{
$url = $this->url('subscriptions/%s/reactivate', $id);
return $this->post($url, $data, $headers);
} |
Link given $zone with the zone given in $zoneData. | private function linkZone(Zone $zone, array $zoneData): void
{
$linkedZoneLayout = $this->layoutService->loadLayout($zoneData['layout_id']);
$linkedZone = $linkedZoneLayout->getZone($zoneData['identifier']);
$this->layoutService->linkZone($zone, $linkedZone);
} |
Creates a Diffie-Hellman key pair.
@return dh keypair | protected KeyPair generateKeyPair() {
KeyPair keyPair = null;
DHParameterSpec keySpec = new DHParameterSpec(DH_MODULUS, DH_BASE);
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
keyGen.initialize(keySpec);
keyPair = keyGen.generateKey... |
Create a package finder appropriate to this install command.
This method is meant to be overridden by subclasses, not
called directly. | def _build_package_finder(self, options, index_urls):
return PackageFinder(find_links=options.find_links,
index_urls=index_urls,
use_mirrors=options.use_mirrors,
mirrors=options.mirrors) |
Generates the data that powers the index page | protected function generateIndex() {
/**
* Handle missing index.html. Solves https://github.com/drupal-pattern-lab/patternlab-php-core/issues/14
* Could also be used to re-add missing styleguidekit assets with a few edits?
*
* 1. @TODO: Figure out a better way to future-proof path resolution for style... |
Parses a complex fault geometry node returning both the attributes and
parameters in a dictionary | def parse_complex_fault_geometry(node):
assert "complexFaultGeometry" in node.tag
# Get general attributes
geometry = {"intermediateEdges": []}
for subnode in node:
crds = subnode.nodes[0].nodes[0].text
if "faultTopEdge" in subnode.tag:
geometry["faultTopEdge"] = numpy.a... |
Compute distance matrix from contact data by applying a negative power
law (alpha) to its nonzero pixels, then interpolating on the zeroes using a
shortest-path algorithm. | def to_distance(matrix, alpha=1):
matrix = np.array(matrix)
try:
import scipy.sparse
except ImportError as e:
print("Scipy not found.")
print(str(e))
raise
if callable(alpha):
distance_function = alpha
else:
try:
a = np.float64(alpha)... |
The wrapper for creating shell instances.
@param string $className Shell class name.
@param \Cake\Console\ConsoleIo $io The IO wrapper for the created shell class.
@return \Cake\Console\Shell|\Cake\Console\Command | protected function createShell($className, ConsoleIo $io)
{
$shell = $this->factory->create($className);
if ($shell instanceof Shell) {
$shell->setIo($io);
}
return $shell;
} |
count
```
$db->count();
```
@param string $table
@param array|string $wheres
@return int
@throws \RuntimeException | public function count(string $table, $wheres)
{
list($where, $bindings) = $this->handleWheres($wheres);
$sql = "SELECT COUNT(*) AS total FROM {$table} WHERE {$where}";
$result = $this->fetchObject($sql, $bindings);
return $result ? (int)$result->total : 0;
} |
Return the extra classes as concatenated strings
@return String $classes | protected function getTableExtraClassesString()
{
$classes_html = '';
if( ! empty($this->table_extra_classes) )
{
foreach($this->table_extra_classes as $class)
{
$classes_html.= "{$class} ";
}
}
return $classes_html;
} |
// ContentTypeHandler wraps and returns a http.Handler, validating the request
// content type is compatible with the contentTypes list. It writes a HTTP 415
// error if that fails.
//
// Only PUT, POST, and PATCH requests are considered. | func ContentTypeHandler(h http.Handler, contentTypes ...string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !(r.Method == "PUT" || r.Method == "POST" || r.Method == "PATCH") {
h.ServeHTTP(w, r)
return
}
for _, ct := range contentTypes {
if isContentType(r.He... |
Notify all listeners that a property has changed.
@param property
the property whose value has changed | private void firePropertyChanged(T property)
{
PropertyEvent<T> event = null;
for (PropertyListener<T> l : listeners)
{
if (event == null)
{
event = new PropertyEvent<T>(this, property);
}
l.changed(event);
... |
/ perform extra validation before submission | function validation($data, $files) {
global $COURSE;
$errors = parent::validation($data, $files);
if (array_key_exists('idnumber', $data)) {
if ($data['id']) {
$grade_item = new grade_item(array('id'=>$data['id'], 'courseid'=>$data['courseid']));
} else ... |
Additionally encodes headers.
:return: | def as_dict(self):
data = super(BaseEmail, self).as_dict()
data["Headers"] = [{"Name": name, "Value": value} for name, value in data["Headers"].items()]
for field in ("To", "Cc", "Bcc"):
if field in data:
data[field] = list_to_csv(data[field])
data["A... |
Splits a line at the first occurrence of :
@param {string} line
@return {Array.<string>}
@private | function splitLine(line) {
var idx = String(line).indexOf(':');
if (!line || idx < 0) {
return null;
}
return [line.slice(0, idx), line.slice(idx + 1)];
} |
Helper to cast string to datetime using :member:`parse_format`.
:param value: String representing a datetime
:type value: str
:return: datetime | def get_parsed_value(self, value):
def get_parser(parser_desc):
try:
return parser_desc['parser']
except TypeError:
try:
return get_parser(self.date_parsers[parser_desc])
except KeyError:
re... |
<code>.google.privacy.dlp.v2.CryptoReplaceFfxFpeConfig crypto_replace_ffx_fpe_config = 4;
</code> | public com.google.privacy.dlp.v2.CryptoReplaceFfxFpeConfigOrBuilder
getCryptoReplaceFfxFpeConfigOrBuilder() {
if (transformationCase_ == 4) {
return (com.google.privacy.dlp.v2.CryptoReplaceFfxFpeConfig) transformation_;
}
return com.google.privacy.dlp.v2.CryptoReplaceFfxFpeConfig.getDefaultInsta... |
List all file `filename` breakpoints | def get_file_breaks(self, filename):
""""""
return [
breakpoint for breakpoint in self.breakpoints
if breakpoint.on_file(filename)
] |
Add an edge for every attribute the given artifact provides.
This method adds a directed edge from the artifact node to every attribute
this artifact provides.
Args:
rdf_artifact: The artifact object. | def _AddProvidesEdges(self, rdf_artifact):
for attribute in rdf_artifact.provides:
self._AddEdge(rdf_artifact.name, attribute) |
// AllCols indicates that all columns should be use | func (engine *Engine) AllCols() *Session {
session := engine.NewSession()
session.isAutoClose = true
return session.AllCols()
} |
Converts the given Metric into datapoints that can be sent to SignalFx.
@param metric The {@link Metric} containing the timeseries of each combination of label values.
@return A list of datapoints for the corresponding metric timeseries of this metric. | static List<DataPoint> adapt(Metric metric) {
MetricDescriptor metricDescriptor = metric.getMetricDescriptor();
MetricType metricType = getType(metricDescriptor.getType());
if (metricType == null) {
return Collections.emptyList();
}
DataPoint.Builder shared = DataPoint.newBuilder();
share... |
Returns a contentset options according to the layout zone.
@param \StdClass $zone
@return array | private function getZoneOptions(\stdClass $zone)
{
$options = array(
'parameters' => array(
'class' => array(
'type' => 'scalar',
'options' => array('default' => 'row'),
),
),
);
if (true === pro... |
Returns a list of pairs (leaf_name, distance) | def _parse_leaves(self, leaves) -> List[Tuple[str, int]]:
""""""
return [(self._leaf_name(leaf), 0) for leaf in leaves] |
------------------------------------------------------------------------------ | function onRequestGetAgents(session, channel, message) {
var agents = session.getAgents()
var infos = agents.map(function(agent){
return agent.info
})
channel.sendMessage({
type: "response",
name: message.name,
from: message.to,
id: message.id,
body: infos
})
} |
Does our comparison need a container? EG: "[* TO *]"? If so, return the opening container brace.
@param string $comparison
@return string
@throws InvalidArgumentException | protected function getOpenComparisonContainer($comparison)
{
switch ($comparison) {
case SearchCriterion::GREATER_EQUAL:
case SearchCriterion::LESS_EQUAL:
case SearchCriterion::ISNULL:
case SearchCriterion::ISNOTNULL:
return '[';
ca... |
Generates an unique auth code.
Implementing classes may want to override this function to implement
other auth code generation schemes.
@return
An unique auth code.
@ingroup oauth2_section_4 | protected function generateAuthorizationCode()
{
$tokenLen = 40;
if (function_exists('random_bytes')) {
$randomData = random_bytes(100);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$randomData = openssl_random_pseudo_bytes(100);
} elseif (funct... |
Recovers a RingSet corresponding to a AtomContainer that has been
stored by storeRingSystem().
@param mol The IAtomContainer for which to recover the IRingSet. | private IRingSet recoverRingSystem(IAtomContainer mol) {
IRingSet ringSet = mol.getBuilder().newInstance(IRingSet.class);
for (Integer[] bondNumbers : listOfRings) {
IRing ring = mol.getBuilder().newInstance(IRing.class, bondNumbers.length);
for (int bondNumber : bondNumbers) {
... |
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.