language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def points_close(a,b):
'''
points_close(a,b) yields True if points a and b are close to each other and False otherwise.
'''
(a,b) = [np.asarray(u) for u in (a,b)]
if len(a.shape) == 2 or len(b.shape) == 2: (a,b) = [np.reshape(u,(len(u),-1)) for u in (a,b)]
return np.isclose(np.sqrt(np.sum((a - b... |
java | @Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!HAS_MUST_BE_CLOSED_ANNOTATION.matches(tree, state)) {
// Ignore methods and constructors that are not annotated with {@link MustBeClosed}.
return NO_MATCH;
}
boolean isAConstructor = methodIsConstructor().mat... |
java | public void sliceNode(final List<Node> nodes, final WaveBase wave) {
final Node node = nodes.get(0);
final long start = System.currentTimeMillis();
if (node != null) {
if (node instanceof ImageView) {
this.imageProperty.set(((ImageView) node).getImage());
... |
java | public Document createDOM(DocumentBuilder documentBuilder, TagNode rootNode) throws ParserConfigurationException
{
Document document = createDocument(documentBuilder, rootNode);
createSubnodes(document, document.getDocumentElement(), rootNode.getAllChildren());
return document;
} |
java | public double rcond(Matrix A, Norm norm) {
if (norm != Norm.One && norm != Norm.Infinity)
throw new IllegalArgumentException(
"Only the 1 or the Infinity norms are supported");
if (A.numRows() != n)
throw new IllegalArgumentException("A.numRows() != n");
... |
java | public Observable<DiagnosticAnalysisInner> getSiteAnalysisSlotAsync(String resourceGroupName, String siteName, String diagnosticCategory, String analysisName, String slot) {
return getSiteAnalysisSlotWithServiceResponseAsync(resourceGroupName, siteName, diagnosticCategory, analysisName, slot).map(new Func1<Serv... |
java | private Animator createAnimation(final View view, float startAlpha, float endAlpha, @Nullable TransitionValues values) {
final float curAlpha = view.getAlpha();
startAlpha = curAlpha * startAlpha;
endAlpha = curAlpha * endAlpha;
if (values != null && values.values.containsKey(PROPNAME_A... |
java | public CategorySeries addSeries(String seriesName, double[] xData, double[] yData) {
return addSeries(seriesName, xData, yData, null);
} |
python | def hysteresis_magic2(path_to_file='.', hyst_file="rmag_hysteresis.txt",
save=False, save_folder='.',
fmt="svg", plots=True):
"""
Calculates hysteresis parameters, saves them in rmag_hysteresis format file.
If selected, this function also plots hysteresis loops, d... |
java | @Override
public void setValueAt(final Object value, final int row, final int col) {
if (!isEditable()) {
throw new IllegalStateException("Attempted to set a value on an uneditable model");
}
data[row][col] = (Serializable) value;
} |
python | def package(self):
"""str: Package `name-version-release` string."""
return u'{0}-{1}-{2}'.format(self.name,
self.version,
self.release) |
python | def first_parent(tag, nodename):
"""
Given a beautiful soup tag, look at its parents and return the first
tag name that matches nodename or the list nodename
"""
if nodename is not None and type(nodename) == str:
nodename = [nodename]
return first(list(filter(lambda tag: tag.name in node... |
python | def build_docker_sshd(ctx):
"""
build docker image sshd-mssh-copy-id
"""
dinfo = DOCKER_SSHD_IMG
ctx.run('docker rmi -f {0}'.format(dinfo['name']), warn=True)
ctx.run('docker build -t {0} {1}'.format(dinfo['name'], dinfo['path'])) |
python | def scale_values(numbers, num_lines=1, minimum=None, maximum=None):
"Scale input numbers to appropriate range."
# find min/max values, ignoring Nones
filtered = [n for n in numbers if n is not None]
min_ = min(filtered) if minimum is None else minimum
max_ = max(filtered) if maximum is None else ma... |
java | public void open(Path errFilePath) throws IOException {
this.fs.mkdirs(errFilePath.getParent());
OutputStream os =
this.closer.register(this.fs.exists(errFilePath) ? this.fs.append(errFilePath) : this.fs.create(errFilePath));
this.writer = this.closer
.register(new BufferedWriter(new OutputS... |
python | def unpersist(self, blocking=False):
"""
Delete cached copies of this broadcast on the executors. If the
broadcast is used after this is called, it will need to be
re-sent to each executor.
:param blocking: Whether to block until unpersisting has completed
"""
if... |
python | def ReadClientPostingLists(self, keywords):
"""Looks up all clients associated with any of the given keywords.
Args:
keywords: A list of keywords we are interested in.
Returns:
A dict mapping each keyword to a list of matching clients.
"""
start_time, end_time, filtered_keywords, _ = ... |
python | def do_folder_update_metadata(client, args):
"""Update file metadata"""
client.update_folder_metadata(args.uri, foldername=args.foldername,
description=args.description,
mtime=args.mtime, privacy=args.privacy,
... |
python | def remove_interval_helper(self, interval, done, should_raise_error):
"""
Returns self after removing interval and balancing.
If interval doesn't exist, raise ValueError.
This method may set done to [1] to tell all callers that
rebalancing has completed.
See Eternally C... |
python | def get_process_breakpoints(self, dwProcessId):
"""
Returns all breakpoint objects for the given process as a list of tuples.
Each tuple contains:
- Process global ID to which the breakpoint applies.
- Thread global ID to which the breakpoint applies, or C{None}.
- Th... |
python | def iter_prefixes(path):
"""
Iterate through all (non-empty) prefixes of a dotted path.
Example:
>>> list(iter_prefixes('foo.bar.baz'))
['foo', 'foo.bar', 'foo.bar.baz']
"""
split_path = path.split('.')
for i in range(1, len(split_path) + 1):
yield join_paths(*split_path[:i]) |
python | def _iter_enum_constant_ids(eid):
"""Iterate the constant IDs of all members in the given enum"""
for bitmask in _iter_bitmasks(eid):
for value in _iter_enum_member_values(eid, bitmask):
for cid, serial in _iter_serial_enum_member(eid, value, bitmask):
yield cid |
python | def fapply(f, x, tz=False):
'''
fapply(f,x) yields the result of applying f either to x, if x is a normal value or array, or to
x.data if x is a sparse matrix. Does not modify x (unless f modifiex x).
The optional argument tz (default: False) may be set to True to specify that, if x is a sparse
... |
java | public Class<?> getGenericType(Field field) {
Type generic = field.getGenericType();
if (generic instanceof ParameterizedType) {
Type actual = ((ParameterizedType) generic).getActualTypeArguments()[0];
if (actual instanceof Class) {
return (Class<?>) actual;
... |
python | def search_auth(self, list_or_file_path, source):
"""
Looking for auth in env, cmdline, str
:param list_or_file_path:
:param source:
"""
_auth = source.args['auth']
if isinstance(_auth, str):
if ':' in _auth:
_auth = _auth.split(':')
... |
java | @Nonnull
public <V extends T> LOiToDblFunctionBuilder<T> aCase(Class<V> argC1, LOiToDblFunction<V> function) {
PartialCaseWithDblProduct.The pc = partialCaseFactoryMethod((a1, a2) -> (argC1 == null || argC1.isInstance(a1)));
pc.evaluate(function);
return self();
} |
python | def find_egg(self, egg_dist):
"""Find an egg by name in the given environment"""
site_packages = self.libdir[1]
search_filename = "{0}.egg-link".format(egg_dist.project_name)
try:
user_site = site.getusersitepackages()
except AttributeError:
user_site = si... |
java | @Override
public Request<DeleteCustomerGatewayRequest> getDryRunRequest() {
Request<DeleteCustomerGatewayRequest> request = new DeleteCustomerGatewayRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
} |
python | def add_format(self, format_id, number, entry_type, description):
"""
Add a format line to the header.
Arguments:
format_id (str): The id of the format line
number (str): Integer or any of [A,R,G,.]
entry_type (str): Any of [Integer,Float,Flag,Character,Strin... |
java | public static String getActivationKey(String gatewayAddress, String activationRegionName) throws AmazonClientException {
try {
HttpParams httpClientParams = new BasicHttpParams();
httpClientParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
DefaultHttpClient cl... |
python | def attach_model(subscription, rgname, vmssvm_model, diskname, lun):
'''Attach a data disk to a VMSS VM model'''
disk_id = '/subscriptions/' + subscription + '/resourceGroups/' + rgname + \
'/providers/Microsoft.Compute/disks/' + diskname
disk_model = {'lun': lun, 'createOption': 'Attach', 'caching'... |
python | def on_cpu_execution_cap_change(self, execution_cap):
"""Notification when the CPU execution cap changes.
in execution_cap of type int
The new CPU execution cap value. (1-100)
"""
if not isinstance(execution_cap, baseinteger):
raise TypeError("execution_cap can ... |
python | def glm(self, data: ['SASdata', str] = None,
absorb: str = None,
by: str = None,
cls: [str, list] = None,
contrast: str = None,
estimate: str = None,
freq: str = None,
id: str = None,
lsmeans: str = None,
manova:... |
java | public static void main(final String[] args) throws IOException {
Utils4Swing.initSystemLookAndFeel();
DirectorySelector.Result result;
try {
result = DirectorySelector.selectDirectory(
"Please select the destination directory:", new File(".")
.getCanonicalPath(), true);
System.out.printl... |
java | public java.lang.String getMethodName() {
java.lang.Object ref = methodName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
me... |
java | public String toJSONString() {
String rawdata = stats.stream().sorted(Comparator.comparingInt(UStats::getIndex))
.map(sr -> sr.toJSONString())
.collect(Collectors.joining(",\n ", "[\n ", "\n ]"));
String fields = Stream.of(UStats.getJSONFields()).c... |
java | public void unsetConstant()
{
boolean oldConstant = constant;
boolean oldConstantESet = constantESet;
constant = CONSTANT_EDEFAULT;
constantESet = false;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.UNSET, TypesPackage.JVM_FIELD__CONSTANT, oldConstant, CONSTANT_EDEFAULT, o... |
java | public String getByGroupWithLog(String key, String group) {
final String value = getByGroup(key, group);
if (value == null) {
log.debug("No key define for [{}] of group [{}] !", key, group);
}
return value;
} |
java | private double[] hiddenDropoutratios(BackendParams bparms) {
double[] hiddenDropoutRatios = (double[]) bparms.get("hidden_dropout_ratios");
if(null != hiddenDropoutRatios) {
return hiddenDropoutRatios;
}
int layerNr = ((int[]) bparms.get("hidden")).length;
hiddenDropo... |
python | def parse_object(self, data):
""" Look for datetime looking strings. """
for key, value in data.items():
if isinstance(value, (str, type(u''))) and \
self.strict_iso_match.match(value):
data[key] = dateutil.parser.parse(value)
return data |
java | public JSONException syntaxError(String message, Throwable causedBy) {
return new JSONException(message + this.toString(), causedBy);
} |
java | public void setClusterStates(java.util.Collection<String> clusterStates) {
if (clusterStates == null) {
this.clusterStates = null;
return;
}
this.clusterStates = new com.amazonaws.internal.SdkInternalList<String>(clusterStates);
} |
python | def is_descendant_of_gradebook(self, id_, gradebook_id):
"""Tests if an ``Id`` is a descendant of a gradebook.
arg: id (osid.id.Id): an ``Id``
arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook
return: (boolean) - ``true`` if the ``id`` is a descendant of
th... |
python | def field_singleton_schema( # noqa: C901 (ignore complexity)
field: Field,
*,
by_alias: bool,
model_name_map: Dict[Type['main.BaseModel'], str],
schema_overrides: bool = False,
ref_prefix: Optional[str] = None,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
This function is indirectly ... |
java | public void addScope(CmsGallerySearchScope scope) {
m_searchObject.setScope(scope);
m_searchObjectChanged = true;
ValueChangeEvent.fire(this, m_searchObject);
} |
java | private void addRelatedType(JSType type, JSTypeBitSet related) {
computeRelatedTypesForNonUnionType(type);
related.or(relatedBitsets.get(type));
} |
java | public <N extends Node> ParseResult<N> parse(ParseStart<N> start, Provider provider) {
assertNotNull(start);
assertNotNull(provider);
final GeneratedDrlConstraintParser parser = getParserForProvider(provider);
try {
N resultNode = start.parse(parser);
ParseResult... |
python | def dropping(n):
"""Create a transducer which drops the first n items"""
if n < 0:
raise ValueError("Cannot drop fewer than zero ({}) items".format(n))
def dropping_transducer(reducer):
return Dropping(reducer, n)
return dropping_transducer |
java | @Override
public RestCollection<Event> getEvents(Token token, EventQueryAttribute queryAttribute, String queryValue) {
final ResultIterator<Event> iterator = new ResultIterator<>(
token,
V2_EVENTS,
Event.class,
queryAttribute,
queryValue);
return new RestCollection<>(iterator.getSize(), iterato... |
java | public static int[] unshuffleIntArray(byte[] input) throws IOException {
int[] output = new int[input.length / 4];
int numProcessed = impl.unshuffle(input, 0, 4, input.length, output, 0);
assert(numProcessed == input.length);
return output;
} |
java | public static MiniSat glucose(final FormulaFactory f) {
return new MiniSat(f, SolverStyle.GLUCOSE, new MiniSatConfig.Builder().build(), new GlucoseConfig.Builder().build());
} |
python | def link(origin, link_name, force=False, model_path=None):
"""
Create a symlink for models within the spacy/data directory. Accepts
either the name of a pip package, or the local path to the model data
directory. Linking models allows loading them via spacy.load(link_name).
"""
msg = Printer()
... |
python | def _process_rules(self, rules: dict, system: System):
""" process a set of rules for a target """
self._source = None # reset the template source
if not self._shall_proceed(rules):
return
self.context.update(rules.get('context', {}))
self.path = rules.get('path', '')... |
python | def _writeCloseFrame(self, reason=DISCONNECT.GO_AWAY):
'''Write a close frame with the given reason and schedule this
connection close.
'''
self.transport.writeClose(reason)
self.transport.loseConnection()
self.transport = None |
java | final String childrenToString(final WComponent... children) {
if (!(this instanceof Container)) {
return "";
}
if (children == null || children.length == 0) {
return "[]";
}
StringBuffer buf = new StringBuffer("\n[");
for (int i = 0; i < children.length; i++) {
buf.append(i == 0 ? "\n " : ",\n... |
python | def _create_tuple(self, format, args):
"""Handle the case where the outermost type of format is a tuple."""
format = format[1:] # eat the '('
if args is None:
# empty value: we need to call _create() to parse the subtype
rest_format = format
while rest_forma... |
python | def from_headers (strheader):
"""Parse cookie data from a string in HTTP header (RFC 2616) format.
@return: list of cookies
@raises: ValueError for incomplete or invalid data
"""
res = []
fp = StringIO(strheader)
headers = httplib.HTTPMessage(fp, seekable=True)
if "Host" not in headers:... |
java | private FacetList calculateFacetList(AbstractDataTable table, String[] facetFields) {
if(facetFields == null || facetFields.length == 0){
throw new NullPointerException("Facet field list empty");
}
FacetList facetList = new FacetList();
for (String facetField : facetFields) ... |
python | def handle_protein_results(permutation_result):
"""Takes in output from multiprocess_permutation function and converts to
a better formatted dataframe.
Parameters
----------
permutation_result : list
output from multiprocess_permutation
Returns
-------
permutation_df : pd.DataF... |
java | public boolean next() throws OdaException
{
int maxRows = getMaxRows();
if( m_currentRowId < maxRows )
{
m_currentRowId++;
currentRow = sqlResult.get(m_currentRowId-1);
return true;
}
return false;
} |
java | @Override
public java.util.List<com.liferay.commerce.tax.engine.fixed.model.CommerceTaxFixedRate> getCommerceTaxFixedRates(
int start, int end) {
return _commerceTaxFixedRateLocalService.getCommerceTaxFixedRates(start,
end);
} |
java | private void initExtendedTypes()
{
m_extendedTypes = new ExtendedType[m_initialSize];
for (int i = 0; i < DTM.NTYPES; i++) {
m_extendedTypes[i] = m_defaultExtendedTypes[i];
m_table[i] = new HashEntry(m_defaultExtendedTypes[i], i, i, null);
}
m_nextType = DTM.NTYPES;
} |
java | public static Throwable deserializeServerFailure(final ByteBuf buf) throws IOException, ClassNotFoundException {
try (ByteBufInputStream bis = new ByteBufInputStream(buf);
ObjectInputStream in = new ObjectInputStream(bis)) {
return (Throwable) in.readObject();
}
} |
java | private static void doInsert(CallInfo callInfo, Table table, DataSet data) {
StringBuilder sql = new StringBuilder("INSERT INTO ");
List<String> tableColumns = table.getColumns();
int columnCount = tableColumns.size();
int[] paramIdx = new int[columnCount];
int param = 0;
Iterator<String> itr = ... |
python | def get_session_not_on_or_after(self):
"""
Gets the SessionNotOnOrAfter from the AuthnStatement
Could be used to set the local session expiration
:returns: The SessionNotOnOrAfter value
:rtype: time|None
"""
not_on_or_after = None
authn_statement_nodes = ... |
java | public static LoggerContext getLoggerContext() {
final long startTime = System.nanoTime();
while (true) {
final ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
if (iLoggerFactory instanceof LoggerContext) {
return (LoggerContext) iLoggerFactory;... |
python | def anti_alias(image):
"""
Apply Anti-Alias filter to a binary image
ANTsR function: N/A
Arguments
---------
image : ANTsImage
binary image to which anti-aliasing will be applied
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.... |
python | def draw_lineage(self, recs, nodecolor="mediumseagreen",
edgecolor="lightslateblue", dpi=96,
lineage_img="GO_lineage.png", engine="pygraphviz",
gml=False, draw_parents=True, draw_children=True):
"""Draw GO DAG subplot."""
assert engine in Gr... |
python | def get_tools_status(self, tool_name=None):
'''Gets the status of tool jobs.
Parameters
----------
tool_name: str, optional
filter jobs by tool name
Returns
-------
dict
status information about tool jobs
See also
-------... |
python | def clock(seg, seconds):
"""
Display current time on device.
"""
interval = 0.5
for i in range(int(seconds / interval)):
now = datetime.now()
seg.text = now.strftime("%H-%M-%S")
# calculate blinking dot
if i % 2 == 0:
seg.text = now.strftime("%H-%M-%S")
... |
java | public final void synpred38_DRL6Expressions_fragment() throws RecognitionException {
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:634:7: ( LEFT_SQUARE RIGHT_SQUARE )
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:634:8: LEFT_SQUARE RIGHT_SQUARE
{
match(input,LEFT_SQUARE,FOL... |
java | public void addListener(MessageKey key, VehicleMessage.Listener listener) {
addListener(ExactKeyMatcher.buildExactMatcher(key), listener);
} |
python | def array_to_native(array, inplace=False):
"""
Convert an array to the native byte order.
NOTE: the inplace keyword argument is not currently used.
"""
if numpy.little_endian:
machine_little = True
else:
machine_little = False
data_little = False
if array.dtype.names is... |
java | public RemoteWebDriver createDriver(MobileNodeType nodeType, WebDriverPlatform platform, CommandExecutor command,
URL url, Capabilities caps) {
if (mobileProviders.containsKey(nodeType)) {
logger.log(Level.FINE, "Found mobile driver provider that supports " +... |
java | public ApiListingBuilder apis(List<ApiDescription> apis) {
if (apis != null) {
this.apis = apis.stream().sorted(descriptionOrdering).collect(toList());
}
return this;
} |
python | def eccentricity(self, **kw):
r"""
Returns the eccentricity computed from the mean apocenter and
mean pericenter.
.. math::
e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}}
Parameters
----------
**kw
Any keyword arguments ... |
python | def rename_tables(cr, table_spec):
"""
Rename tables. Typically called in the pre script.
This function also renames the id sequence if it exists and if it is
not modified in the same run.
:param table_spec: a list of tuples (old table name, new table name). Use \
None for new_name to trigger a... |
python | def svg(*args, **kw):
"""
Use in this way:
´from remarkuple import helper as h, svg´
"""
class svg(type(helper.svg())):
def __init__(self, *args, **kw):
super(self.__class__, self).__init__(*args, **kw)
# cartesian grid on/off
self.__dic... |
java | public SimpleOrderedMap<Object> create(ComponentPrefix prefix, Boolean encode)
throws IOException {
SimpleOrderedMap<Object> mtasPrefixResponse = new SimpleOrderedMap<>();
mtasPrefixResponse.add("key", prefix.key);
if (encode) {
mtasPrefixResponse.add("_encoded_singlePosition",
MtasSol... |
java | public OverpassFilterQuery around(double radius, double lat, double lon) {
builder.around(radius, lat, lon);
return this;
} |
python | def bool(self, name):
"""parse a boolean frame"""
self._assert_is_string(name)
frame = self._next_frame()
if len(frame) != 1:
raise MessageParserError("Expected exacty 1 byte for boolean value")
val = frame != b"\x00"
self.results.__dict__[name] = val
... |
python | def pause(self):
"""Pause pulse capture"""
self._mq.send("p", True, type=1)
self._paused = True |
python | def get_balance(self, acc_id=None, site='Pro', _async=False):
"""
获取当前账户资产
:return:
"""
acc_id = self.acc_id if acc_id is None else acc_id
assert site in ['Pro', 'HADAX']
path = f'/v1{"/" if site == "Pro" else "/hadax/"}account/accounts/{acc_id}/balance'
#... |
java | public IntervalConverter getIntervalConverter(Object object) {
IntervalConverter converter =
(IntervalConverter)iIntervalConverters.select(object == null ? null : object.getClass());
if (converter != null) {
return converter;
}
throw new IllegalArgumentException("... |
python | def get_profile_from_tokens(token_records, public_key_or_address,
hierarchical_keys=False):
""" A function for extracting a profile from a list of tokens.
"""
if hierarchical_keys:
raise NotImplementedError("Hierarchical key support not implemented")
profile = {}
... |
python | def make_metatab_citation_dict(t):
"""
Return a dict with BibText key/values for metatab data
:param t:
:return:
"""
try:
if parse_app_url(t.url).proto == 'metatab':
try:
url = parse_app_url(str(t.resolved_url)).resource_url
doc = t.row_gene... |
python | def forwards(self, orm):
"Write your forwards methods here."
projects = orm['samples.Project'].objects.exclude(name=DEFAULT_PROJECT_NAME)
for project in projects:
cohort = orm['samples.Cohort'](name=project.label, autocreated=True)
cohort.project = project
co... |
java | private void createOrOpenBDBEnv(String BDBEnvHome) throws Exception {
// create the BDBEnvHome directory if it does not exist
File BDBEnvHomeDir = new File(BDBEnvHome);
if (!BDBEnvHomeDir.isDirectory()) {
boolean success = BDBEnvHomeDir.mkdir();
if (success) {
System.out.println(BDBEnvHome + " dir... |
python | def get_es_ids(self):
"""
reads all the elasticssearch ids for an index
"""
search = self.search.source(['uri']).sort(['uri'])
es_ids = [item.meta.id for item in search.scan()]
return es_ids |
python | def get_link(self, peer):
"""
Retrieves the link to the given peer
"""
for access in peer.accesses:
if access.type == 'mqtt':
break
else:
# No MQTT access found
return None
# Get server access tuple
server = (ac... |
java | public Response fetchEvernoteUrl(String url) throws IOException {
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.addHeader("Cookie", mAuthHeader)
.get();
return mHttpClient.newCall(requestBuilder.build()).execute();
} |
java | public ListActionTypesResult withActionTypes(ActionType... actionTypes) {
if (this.actionTypes == null) {
setActionTypes(new java.util.ArrayList<ActionType>(actionTypes.length));
}
for (ActionType ele : actionTypes) {
this.actionTypes.add(ele);
}
return th... |
python | def _rewrite_error_path(self, error, offset=0):
"""
Recursively rewrites the error path to correctly represent logic errors
"""
if error.is_logic_error:
self._rewrite_logic_error_path(error, offset)
elif error.is_group_error:
self._rewrite_group_error_path... |
java | protected void associateBatched(Collection owners, Collection children, Collection mToNImplementors)
{
CollectionDescriptor cds = getCollectionDescriptor();
PersistentField field = cds.getPersistentField();
PersistenceBroker pb = getBroker();
Class ownerTopLevelClass = pb.getTop... |
java | public void add(Widget w, String tabText, boolean asHTML) {
insert(w, tabText, asHTML, getWidgetCount());
} |
java | public static Collection<Locale> getLocales(final HttpServletRequest req) {
if (req.getHeader("Accept-Language") == null) {
return null;
}
@SuppressWarnings("unchecked")
Enumeration<Locale> lcs = req.getLocales();
ArrayList<Locale> locales = new ArrayList<Locale>();
while (lcs.hasMoreElem... |
python | def error_per_row(self):
"""This function calculates the error of the design based on the
differences between the predicted flow rate
and the actual flow rate through the LFOM."""
FLOW_lfom_error = np.zeros(self.n_rows)
for i in range(self.n_rows):
actual_flow = self.... |
python | def setHeader(package_path,
header_start='', header_end='', header_text='',
remove_header=False,
exclude_init=True, exclude_empty_files=True):
"""
Adds, modifies removes a header text in all *.py files in a python package
header_start -> string indicating the begin... |
java | public static String hexAll(String s) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
result.append(Integer.toHexString(s.charAt(i)).toUpperCase()).append(' ');
}
return (result.toString());
} |
java | public List<SimpleJsonSchema> filter(List<JsonSchemaRepository> schemaRepositories,
JsonMessageValidationContext jsonMessageValidationContext,
ApplicationContext applicationContext) {
if (isSchemaRepositorySpecified(jsonMessageVal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.