language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public ProcessExecutor redirectOutput(OutputStream output) {
if (output == null)
output = NullOutputStream.NULL_OUTPUT_STREAM;
PumpStreamHandler pumps = pumps();
// Only set the output stream handler, preserve the same error stream handler
return streams(new PumpStreamHandler(output, pumps == null... |
java | @Override
public DataSet get(int[] i) {
List<DataSet> list = new ArrayList<>();
for(int ex : i){
list.add(get(ex));
}
return DataSet.merge(list);
} |
java | public static String mergeSlashesInUrl(String url) {
StringBuilder builder = new StringBuilder();
boolean prevIsColon = false;
boolean inMerge = false;
for (int i = 0; i < url.length(); i++) {
char c = url.charAt(i);
if (c == ':') {
prevIsColon = t... |
python | def _dist_kw_arg(self, k):
"""
Returns a dictionary of keyword arguments
for the k'th distribution.
:param int k: Index of the distribution in question.
:rtype: ``dict``
"""
if self._dist_kw_args is not None:
return {
key:self._dist_kw... |
java | public void end() {
if (TransitionConfig.isPrintDebug()) {
getTransitionStateHolder().end();
getTransitionStateHolder().print();
}
for (int i = 0, size = mTransitionControls.size(); i < size; i++) {
mTransitionControls.get(i).end();
}
} |
python | def infix_handle(tokens):
"""Process infix calls."""
func, args = get_infix_items(tokens, callback=infix_handle)
return "(" + func + ")(" + ", ".join(args) + ")" |
python | def return_markers(self):
"""Reads the notes of the Ktlx recordings.
"""
ent_file = self._filename.with_suffix('.ent')
if not ent_file.exists():
ent_file = self._filename.with_suffix('.ent.old')
try:
ent_notes = _read_ent(ent_file)
except (FileNo... |
java | @Override
public Thread newThread(Runnable runnable) {
Runnable wrappedRunnable = new InstrumentedRunnable(runnable);
Thread thread = delegate.newThread(wrappedRunnable);
created.mark();
return thread;
} |
java | private void initializeBuiltInImplementors() {
builtInImplementors.put(ArrayList.class, new ArrayListImplementor());
builtInImplementors.put(ConcurrentHashMap.class, new ConcurrentHashMapImplementor());
builtInImplementors.put(GregorianCalendar.class, new GregorianCalendarImplementor());
builtInImplementors.put... |
java | public void writeUTF(String pString) throws IOException {
int numchars = pString.length();
int numbytes = 0;
for (int i = 0; i < numchars; i++) {
int c = pString.charAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
numbytes++;
}
... |
java | public <T> Class<T> getType(String typeName) {
try {
return (Class<T>) classLoader.loadClass(typeName);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Cannot find class " + typeName, e);
}
} |
python | def makeNodeID(Rec, ndType, extras = None):
"""Helper to make a node ID, extras is currently not used"""
if ndType == 'raw':
recID = Rec
else:
recID = Rec.get(ndType)
if recID is None:
pass
elif isinstance(recID, list):
recID = tuple(recID)
else:
recID = r... |
java | public static SubsystemSuspensionLevels findBySubsystem(EntityManager em, SubSystem subSystem) {
SystemAssert.requireArgument(em != null, "Entity manager can not be null.");
SystemAssert.requireArgument(subSystem != null, "Subsystem cannot be null.");
TypedQuery<SubsystemSuspensionLevels> query... |
python | def prune_by_ngram_count_per_work(self, minimum=None, maximum=None,
label=None):
"""Removes results rows if the n-gram count for all works bearing that
n-gram is outside the range specified by `minimum` and
`maximum`.
That is, if a single witness of... |
java | @Override
public String resolve(String code, Object... arguments) {
return String.format(code, arguments);
} |
python | def get_mapping(version=1, exported_at=None, app_name=None):
"""
Return Heroku Connect mapping for the entire project.
Args:
version (int): Version of the Heroku Connect mapping, default: ``1``.
exported_at (datetime.datetime): Time the export was created, default is ``now()``.
app_... |
python | def broadcast(self, command, *args, **kwargs):
"""
Notifies each user with a specified command.
"""
criterion = kwargs.pop('criterion', self.BROADCAST_FILTER_ALL)
for index, user in items(self.users()):
if criterion(user, command, *args, **kwargs):
sel... |
python | def deactivate_mfa_device(self, user_name, serial_number):
"""Deactivate and detach MFA Device from user if device exists."""
user = self.get_user(user_name)
if serial_number not in user.mfa_devices:
raise IAMNotFoundException(
"Device {0} not found".format(serial_num... |
python | def to_dict(self):
"""Return the resource as a dictionary.
:rtype: dict
"""
result_dict = {}
for column in self.__table__.columns.keys(): # pylint: disable=no-member
value = result_dict[column] = getattr(self, column, None)
if isinstance(value, Decimal):... |
python | def visualize_model(onnx_model, open_browser=True, dest="index.html"):
"""
Creates a graph visualization of an ONNX protobuf model.
It creates a SVG graph with *d3.js* and stores it into a file.
:param model: ONNX model (protobuf object)
:param open_browser: opens the browser
:param dest: d... |
python | def _get_render_prepared_object(cls, context, **option_values):
"""
Returns a fully prepared, request-aware menu object that can be used
for rendering. ``context`` could be a ``django.template.Context``
object passed to ``render_from_tag()`` by a menu tag.
"""
ctx_vals = ... |
python | def within_hull(point, hull):
'''Return true if the point is within the convex hull'''
h_prev_pt = hull[-1,:]
for h_pt in hull:
if np.cross(h_pt-h_prev_pt, point - h_pt) >= 0:
return False
h_prev_pt = h_pt
return True |
java | public <R> JoinOperatorSetsBase<T, R> fullOuterJoin(DataSet<R> other) {
return new JoinOperatorSetsBase<>(this, other, JoinHint.OPTIMIZER_CHOOSES, JoinType.FULL_OUTER);
} |
java | public static boolean isArrayOfUnboundedTypeVariablesOrObjects(Type[] types) {
for (Type type : types) {
if (Object.class.equals(type)) {
continue;
}
if (type instanceof TypeVariable<?>) {
Type[] bounds = ((TypeVariable<?>) type).getBounds();
... |
java | public static Deferred<Tree> fetchTree(final TSDB tsdb, final int tree_id) {
if (tree_id < 1 || tree_id > 65535) {
throw new IllegalArgumentException("Invalid Tree ID");
}
// fetch the whole row
final GetRequest get = new GetRequest(tsdb.treeTable(), idToBytes(tree_id));
get.family(TREE_FAMIL... |
java | protected boolean setFieldIfNecessary(String field, Object value) {
if (!isOpen())
throw new ClosedObjectException("The Document object is closed.");
if (!compareFieldValue(field, value)) {
_doc.setField(field, value);
return true;
}
return false;
} |
java | @Override
public boolean tryToExpand(double splitConfidence, double tieThreshold) {
// splitConfidence. Hoeffding Bound test parameter.
// tieThreshold. Hoeffding Bound test parameter.
SplitCriterion splitCriterion = new SDRSplitCriterionAMRules();
//SplitCriterion splitCriterion = new SDRSplitCriterionAMRul... |
java | @Override
public ListOrganizationsResult listOrganizations(ListOrganizationsRequest request) {
request = beforeClientExecution(request);
return executeListOrganizations(request);
} |
java | void remoteGoto(String filename, int page, float llx, float lly, float urx, float ury) {
addAnnotation(new PdfAnnotation(writer, llx, lly, urx, ury, new PdfAction(filename, page)));
} |
python | def normalize_jr(jr, url=None):
""" normalize JSON reference, also fix
implicit reference of JSON pointer.
input:
- #/definitions/User
- http://test.com/swagger.json#/definitions/User
output:
- http://test.com/swagger.json#/definitions/User
input:
- some_folder/User.json
output:... |
python | def prev(self):
"""Fetch a set of items with IDs greater than current set."""
if self.limit and self.limit == self.num_tweets:
raise StopIteration
self.index -= 1
if self.index < 0:
# There's no way to fetch a set of tweets directly 'above' the
# curr... |
python | def set_volume(self, pct, channel=None):
"""
Sets the sound volume to the given percentage [0-100] by calling
``amixer -q set <channel> <pct>%``.
If the channel is not specified, it tries to determine the default one
by running ``amixer scontrols``. If that fails as well, it uses... |
python | def startRecording(self, url, **options):
"""
Allows Tropo applications to begin recording the current session.
Argument: url is a string
Argument: **options is a set of optional keyword arguments.
See https://www.tropo.com/docs/webapi/startrecording
"""
self._ste... |
python | def build_input(data, batch_size, dataset, train):
"""Build CIFAR image and labels.
Args:
data_path: Filename for cifar10 data.
batch_size: Input batch size.
train: True if we are training and false if we are testing.
Returns:
images: Batches of images of size
[... |
java | private int calcHanSum(List<NormalYaku> yakuStock) {
int hanSum = 0;
if (hands.isOpen()) {
for (NormalYaku yaku : yakuStock) {
hanSum += yaku.getKuisagari();
}
} else {
for (NormalYaku yaku : yakuStock) {
hanSum += yaku.getHan()... |
python | def request(self,
method,
url,
header_auth=False,
realm='',
**req_kwargs):
'''
A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects OAuth 1.0/a parameters.
:param method: A stri... |
java | private void fireControlRelease(int index, int controllerIndex) {
consumed = false;
for (int i=0;i<controllerListeners.size();i++) {
ControllerListener listener = (ControllerListener) controllerListeners.get(i);
if (listener.isAcceptingInput()) {
switch (index) {
case LEFT:
listener.contro... |
python | def set_connection_string_by_user_input(self):
"""Prompts the user to input a connection string"""
user_connection = input(
bcolors.WARNING + "\nFor any reason connection to " + bcolors.ENDC +
bcolors.FAIL + "{}".format(self.connection) + bcolors.ENDC +
bcolors.WARNIN... |
python | def dispatch(self, receiver):
''' Dispatch handling of this event to a receiver.
This method will invoke ``receiver._columns_streamed`` if it exists.
'''
super(ColumnsStreamedEvent, self).dispatch(receiver)
if hasattr(receiver, '_columns_streamed'):
receiver._column... |
java | private final void dcompute() {// Work to do the distribution
// Split out the keys into disjointly-homed sets of keys.
// Find the split point. First find the range of home-indices.
H2O cloud = H2O.CLOUD;
int lo=cloud._memary.length, hi=-1;
for( Key k : _keys ) {
int i = k.home(cloud);
... |
java | public Set<Profile> getProfiles()
{
final Set<Profile> ret = new HashSet<Profile>();
if (this.profileNames.isEmpty()) {
ret.add(Profile.getDefaultProfile());
} else {
for (final String name : this.profileNames) {
ret.add(Profile.getProfile(name));
... |
java | protected void setConnection(Text line) throws ParseException {
connection = new ConnectionField();
connection.strain(line);
Collections.sort(this.candidates);
} |
java | public void tryVibrate() {
if (mVibrator != null) {
long now = SystemClock.uptimeMillis();
// We want to try to vibrate each individual tick discretely.
if (now - mLastVibrate >= 125) {
mVibrator.vibrate(5);
mLastVibrate = now;
}
... |
java | @When("^I create the zNode '(.+?)'( with content '(.+?)')? which (IS|IS NOT) ephemeral$")
public void createZNode(String path, String foo, String content, boolean ephemeral) throws Exception {
if (content != null) {
commonspec.getZookeeperSecClient().zCreate(path, content, ephemeral);
} ... |
java | public static void initUBLBE (@Nonnull final ValidationExecutorSetRegistry aRegistry)
{
ValueEnforcer.notNull (aRegistry, "Registry");
// For better error messages
LocationBeautifierSPI.addMappings (UBL21NamespaceContext.getInstance ());
final IValidationExecutorSet aVESInvoice = aRegistry.getOfID (... |
python | def call_method(self, method_name_or_object, params=None):
"""
Calls the ``method_name`` method from the given service and returns a
:py:class:`gemstone.client.structs.Result` instance.
:param method_name_or_object: The name of te called method or a ``MethodCall`` instance
:para... |
java | public boolean addAll(CompactIntSet ints) {
int oldSize = size();
bitSet.or(ints.bitSet);
return oldSize != size();
} |
python | def parseline(line,format):
"""\
Given a line (a string actually) and a short string telling
how to format it, return a list of python objects that result.
The format string maps words (as split by line.split()) into
python code:
x -> Nothing; skip this word
s -> Return this word ... |
java | @Override
public CommandGroup createCommandGroup(String groupId, Object[] members, CommandConfigurer configurer) {
return createCommandGroup(groupId, members, false, configurer);
} |
python | def _get_show_ids(self):
"""Get the ``dict`` of show ids per series by querying the `shows.php` page.
:return: show id per series, lower case and without quotes.
:rtype: dict
"""
# get the show page
logger.info('Getting show ids')
r = self.session.get(self.serve... |
java | private double bend(AtomPair pair, IntStack stack, Point2d[] coords, Map<IBond,AtomPair> firstVisit) {
stackBackup.clear();
assert stack.len == 0;
final double score = congestion.score();
double min = score;
// special case: if we have an even length path where the two
... |
java | private boolean createPhotoFolder(DropboxAPI<AndroidAuthSession> dropboxApi) {
boolean folderCreated = false;
if (dropboxApi != null) {
try {
dropboxApi.createFolder(mContext.getString(R.string.wings_dropbox__photo_folder));
folderCreated = true;
}... |
python | def read_pgroups(in_file):
"""Read HLAs and the pgroups they fall in.
"""
out = {}
with open(in_file) as in_handle:
for line in (l for l in in_handle if not l.startswith("#")):
locus, alleles, group = line.strip().split(";")
for allele in alleles.split("/"):
... |
java | private void replaceHeaders(final Message from, final Message to) {
to.getHeaders().clear();
to.getHeaders().putAll(from.getHeaders());
} |
python | def remove_numbers(text_string):
'''
Removes any digit value discovered within text_string and returns the new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
'''
if text_string is Non... |
java | public String getString(String key, String defaultValue) {
return configuration.getString(key, defaultValue);
} |
python | def _conv_general_shape_tuple(self, lhs_shape, rhs_shape, window_strides,
padding, dimension_numbers):
"""Generalized computation of conv shape."""
lhs_perm, rhs_perm, out_perm = self._conv_general_permutations(
dimension_numbers)
lhs_trans = onp.take(lhs_shape, lhs_p... |
java | public MoneyFormatterBuilder appendSigned(
MoneyFormatter whenPositiveOrZero, MoneyFormatter whenNegative) {
return appendSigned(whenPositiveOrZero, whenPositiveOrZero, whenNegative);
} |
java | public String verifyAndExtract(String signedStr) {
int index = signedStr.lastIndexOf(SIGNATURE);
if (index == -1) {
throw new IllegalArgumentException("Invalid input sign: " + signedStr);
}
String originalSignature = signedStr.substring(index + SIGNATURE.length());
String rawValue = signedStr.... |
python | def directives():
'''
Return list of directives together with expected arguments
and places where the directive is valid (``apachectl -L``)
CLI Example:
.. code-block:: bash
salt '*' apache.directives
'''
cmd = '{0} -L'.format(_detect_os())
ret = {}
out = __salt__['cmd.run... |
java | public static <T> String getSoftDeleteSQL(T t, Column softDeleteColumn, List<Object> values) {
String setSql = getColumnName(softDeleteColumn) + "="
+ softDeleteColumn.softDelete()[1];
return getCustomDeleteSQL(t, values, setSql);
} |
python | def masters(self):
"""Returns a list of dictionaries containing each master's state."""
fut = self.execute(b'MASTERS', encoding='utf-8')
# TODO: process masters: we can adjust internal state
return wait_convert(fut, parse_sentinel_masters) |
java | @Override
public Map<String, Object> getQueryParameters() {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("type", this.type.toString());
return params;
} |
java | protected void unregisterElementErrListener(MediaElement element, final ListenerSubscription subscription) {
if (element == null || subscription == null) {
return;
}
element.removeErrorListener(subscription);
} |
java | private void printServiceInstance(ServiceInstance instance) {
print("\nServiceInstance\n-------------------------");
if (instance == null) {
print("null");
return;
}
print("serviceName: " + instance.getServiceName());
print("status: " + instance.getStatu... |
java | @Override
public MatchResult match(URI origin, URI destination) {
String queryStr = new StringBuffer()
.append(generateQueryHeader())
.append(generateMatchWhereClause(origin, destination, false))
.append(generateQueryFooter())
.toString();
... |
python | def set_data(self, value):
"""Sets a new string as response. The value set must either by a
unicode or bytestring. If a unicode string is set it's encoded
automatically to the charset of the response (utf-8 by default).
.. versionadded:: 0.9
"""
# if an unicode string ... |
java | public static <T> JoinerQuery<T, Long> count(EntityPath<T> from) {
JoinerQueryBase<T, Long> request = new JoinerQueryBase<>(from, true);
request.distinct(false);
return request;
} |
python | def cursor(self):
"""Analogous to :any:`sqlite3.Connection.cursor`"""
if self.single_cursor_mode:
if self._cursor is None:
raise sqlite3.ProgrammingError("Cannot operate on a closed database.")
return self._cursor
return Cursor(self) |
python | def get_token(self, user_id, password, redirect_uri,
scope='/activities/update'):
"""Get the token.
Parameters
----------
:param user_id: string
The id of the user used for authentication.
:param password: string
The user password.
... |
java | public void onInfoChanged(AVIMClient client, AVIMConversation conversation, JSONObject attr,
String operator) {
LOGGER.d("Notification --- " + operator + " by member: " + operator + ", changedTo: " + attr.toJSONString());
} |
java | public static /*@pure@*/ int maxIndex(int[] ints) {
int maximum = 0;
int maxIndex = 0;
for (int i = 0; i < ints.length; i++) {
if ((i == 0) || (ints[i] > maximum)) {
maxIndex = i;
maximum = ints[i];
}
}
return maxIndex;
} |
java | public SDVariable cosineDistance(String name, @NonNull SDVariable label, @NonNull SDVariable predictions, int dimension) {
return cosineDistance(name, label, predictions, null, LossReduce.MEAN_BY_NONZERO_WEIGHT_COUNT, dimension);
} |
python | def remove_section(self, section):
"""Remove a file section."""
existed = section in self._sections
if existed:
del self._sections[section]
del self._proxies[section]
return existed |
java | @Deprecated
@Override
public String render(
SoyTemplateInfo templateInfo, @Nullable SoyRecord data, @Nullable SoyMsgBundle msgBundle) {
return (new RendererImpl(this, templateInfo.getName()))
.setData(data)
.setMsgBundle(msgBundle)
.render();
} |
python | def get(self, key: Any, default: Any = None) -> Any:
"""
获取 cookie 中的 value
"""
if key in self:
return self[key].value
return default |
python | def construct_latent_tower(self, images, time_axis):
"""Create the latent tower."""
# No latent in the first phase
first_phase = tf.less(
self.get_iteration_num(), self.hparams.num_iterations_1st_stage)
# use all frames by default but this allows more
# predicted frames at inference time
... |
python | def _from_dict(cls, _dict):
"""Initialize a SourceOptions object from a json dictionary."""
args = {}
if 'folders' in _dict:
args['folders'] = [
SourceOptionsFolder._from_dict(x)
for x in (_dict.get('folders'))
]
if 'objects' in _di... |
java | public AmqpChannel closeChannel(int replyCode, String replyText, int classId, int methodId1) {
if (readyState == ReadyState.CLOSED) {
return this;
}
Object[] args = {replyCode, replyText, classId, methodId1};
WrappedByteBuffer bodyArg = null;
HashMap<String, ... |
python | def identical_functions(self):
"""
:returns: A list of function matches that appear to be identical
"""
identical_funcs = []
for (func_a, func_b) in self.function_matches:
if self.functions_probably_identical(func_a, func_b):
identical_funcs.append((fu... |
python | def _replace_tex_math(node, mml_url, mc_client=None, retry=0):
"""call mml-api service to replace TeX math in body of node with mathml"""
math = node.attrib['data-math'] or node.text
if math is None:
return None
eq = {}
if mc_client:
math_key = hashlib.md5(math.encode('utf-8')).hex... |
python | def subs2seqs(self) -> Dict[str, List[str]]:
"""A |collections.defaultdict| containing the node-specific
information provided by XML `sequences` element.
>>> from hydpy.auxs.xmltools import XMLInterface
>>> from hydpy import data
>>> interface = XMLInterface('single_run.xml', da... |
python | def applyKeyMapping(self, mapping):
"""
Used as the second half of the key reassignment algorithm.
Loops over each row in the table, replacing references to
old row keys with the new values from the mapping.
"""
for coltype, colname in zip(self.columntypes, self.columnnames):
if coltype in ligolwtypes.ID... |
java | public Observable<ServiceResponse<List<MetricDefinitionInner>>> listMetricDefinitionsWithServiceResponseAsync(String resourceGroupName, String serverName, String databaseName) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is ... |
python | def _help():
""" Display both SQLAlchemy and Python help statements """
statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))
print statement.strip() |
java | protected String buildActionName(MappingPathResource mappingResource, String pkg, String classPrefix) {
final String actionNameSuffix = mappingResource.getActionNameSuffix().orElse(""); // option so basically empty
final String actionSuffix = namingConvention.getActionSuffix(); // e.g. 'Action'
... |
python | def _break_signals(self):
r"""Break N-dimensional signals into N 1D signals."""
for name in list(self.signals.keys()):
if self.signals[name].ndim == 2:
for i, signal_1d in enumerate(self.signals[name].T):
self.signals[name + '_' + str(i)] = signal_1d
... |
python | def typecast(type_, value):
""" Tries to smartly typecast the given value with the given type.
:param type_: The type to try to use for the given value
:param value: The value to try and typecast to the given type
:return: The typecasted value if possible, otherwise just the original value
"""
... |
java | public BigInteger unpackBigInteger()
throws IOException
{
byte b = readByte();
if (Code.isFixInt(b)) {
return BigInteger.valueOf((long) b);
}
switch (b) {
case Code.UINT8: // unsigned int 8
byte u8 = readByte();
retu... |
java | @Override
public void terminateMachine( TargetHandlerParameters parameters, String machineId ) throws TargetException {
this.logger.fine( "Terminating an in-memory agent." );
Map<String,String> targetProperties = preventNull( parameters.getTargetProperties());
// If we executed real recipes, undeploy everythin... |
python | def use_refresh_token(self, refresh_token, scope=None):
# type (str, Optional[List[str]]) -> Tuple[se_leg_op.access_token.AccessToken, Optional[str]]
"""
Creates a new access token, and refresh token, based on the supplied refresh token.
:return: new access token and new refresh token if... |
python | def get_derived_metric_by_version(self, id, version, **kwargs): # noqa: E501
"""Get a specific historical version of a specific derived metric definition # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please p... |
python | def sort_values(self, ascending=False):
""" Sorts the values of this series
"""
if self.index_type is not None:
index_expr = grizzly_impl.get_field(self.expr, 0)
column_expr = grizzly_impl.get_field(self.expr, 1)
zip_expr = grizzly_impl.zip_columns([index_exp... |
python | def execute(self):
"""Run selected module generator."""
if self._cli_arguments['cfn']:
generate_sample_cfn_module(self.env_root)
elif self._cli_arguments['sls']:
generate_sample_sls_module(self.env_root)
elif self._cli_arguments['sls-tsc']:
generate_sa... |
java | public static String buildUrl(String baseUrl, String path) {
if (path.startsWith("http:") || path.startsWith("https:")) {
return path;
}
if (StringUtils.isEmpty(baseUrl)) {
return file2url(concatPath(LOCAL_BASE_URL, path));
} else {
if (baseUrl.... |
java | private int renderMBeans(JsonGenerator jg, String[] mBeanNames) throws IOException,
MalformedObjectNameException {
jg.writeStartObject();
Set<ObjectName> nameQueries, queriedObjects;
nameQueries = new HashSet<ObjectName>();
queriedObjects = new HashSet<ObjectName>();
// if no mbean names pro... |
python | def update_role(role,**kwargs):
"""
Update the role.
Used to add permissions and users to a role.
"""
#check_perm(kwargs.get('user_id'), 'edit_role')
try:
role_i = db.DBSession.query(Role).filter(Role.id==role.id).one()
role_i.name = role.name
role_i.code = role.c... |
python | def gather_explicit_activities(self):
"""Aggregate all explicit activities and active forms of Agents.
This function iterates over self.statements and extracts explicitly
stated activity types and active forms for Agents.
"""
for stmt in self.statements:
agents = stm... |
java | public static <K, V> Map<K, V> toMap(Collection<Mappable<K, V>> aMappables)
{
if (aMappables == null)
throw new IllegalArgumentException(
"aMappables required in Organizer");
Map<K, V> map = new HashMap<K, V>(aMappables.size());
Mappable<K, V> mappable = null;
for (Iterator<Mappable<K, V>> i = a... |
python | def _clean_data(cls, *args, **kwargs):
"""
Convert raw data into a dictionary with plot-type specific methods.
The result of the cleaning operation should be a dictionary.
If the dictionary contains a 'data' field it will be passed directly
(ensuring appropriate formatting). Oth... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.