comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
// SetNextToken sets the NextToken field's value.
|
func (s *SegmentsResponse) SetNextToken(v string) *SegmentsResponse {
s.NextToken = &v
return s
}
|
// Bool get cookie as bool
|
func (c *cookies) Bool(key string) (bool, error) {
ck, err := c.req.Cookie(key)
if err != nil {
return false, err
}
return strconv.ParseBool(ck.Value)
}
|
Initiate the module
@param config The configuration for the module
|
function(config){
if(isString(config)){
this.config.appBase = config;
}else if(isObject(config)){// If the config object is provided
this.config = Object.assign(this.config, config);
}
// If the app base isn't provided
if(!this.config.appBase){
this.config.appBase = utils.getAppLocalPath();
}else if(this.config.appBase.length && this.config.appBase[this.config.appBase.length-1] !== '/'){
this.config.appBase += '/';
}
// If the layouts list was passed in the config
if(this.config.layouts && isObject(this.config.layouts)){
Object.keys(this.config.layouts).forEach(key => {
layouts.add(key, this.config.layouts[key]);
});
}
// If the dev mode is on
if(this.config.devMode === true){
// Attach some shortcuts
Application.on('ready', function(){
// Ctrl+F12 to toggle the dev tools
Shortcuts.register('CmdOrCtrl+F12', function(){
const window = windowManager.getCurrent();
if(window) window.toggleDevTools();
});
// Ctrl+R to reload the page
Shortcuts.register('CmdOrCtrl+R', function(){
const window = windowManager.getCurrent();
if(window) window.reload();
});
});
}
// If a default setup is provided
if(this.config.defaultSetup){
this.setDefaultSetup(this.config.defaultSetup);
delete this.config.defaultSetup;
}
}
|
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Preferences.
|
func (in *Preferences) DeepCopy() *Preferences {
if in == nil {
return nil
}
out := new(Preferences)
in.DeepCopyInto(out)
return out
}
|
Suffix unique index to slug
@param $slug
@param $list
@return string
|
private function generateSuffix($slug, $list)
{
// loop through list and get highest index number
$index = $list->map(function ($s) use ($slug) {
// str_replace instead of explode('-');
return intval(str_replace($slug . '-', '', $s));
})->sort()->last();
return $slug . '-' . ($index + 1);
}
|
Sets self.input to inputs. Load order is by default random. Use setOrderedInputs() to order inputs.
|
def setInputs(self, inputs):
if not self.verifyArguments(inputs) and not self.patterned:
raise NetworkError('setInputs() requires [[...],[...],...] or [{"layerName": [...]}, ...].', inputs)
self.inputs = inputs
self.loadOrder = [0] * len(self.inputs)
for i in range(len(self.inputs)):
self.loadOrder[i] = i
|
Starts an HTTP {@link Operation} with the given method and {@link HttpUrl}.
@param method The uppercased HTTP method to use.
@param url An {@link HttpUrl} target.
@return An {@link Operation} builder.
|
protected Operation httpOp(String method, HttpUrl url) {
return new Operation(httpClient).method(method).httpUrl(url);
}
|
Evaluate processors on given value.
@param mixed $valueToProcess
@param array $configurationWithEventualProcessors
@param string $fusionPath
@param AbstractFusionObject $contextObject
@return mixed
|
protected function evaluateProcessors($valueToProcess, $configurationWithEventualProcessors, $fusionPath, AbstractFusionObject $contextObject = null)
{
if (isset($configurationWithEventualProcessors['__meta']['process'])) {
$processorConfiguration = $configurationWithEventualProcessors['__meta']['process'];
$positionalArraySorter = new PositionalArraySorter($processorConfiguration, '__meta.position');
foreach ($positionalArraySorter->getSortedKeys() as $key) {
$processorPath = $fusionPath . '/__meta/process/' . $key;
if ($this->evaluateIfCondition($processorConfiguration[$key], $processorPath, $contextObject) === false) {
continue;
}
if (isset($processorConfiguration[$key]['expression'])) {
$processorPath .= '/expression';
}
$this->pushContext('value', $valueToProcess);
$result = $this->evaluateInternal($processorPath, self::BEHAVIOR_EXCEPTION, $contextObject);
if ($this->getLastEvaluationStatus() !== static::EVALUATION_SKIPPED) {
$valueToProcess = $result;
}
$this->popContext();
}
}
return $valueToProcess;
}
|
new syntax for mapping routes
|
public static function map(
string $url = null, string $destination, string $route_name = null, string $method = null
) :Route {
// We cannot allow duplicate route names for reversing reasons
if($route_name && self::hasRoute($route_name)) {
// throw an exception
throw new Exception("Router::map() The route {$route_name} has already been declared");
}
// create a new route
$route = new Route($route_name);
// configure the route
$route
->setUrl($url)
->setDestination($destination)
->setMethod($method);
// add it to the list of known routes
self::$_routes[$route->name] = $route;
// return the route for finer tuning
return self::$_routes[$route->name];
}
|
setRootDir
Sets the application root directory
(This is typically unneeded except for tests)
@param string $rootDir
@return self $this
|
public function setRootDir($rootDir)
{
if (!is_dir($rootDir)) {
throw new \InvalidArgumentException(
sprintf('Invalid Application Configuration Directory: %s', $rootDir)
);
}
$this->rootDir = $rootDir;
}
|
Sort by function.
@param string $function
@param string $order
@return SortBy
|
public function byFunction(
string $function,
string $order
): SortBy {
$this->sortsBy[] = [
'type' => self::TYPE_FUNCTION,
'function' => $function,
'order' => $order,
];
return $this;
}
|
Return the sentences that led to the construction of a specified edge.
Args:
G
source: The source of the edge.
target: The target of the edge.
|
def _get_edge_sentences(
G: AnalysisGraph, source: str, target: str
) -> List[str]:
return chain.from_iterable(
[
[repr(e.text) for e in s.evidence]
for s in G.edges[source, target]["InfluenceStatements"]
]
)
|
Finds the path to the file where the class is defined.
@param string $class The name of the class
@return string|null The path, if found
|
public function findFile($class)
{
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$namespace = substr($class, 0, $pos);
$className = substr($class, $pos + 1);
$normalizedClass = str_replace('\\', DIRECTORY_SEPARATOR, $namespace).DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $className).'.php';
foreach ($this->namespaces as $ns => $dirs) {
if (0 !== strpos($namespace, $ns)) {
continue;
}
foreach ($dirs as $dir) {
$file = $dir.DIRECTORY_SEPARATOR.$normalizedClass;
if (is_file($file)) {
return $file;
}
}
}
foreach ($this->namespaceFallbacks as $dir) {
$file = $dir.DIRECTORY_SEPARATOR.$normalizedClass;
if (is_file($file)) {
return $file;
}
}
} else {
// PEAR-like class name
$normalizedClass = str_replace('_', DIRECTORY_SEPARATOR, $class).'.php';
foreach ($this->prefixes as $prefix => $dirs) {
if (0 !== strpos($class, $prefix)) {
continue;
}
foreach ($dirs as $dir) {
$file = $dir.DIRECTORY_SEPARATOR.$normalizedClass;
if (is_file($file)) {
return $file;
}
}
}
foreach ($this->prefixFallbacks as $dir) {
$file = $dir.DIRECTORY_SEPARATOR.$normalizedClass;
if (is_file($file)) {
return $file;
}
}
}
if ($this->useIncludePath && $file = stream_resolve_include_path($normalizedClass)) {
return $file;
}
}
|
// MethodsFromTypes create a method set from the include slice, excluding any
// method in exclude.
|
func (c *Inspector) MethodsFromTypes(include []reflect.Type, exclude []reflect.Type) Methods {
c.parseSource()
var methods Methods
var excludes = make(map[string]bool)
if len(exclude) > 0 {
for _, m := range c.MethodsFromTypes(exclude, nil) {
excludes[m.Name] = true
}
}
// There may be overlapping interfaces in types. Do a simple check for now.
seen := make(map[string]bool)
nameAndPackage := func(t reflect.Type) (string, string) {
var name, pkg string
isPointer := t.Kind() == reflect.Ptr
if isPointer {
t = t.Elem()
}
pkgPrefix := ""
if pkgPath := t.PkgPath(); pkgPath != "" {
pkgPath = strings.TrimSuffix(pkgPath, "/")
_, shortPath := path.Split(pkgPath)
pkgPrefix = shortPath + "."
pkg = pkgPath
}
name = t.Name()
if name == "" {
// interface{}
name = t.String()
}
if isPointer {
pkgPrefix = "*" + pkgPrefix
}
name = pkgPrefix + name
return name, pkg
}
for _, t := range include {
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
if excludes[m.Name] || seen[m.Name] {
continue
}
seen[m.Name] = true
if m.PkgPath != "" {
// Not exported
continue
}
numIn := m.Type.NumIn()
ownerName, _ := nameAndPackage(t)
method := Method{Owner: t, OwnerName: ownerName, Name: m.Name}
for i := 0; i < numIn; i++ {
in := m.Type.In(i)
name, pkg := nameAndPackage(in)
if pkg != "" {
method.Imports = append(method.Imports, pkg)
}
method.In = append(method.In, name)
}
numOut := m.Type.NumOut()
if numOut > 0 {
for i := 0; i < numOut; i++ {
out := m.Type.Out(i)
name, pkg := nameAndPackage(out)
if pkg != "" {
method.Imports = append(method.Imports, pkg)
}
method.Out = append(method.Out, name)
}
}
methods = append(methods, method)
}
}
sort.SliceStable(methods, func(i, j int) bool {
mi, mj := methods[i], methods[j]
wi := c.methodWeight[mi.OwnerName][mi.Name]
wj := c.methodWeight[mj.OwnerName][mj.Name]
if wi == wj {
return mi.Name < mj.Name
}
return wi < wj
})
return methods
}
|
Creates an ad group in the Shopping campaign.
|
private static function createAdGroup(
AdWordsServices $adWordsServices,
AdWordsSession $session,
Campaign $campaign
) {
$adGroupService = $adWordsServices->get($session, AdGroupService::class);
// Create ad group.
$adGroup = new AdGroup();
$adGroup->setCampaignId($campaign->getId());
$adGroup->setName('Ad Group #' . uniqid());
// Required: Set the ad group type to SHOPPING_SHOWCASE_ADS.
$adGroup->setAdGroupType(AdGroupType::SHOPPING_SHOWCASE_ADS);
// Required: Set the ad group's bidding strategy configuration.
// Note: Showcase ads require that the campaign has a ManualCpc
// BiddingStrategyConfiguration.
$biddingStrategyConfiguration = new BiddingStrategyConfiguration();
// Optional: Set the bids.
$bidAmount = new Money();
$bidAmount->setMicroAmount(100000);
$cpcBid = new CpcBid();
$cpcBid->setBid($bidAmount);
$biddingStrategyConfiguration->setBids([$cpcBid]);
$adGroup->setBiddingStrategyConfiguration($biddingStrategyConfiguration);
// Create operation.
$adGroupOperation = new AdGroupOperation();
$adGroupOperation->setOperand($adGroup);
$adGroupOperation->setOperator(Operator::ADD);
// Make the mutate request.
$adGroupAddResult = $adGroupService->mutate([$adGroupOperation]);
$adGroup = $adGroupAddResult->getValue()[0];
return $adGroup;
}
|
Creates copies of the fields we are keeping
track of for the provided model, returning a
dictionary mapping field name to a copied field object.
|
def copy_fields(self, model):
fields = {'__module__' : model.__module__}
for field in model._meta.fields:
if not field.name in self._exclude:
field = copy.deepcopy(field)
if isinstance(field, models.AutoField):
#we replace the AutoField of the original model
#with an IntegerField because a model can
#have only one autofield.
field.__class__ = models.IntegerField
if field.primary_key:
field.serialize = True
#OneToOne fields should really be tracked
#as ForeignKey fields
if isinstance(field, models.OneToOneField):
field.__class__ = models.ForeignKey
if field.primary_key or field.unique:
#unique fields of the original model
#can not be guaranteed to be unique
#in the audit log entry but they
#should still be indexed for faster lookups.
field.primary_key = False
field._unique = False
field.db_index = True
if field.remote_field and field.remote_field.related_name:
field.remote_field.related_name = '_auditlog_{}_{}'.format(
model._meta.model_name,
field.remote_field.related_name
)
elif field.remote_field:
try:
if field.remote_field.get_accessor_name():
field.remote_field.related_name = '_auditlog_{}_{}'.format(
model._meta.model_name,
field.remote_field.get_accessor_name()
)
except e:
pass
fields[field.name] = field
return fields
|
Convert to `Set-Cookie` headers
@return string[]
|
public function toHeaders(): array
{
$headers = [];
foreach ($this as $name => $properties) {
$headers[] = $this->toHeaderLine($name, $properties);
}
return $headers;
}
|
Genera texto en markdown a partir de los metadatos de un `field`.
Args:
field (dict): Diccionario con metadatos de un `field`.
Returns:
str: Texto que describe un `field`.
|
def field_to_markdown(field):
if "title" in field:
field_title = "**{}**".format(field["title"])
else:
raise Exception("Es necesario un `title` para describir un campo.")
field_type = " ({})".format(field["type"]) if "type" in field else ""
field_desc = ": {}".format(
field["description"]) if "description" in field else ""
text_template = "{title}{type}{description}"
text = text_template.format(title=field_title, type=field_type,
description=field_desc)
return text
|
// RematchPointersToClusters will take a set of pointers and map them to the closest cluster.
// Basically creates a new cluster from that one point and does the ClusterDistance between them.
// Will return a new list.
|
func RematchPointersToClusters(
clusters []*clustering.Cluster,
pointers []geo.Pointer,
distancer clustering.ClusterDistancer,
threshold float64,
) []*clustering.Cluster {
if len(clusters) == 0 {
return []*clustering.Cluster{}
}
newClusters := make([]*clustering.Cluster, 0, len(clusters))
// clear the current members
for _, c := range clusters {
newClusters = append(newClusters, clustering.NewClusterWithCentroid(c.Centroid))
}
// remap all the groupers to these new groups
for _, pointer := range pointers {
minDist := math.MaxFloat64
index := 0
pointerCluster := clustering.NewCluster(pointer)
// find the closest group
for i, c := range newClusters {
if d := distancer.ClusterDistance(c, pointerCluster); d < minDist {
minDist = d
index = i
}
}
if minDist < threshold {
// leaves the center as found by the previous clustering
newClusters[index].Pointers = append(newClusters[index].Pointers, pointer)
}
}
return newClusters
}
|
// See cairo_rel_line_to().
//
// C API documentation: http://cairographics.org/manual/cairo-Paths.html#cairo-rel-line-to
|
func (cr *Context) RelLineTo(dx, dy float64) {
C.cairo_rel_line_to(cr.Ptr, C.double(dx), C.double(dy))
if err := cr.status(); err != nil {
panic(err)
}
}
|
Return data to a mysql server
|
def returner(ret):
'''
'''
# if a minion is returning a standalone job, get a jobid
if ret['jid'] == 'req':
ret['jid'] = prep_jid(nocache=ret.get('nocache', False))
save_load(ret['jid'], ret)
try:
with _get_serv(ret, commit=True) as cur:
sql = '''INSERT INTO `salt_returns`
(`fun`, `jid`, `return`, `id`, `success`, `full_ret`)
VALUES (%s, %s, %s, %s, %s, %s)'''
cur.execute(sql, (ret['fun'], ret['jid'],
salt.utils.json.dumps(ret['return']),
ret['id'],
ret.get('success', False),
salt.utils.json.dumps(ret)))
except salt.exceptions.SaltMasterError as exc:
log.critical(exc)
log.critical('Could not store return with MySQL returner. MySQL server unavailable.')
|
// WithPrefix returns a router that prefixes all registered routes with prefix.
|
func (r *Router) WithPrefix(prefix string) *Router {
return &Router{rtr: r.rtr, prefix: r.prefix + prefix, instrh: r.instrh}
}
|
// Reallocate will avoid deleting all keys and reallocate a new
// map, this is useful if you believe you have a large map and
// will not need to grow back to a similar size.
|
func (m *Map) Reallocate() {
if m.initialSize > 0 {
m.lookup = make(map[MapHash]MapEntry, m.initialSize)
} else {
m.lookup = make(map[MapHash]MapEntry)
}
}
|
Drag around label if visible.
|
def _on_motion(self, event):
""""""
if not self._visual_drag.winfo_ismapped():
return
if self._drag_cols and self._dragged_col is not None:
self._drag_col(event)
elif self._drag_rows and self._dragged_row is not None:
self._drag_row(event)
|
Utility method to invalidate Connection. Parameters passed to ConnectionInterface.invalidate
@param notifyPeer
@param throwable
@param debugReason
|
protected void invalidateConnection(boolean notifyPeer, Throwable throwable, String debugReason)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "invalidateConnection", new Object[]{new Boolean(notifyPeer),
throwable,
debugReason});
if (con != null)
{
ConnectionInterface connection = con.getConnectionReference();
if (connection != null)
{
connection.invalidate(notifyPeer, throwable, debugReason);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "invalidateConnection");
}
|
// Validate checks that the label does not include unexpected options
|
func Validate(label string) error {
if strings.Contains(label, "z") && strings.Contains(label, "Z") {
return ErrIncompatibleLabel
}
return nil
}
|
Removes all from->to and to->from edges.
Note: the symmetric kwarg is unused.
|
def remove_edges(self, from_idx, to_idx, symmetric=False, copy=False):
''''''
flat_inds = self._pairs.dot((self._num_vertices, 1))
# convert to sorted order and flatten
to_remove = (np.minimum(from_idx, to_idx) * self._num_vertices
+ np.maximum(from_idx, to_idx))
mask = np.in1d(flat_inds, to_remove, invert=True)
res = self.copy() if copy else self
res._pairs = res._pairs[mask]
res._offdiag_mask = res._offdiag_mask[mask]
return res
|
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated
|
public EClass getIfcLinearMomentMeasure() {
if (ifcLinearMomentMeasureEClass == null) {
ifcLinearMomentMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(696);
}
return ifcLinearMomentMeasureEClass;
}
|
// ParseCiphers parses ciphersuites from the comma-separated string into
// recognized slice
|
func ParseCiphers(tlsConfig *config.TLSConfig) ([]uint16, error) {
suites := []uint16{}
cipherStr := strings.TrimSpace(tlsConfig.TLSCipherSuites)
var parsedCiphers []string
if cipherStr == "" {
parsedCiphers = defaultTLSCiphers
} else {
parsedCiphers = strings.Split(tlsConfig.TLSCipherSuites, ",")
}
for _, cipher := range parsedCiphers {
c, ok := supportedTLSCiphers[cipher]
if !ok {
return suites, fmt.Errorf("unsupported TLS cipher %q", cipher)
}
suites = append(suites, c)
}
// Ensure that the specified cipher suite list is supported by the TLS
// Certificate signature algorithm. This is a check for user error, where a
// TLS certificate could support RSA but a user has configured a cipher suite
// list of ciphers where only ECDSA is supported.
keyLoader := tlsConfig.GetKeyLoader()
// Ensure that the keypair has been loaded before continuing
keyLoader.LoadKeyPair(tlsConfig.CertFile, tlsConfig.KeyFile)
if keyLoader.GetCertificate() != nil {
supportedSignatureAlgorithm, err := getSignatureAlgorithm(keyLoader.GetCertificate())
if err != nil {
return []uint16{}, err
}
for _, cipher := range parsedCiphers {
if supportedCipherSignatures[cipher] == supportedSignatureAlgorithm {
// Positive case, return the matched cipher suites as the signature
// algorithm is also supported
return suites, nil
}
}
// Negative case, if this is reached it means that none of the specified
// cipher suites signature algorithms match the signature algorithm
// for the certificate.
return []uint16{}, fmt.Errorf("Specified cipher suites don't support the certificate signature algorithm %s, consider adding more cipher suites to match this signature algorithm.", supportedSignatureAlgorithm)
}
// Default in case this function is called but TLS is not actually configured
// This is only reached if the TLS certificate is nil
return []uint16{}, nil
}
|
<p>consume.</p>
@param args a {@link java.util.List} object.
@throws com.greenpepper.util.cli.WrongOptionUsageException if any.
|
public void consume( List<String> args ) throws WrongOptionUsageException
{
if (wantsArg() && (args.isEmpty())) throw new WrongOptionUsageException( this );
value = wantsArg() ? convert( CollectionUtil.shift( args ) ) : true;
}
|
Determine if two models have the same ID and belong to the same table.
@param \Illuminate\Database\Eloquent\Model|null $model
@return bool
|
public function is($model)
{
return ! is_null($model) &&
$this->getKey() === $model->getKey() &&
$this->getTable() === $model->getTable() &&
$this->getConnectionName() === $model->getConnectionName();
}
|
Check if add-on was connected to install
@author Vova Feldman (@svovaf)
@since 1.1.7
@param string|number $id_or_slug
@return bool
|
function is_addon_connected( $id_or_slug ) {
$this->_logger->entrance();
$sites = self::get_all_sites( WP_FS__MODULE_TYPE_PLUGIN );
$addon_id = self::get_module_id( $id_or_slug );
$addon = $this->get_addon( $addon_id );
$slug = $addon->slug;
if ( ! isset( $sites[ $slug ] ) ) {
return false;
}
$site = $sites[ $slug ];
$plugin = FS_Plugin_Manager::instance( $addon_id )->get();
if ( $plugin->parent_plugin_id != $this->_plugin->id ) {
// The given slug do NOT belong to any of the plugin's add-ons.
return false;
}
return ( is_object( $site ) &&
is_numeric( $site->id ) &&
is_numeric( $site->user_id ) &&
FS_Plugin_Plan::is_valid_id( $site->plan_id )
);
}
|
Fisher's method for combining independent p-values.
|
def fishers_method(pvals):
""""""
pvals = np.asarray(pvals)
degrees_of_freedom = 2 * pvals.size
chisq_stat = np.sum(-2*np.log(pvals))
fishers_pval = stats.chi2.sf(chisq_stat, degrees_of_freedom)
return fishers_pval
|
// SetGrantWriteACP sets the GrantWriteACP field's value.
|
func (s *PutObjectAclInput) SetGrantWriteACP(v string) *PutObjectAclInput {
s.GrantWriteACP = &v
return s
}
|
// SoftClip clips the constant to the range [-0.5, 0.5]
|
func (c C) SoftClip() Input {
if float32(c) < -0.5 {
return C(-0.5)
} else if float32(c) > 0.5 {
return C(0.5)
}
return c
}
|
Adds parameters for the root expression only.
@param param The parameter to add, cannot be null or empty
@throws IllegalArgumentException if the parameter is null or empty
|
public void addFunctionParameter(final String param) {
if (param == null || param.isEmpty()) {
throw new IllegalArgumentException("Parameter cannot be null or empty");
}
if (func_params == null) {
func_params = Lists.newArrayList();
}
func_params.add(param);
}
|
icon ( or generic html if icon not available )
|
private String getSingleSlotHtml(TestSlot s, String icon) {
StringBuilder builder = new StringBuilder();
TestSession session = s.getSession();
if (icon != null) {
builder.append("<img ");
builder.append("src='").append(icon).append("' width='16' height='16'");
} else {
builder.append("<a href='#' ");
}
if (session != null) {
builder.append(" class='busy' ");
builder.append(" title='").append(session.get("lastCommand")).append("' ");
} else {
builder.append(" title='").append(s.getCapabilities()).append("'");
}
if (icon != null) {
builder.append(" />\n");
} else {
builder.append(">");
builder.append(s.getCapabilities().get(CapabilityType.BROWSER_NAME));
builder.append("</a>");
}
return builder.toString();
}
|
check if a feed is available from a peer apart from ignore_id
|
function isAvailable(state, feed_id, ignore_id) {
for(var peer_id in state.peers) {
if(peer_id != ignore_id) {
var peer = state.peers[peer_id]
//BLOCK: check wether id has blocked this peer
if((peer.clock && peer.clock[feed_id] || 0) > (state.clock[feed_id] || 0) && isShared(state, feed_id, peer_id)) {
return true
}
}
}
}
|
thePu239_lamda is lamda in ANS-5.1-1979 Table 8.
|
def thePu239_lamda
array = Array.new(23)
array[0] = 1.002E+01
array[1] = 6.433E-01
array[2] = 2.186E-01
array[3] = 1.004E-01
array[4] = 3.728E-02
array[5] = 1.435E-02
array[6] = 4.549E-03
array[7] = 1.328E-03
array[8] = 5.356E-04
array[9] = 1.730E-04
array[10] = 4.881E-05
array[11] = 2.006E-05
array[12] = 8.319E-06
array[13] = 2.358E-06
array[14] = 6.450E-07
array[15] = 1.278E-07
array[16] = 2.466E-08
array[17] = 9.378E-09
array[18] = 7.450E-10
array[19] = 2.426E-10
array[20] = 2.210E-13
array[21] = 2.640E-14
array[22] = 1.380E-14
array
end
|
Updates httpRequest with region. If region is not provided, then
the httpRequest will be updated based on httpRequest.region
@api private
|
function updateReqBucketRegion(request, region) {
var httpRequest = request.httpRequest;
if (typeof region === 'string' && region.length) {
httpRequest.region = region;
}
if (!httpRequest.endpoint.host.match(/s3(?!-accelerate).*\.amazonaws\.com$/)) {
return;
}
var service = request.service;
var s3Config = service.config;
var s3BucketEndpoint = s3Config.s3BucketEndpoint;
if (s3BucketEndpoint) {
delete s3Config.s3BucketEndpoint;
}
var newConfig = AWS.util.copy(s3Config);
delete newConfig.endpoint;
newConfig.region = httpRequest.region;
httpRequest.endpoint = (new AWS.S3(newConfig)).endpoint;
service.populateURI(request);
s3Config.s3BucketEndpoint = s3BucketEndpoint;
httpRequest.headers.Host = httpRequest.endpoint.host;
if (request._asm.currentState === 'validate') {
request.removeListener('build', service.populateURI);
request.addListener('build', service.removeVirtualHostedBucketFromPath);
}
}
|
Run the migrations.
@return void
|
public function up()
{
$this->down();
Schema::create('tbl_widgets', function(Blueprint $table) {
$table->increments('id');
$table->integer('type_id')->unsigned()->index('type_id');
$table->string('name')->index('name');
$table->timestamps();
$table->softDeletes();
});
Schema::create('tbl_widget_types', function(Blueprint $table) {
$table->increments('id');
$table->string('slug')->index('slug');
$table->string('name')->index('name');
$table->string('description', 500)->nullable();
});
Schema::create('tbl_widgets_params', function(Blueprint $table) {
$table->increments('id');
$table->integer('parent_id')->unsigned()->nullable()->index('parent_id');
$table->integer('wid')->unsigned()->index('wid');
$table->integer('uid')->unsigned()->index('uid');
$table->integer('brand_id')->unsigned()->index('FK_tbl_widgets_params');
$table->string('resource', 500)->nullable();
$table->string('name')->index('tbl_widgets_custom_name_unique');
$table->text('data')->nullable();
});
Schema::create('tbl_page_closure', function(Blueprint $table) {
$table->increments('closure_id');
$table->integer('ancestor')->unsigned()->index('page_closure_ancestor_foreign');
$table->integer('descendant')->unsigned()->index('page_closure_descendant_foreign');
$table->integer('depth')->unsigned();
});
Schema::table('tbl_widgets', function(Blueprint $table) {
$table->foreign('type_id', 'tbl_widgets_ibfk_1')->references('id')->on('tbl_widget_types')->onUpdate('NO ACTION')->onDelete('CASCADE');
});
Schema::table('tbl_widgets_params', function(Blueprint $table) {
$table->foreign('brand_id', 'tbl_widgets_params_ibfk_4')->references('id')->on('tbl_brands')->onUpdate('NO ACTION')->onDelete('CASCADE');
$table->foreign('parent_id', 'tbl_widgets_params_ibfk_1')->references('id')->on('tbl_widgets_params')->onUpdate('NO ACTION')->onDelete('SET NULL');
$table->foreign('wid', 'tbl_widgets_params_ibfk_2')->references('id')->on('tbl_widgets')->onUpdate('NO ACTION')->onDelete('CASCADE');
$table->foreign('uid', 'tbl_widgets_params_ibfk_3')->references('id')->on('tbl_users')->onUpdate('NO ACTION')->onDelete('CASCADE');
});
Schema::table('tbl_page_closure', function(Blueprint $table) {
$table->foreign('ancestor', 'page_closure_ancestor_foreign')->references('id')->on('tbl_widgets_params')->onUpdate('RESTRICT')->onDelete('CASCADE');
$table->foreign('descendant', 'page_closure_descendant_foreign')->references('id')->on('tbl_widgets_params')->onUpdate('RESTRICT')->onDelete('CASCADE');
});
}
|
Accessor for the specifier's values. The values are URL encoded and
separated by commas.
@return The specifier's value.
|
protected String getValuesString() {
final StringBuilder builder = new StringBuilder();
for(final String value : values) {
builder.append(AciURLCodec.getInstance().encode(value)).append(',');
}
if(builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
return builder.toString();
}
|
Show the form for editing the specified resource.
@param Category $category
@return Response
|
public function edit(Category $category)
{
$categories = $this->category->all()->nest()->listsFlattened('name');
return view('product::admin.categories.edit', compact('category', 'categories'));
}
|
Batch Keep Absolute (retrain)
xlabel = "Fraction of features kept"
ylabel = "ROC AUC"
transform = "identity"
sort_order = 13
|
def batch_keep_absolute_retrain__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
return __run_batch_abs_metric(measures.batch_keep_retrain, X, y, model_generator, method_name, sklearn.metrics.roc_auc_score, num_fcounts)
|
Constructs the matrix A and the vector b from a timeseries of toy
action-angles AA to solve for the vector x = (J_0,J_1,J_2,S...) where
x contains all Fourier components of the generating function with |n|<N_max
|
def solver(AA, N_max, symNx = 2, throw_out_modes=False):
# Find all integer component n_vectors which lie within sphere of radius N_max
# Here we have assumed that the potential is symmetric x->-x, y->-y, z->-z
# This can be relaxed by changing symN to 1
# Additionally due to time reversal symmetry S_n = -S_-n so we only consider
# "half" of the n-vector-space
angs = unroll_angles(AA.T[3:].T,np.ones(3))
symNz = 2
NNx = range(-N_max, N_max+1, symNx)
NNy = range(-N_max, N_max+1, symNz)
NNz = range(-N_max, N_max+1, symNz)
n_vectors = np.array([[i,j,k] for (i,j,k) in product(NNx,NNy,NNz)
if(not(i==0 and j==0 and k==0) # exclude zero vector
and (k>0 # northern hemisphere
or (k==0 and j>0) # half of x-y plane
or (k==0 and j==0 and i>0)) # half of x axis
and np.sqrt(i*i+j*j+k*k)<=N_max)]) # inside sphere
xxx = check_each_direction(n_vectors,angs)
if(throw_out_modes):
n_vectors = np.delete(n_vectors,check_each_direction(n_vectors,angs),axis=0)
n = len(n_vectors)+3
b = np.zeros(shape=(n, ))
a = np.zeros(shape=(n,n))
a[:3,:3]=len(AA)*np.identity(3)
for i in AA:
a[:3,3:]+=2.*n_vectors.T[:3]*np.cos(np.dot(n_vectors,i[3:]))
a[3:,3:]+=4.*np.dot(n_vectors,n_vectors.T)*np.outer(np.cos(np.dot(n_vectors,i[3:])),np.cos(np.dot(n_vectors,i[3:])))
b[:3]+=i[:3]
b[3:]+=2.*np.dot(n_vectors,i[:3])*np.cos(np.dot(n_vectors,i[3:]))
a[3:,:3]=a[:3,3:].T
return np.array(solve(a,b)), n_vectors
|
Gets the customField, null if the key does not exist.
@param object $owningEntity
@param string $key
@return CustomFieldBase|null
|
public static function getField($owningEntity, $key)
{
$entity = $owningEntity->getNonemptyCustomFields()->get($key);
if (!$entity) {
self::checkCustomFieldExists($owningEntity, $key);
}
return $entity;
}
|
// Take apart and rebuild the connection string. Also return the dbname.
|
func rebuildConnectionString(connectionString string) (string, string) {
username, password, hasPassword, hostname, port, dbname := splitConnectionString(connectionString)
return buildConnectionString(username, password, hasPassword, hostname, port, dbname), dbname
}
|
Change directory. It behaves like "cd directory".
|
def cd(cls, directory):
""""""
Log.debug('CMD: cd {0}'.format(directory))
os.chdir(directory)
|
Return the textual representation of the given :class:`~taxi.timesheet.lines.DateLine` instance. The date
format is set by the `date_format` parameter given when instanciating the parser instance.
|
def date_line_to_text(self, date_line):
# Changing the date in a dateline is not supported yet, but if it gets implemented someday this will need to be
# changed
if date_line._text is not None:
return date_line._text
else:
return date_utils.unicode_strftime(date_line.date, self.date_format)
|
// SetOutputDataConfig sets the OutputDataConfig field's value.
|
func (s *HyperParameterTrainingJobDefinition) SetOutputDataConfig(v *OutputDataConfig) *HyperParameterTrainingJobDefinition {
s.OutputDataConfig = v
return s
}
|
// RunOnAllMachines attempts to run the specified command on all the machines.
|
func (a *ActionAPI) RunOnAllMachines(run params.RunParams) (results params.ActionResults, err error) {
if err := a.checkCanAdmin(); err != nil {
return results, err
}
if err := a.check.ChangeAllowed(); err != nil {
return results, errors.Trace(err)
}
machines, err := a.state.AllMachines()
if err != nil {
return results, err
}
machineTags := make([]names.Tag, len(machines))
for i, machine := range machines {
machineTags[i] = machine.Tag()
}
actionParams := a.createActionsParams(machineTags, run.Commands, run.Timeout)
return queueActions(a, actionParams)
}
|
Uses the $writer object to write the table definition $table for $tableName
@param string $tableName
@param ezcDbSchemaTable $table
|
private function writeTable( $tableName, ezcDbSchemaTable $table )
{
$this->writer->startElement( 'table' );
$this->writer->startElement( 'name' );
$this->writer->text( $tableName );
$this->writer->endElement();
$this->writer->flush();
$this->writer->startElement( 'declaration' );
$this->writer->flush();
// fields
foreach ( $table->fields as $fieldName => $field )
{
$this->writer->startElement( 'field' );
$this->writeField( $fieldName, $field );
$this->writer->endElement();
$this->writer->flush();
}
// indices
foreach ( $table->indexes as $indexName => $index )
{
$this->writer->startElement( 'index' );
$this->writeIndex( $indexName, $index );
$this->writer->endElement();
$this->writer->flush();
}
$this->writer->endElement();
$this->writer->flush();
$this->writer->endElement();
}
|
Extract Multiple fields for record
|
def extract_multiple(record, field, tag)
a = Array.new
record.fields(field).each do |field|
a.push field[tag]
end
return a
end
|
First start of frame (SOFn) marker in this sequence.
|
def sof(self):
for m in self._markers:
if m.marker_code in JPEG_MARKER_CODE.SOF_MARKER_CODES:
return m
raise KeyError('no start of frame (SOFn) marker in image')
|
Removes a parameter by index, from the table's internal set and backing
maps and adjusts indices.
<p>
If no parameter exists for the specified index, this method is a no-op.
</p>
@param pid Table parameter index
|
public void removeTableParameter(final int pid) {
final TableParameter p = indexParameter.get(pid);
if (p == null) return;
// Pull the reference count
final Integer pcount = count.get(p);
// Alter maps and set only if 1 ref
if (pcount == 1 && parameters.remove(p)) {
Integer value = parameterIndex.remove(p);
indexParameter.remove(value);
count.remove(p);
} else {
count.put(p, pcount - 1);
}
}
|
Add new divider item.
@param int $order
@param array $attributes
@return \Rinvex\Menus\Models\MenuItem
|
public function divider(int $order = null, array $attributes = []): MenuItem
{
return $this->add(['type' => 'divider', 'order' => $order, 'attributes' => $attributes]);
}
|
Create new vector of type variables from list of variables
changing all recursive bounds from old to new list.
|
public List<Type> newInstances(List<Type> tvars) {
List<Type> tvars1 = tvars.map(newInstanceFun);
for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
TypeVar tv = (TypeVar) l.head;
tv.bound = subst(tv.bound, tvars, tvars1);
}
return tvars1;
}
|
Returns a temporary buffer of at least the given size
|
static ByteBuffer getTemporaryDirectBuffer(int size) {
BufferCache cache = bufferCache.get();
ByteBuffer buf = cache.get(size);
if (buf != null) {
return buf;
} else {
// No suitable buffer in the cache so we need to allocate a new
// one. To avoid the cache growing then we remove the first
// buffer from the cache and free it.
if (!cache.isEmpty()) {
buf = cache.removeFirst();
free(buf);
}
return ByteBuffer.allocateDirect(size);
}
}
|
We need to parse the padding and type as soon as possible,
else we won't be able to parse the message list...
|
def pre_dissect(self, s):
if len(s) < 1:
raise Exception("Invalid InnerPlaintext (too short).")
tmp_len = len(s) - 1
if s[-1] != b"\x00":
msg_len = tmp_len
else:
n = 1
while s[-n] != b"\x00" and n < tmp_len:
n += 1
msg_len = tmp_len - n
self.fields_desc[0].length_from = lambda pkt: msg_len
self.type = struct.unpack("B", s[msg_len:msg_len + 1])[0]
return s
|
Returns true if the value is truthy
@param mixed $value Value to check
@return bool
|
public static function isTruthy($value)
{
if (!$value) {
return $value === 0 || $value === '0';
} elseif ($value instanceof \stdClass) {
return (bool) get_object_vars($value);
} else {
return true;
}
}
|
Sets the parent control - this is important for link generation
@param Control $parentControl
|
public function setParentControl(Control $parentControl = null)
{
$this->parentControl = $parentControl;
$this->matcher->setParentControl($parentControl);
}
|
@param string $subscriptionExtUid
@return \DVelopment\FastBill\Model\Subscription
|
public function getSubscriptionByExtUid($subscriptionExtUid)
{
/** @var SubscriptionFbApi $response */
$response = $this->call(new Request('subscription.get', array('subscription_ext_uid' => $subscriptionExtUid)), 'DVelopment\FastBill\Model\SubscriptionFbApi');
$subscriptions = $response->getResponse()->getSubscriptions();
return reset($subscriptions);
}
|
/*
This method does a run over all of the data keeps a list of the k smallest
indices that it has seen so far. At the end, it swaps those k elements and
moves them to the front.
*/
|
func naiveSelectionFinding(data Interface, k int) {
smallestIndices := make([]int, k)
for i := 0; i < k; i++ {
smallestIndices[i] = i
}
resetLargestIndex(smallestIndices, data)
for i := k; i < data.Len(); i++ {
if data.Less(i, smallestIndices[k-1]) {
smallestIndices[k-1] = i
resetLargestIndex(smallestIndices, data)
}
}
insertionSort(IntSlice(smallestIndices), 0, k)
for i := 0; i < k; i++ {
data.Swap(i, smallestIndices[i])
}
}
|
this function will iterate over each list elements
setting the one on key to true an all other on false
@param key String, the key to set as true
@param list Object, the object to search for the key to set to true
@return void
|
function commutate(key, list) {
_.each(list, function (v, k, l) {
if (k === key) {
l[key] = true
}
if (v === true && k !== key) {
l[k] = false
}
})
}
|
Marshall the given parameter object.
|
public void marshall(DescribeParametersRequest describeParametersRequest, ProtocolMarshaller protocolMarshaller) {
if (describeParametersRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeParametersRequest.getParameterGroupName(), PARAMETERGROUPNAME_BINDING);
protocolMarshaller.marshall(describeParametersRequest.getSource(), SOURCE_BINDING);
protocolMarshaller.marshall(describeParametersRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(describeParametersRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
|
// getCode retrieves the next code using the provided
// huffman tree. It sets f.err on error.
|
func (f *decompressor) getCode(h *huffman) uint16 {
if h.maxbits > 0 {
if f.nbits < maxTreePathLen {
f.feed()
}
// For codes with length < tablebits, it doesn't matter
// what the remainder of the bits used for table lookup
// are, since entries with all possible suffixes were
// added to the table.
c := h.table[f.c>>(32-tablebits)]
if c >= 1<<lenshift {
// The code is already in c.
} else {
c = h.extra[c][f.c<<tablebits>>(32-(h.maxbits-tablebits))]
}
n := byte(c >> lenshift)
if f.nbits >= n {
// Only consume the length of the code, not the maximum
// code length.
f.c <<= n
f.nbits -= n
return c & codemask
}
f.fail(io.ErrUnexpectedEOF)
return 0
}
// This is an empty tree. It should not be used.
f.fail(errCorrupt)
return 0
}
|
Defines a template for the given media type.
@param string $type The media type
@param string|callable $template The template
|
public function setTemplate($type, $template)
{
if (!is_callable($template)) {
$template = (string) $template;
}
$this->templates[$type] = $template;
}
|
Consume a token from plannedTokens.
|
function (stream, state) {
var plannedToken = state.plannedTokens.shift();
if (plannedToken === undefined) {
return null;
}
stream.match(plannedToken.value);
var tokens = plannedToken.type.split('.');
return cmTokenFromAceTokens(tokens);
}
|
// SetScheduledUpdateGroupActions sets the ScheduledUpdateGroupActions field's value.
|
func (s *DescribeScheduledActionsOutput) SetScheduledUpdateGroupActions(v []*ScheduledUpdateGroupAction) *DescribeScheduledActionsOutput {
s.ScheduledUpdateGroupActions = v
return s
}
|
// ok sets status to 200 and puts "OK" in response.
|
func (c *requestContext) ok() {
c.Writer.Header().Set("Content-Type", "text/plain; charset=utf-8")
c.Writer.WriteHeader(200)
fmt.Fprintln(c.Writer, "OK")
}
|
//ExpireValidation removes a pending validation
|
func (service *IYOEmailAddressValidationService) ExpireValidation(request *http.Request, key string) (err error) {
if key == "" {
return
}
valMngr := validation.NewManager(request)
err = valMngr.RemoveEmailAddressValidationInformation(key)
return
}
|
{@inheritdoc}
@param string $key
@param mixed $steps
@return int|bool
|
public function increment($key, $steps = 1)
{
$previous = $this->has($key) ? $this->get($key) : 0;
$previous += $steps;
$this->put($key, $previous);
return $previous;
}
|
Display the primary field.
@param $item
@param null $config
@return mixed
|
public function displayPrimaryField($item, $config = null)
{
$field = $this->getPrimaryField($item, $config);
return $item->$field;
}
|
A powerful spider system in python.
|
def cli(ctx, **kwargs):
if kwargs['add_sys_path']:
sys.path.append(os.getcwd())
logging.config.fileConfig(kwargs['logging_config'])
# get db from env
for db in ('taskdb', 'projectdb', 'resultdb'):
if kwargs[db] is not None:
continue
if os.environ.get('MYSQL_NAME'):
kwargs[db] = utils.Get(lambda db=db: connect_database(
'sqlalchemy+mysql+%s://%s:%s/%s' % (
db, os.environ['MYSQL_PORT_3306_TCP_ADDR'],
os.environ['MYSQL_PORT_3306_TCP_PORT'], db)))
elif os.environ.get('MONGODB_NAME'):
kwargs[db] = utils.Get(lambda db=db: connect_database(
'mongodb+%s://%s:%s/%s' % (
db, os.environ['MONGODB_PORT_27017_TCP_ADDR'],
os.environ['MONGODB_PORT_27017_TCP_PORT'], db)))
elif ctx.invoked_subcommand == 'bench':
if kwargs['data_path'] == './data':
kwargs['data_path'] += '/bench'
shutil.rmtree(kwargs['data_path'], ignore_errors=True)
os.mkdir(kwargs['data_path'])
if db in ('taskdb', 'resultdb'):
kwargs[db] = utils.Get(lambda db=db: connect_database('sqlite+%s://' % (db)))
elif db in ('projectdb', ):
kwargs[db] = utils.Get(lambda db=db: connect_database('local+%s://%s' % (
db, os.path.join(os.path.dirname(__file__), 'libs/bench.py'))))
else:
if not os.path.exists(kwargs['data_path']):
os.mkdir(kwargs['data_path'])
kwargs[db] = utils.Get(lambda db=db: connect_database('sqlite+%s:///%s/%s.db' % (
db, kwargs['data_path'], db[:-2])))
kwargs['is_%s_default' % db] = True
# create folder for counter.dump
if not os.path.exists(kwargs['data_path']):
os.mkdir(kwargs['data_path'])
# message queue, compatible with old version
if kwargs.get('message_queue'):
pass
elif kwargs.get('amqp_url'):
kwargs['message_queue'] = kwargs['amqp_url']
elif os.environ.get('RABBITMQ_NAME'):
kwargs['message_queue'] = ("amqp://guest:guest@%(RABBITMQ_PORT_5672_TCP_ADDR)s"
":%(RABBITMQ_PORT_5672_TCP_PORT)s/%%2F" % os.environ)
elif kwargs.get('beanstalk'):
kwargs['message_queue'] = "beanstalk://%s/" % kwargs['beanstalk']
for name in ('newtask_queue', 'status_queue', 'scheduler2fetcher',
'fetcher2processor', 'processor2result'):
if kwargs.get('message_queue'):
kwargs[name] = utils.Get(lambda name=name: connect_message_queue(
name, kwargs.get('message_queue'), kwargs['queue_maxsize']))
else:
kwargs[name] = connect_message_queue(name, kwargs.get('message_queue'),
kwargs['queue_maxsize'])
# phantomjs-proxy
if kwargs.get('phantomjs_proxy'):
pass
elif os.environ.get('PHANTOMJS_NAME'):
kwargs['phantomjs_proxy'] = os.environ['PHANTOMJS_PORT_25555_TCP'][len('tcp://'):]
# puppeteer-proxy
if kwargs.get('puppeteer_proxy'):
pass
elif os.environ.get('PUPPETEER_NAME'):
kwargs['puppeteer_proxy'] = os.environ['PUPPETEER_PORT_22222_TCP'][len('tcp://'):]
ctx.obj = utils.ObjectDict(ctx.obj or {})
ctx.obj['instances'] = []
ctx.obj.update(kwargs)
if ctx.invoked_subcommand is None and not ctx.obj.get('testing_mode'):
ctx.invoke(all)
return ctx
|
// Quicksort, loosely following Bentley and McIlroy,
// ``Engineering a Sort Function,'' SP&E November 1993.
// medianOfThree moves the median of the three values data[m0], data[m1], data[m2] into data[m1].
|
func medianOfThree(data Interface, m1, m0, m2 int) {
// sort 3 elements
if data.Less(m1, m0) {
data.Swap(m1, m0)
}
// data[m0] <= data[m1]
if data.Less(m2, m1) {
data.Swap(m2, m1)
// data[m0] <= data[m2] && data[m1] < data[m2]
if data.Less(m1, m0) {
data.Swap(m1, m0)
}
}
// now data[m0] <= data[m1] <= data[m2]
}
|
{@link #close(Connection) Close} the connection and log any exceptions instead of throwing
them.
@param con
may be null
|
public static void closeQuietly(@Nullable Connection con) {
try {
close(con);
} catch (SQLException e) {
Loggers.get(Connections.class).log(SEVERE, "closing connection", e);
}
}
|
Returns all variant annotation sets on the server.
|
def getAllAnnotationSets(self):
for variantSet in self.getAllVariantSets():
iterator = self._client.search_variant_annotation_sets(
variant_set_id=variantSet.id)
for variantAnnotationSet in iterator:
yield variantAnnotationSet
|
// LeftJoin LEFT JOIN the table
|
func (qb *TiDBQueryBuilder) LeftJoin(table string) QueryBuilder {
qb.Tokens = append(qb.Tokens, "LEFT JOIN", table)
return qb
}
|
// L259
/*
Expert: set the Similarity implementation used by this IndexWriter.
NOTE: the similarity cannot be nil.
Only takes effect when IndexWriter is first created.
*/
|
func (conf *IndexWriterConfig) SetSimilarity(similarity Similarity) *IndexWriterConfig {
assert2(similarity != nil, "similarity must not be nil")
conf.similarity = similarity
return conf
}
|
return differences from this catalog and right catalog
param [Cat] right
@return [CatOnYaml]
|
def -(right)
result = CatOnYaml.new
@entries.each do |e|
result.add_entry(e) unless right.contains(e)
end
result
end
|
// Int64 returns the value of cell as 64-bit integer.
|
func (c *Cell) Int64() (int64, error) {
f, err := strconv.ParseInt(c.Value, 10, 64)
if err != nil {
return -1, err
}
return f, nil
}
|
// verifyPermittedHooks verifies all hooks are permitted in the project
|
func (sc *syncContext) verifyPermittedHooks(hooks []*unstructured.Unstructured) bool {
for _, hook := range hooks {
gvk := hook.GroupVersionKind()
serverRes, err := kube.ServerResourceForGroupVersionKind(sc.disco, gvk)
if err != nil {
sc.setOperationPhase(appv1.OperationError, fmt.Sprintf("unable to identify api resource type: %v", gvk))
return false
}
if !sc.proj.IsResourcePermitted(metav1.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, serverRes.Namespaced) {
sc.setOperationPhase(appv1.OperationFailed, fmt.Sprintf("Hook resource %s:%s is not permitted in project %s", gvk.Group, gvk.Kind, sc.proj.Name))
return false
}
if serverRes.Namespaced && !sc.proj.IsDestinationPermitted(appv1.ApplicationDestination{Namespace: hook.GetNamespace(), Server: sc.server}) {
gvk := hook.GroupVersionKind()
sc.setResourceDetails(&appv1.ResourceResult{
Name: hook.GetName(),
Group: gvk.Group,
Version: gvk.Version,
Kind: hook.GetKind(),
Namespace: hook.GetNamespace(),
Message: fmt.Sprintf("namespace %v is not permitted in project '%s'", hook.GetNamespace(), sc.proj.Name),
Status: appv1.ResultCodeSyncFailed,
})
return false
}
}
return true
}
|
Get the edit page.
@param \Arcanesoft\Seo\Models\Redirect $redirect
@return \Illuminate\View\View
|
public function edit(Redirect $redirect)
{
$this->authorize(RedirectsPolicy::PERMISSION_UPDATE);
$statuses = RedirectStatuses::all();
$this->setTitle($title = trans('seo::redirects.titles.edit-redirection'));
$this->addBreadcrumb($title);
return $this->view('admin.redirects.edit', compact('redirect', 'statuses'));
}
|
@param object $entity
@return boolean
|
public function hasDocumentDeclaration($entity)
{
if ($rootDocument = $this->getClassAnnotation($entity, self::DOCUMENT_CLASS)) {
return true;
}
if ($this->isNested($entity)) {
return true;
}
return false;
}
|
Handle the compilation of the templates
@param $template
|
public function parse($template)
{
$viewsFromConfig = $this->app['config']->get('view.paths');
$views = array_merge((array)$viewsFromConfig, (array)$this->paths['theme']);
$cache = $this->paths['storage'] . '/views';
$blade = new BladeAdapter($views, $cache);
if (!$blade->getCompiler()->isExpired($template))
{
return $blade->getCompiler()->getCompiledPath($template);
}
$blade->getCompiler()->compile($template);
return $blade->getCompiler()->getCompiledPath($template);
}
|
Check the given plain value against a hash.
@param string $value
@param string $hashedValue
@param array $options
@return bool
|
public function check($value, $hashedValue, array $options = array()) {
return strtoupper($this->make($value)) === strtoupper($hashedValue);
}
|
read the designated TOC file (toc.html)
|
function(next) {
fs.readFile(path.join(config.root_out, config.akashacmsEPUB.bookmetadata.toc.href), 'utf8',
function(err, data) {
if (err) next(err);
else {
// logger.info('read '+ path.join(config.root_out, config.akashacmsEPUB.bookmetadata.toc.href));
tocHtml = data;
next();
}
});
}
|
Removes ignore fields from the data that we got from Solr.
|
def _trim_fields(self, docs):
'''
'''
for doc in docs:
for field in self._ignore_fields:
if field in doc:
del(doc[field])
return docs
|
Obtain the number of centres adjacent to the atom at the index, i.
@param i atom index
@return number of adjacent centres
|
private int nAdjacentCentres(int i) {
int n = 0;
for (IAtom atom : tetrahedralElements[i].getLigands())
if (tetrahedralElements[atomToIndex.get(atom)] != null) n++;
return n;
}
|
Build link to local asset.
Detects packages links.
@param string $asset
@param string $dir
@return string the link
|
protected function buildLocalLink($asset, $dir)
{
$collection = $this->assetIsFromCollection($asset);
if ($collection !== false) {
return $this->collections_dir.'/'.$collection[0].'/'.ltrim($dir, '/').'/'.$collection[1];
}
return parent::buildLocalLink($asset, $dir);
}
|
run before
@access public
@param array $aParams parameters
@return \Apollina\Template\HtmlOptions
|
public function replaceBy($aParams = array())
{
$aOptions = array();
$mSelected = '';
if (isset($aParams['options'])) { $aOptions = $aParams['options']; }
else { new \Exception('HtmlOptions: options obligatory');}
if (isset($aParams['selected'])) { $mSelected = $aParams['selected']; }
$sOption = '';
foreach ($aOptions as $mOne) {
$sOption .= '<option value="'.$mOne.'">'.$mOne.'</option>';
}
return $sOption;
}
|
// Action sets the command action.
|
func Action(a func(*cli.Context)) Option {
return func(o *Options) {
o.Action = a
}
}
|
full_name => class
|
def name2class(name)
klass = Kernel
name.to_s.split(%r{/}).each do |part|
klass = klass.const_get(
part.capitalize.gsub(/[_-](.)/) { |match| match[1].upcase }
)
end
klass
end
|
// ImportSigningKey imports the raw signing key into the keyring.
|
func (k *Keyring) ImportSigningKey(pub *[ed25519.PublicKeySize]byte, sec *[ed25519.PrivateKeySize]byte) {
nk := NewSigningSecretKey(pub, sec)
k.sigKeys[nk.pub] = nk
}
|
Removes a contact from group. You need to supply the IDs of the group
and contact. Does not delete the contact.
|
public void deleteGroupContact(final String groupId, final String contactId) throws NotFoundException, GeneralException, UnauthorizedException {
if (groupId == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
if (contactId == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
String id = String.format("%s%s/%s", groupId, CONTACTPATH, contactId);
messageBirdService.deleteByID(GROUPPATH, id);
}
|
Prepare request params for POST request, convert to multipart when needed
@param array $data
@return array
|
private function prepareRequestParams(array $data)
{
$has_resource = false;
$multipart = [];
foreach ($data as $key => $value) {
if (!is_array($value)) {
$multipart[] = ['name' => $key, 'contents' => $value];
continue;
}
foreach ($value as $multiKey => $multiValue) {
is_resource($multiValue) && $has_resource = true;
$multiName = $key . '[' . $multiKey . ']' . (is_array($multiValue) ? '[' . key($multiValue) . ']' : '') . '';
$multipart[] = ['name' => $multiName, 'contents' => (is_array($multiValue) ? reset($multiValue) : $multiValue)];
}
}
if ($has_resource) {
return ['multipart' => $multipart];
}
return ['form_params' => $data];
}
|
// tried in succession and the first to succeed is returned. If none succeed,
// a random high port is returned.
|
func getFreePort(host string, ports ...int) (int, error) {
for _, port := range ports {
c, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
if err == nil {
c.Close()
return port, nil
}
}
c, err := net.Listen("tcp", host+":0")
if err != nil {
return 0, err
}
addr := c.Addr().(*net.TCPAddr)
c.Close()
return addr.Port, nil
}
|
@param User $user
@return array
|
private function serializePublic(User $user)
{
$settingsProfile = $this->facetManager->getVisiblePublicPreference();
$publicUser = [];
foreach ($settingsProfile as $property => $isViewable) {
if ($isViewable || $user === $this->tokenStorage->getToken()->getUser()) {
switch ($property) {
case 'baseData':
$publicUser['lastName'] = $user->getLastName();
$publicUser['firstName'] = $user->getFirstName();
$publicUser['fullName'] = $user->getFirstName().' '.$user->getLastName();
$publicUser['username'] = $user->getUsername();
$publicUser['picture'] = $user->getPicture();
$publicUser['description'] = $user->getDescription();
break;
case 'email':
$publicUser['mail'] = $user->getEmail();
break;
case 'phone':
$publicUser['phone'] = $user->getPhone();
break;
case 'sendMail':
$publicUser['mail'] = $user->getEmail();
$publicUser['allowSendMail'] = true;
break;
case 'sendMessage':
$publicUser['allowSendMessage'] = true;
$publicUser['id'] = $user->getId();
break;
}
}
}
$publicUser['groups'] = [];
//this should be protected by the visiblePublicPreference but it's not yet the case
foreach ($user->getGroups() as $group) {
$publicUser['groups'][] = ['name' => $group->getName(), 'id' => $group->getId()];
}
return $publicUser;
}
|
// Error can be either of the following types:
//
// - InvalidObjectFault
// - RuntimeFault
|
func (service *VboxPortType) IConsolereset(request *IConsolereset) (*IConsoleresetResponse, error) {
response := new(IConsoleresetResponse)
err := service.client.Call("", request, response)
if err != nil {
return nil, err
}
return response, nil
}
|
Creates an exception from an plan id and version.
@param planId the plan id
@param version the version id
@return the exception
|
public static final PlanVersionNotFoundException planVersionNotFoundException(String planId, String version) {
return new PlanVersionNotFoundException(Messages.i18n.format("PlanVersionDoesNotExist", planId, version)); //$NON-NLS-1$
}
|
Subsets and Splits
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.