language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public synchronized static void assimilate()
{
if (assimilated) {
return;
}
assimilated = true;
// Assimilate java.util.logging
final Logger rootLogger = LogManager.getLogManager().getLogger("");
final Handler[] handlers = rootLogger.getHandlers();
... |
python | def _get_retro_id(cls, home_team_id, timestamp, game_number):
"""
get retro id
:param home_team_id: home team id
:param timestamp: game day
:param game_number: game number
:return: retro id
"""
return '{home_team_id}{year}{month}{day}{game_number}'.format(... |
python | def reguid(zpool):
'''
Generates a new unique identifier for the pool
.. warning::
You must ensure that all devices in this pool are online and healthy
before performing this action.
zpool : string
name of storage pool
.. versionadded:: 2016.3.0
CLI Example:
.. c... |
python | def add_ipv4addr(self, ipv4addr):
"""Add an IPv4 address to the host.
:param str ipv4addr: The IP address to add.
:raises: ValueError
"""
for addr in self.ipv4addrs:
if ((isinstance(addr, dict) and addr['ipv4addr'] == ipv4addr) or
(isinstance(addr, H... |
python | def search_line(line, search, searchtype):
"""Return True if search term is found in given line, False otherwise."""
if searchtype == 're' or searchtype == 'word':
return re.search(search, line) #, re.IGNORECASE)
elif searchtype == 'pos':
return searcher.search_out(line, search)
elif se... |
java | @Deprecated
public NearCacheConfig setEvictionPolicy(String evictionPolicy) {
this.evictionPolicy = checkNotNull(evictionPolicy, "Eviction policy cannot be null!");
this.evictionConfig.setEvictionPolicy(EvictionPolicy.valueOf(evictionPolicy));
this.evictionConfig.setMaximumSizePolicy(ENTRY_C... |
python | def PlistValueToPlainValue(plist):
"""Takes the plist contents generated by binplist and returns a plain dict.
binplist uses rich types to express some of the plist types. We need to
convert them to types that RDFValueArray will be able to transport.
Args:
plist: A plist to convert.
Returns:
A simp... |
java | public static int sum (int[] list)
{
int total = 0, lsize = list.length;
for (int ii = 0; ii < lsize; ii++) {
total += list[ii];
}
return total;
} |
java | public List<CustomWindowStateType<PortletAppType<T>>> getAllCustomWindowState()
{
List<CustomWindowStateType<PortletAppType<T>>> list = new ArrayList<CustomWindowStateType<PortletAppType<T>>>();
List<Node> nodeList = childNode.get("custom-window-state");
for(Node node: nodeList)
{
Cu... |
java | public static String extractRegexGroup(String fromContent, String regex, int groupNumber) throws Exception {
if (regex == null) {
throw new Exception("Cannot extract regex group because the provided regular expression is null.");
}
Pattern expectedPattern = Pattern.compile(regex);
... |
python | def netconf_state_statistics_in_rpcs(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring")
statistics = ET.SubElement(netconf_state, "statistics... |
java | private Object extractAttributeValueIfAttributeQueryConstant(String attributeName) {
if (KEY_ATTRIBUTE_NAME.value().equals(attributeName)) {
return getKey();
} else if (THIS_ATTRIBUTE_NAME.value().equals(attributeName)) {
return getValue();
}
return null;
} |
java | public static JSONObject copy(final JSONObject src, final boolean deep) {
final JSONObject dest = new JSONObject();
Iterator<String> keys = src.keys();
while (keys.hasNext()) {
final String key = keys.next();
final Object value = src.opt(key);
if (deep) {
... |
python | def start(self):
"""
function to initialize thread for downloading
"""
global parallel
for self.i in range(0, self.length):
if parallel:
self.thread.append(myThread(self.url[ self.i ], self.directory, self.i,
self.min_file_size, self.max_file_size, self.no_redirects))
else:
# if not ... |
java | private void initAttributes(Context context, AttributeSet attributeSet) {
TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.MotionView);
friction = typedArray.getFloat(R.styleable.MotionView_friction, 0.75f) * 1000;
typedArray.recycle();
} |
python | def system_info(url, auth, verify_ssl):
"""Retrieve SDC system information.
Args:
url (str): the host url.
auth (tuple): a tuple of username, and password.
"""
sysinfo_response = requests.get(url + '/info', headers=X_REQ_BY, auth=auth, verify=verify_ssl)
sysinfo_response.raise_for_... |
java | public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException {
// can't use the new constructor for Android support
// JSONObject jo = new JSONObject(properties == null ? 0 : properties.size());
JSONObject jo = new JSONObject();
if (properties != null && !p... |
java | public String[] getPartitionKeys(String location, Job job) throws IOException
{
if (!usePartitionFilter)
return null;
List<ColumnDef> indexes = getIndexes();
String[] partitionKeys = new String[indexes.size()];
for (int i = 0; i < indexes.size(); i++)
{
... |
python | def select(self, domain_or_name, query='', next_token=None,
consistent_read=False):
"""
Returns a set of Attributes for item names within domain_name that
match the query. The query must be expressed in using the SELECT
style syntax rather than the original SimpleDB query... |
python | def number(input):
"""Convert the given input to a floating point or integer value.
In cases of ambiguity, integers will be prefered to floating point.
:param input: the value to convert to a number
:type input: any
:returns: converted integer value
:rtype: float or int
"""
... |
java | public TrackInfos getTrackInfos(final Integer msgId, Application app)
throws UnknownMessageIdException {
logger.info("WS SendTrack receives the client request with parameter msgId = " + msgId);
TrackInfos infos = new TrackInfos();
infos.setNbDestTotal(daoService.getNbDest(msgId, app));
... |
python | def tty_create_child(args):
"""
Return a file descriptor connected to the master end of a pseudo-terminal,
whose slave end is connected to stdin/stdout/stderr of a new child process.
The child is created such that the pseudo-terminal becomes its controlling
TTY, ensuring access to /dev/tty returns a... |
java | public void init() {
nodeState = StateHelper.getStateImpl();
try {
nodeState.load();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
nodesSet = nodeState.getNodes();
Iterator it = nodesSet.iterator();
allNodes = new Node[nodesSet.s... |
java | public static InternationalFixedDate now(Clock clock) {
LocalDate now = LocalDate.now(clock);
return InternationalFixedDate.ofEpochDay(now.toEpochDay());
} |
python | def simulate_experiment(self, modelparams, expparams, repeat=1):
"""
Produces data according to the given model parameters and experimental
parameters, structured as a NumPy array.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
array of model parameter ... |
python | def column_exists(cr, table, column):
""" Check whether a certain column exists """
cr.execute(
'SELECT count(attname) FROM pg_attribute '
'WHERE attrelid = '
'( SELECT oid FROM pg_class WHERE relname = %s ) '
'AND attname = %s',
(table, column))
return cr.fetchone()[... |
java | public void add(final Condition condition) {
if (andConditions.isEmpty()) {
andConditions.add(new AndCondition());
}
andConditions.get(0).getConditions().add(condition);
} |
python | def load_cities(self, filename):
"""
Load up all cities in lowercase for easier matching. The file should have one city per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line... |
python | def register_shipping_query_handler(self, callback, *custom_filters, state=None, run_task=None,
**kwargs):
"""
Register handler for shipping query
Example:
.. code-block:: python3
dp.register_shipping_query_handler(some_shipping_quer... |
java | protected String getArtifactId(String artifactId) {
return this.artifactId == null || this.artifactId.length() == 0
? artifactId
: this.artifactId;
} |
python | def set(self, instance, value, **kwargs):
"""writes the value to the same named field on the proxy object
"""
# Retrieve the proxy object
proxy_object = self.get_proxy(instance)
# Return None if we could not find a proxied object, e.g. through
# the proxy expression 'con... |
java | public com.google.api.ads.admanager.axis.v201902.DateRange getTimeSeriesDateRange() {
return timeSeriesDateRange;
} |
python | def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autos... |
java | private CodeableConcept makeUnits(String text, String ucum) {
if (Utilities.noString(text) && Utilities.noString(ucum))
return null;
CodeableConcept cc = new CodeableConcept();
cc.setText(text);
cc.getCoding().add(new Coding().setCode(ucum).setSystem("http://unitsofmeasure.org"));
return cc;
} |
python | def execstr(self, local_name):
"""returns a string which when evaluated will
add the stored variables to the current namespace
localname is the name of the variable in the current scope
* use locals().update(dyn.to_dict()) instead
"""
execstr = ''
for (k... |
python | def get_learning_curves(self, lc_extractor=extract_HBS_learning_curves, config_ids=None):
"""
extracts all learning curves from all run configurations
Parameters
----------
lc_extractor: callable
a function to return a list of learning_curves.
defaults to hpbanster.HB_result.extract_HP_learning_curv... |
java | private void restoreWithRescaling(Collection<KeyedStateHandle> restoreStateHandles) throws Exception {
// Prepare for restore with rescaling
KeyedStateHandle initialHandle = RocksDBIncrementalCheckpointUtils.chooseTheBestStateHandleForInitial(
restoreStateHandles, keyGroupRange);
// Init base DB instance
i... |
python | def loadFile(self, filePath=None):
"""Load the specified file, or the last opened file if None."""
self.resetState()
self.canvas.setEnabled(False)
if filePath is None:
filePath = self.settings.get(SETTING_FILENAME)
# Make sure that filePath is a regular python string... |
java | public Quaterniond rotationYXZ(double angleY, double angleX, double angleZ) {
double sx = Math.sin(angleX * 0.5);
double cx = Math.cosFromSin(sx, angleX * 0.5);
double sy = Math.sin(angleY * 0.5);
double cy = Math.cosFromSin(sy, angleY * 0.5);
double sz = Math.sin(angleZ * 0.5);
... |
python | def contents_equal(self, other, **kwargs):
"""
Test the equality of the fileset contents with another fileset. If the
fileset's format implements a 'contents_equal' method than that is used
to determine the equality, otherwise a straight comparison of the
checksums is used.
... |
python | def get_adjacent_index(I, shape, size):
"""
Find indices 2d-adjacent to those in I. Helper function for get_border*.
Parameters
----------
I : np.ndarray(dtype=int)
indices in the flattened region
shape : tuple(int, int)
region shape
size : int
region size (technical... |
python | def _ctrl_meas(self):
"""Value to be written to the device's ctrl_meas register """
ctrl_meas = (self.overscan_temperature << 5)
ctrl_meas += (self.overscan_pressure << 2)
ctrl_meas += self.mode
return ctrl_meas |
java | public Map<String, String> getCellValuesAsMap(String regex, int groupIdx,
List<ReplacePattern> replaces) {
Map<String, String> map = new TreeMap<String, String>();
Pattern pattern = Pattern.compile(regex);
for (Entry<String, String> entry : getData().entrySet()) {
... |
java | @Override
public RandomVariable getBrownianIncrement(int timeIndex, int factor) {
RandomVariable brownianIncrement = new RandomVariableFromDoubleArray(0.0);
for(int factorIndex=0; factorIndex<factorLoadings[factor].length; factorIndex++) {
if(factorLoadings[factor][factorIndex] != 0) {
RandomVariable indepe... |
python | def has_pkgs_signed_with(self, allowed_keys):
"""
Check signature of packages installed in image.
Raises exception when
* rpm binary is not installed in image
* parsing of rpm fails
* there are packages in image that are not signed with one of allowed keys
:para... |
python | def read_tf_checkpoint(path):
"""read tensorflow checkpoint"""
from tensorflow.python import pywrap_tensorflow
tensors = {}
reader = pywrap_tensorflow.NewCheckpointReader(path)
var_to_shape_map = reader.get_variable_to_shape_map()
for key in sorted(var_to_shape_map):
tensor = reader.get_... |
java | private void resolve(Collection<Tile> resolved, Collection<Tile> toResolve, Tile tile)
{
updateTile(resolved, toResolve, tile, -1, 0);
updateTile(resolved, toResolve, tile, 1, 0);
updateTile(resolved, toResolve, tile, 0, 1);
updateTile(resolved, toResolve, tile, 0, -1);
... |
python | def _parse_all_merged_entities(self):
"""set self._all_merged_entities to the longest possible(wrapping)
tokens including non-entity tokens
"""
self._all_merged_entities = list(filterfalse(
lambda token: self._is_wrapped(token, self.all_entities),
self.all_entitie... |
python | def fabs(x):
"""
Absolute value function
"""
if isinstance(x, UncertainFunction):
mcpts = np.fabs(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.fabs(x) |
python | def get_scorer(scoring, compute=True):
"""Get a scorer from string
Parameters
----------
scoring : str | callable
scoring method as string. If callable it is returned as is.
Returns
-------
scorer : callable
The scorer.
"""
# This is the same as sklearns, only we us... |
python | def build(self):
"""
Build the schema (object graph) using the root node
using the factory.
- Build the graph.
- Collate the children.
"""
self.children = BasicFactory.build(self.root, self)
collated = BasicFactory.collate(self.children)
se... |
java | public void readExternal(PofReader reader)
throws IOException {
super.readExternal(reader);
numInc = (Number) reader.readObject(10);
fPostInc = reader.readBoolean(11);
} |
python | def show_window_options(self, option=None, g=False):
"""
Return a dict of options for the window.
For familiarity with tmux, the option ``option`` param forwards to
pick a single option, forwarding to :meth:`Window.show_window_option`.
Parameters
----------
opti... |
java | public static <T extends IHasIntegerId> void insertFlatList( List<T> list, TableCollectionManager<T> mng, Func1<T, Integer> parentIdGetter )
{
HashSet<Integer> inserted = new HashSet<>();
List<T> toInsert = new ArrayList<>( list );
List<T> postPoned = new ArrayList<>();
List<T> inOrder = new ArrayList<>();
... |
python | def open(self, _file, target=DEFAULT_TARGET):
"""
Open the existing file for reading.
@param _file : A filename of file descriptor.
@param target: A user-specific BFD target name.
@return : None
"""
# Close any existing BFD structure instance.
self.clos... |
java | public AttributeDataset numericDataset(String responseColName, String... variablesColNames) {
return dataset(table.numberColumn(responseColName), AttributeType.NUMERIC, table.columns(variablesColNames));
} |
python | def intent_path(cls, project, intent):
"""Return a fully-qualified intent string."""
return google.api_core.path_template.expand(
'projects/{project}/agent/intents/{intent}',
project=project,
intent=intent,
) |
python | def assign_value(self, comp_def, value, src_ref):
"""
Set both alias and actual value
"""
super().assign_value(comp_def, value, src_ref)
comp_def.properties['incrthreshold'] = value |
java | public static double getRMSD(MultipleAlignment alignment) {
List<Atom[]> trans = MultipleAlignmentTools.transformAtoms(alignment);
return getRMSD(trans);
} |
python | def return_markers(self):
"""Return all the markers (also called triggers or events).
Returns
-------
list of dict
where each dict contains 'name' as str, 'start' and 'end' as float
in seconds from the start of the recordings, and 'chan' as list of
st... |
python | def sort(self, callback=None):
"""
Sort through each item with a callback.
:param callback: The callback
:type callback: callable or None
:rtype: Collection
"""
items = self.items
if callback:
return self.__class__(sorted(items, key=callback... |
java | public synchronized void push(@Nullable T item) {
if( waiting == null ) {
throw new IllegalStateException("Invalid attempt to add an item to a completed list.");
}
if( filter != null ) {
try {
if( !filter.filter(item) ) {
return;
... |
java | public Swagger2MarkupConfigBuilder withMarkupLanguage(MarkupLanguage markupLanguage) {
Validate.notNull(markupLanguage, "%s must not be null", "markupLanguage");
config.markupLanguage = markupLanguage;
return this;
} |
python | def compute_key_composite(password=None, keyfile=None):
"""Compute composite key.
Used in header verification and payload decryption."""
# hash the password
if password:
password_composite = hashlib.sha256(password.encode('utf-8')).digest()
else:
password_composite = b''
# hash ... |
python | def sinkhorn_knopp(a, b, M, reg, numItermax=1000,
stopThr=1e-9, verbose=False, log=False, **kwargs):
"""
Solve the entropic regularization optimal transport problem and return the OT matrix
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\g... |
python | def batch_remove_retrain(nmask_train, nmask_test, X_train, y_train, X_test, y_test, attr_train, attr_test, model_generator, metric):
""" An approximation of holdout that only retraines the model once.
This is alse called ROAR (RemOve And Retrain) in work by Google. It is much more computationally
efficient... |
python | def one_hot(indices, output_dim, on_value=1.0,
off_value=0.0, dtype=tf.float32, name=None):
"""One hot operation.
TODO(noam): Is there a good reason we need a special mtf.Operation here?
We could just use some code like this:
cast(equal(indices, mtf_range(indices.mesh, output_dim, dtype=indices.dty... |
python | def drop_tips(self, names=None, wildcard=None, regex=None):
"""
Returns a copy of the tree with the selected tips removed. The entered
value can be a name or list of names. To prune on an internal node to
create a subtree see the .prune() function instead.
Parameters:
ti... |
java | private float[] LABtoXYZ(float L, float a, float b, float[] xyzResult) {
// Significant speedup: Removing Math.pow
float y = (L + 16.0f) / 116.0f;
float y3 = y * y * y; // Math.pow(y, 3.0);
float x = (a / 500.0f) + y;
float x3 = x * x * x; // Math.pow(x, 3.0);
float z = y... |
python | def _gridmake2(x1, x2):
"""
Expands two vectors (or matrices) into a matrix where rows span the
cartesian product of combinations of the input arrays. Each column of the
input arrays will correspond to one column of the output matrix.
Parameters
----------
x1 : np.ndarray
First vec... |
java | protected void createSamplePoints(int numSamples) {
for( int y = 0; y < numSamples; y++ ) {
float regionY = (y/(numSamples-1.0f) - 0.5f);
for( int x = 0; x < numSamples; x++ ) {
float regionX = (x/(numSamples-1.0f) - 0.5f);
samplePts.add( new Point2D_F32(regionX,regionY));
}
}
} |
java | public void getPresenter(final Consumer<Object> presenterConsumer) {
presenterProperty.addListener(
(final ObservableValue<? extends Object> o, final Object oldValue, final Object newValue) -> {
presenterConsumer.accept(newValue);
});
} |
java | public synchronized FhirValidator setValidateAgainstStandardSchematron(boolean theValidateAgainstStandardSchematron) {
if (theValidateAgainstStandardSchematron && !ourPhPresentOnClasspath) {
throw new IllegalArgumentException(myContext.getLocalizer().getMessage(I18N_KEY_NO_PH_ERROR));
}
if (!theValidateAgainst... |
python | def upload_file(self, filepath, key):
"""Uploads a file using the passed S3 key
This method uploads a file specified by the filepath to S3
using the provided S3 key.
:param filepath: (str) Full path to the file to be uploaded
:param key: (str) S3 key to be set for the upload
... |
python | def chk_qualifiers(self):
"""Check format of qualifier"""
if self.name == 'id2gos':
return
for ntd in self.associations:
# print(ntd)
qual = ntd.Qualifier
assert isinstance(qual, set), '{NAME}: QUALIFIER MUST BE A LIST: {NT}'.format(
... |
python | def lfu_cache(max_size=128):
"""
Least Frequently Used cache decorator, implementing :class:`faste.caches.LFUCache`
:keyword max_size: max cache size
"""
def actual_decorator(func):
return _cached_func(func, caches.LFUCache, max_size)
return actual_decorator |
python | def read_list_from_csv(filepath, dict_form=False, headers=None, **kwargs):
# type: (str, bool, Union[int, List[int], List[str], None], Any) -> List[Union[Dict, List]]
"""Read a list of rows in dict or list form from a csv. (The headers argument is either a row
number or list of row numbers (in case of mu... |
python | def Rz(rads: Union[float, sympy.Basic]) -> ZPowGate:
"""Returns a gate with the matrix e^{-i Z rads / 2}."""
pi = sympy.pi if protocols.is_parameterized(rads) else np.pi
return ZPowGate(exponent=rads / pi, global_shift=-0.5) |
python | def QA_SU_save_option_min(client=DATABASE, ui_log=None, ui_progress=None):
'''
:param client:
:return:
'''
option_contract_list = QA_fetch_get_option_contract_time_to_market()
coll_option_min = client.option_day_min
coll_option_min.create_index(
[("code",
pymongo.ASCENDING)... |
java | int at(int n) throws
IOException
{
Mark mark = mark();
List<Integer> cbuf = Lists.newArrayList();
for (int i = 0; i < n; i++)
{
cbuf.add(next());
if (curChar == -1)
{
break;
}
}
unread(cbuf, mark);
return cbuf.get(cbuf.size() - 1);
} |
java | public static MutableDoubleTuple arithmeticMean(
Collection<? extends DoubleTuple> tuples,
MutableDoubleTuple result)
{
if (tuples.isEmpty())
{
return null;
}
result = add(tuples, result);
return DoubleTuples.multiply(result, 1.0 / tuples.... |
java | @Override
public InetAddress getHostAddress(Object endPoint)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "getHostAddress", endPoint);
InetAddress address = null;
if (endPoint instanceof CFEndPoint)
{
address = ... |
python | def sto(zeta,N=1,L=0,M=0,origin=(0,0,0)):
"""
Use Stewarts STO-6G fits to create a contracted Gaussian approximation to a
Slater function. Fits of other expansion lengths (1G, 3G, etc) are in the paper.
Reference: RF Stewart, JCP 52, 431 (1970)
>>> s = sto(1)
>>> np.isclose(s(0,0,0),0.530121)
... |
python | def createLabels2D(self):
""" 2D labeling at zmax """
logger.debug(" Creating 2D labels...")
self.zmax = np.argmax(self.values,axis=1)
self.vmax = self.values[np.arange(len(self.pixels),dtype=int),self.zmax]
kwargs=dict(pixels=self.pixels,values=self.vmax,nside=self.nside,
... |
python | def lookup_controller(obj, remainder, request=None):
'''
Traverses the requested url path and returns the appropriate controller
object, including default routes.
Handles common errors gracefully.
'''
if request is None:
warnings.warn(
(
"The function signatu... |
java | public void marshall(DestinationSettings destinationSettings, ProtocolMarshaller protocolMarshaller) {
if (destinationSettings == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(destinationSettings.ge... |
java | @Check(CheckType.FAST)
public void checkDiscouragedCalls(XAbstractFeatureCall expression) {
if (!isIgnored(DISCOURAGED_REFERENCE)
&& this.featureCallValidator.isDiscouragedCall(expression)) {
addIssue(
MessageFormat.format(Messages.SARLValidator_37,
expression.getConcreteSyntaxFeatureName()),
... |
python | def new_metric(self, meta):
"""
Create and register metric,
find subscribers for this metric (using meta as filter) and subscribe
Return:
metric (available_metrics[0]): one of Metric
"""
type_ = meta.get('type')
if not type_:
raise ValueEr... |
python | def locate_arcgis():
'''
Find the path to the ArcGIS Desktop installation.
Keys to check:
HLKM/SOFTWARE/ESRI/ArcGIS 'RealVersion' - will give the version, then we can use
that to go to
HKLM/SOFTWARE/ESRI/DesktopXX.X 'InstallDir'. Where XX.X is the version
We may need to check HKLM/SOFTWARE/Wow6432Node/... |
python | def compress(self, setup):
"""
Returns the compressed graph according to the given experimental setup
Parameters
----------
setup : :class:`caspo.core.setup.Setup`
Experimental setup used to compress the graph
Returns
-------
caspo.core.graph... |
python | def api_token_required(f, *args, **kwargs):
"""
Decorator helper function to ensure some methods aren't needlessly called
without an api_token configured.
"""
try:
if args[0].api_token is None:
raise AttributeError('Parameter api_token is required.')
except AttributeError:
... |
java | public static String likePrefix(String param) {
return param != null ? param.toLowerCase().replace("_", "\\_").replace("%", "\\%") + "%" : null;
} |
java | @Override
final public void putAll(Map map) {
ValidateUtility.objectNotNull(map, "map");
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
put(e.getKey(), e.getValue());
}
} |
java | public void setFleetDetails(java.util.Collection<Fleet> fleetDetails) {
if (fleetDetails == null) {
this.fleetDetails = null;
return;
}
this.fleetDetails = new java.util.ArrayList<Fleet>(fleetDetails);
} |
java | private BitSet parseQuery(FilterQuery filterQuery, DataSchema schema) {
BitSet queryBitSet = new BitSet();
if(filterQuery instanceof MatchAllQuery || filterQuery.getFilterQueries().size() < 1) return queryBitSet;
//facet drill down happens here
for (String filterField : filterQuery.getF... |
java | public static String serializeAsString(Object o) throws IOException {
try {
JsonStructure builtJsonObject = findFieldsToSerialize(o).mainObject;
return builtJsonObject.toString();
} catch (IllegalStateException ise) {
// the reflective attempt to build the object fail... |
python | def on_okButton(self, event):
"""
Complies information input in GUI into a kwargs dictionary which can
be passed into the utrecht_magic script and run to output magic files
"""
os.chdir(self.WD)
options_dict = {}
wd = self.WD
options_dict['dir_path'] = wd
... |
java | public Matrix3x2f rotateTo(Vector2fc fromDir, Vector2fc toDir, Matrix3x2f dest) {
float dot = fromDir.x() * toDir.x() + fromDir.y() * toDir.y();
float det = fromDir.x() * toDir.y() - fromDir.y() * toDir.x();
float rm00 = dot;
float rm01 = det;
float rm10 = -det;
float rm1... |
python | def get_latex_figure_str(fpath_list, caption_str=None, label_str=None,
width_str=r'\textwidth', height_str=None, nCols=None,
dpath=None, colpos_sep=' ', nlsep='',
use_sublbls=None, use_frame=False):
r"""
Args:
fpath_list (list):
... |
java | public static <E, K extends Comparable> int binarySearch(
List<E> list,
Function<? super E, K> keyFunction,
@Nullable K key,
KeyPresentBehavior presentBehavior,
KeyAbsentBehavior absentBehavior) {
return binarySearch(
list, keyFunction, key, Ordering.natural(), presentBehavior,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.