ig1/Qwen3-Coder-30B-A3B-Instruct-NVFP4
Text Generation • 17B • Updated • 2.48k • 1
comment stringlengths 16 255 | code stringlengths 52 3.87M |
|---|---|
Computes the new parent id for the node being moved.
@return int | protected function parentId()
{
switch ( $this->position )
{
case 'root':
return null;
case 'child':
return $this->target->getKey();
default:
return $this->target->getParentId();
}
} |
// SetWinSize overwrites the playlist's window size. | func (p *MediaPlaylist) SetWinSize(winsize uint) error {
if winsize > p.capacity {
return errors.New("capacity must be greater than winsize or equal")
}
p.winsize = winsize
return nil
} |
Show the sidebar and squish the container to make room for the sidebar.
If hideOthers is true, hide other open sidebars. | function() {
var options = this.options;
if (options.hideOthers) {
this.secondary.each(function() {
var sidebar = $(this);
if (sidebar.hasClass('is-expanded')) {
sidebar.toolkit('offCanvas', 'hide');
}
});
... |
Decide the fate of the cells | def nextGen(self):
self.current_gen += 1
self.change_gen[self.current_gen % 3] = copy.copy(self.grid)
grid_cp = copy.copy(self.grid)
for cell in self.grid:
y, x = cell
y1 = (y - 1) % self.y_grid
y2 = (y + 1) % self.y_grid
x1 = (x ... |
Return the kind specified by a given __property__ key.
Args:
key: key whose kind name is requested.
Returns:
The kind specified by key. | def key_to_kind(cls, key):
if key.kind() == Kind.KIND_NAME:
return key.id()
else:
return key.parent().id() |
Gets a recursive list of traits used by a class
@param string $class Full class name
@return array | private function getRecursiveTraits($class = null)
{
if (null == $class) {
$class = get_class($this);
}
$reflection = new \ReflectionClass($class);
$traits = array_keys($reflection->getTraits());
foreach ($traits as $trait) {
$traits = array_merge($t... |
// SetMaxRecords sets the MaxRecords field's value. | func (s *DescribeSnapshotCopyGrantsInput) SetMaxRecords(v int64) *DescribeSnapshotCopyGrantsInput {
s.MaxRecords = &v
return s
} |
Check if the current position of the pointer is valid
@return bool True if the pointer position is valid | public function valid() : bool
{
if ($this->pointer >= 0 && $this->pointer < count($this->members)) {
return true;
}
return false;
} |
Creates a new {@link TopicProducer}. The producer accepts arbitrary objects and uses the Jackson object mapper to convert them into
JSON and sends them as a text message. | public TopicProducer<Object> createTopicJsonProducer(final String topic)
{
Preconditions.checkState(connectionFactory != null, "connection factory was never injected!");
return new TopicProducer<Object>(connectionFactory, jmsConfig, topic, producerCallback);
} |
Dynamically add an array of setting items
@param string $owner
@param array $definitions | public function addSettingItems($owner, array $definitions)
{
foreach ($definitions as $code => $definition) {
$this->addSettingItem($owner, $code, $definition);
}
} |
Update brand group of parameters. | def update_brand(self) -> None:
""""""
self.update(path=URL_GET + GROUP.format(group=BRAND)) |
construct a string of space-delimited control keys based on properties of this class.
@param bool $disconnect
@return string | protected function getControlKey($disconnect = false)
{
$key = '';
if ($disconnect) {
return "*immed";
}
/*
if(?) *justproc
if(?) *debug
if(?) *debugproc
if(?) *nostart
if(?) *rpt*/
// Idle timeout supported by XMLSERVICE... |
Need to refactor, fukken complicated conditions. | def check_symbol_to_proc
return unless method_call.block_argument_names.count == 1
return if method_call.block_body.nil?
return unless method_call.block_body.sexp_type == :call
return if method_call.arguments.count > 0
body_method_call = MethodCall.new(method_call.block_body)
retur... |
Helper method to lookup a DAO if it has already been associated with the table-config. Otherwise this returns
null. | public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource,
DatabaseTableConfig<T> tableConfig) {
if (connectionSource == null) {
throw new IllegalArgumentException("connectionSource argument cannot be null");
}
TableConfigConnectionSource key = new TableConfigConnecti... |
// Provided for compatibility with the Transformer interface. Since Caser has no
// special treatment of bytes, the bytes are converted to and from strings.
// Will treat the entirety of src as ONE variable name. | func (c Caser) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
nSrc = len(src) // Always read all the bytes of src
result := c.Bytes(src)
if len(result) > len(dst) {
err = transform.ErrShortDst
}
nDst = copy(dst, result)
return
} |
Creates (or updates) a new ProjectStatus for the given build and
returns it. | def create_or_update(cls, build):
test_summary = build.test_summary
metrics_summary = MetricsSummary(build)
now = timezone.now()
test_runs_total = build.test_runs.count()
test_runs_completed = build.test_runs.filter(completed=True).count()
test_runs_incomplete =... |
Static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa | def p44(msg):
d = hex2bin(data(msg))
if d[34] == '0':
return None
p = bin2int(d[35:46]) # hPa
return p |
Trace TCP flows.
Keyword arguments:
* fout -- str, output path
* format -- str, output format
* byteorder -- str, output file byte order
* nanosecond -- bool, output nanosecond-resolution file flag | def trace(fout=None, format=None, byteorder=sys.byteorder, nanosecond=False):
str_check(fout or '', format or '')
return TraceFlow(fout=fout, format=format, byteorder=byteorder, nanosecond=nanosecond) |
Sets the URL to navigate to when the menu item is invoked.
@param url the url to set. | public void setUrl(final String url) {
MenuItemModel model = getOrCreateComponentModel();
model.url = url;
model.action = null;
} |
// SetSecurityGroupArns sets the SecurityGroupArns field's value. | func (s *Ec2Config) SetSecurityGroupArns(v []*string) *Ec2Config {
s.SecurityGroupArns = v
return s
} |
Does not perform {@link PrivilegedAction} unless necessary.
@param javaClass
@param fieldName
@return a field from the class
@throws NoSuchMethodException | static Field lookupField(Class<?> javaClass, String fieldName) throws NoSuchFieldException {
if (System.getSecurityManager() != null) {
try {
return AccessController.doPrivileged(new FieldLookupAction(javaClass, fieldName));
} catch (PrivilegedActionException e) {
... |
migrate the retry jobs of a queue
@param string $queue
@return array | protected function migrateRetryJobs($queue)
{
$luaScript = <<<LUA
-- Get all of the jobs with an expired "score"...
local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1])
-- If we have values in the array, we will remove them from the first queue
-- and add them onto the destination queue in chu... |
Dump the payload to JSON | def jsonify_payload(self):
# Assume already json serialized
if isinstance(self.payload, string_types):
return self.payload
return json.dumps(self.payload, cls=StandardJSONEncoder) |
Get system backtrace in formated view
@param bool $trace Custom php backtrace
@param bool $addObject Show objects in result
@return JBDump | public static function trace($trace = null, $addObject = false)
{
if (!self::isDebug()) {
return false;
}
$_this = self::i();
$trace = $trace ? $trace : debug_backtrace($addObject);
unset($trace[0]);
$result = $_this->convertTrace($trace, $ad... |
Get a short value from the form, and place it in <code>attribute</code>.
@param name attribute name
@param attribute attribute to put value
@since 1.11.1 | @Api
public void getValue(String name, ShortAttribute attribute) {
attribute.setValue(toShort(formWidget.getValue(name)));
} |
Submits the {@link org.apache.gobblin.metrics.GobblinTrackingEvent} to the {@link org.apache.gobblin.metrics.MetricContext}.
@param name Name of the event.
@param additionalMetadata Additional metadata to be added to the event. | public void submit(String name, Map<String, String> additionalMetadata) {
if(this.metricContext.isPresent()) {
Map<String, String> finalMetadata = Maps.newHashMap(this.metadata);
if(!additionalMetadata.isEmpty()) {
finalMetadata.putAll(additionalMetadata);
}
// Timestamp is set by m... |
// FallbackAddr is a functional option that allows callers of NewInvoice to set
// the Invoice's fallback on-chain address that can be used for payment in case
// the Lightning payment fails | func FallbackAddr(fallbackAddr btcutil.Address) func(*Invoice) {
return func(i *Invoice) {
i.FallbackAddr = fallbackAddr
}
} |
Get our daemon script path. | def get_manager_cmd(self):
""""""
cmd = os.path.abspath(os.path.join(os.path.dirname(__file__), "server", "notebook_daemon.py"))
assert os.path.exists(cmd)
return cmd |
// SetMaxHumanLabeledObjectCount sets the MaxHumanLabeledObjectCount field's value. | func (s *LabelingJobStoppingConditions) SetMaxHumanLabeledObjectCount(v int64) *LabelingJobStoppingConditions {
s.MaxHumanLabeledObjectCount = &v
return s
} |
Create a default {@link FeatureInfoWidget} with a {@link ZoomToObjectAction}
to allow zooming to selected features.
@param mapPresenter The map presenter used by the action(s).
@return A feature info widget with actions. | public FeatureInfoWithActions getFeatureInfoWidgetWithActions(MapPresenter mapPresenter) {
FeatureInfoWithActions widgetWithActions = new FeatureInfoWithActions();
widgetWithActions.addHasFeature(new ZoomToObjectAction(mapPresenter));
return widgetWithActions;
} |
// SetError sets the Error field's value. | func (s *TaskFailedEventDetails) SetError(v string) *TaskFailedEventDetails {
s.Error = &v
return s
} |
Access the Monitor Twilio Domain
:returns: Monitor Twilio Domain
:rtype: twilio.rest.monitor.Monitor | def monitor(self):
if self._monitor is None:
from twilio.rest.monitor import Monitor
self._monitor = Monitor(self)
return self._monitor |
// ExecuteRaw receives, parse and executes raw source template contents
// it's super-simple function without options and funcs, it's not used widely
// implements the EngineRawExecutor interface | func (p *Engine) ExecuteRaw(src string, wr io.Writer, binding interface{}) (err error) {
set := pongo2.NewSet("", pongo2.DefaultLoader)
set.Globals = getPongoContext(p.Config.Globals)
tmpl, err := set.FromString(src)
if err != nil {
return err
}
return tmpl.ExecuteWriter(getPongoContext(binding), wr)
} |
Returns a parameter value in the specified array, if not in, returns the
first element instead
@param string $name The parameter name
@param array $array The array to be search
@return mixed The parameter value | public function getInArray($name, array $array)
{
$value = $this->get($name);
return in_array($value, $array) ? $value : $array[key($array)];
} |
Sets metainfo properties as JCR properties to node. | private void setJCRProperties(NodeImpl parent, Properties props) throws Exception
{
if (!parent.isNodeType("dc:elementSet"))
{
parent.addMixin("dc:elementSet");
}
ValueFactory vFactory = parent.getSession().getValueFactory();
LocationFactory lFactory = parent.getSession().getL... |
Get profiles grouped by account and webproperty
TODO Handle "(403) User does not have any Google Analytics account."
@return array | protected function getGroupedProfiles()
{
$this->analytics->requireAuthentication();
$groupedProfiles = [];
$accounts = $this->analytics->management_accounts->listManagementAccounts();
foreach ($accounts as $account) {
$groupedProfiles[$account->getId()]['label'] = $acco... |
// addValueToMap adds the given value to the map on which the method is run.
// This allows us to merge maps such as {foo: {bar: baz}} and {foo: {baz: faz}}
// into {foo: {bar: baz, baz: faz}}. | func addValueToMap(keys []string, value interface{}, target map[string]interface{}) {
next := target
for i := range keys {
// If we are on last key set or overwrite the val.
if i == len(keys)-1 {
next[keys[i]] = value
break
}
if iface, ok := next[keys[i]]; ok {
switch typed := iface.(type) {
cas... |
// Run parses arguments from the command line and passes them to RunCommand. | func (s *Service) Run() {
flag.Usage = s.Usage
flag.Parse()
args := flag.Args()
if len(args) == 0 && s.defaultCommand != "" {
args = append([]string{s.defaultCommand}, args...)
}
if len(args) == 0 {
s.Usage()
BootPrintln()
return
}
err := s.RunCommand(args[0], args[1:]...)
if err != nil {
panic(err)
... |
store one item in database | def _put_one(self, item):
'''
'''
# prepare values
values = []
for k, v in item.items():
if k == '_id':
continue
if 'dblite_serializer' in item.fields[k]:
serializer = item.fields[k]['dblite_serializer']
v =... |
Computes the theta & phi angles of the vector.
@memberof Vec3#
@returns {object} ret
@returns {Number} ret.theta - angle from the xz plane
@returns {Number} ret.phi - angle from the y axis | function() {
return {
theta: Math.atan2(this.z, this.x),
phi: Math.asin(this.y / this.length())
};
} |
CArray with evenly spaced numbers over a specified interval.
@param $start The starting value of the sequence.
@param $stop The end value of the sequence
@param int $num Number of samples to generate. Default is 50.
@return \CArray | public static function linspace($start, $stop, int $num): \CArray
{
return parent::linspace($start, $stop, $num);
} |
// Digests hashes each segment of each key fragment 26 times and returns them.
// Optionally takes the SpongeFunction to use. Default is Kerl. | func Digests(key Trits, spongeFunc ...SpongeFunction) (Trits, error) {
var err error
fragments := int(math.Floor(float64(len(key)) / KeyFragmentLength))
digests := make(Trits, fragments*HashTrinarySize)
buf := make(Trits, HashTrinarySize)
h := GetSpongeFunc(spongeFunc, kerl.NewKerl)
defer h.Reset()
// iterate ... |
Loading hparams from json; can also start from hparams if specified. | def create_hparams_from_json(json_path, hparams=None):
""""""
tf.logging.info("Loading hparams from existing json %s" % json_path)
with tf.gfile.Open(json_path, "r") as f:
hparams_values = json.load(f)
# Prevent certain keys from overwriting the passed-in hparams.
# TODO(trandustin): Remove this hack ... |
Sort an collection by values using a user-defined comparison function
@param \Closure $callback
@param bool $save_keys maintain index association
@return static | public function sortBy( \Closure $callback, bool $save_keys = true )
{
$items = $this->items;
$save_keys ? uasort($items, $callback) : usort($items, $callback);
return new static($items);
} |
Attempts to upload the Docker image for a given tool to
`DockerHub <https://hub.docker.com>`_. | def upload(self, tool: Tool) -> bool:
return self.__installation.build.upload(tool.image) |
SET CHECK
@param string $name
@param string $arg
@return $this | public function checks($name, $arg = null) {
if (empty($arg)) {
$this->checks[] = $name;
} else {
$this->checks[$name] = $arg;
}
return $this;
} |
From a list of top level trees, return the list of contained class definitions | List<JCClassDecl> listClasses(List<JCCompilationUnit> trees) {
List<JCClassDecl> result = new ArrayList<>();
for (JCCompilationUnit t : trees) {
for (JCTree def : t.defs) {
if (def.hasTag(JCTree.Tag.CLASSDEF))
result.add((JCClassDecl)def);
}
... |
-------------------------------------------------------------------------------------------- | @Override
public void configure(Configuration parameters) {
// enforce sequential configuration() calls
synchronized (CONFIGURE_MUTEX) {
if (mapreduceInputFormat instanceof Configurable) {
((Configurable) mapreduceInputFormat).setConf(configuration);
}
}
} |
Parses the requested parameter from the given state.<p>
@param state the state
@param paramName the parameter name
@return the parameter value | public static String getParamFromState(String state, String paramName) {
String prefix = PARAM_SEPARATOR + paramName + PARAM_ASSIGN;
if (state.contains(prefix)) {
String result = state.substring(state.indexOf(prefix) + prefix.length());
if (result.contains(PARAM_SEPARATOR)) {
... |
// intIf returns a if cnd is true, otherwise b | func intIf(cnd bool, a, b int) int {
if cnd {
return a
}
return b
} |
Create a writer builder for Ebi41InvoiceType.
@return The builder and never <code>null</code> | @Nonnull
public static EbInterfaceWriter <Ebi41InvoiceType> ebInterface41 ()
{
final EbInterfaceWriter <Ebi41InvoiceType> ret = EbInterfaceWriter.create (Ebi41InvoiceType.class);
ret.setNamespaceContext (EbInterface41NamespaceContext.getInstance ());
return ret;
} |
// SetKey sets the Key field's value. | func (s *GetObjectLegalHoldInput) SetKey(v string) *GetObjectLegalHoldInput {
s.Key = &v
return s
} |
// Range check string's length | func Range(str string, params ...string) bool {
if len(params) == 2 {
value, _ := ToFloat(str)
min, _ := ToFloat(params[0])
max, _ := ToFloat(params[1])
return InRange(value, min, max)
}
return false
} |
Add command arguments | def add_arguments(self, parser):
""""""
parser.add_argument(self._source_param, **self._source_kwargs)
parser.add_argument('--base', '-b', action='store',
help= 'Supply the base currency as code or a settings variable name. '
'The default is taken from settings ... |
Grab values from the $_SERVER global.
@param mixed $index The index that we will be searching for.
@param boolean $xss_clean Whether we want to clean it or not.
@since 1.0.0
@return mixed | public function server(string $index = '', $xss_clean = false)
{
return $this->fetchFromArray($_SERVER, $index, $xss_clean);
} |
Get a server by calling {@link AbstractServerPredicate#chooseRandomlyAfterFiltering(java.util.List, Object)}.
The performance for this method is O(n) where n is number of servers to be filtered. | @Override
public Server choose(Object key) {
ILoadBalancer lb = getLoadBalancer();
Optional<Server> server = getPredicate().chooseRoundRobinAfterFiltering(lb.getAllServers(), key);
if (server.isPresent()) {
return server.get();
} else {
return null;
} ... |
Validate that an attribute is greater than another attribute.
@param string $attribute
@param mixed $value
@param array $parameters
@return bool | public function validateGt($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'gt');
$comparedToValue = $this->getValue($parameters[0]);
$this->shouldBeNumeric($attribute, 'Gt');
if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($param... |
// SetErrorCode returns source code that sets return parameters. | func (r *Rets) SetErrorCode() string {
const code = `if r0 != 0 {
%s = %sErrno(r0)
}`
if r.Name == "" && !r.ReturnsError {
return ""
}
if r.Name == "" {
return r.useLongHandleErrorCode("r1")
}
if r.Type == "error" {
return fmt.Sprintf(code, r.Name, syscalldot())
}
s := ""
switch {
case r.Type[0] == '... |
// StartPlugins starts all plugins in the correct order. | func (co *Coordinator) StartPlugins() {
// Launch routers
for _, router := range co.routers {
logrus.Debug("Starting ", reflect.TypeOf(router))
if err := router.Start(); err != nil {
logrus.WithError(err).Errorf("Failed to start router of type '%s'", reflect.TypeOf(router))
}
}
// Launch producers
co.sta... |
Get a consumer for a connection. | def consumer(self, conn):
""""""
return Consumer(
connection=conn,
queue=self.queue.name,
exchange=self.exchange.name,
exchange_type=self.exchange.type,
durable=self.exchange.durable,
auto_delete=self.exchange.auto_delete,
... |
Returns the generator reactive power variable set. | def _get_qgen_var(self, generators, base_mva):
Qg = array([g.q / base_mva for g in generators])
Qmin = array([g.q_min / base_mva for g in generators])
Qmax = array([g.q_max / base_mva for g in generators])
return Variable("Qg", len(generators), Qg, Qmin, Qmax) |
Associations labels getter.
@param \Cake\Datasource\RepositoryInterface $table Table instance
@return mixed[] | public function getAssociationLabels(RepositoryInterface $table) : array
{
/** @var \Cake\ORM\Table */
$table = $table;
$result = [];
foreach ($table->associations() as $association) {
if (!in_array($association->type(), $this->searchableAssociations)) {
... |
Return matched comments
@param int $page
@return array | public function get_comments($page = '') {
global $DB, $CFG, $USER, $OUTPUT;
if (!$this->can_view()) {
return false;
}
if (!is_numeric($page)) {
$page = 0;
}
$params = array();
$perpage = (!empty($CFG->commentsperpage))?$CFG->commentsperpag... |
// WeekdayWide returns the locales wide weekday given the 'weekday' provided | func (ne *ne_IN) WeekdayWide(weekday time.Weekday) string {
return ne.daysWide[weekday]
} |
/*!
Returns the objects which have at least one keyword in common
\return an array of eZContentObjectTreeNode instances, or null if the attribute is not stored yet | function relatedObjects()
{
$return = false;
if ( $this->ObjectAttributeID )
{
$return = array();
// Fetch words
$db = eZDB::instance();
$wordArray = $db->arrayQuery( "SELECT * FROM ezkeyword_attribute_link
... |
Extract read and write part values to an object for SCALAR, SPECTRUM and IMAGE
@param da
@return array of primitives for SCALAR, array of primitives for SPECTRUM, array of primitives array of primitives
for IMAGE
@throws DevFailed | public static Object extract(final DeviceAttribute da) throws DevFailed {
if (da == null) {
throw DevFailedUtils.newDevFailed(ERROR_MSG_DA);
}
return InsertExtractFactory.getAttributeExtractor(da.getType()).extract(da);
} |
Add values for PromotionIds, return this.
@param promotionIds
New values to add.
@return This instance. | public OrderItem withPromotionIds(String... values) {
List<String> list = getPromotionIds();
for (String value : values) {
list.add(value);
}
return this;
} |
Parses the element and subelements and parses any HTML enabled text to
its original HTML form for rendering.
:returns: Parsed HTML enabled text content.
:rtype: str | def get_html_content(self):
# Extract full element node content (including subelements)
html_content = ''
if hasattr(self, 'xml_element'):
xml = self.xml_element
content_list = ["" if xml.text is None else xml.text]
def to_string(xml):
... |
Get the list of files changed with the type of change for a given revision.
Results are returned as a structured array.
@param String $rev A valid changeset for this repo
@return array List of file changes | public function getChangedFiles($rev)
{
$raw_changes = $this->execute('hg status --change ' . $rev);
$this->repository_type = 'hg';
$changes = [];
foreach ($raw_changes as $key => $change) {
$exploded_change = explode(' ', $change);
$changes[$key]['type'] = $... |
Returns the loaded behaviors and loads them if not done before
@return array behaviors | public function getBehaviors()
{
if (null === $this->behaviors) {
// find behaviors in composer.lock file
$lock = $this->findComposerLock();
if (null === $lock) {
$this->behaviors = [];
} else {
$this->behaviors = $this->loadBe... |
APIMethod: getCentroid
Returns:
{<OpenLayers.Geometry.Point>} The centroid of the collection | function() {
if (this.components) {
var len = this.components.length;
if (len > 0 && len <= 2) {
return this.components[0].clone();
} else if (len > 2) {
var sumX = 0.0;
var sumY = 0.0;
var x0 = this.components[0... |
Returns bearing from (lat1, lon1) to (lat2, lon2) in degrees
@param lat1
@param lon1
@param lat2
@param lon2
@return | public static final double bearing(double lat1, double lon1, double lat2, double lon2)
{
return Math.toDegrees(radBearing(lat1, lon1, lat2, lon2));
} |
Return the flow rate with only minor losses.
This function applies to both laminar and turbulent flows. | def flow_pipeminor(Diam, HeadLossExpans, KMinor):
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([HeadLossExpans, ">=0", "Headloss due to expansion"],
[KMinor, ">0", "K minor"])
return (area_circle(Diam).magnitude ... |
Parse a run of ordinary characters, or a single character with a special meaning in markdown, as a plain string, adding to inlines. | function(inlines) {
var m;
if ((m = this.match(reMain))) {
inlines.push({ t: 'Str', c: m });
return m.length;
} else {
return 0;
}
} |
Assigns value to all unfilled feature variables.
@param value
@return | public SyntacticCategory assignAllFeatures(String value) {
Set<Integer> featureVars = Sets.newHashSet();
getAllFeatureVariables(featureVars);
Map<Integer, String> valueMap = Maps.newHashMap();
for (Integer var : featureVars) {
valueMap.put(var, value);
}
return assignFeatures(valueMap, Co... |
Return true if gate tensor is (almost) unitary | def almost_unitary(gate: Gate) -> bool:
""""""
res = (gate @ gate.H).asoperator()
N = gate.qubit_nb
return np.allclose(asarray(res), np.eye(2**N), atol=TOLERANCE) |
Adds limit and offset to SQL statement.
@param int $limit
@param int $offset
@return void | public function addLimitOffset(int $limit, int $offset): void
{
if ($limit === 0 && $offset === 0) {
return;
}
if ($limit === 0 && $offset <> 0) {
return;
}
if ($offset === 0) {
$this->statement .= ' LIMIT ' . $limit;
} else {
... |
Finds actions, angles and frequencies for box orbit.
Takes a series of phase-space points from an orbit integration at times t and returns
L = (act,ang,n_vec,toy_aa, pars) -- explained in find_actions() below. | def box_actions(results, times, N_matrix, ifprint):
if(ifprint):
print("\n=====\nUsing triaxial harmonic toy potential")
t = time.time()
# Find best toy parameters
omega = toy.findbestparams_ho(results)
if(ifprint):
print("Best omega "+str(omega)+" found in "+str(time.time()-t)... |
将map的属性映射到bean对象
@param target
@param properties
@throws BeanMappingException | public void populate(Object target, Map properties) throws BeanMappingException {
BeanMappingParam param = new BeanMappingParam();
param.setSrcRef(properties);
param.setTargetRef(target);
param.setConfig(this.populateConfig);
param.setProcesses(BeanMappingEnvironment.getBeanMapVp... |
// getOrCreateAutopilotConfig is used to get the autopilot config, initializing it if necessary | func (s *Server) getOrCreateAutopilotConfig() *autopilot.Config {
state := s.fsm.State()
_, config, err := state.AutopilotConfig()
if err != nil {
s.logger.Printf("[ERR] autopilot: failed to get config: %v", err)
return nil
}
if config != nil {
return config
}
if !ServersMeetMinimumVersion(s.LANMembers(),... |
Set whether or not to display the bank
@param bool $displayBank True if yes, false if no
@return $this The current instance for a fluent interface. | public function setDisplayBank($displayBank = true)
{
$this->isBool($displayBank, 'displayBank');
$this->displayBank = $displayBank;
return $this;
} |
// fullCompactionStrategy returns a compactionStrategy for higher level generations of TSM files.
// It returns nil if there are no TSM files to compact. | func (e *Engine) fullCompactionStrategy(group CompactionGroup, optimize bool) *compactionStrategy {
s := &compactionStrategy{
group: group,
logger: e.logger.With(zap.String("tsm1_strategy", "full"), zap.Bool("tsm1_optimize", optimize)),
fileStore: e.FileStore,
compactor: e.Compactor,
fast: optimi... |
Render the modal template
@since 1.0.0
@see \uix\ui\uix
@access public
@return string HTML of modals templates | public function modal_template() {
$output = '<script type="text/html" id="' . esc_attr( $this->id() ) . '-components">';
foreach ( $this->modals as $modal ) {
$label = $modal->struct['label'];
$data = $modal->get_data();
$data_template = $this->drill_in( $data[ $modal->slug ], '{{@root'... |
Convert the input URI into a correctly formatted uri prefix. In the future, may also resolve d2 uris. | public static String resolveUriPrefix(URI serverURI)
throws URISyntaxException {
if (RESTLI_SCHEMES.contains(serverURI.getScheme())) {
return new URI(serverURI.getScheme(), serverURI.getAuthority(), null, null, null).toString() + "/";
}
throw new RuntimeException("Unrecognized scheme for URI " ... |
Writes the given {@link Object} to the {@link JsonWriter}.
@throws IOException | private static void writeValue(Object value, JsonWriter writer) throws IOException {
if (value == null) {
writer.nullValue();
} else if (value instanceof Number) {
writer.value((Number) value);
} else if (value instanceof Boolean) {
writer.value((Boolean) value);
} else if (value insta... |
Creates a procedure.
@param string $name Procedure name
@return $this | public function createProcedure($name)
{
$definition = array(
'parent' => $this->context,
'name' => $name,
'sources' => array(),
'workers' => array(),
'targets' => array(),
'children' => array(),
);
$this->definitions[$... |
Converts a value from one unit to another.
@param int $to unit to convert to
@param mixed $val value to convert
@return float converted value | protected function convert($to, $val)
{
$val = $this->parseValue($val);
return base_convert($val, $this->unit, $to);
} |
// SetMaxResults sets the MaxResults field's value. | func (s *ListAlgorithmsInput) SetMaxResults(v int64) *ListAlgorithmsInput {
s.MaxResults = &v
return s
} |
The typed collection type. Contains only elements of the
supplied class.
@see ITypedCollection
@param IType $elementType
@param string $collectionClass
@return CollectionType | public static function collectionOf(IType $elementType, string $collectionClass = ITypedCollection::class) : CollectionType
{
$elementTypeString = $elementType->asTypeString();
if (!isset(self::$collections[$collectionClass][$elementTypeString])) {
self::$collections[$collectionClass][$... |
-------------------------------------------------------------------------- TODO: move the code below to the core (?) | function computeGameStateOfTaskEnvironment(taskEnvironment) {
const { pastActions, currentAction } = taskEnvironment;
const initialState = getInitialGameState(taskEnvironment);
let currentState = doActionMoves(initialState, pastActions);
if (currentAction !== null) {
currentState = doAction(currentState, cu... |
The :meth:`sqlalchemy.crud.updating.upsert_all` function in ORM syntax.
:param engine: an engine created by``sqlalchemy.create_engine``.
:param obj_or_data: single object or list of object | def upsert_all(cls, engine, obj_or_data):
cls.update_all(
engine=engine,
obj_or_data=obj_or_data,
upsert=True,
) |
// SetBody sets the Body field's value. | func (s *ADMMessage) SetBody(v string) *ADMMessage {
s.Body = &v
return s
} |
Cleas the cache of a specific post id
@param integer $postId Post id to clear
@return boolean | public static function clearCache($postId, $post)
{
if (wp_is_post_revision($postId) || get_post_status($postId) != 'publish') {
return false;
}
wp_cache_delete($postId, self::getKeyGroup());
wp_cache_delete($post->post_type, self::getKeyGroup());
// Empty post ... |
Synchronizes the values for the given element path.<p>
@param cms the cms context
@param elementPath the element path
@param skipPaths the paths to skip
@param sourceLocale the source locale | private void synchronizeElement(
CmsObject cms,
String elementPath,
Collection<String> skipPaths,
Locale sourceLocale) {
if (elementPath.contains("/")) {
String parentPath = CmsXmlUtils.removeLastXpathElement(elementPath);
List<I_CmsXmlContentValue> paren... |
// UnmarshalTOML implements toml.UnmarshalerRec. | func (l *Netlist) UnmarshalTOML(fn func(interface{}) error) error {
var masks []string
if err := fn(&masks); err != nil {
return err
}
for _, mask := range masks {
_, n, err := net.ParseCIDR(mask)
if err != nil {
return err
}
*l = append(*l, *n)
}
return nil
} |
See the {@link debug} property for more information.
@access private
@return void | private function _write_log($daily = false, $hourly = false, $backtrace = false) {
// if we are using a callback function to handle logs
if (is_callable($this->log_path) && !isset($this->log_path_is_function))
// set flag
$this->log_path_is_function = true;
// if we ar... |
Attempts to extract a name of a missing class loader dependency from an exception such as {@link NoClassDefFoundError} or {@link ClassNotFoundException}. | public static String getNameOfMissingClassLoaderDependency(Throwable e) {
if (e instanceof NoClassDefFoundError) {
// NoClassDefFoundError sometimes includes CNFE as the cause. Since CNFE has a better formatted class name
// and may also include classloader info, we prefer CNFE's over NC... |
Serialize to a non-circular Javascript object | function(obj) {
if (obj instanceof Cell) {
return {
inside: obj.inside
};
} else {
return {
back : serialize(obj.back),
front : serialize(obj.front),
plane: obj.plane,
shp: obj.shp,
complemented: obj.complemented,
};
}
} |
Get option for output (cloned option and inner info removed)
@public
@return {Object} | function () {
var option = clone(this.option);
each(option, function (opts, mainType) {
if (ComponentModel.hasClass(mainType)) {
var opts = modelUtil.normalizeToArray(opts);
for (var i = opts.length - 1; i >= 0; i--) {
// Remove options wi... |
// CreateNonce generates a nonce using the common/crypto package. | func CreateNonce() ([]byte, error) {
nonce, err := crypto.GetRandomNonce()
return nonce, errors.WithMessage(err, "error generating random nonce")
} |
This dataset is a collection of comment-code pairs of various programming languages. See code_search_net for additional information. This dataset can be used directly with Sentence Transformers to train embedding models.
pair subset
str, str{
'comment': 'Computes the new parent id for the node being moved.\n\n@return int',
'code': "protected function parentId()\n\t{\n\t\tswitch ( $this->position )\n\t\t{\n\t\t\tcase 'root':\n\t\t\t\treturn null;\n\n\t\t\tcase 'child':\n\t\t\t\treturn $this->target->getKey();\n\n\t\t\tdefault:\n\t\t\t\treturn $this->target->getParentId();\n\t\t}\n\t}",
}