language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def find_videos_by_show(self, show_id, show_videotype=None,
show_videostage=None, orderby='videoseq-asc',
page=1, count=20):
"""doc: http://open.youku.com/docs/doc?id=64
"""
url = 'https://openapi.youku.com/v2/shows/videos.json'
params = {
'client_id': self.client_id,
'show_id': show_id,
'page': page,
'count': count,
'show_videotype': show_videotype,
'show_videostage': show_videostage,
'orderby': orderby
}
params = remove_none_value(params)
r = requests.get(url, params=params)
check_error(r)
return r.json() |
python | def get_template_options():
"""
Returns a list of all templates that can be used for CMS pages.
The paths that are returned are relative to TURRENTINE_TEMPLATE_ROOT.
"""
template_root = turrentine_settings.TURRENTINE_TEMPLATE_ROOT
turrentine_dir = turrentine_settings.TURRENTINE_TEMPLATE_SUBDIR
output = []
for root, dirs, files in os.walk(turrentine_dir):
for file_name in files:
full_path = os.path.join(root, file_name)
relative_path = os.path.relpath(full_path, template_root)
output.append(relative_path)
return output |
python | def tell(self):
"""Return the file's current position.
Returns:
int, file's current position in bytes.
"""
self._check_open_file()
if self._flushes_after_tell():
self.flush()
if not self._append:
return self._io.tell()
if self._read_whence:
write_seek = self._io.tell()
self._io.seek(self._read_seek, self._read_whence)
self._read_seek = self._io.tell()
self._read_whence = 0
self._io.seek(write_seek)
return self._read_seek |
java | private static int getDay(Calendar cal, int dayOfWeek, int orderNum){
int day = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, day);
int lastWeekday = cal.get(Calendar.DAY_OF_WEEK);
int shift = lastWeekday >= dayOfWeek ? (lastWeekday - dayOfWeek) : (lastWeekday + 7 - dayOfWeek);
//find last dayOfWeek of this month
day -= shift;
if(orderNum < 0)
return day;
cal.set(Calendar.DAY_OF_MONTH, day);
int lastOrderNum = (cal.get(Calendar.DAY_OF_MONTH) - 1) / 7;
if(orderNum >= lastOrderNum)
return day;
return day - (lastOrderNum - orderNum) * 7;
} |
java | public static <T> EditableTextArea<T> of(final String id, final IModel<T> model,
final IModel<String> labelModel, final ModeContext modeContext)
{
final EditableTextArea<T> editableTextArea = new EditableTextArea<>(id, model, labelModel,
modeContext);
return editableTextArea;
} |
python | def _publish(
tgt,
fun,
arg=None,
tgt_type='glob',
returner='',
timeout=5,
form='clean',
wait=False,
via_master=None):
'''
Publish a command from the minion out to other minions, publications need
to be enabled on the Salt master and the minion needs to have permission
to publish the command. The Salt master will also prevent a recursive
publication loop, this means that a minion cannot command another minion
to command another minion as that would create an infinite command loop.
The arguments sent to the minion publish function are separated with
commas. This means that for a minion executing a command with multiple
args it will look like this::
salt system.example.com publish.publish '*' user.add 'foo,1020,1020'
CLI Example:
.. code-block:: bash
salt system.example.com publish.publish '*' cmd.run 'ls -la /tmp'
'''
if 'master_uri' not in __opts__:
log.error('Cannot run publish commands without a connection to a salt master. No command sent.')
return {}
if fun.startswith('publish.'):
log.info('Cannot publish publish calls. Returning {}')
return {}
arg = _parse_args(arg)
if via_master:
if 'master_uri_list' not in __opts__:
raise SaltInvocationError(message='Could not find list of masters \
in minion configuration but `via_master` was specified.')
else:
# Find the master in the list of master_uris generated by the minion base class
matching_master_uris = [master for master in __opts__['master_uri_list']
if '//{0}:'.format(via_master) in master]
if not matching_master_uris:
raise SaltInvocationError('Could not find match for {0} in \
list of configured masters {1} when using `via_master` option'.format(
via_master, __opts__['master_uri_list']))
if len(matching_master_uris) > 1:
# If we have multiple matches, consider this a non-fatal error
# and continue with whatever we found first.
log.warning('The `via_master` flag found '
'more than one possible match found for %s when '
'evaluating list %s',
via_master, __opts__['master_uri_list'])
master_uri = matching_master_uris.pop()
else:
# If no preference is expressed by the user, just publish to the first master
# in the list.
master_uri = __opts__['master_uri']
log.info('Publishing \'%s\' to %s', fun, master_uri)
auth = salt.crypt.SAuth(__opts__)
tok = auth.gen_token(b'salt')
load = {'cmd': 'minion_pub',
'fun': fun,
'arg': arg,
'tgt': tgt,
'tgt_type': tgt_type,
'ret': returner,
'tok': tok,
'tmo': timeout,
'form': form,
'id': __opts__['id'],
'no_parse': __opts__.get('no_parse', [])}
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master_uri)
try:
try:
peer_data = channel.send(load)
except SaltReqTimeoutError:
return '\'{0}\' publish timed out'.format(fun)
if not peer_data:
return {}
# CLI args are passed as strings, re-cast to keep time.sleep happy
if wait:
loop_interval = 0.3
matched_minions = set(peer_data['minions'])
returned_minions = set()
loop_counter = 0
while returned_minions ^ matched_minions:
load = {'cmd': 'pub_ret',
'id': __opts__['id'],
'tok': tok,
'jid': peer_data['jid']}
ret = channel.send(load)
returned_minions = set(ret.keys())
end_loop = False
if returned_minions >= matched_minions:
end_loop = True
elif (loop_interval * loop_counter) > timeout:
# This may be unnecessary, but I am paranoid
if not returned_minions:
return {}
end_loop = True
if end_loop:
if form == 'clean':
cret = {}
for host in ret:
cret[host] = ret[host]['ret']
return cret
else:
return ret
loop_counter = loop_counter + 1
time.sleep(loop_interval)
else:
time.sleep(float(timeout))
load = {'cmd': 'pub_ret',
'id': __opts__['id'],
'tok': tok,
'jid': peer_data['jid']}
ret = channel.send(load)
if form == 'clean':
cret = {}
for host in ret:
cret[host] = ret[host]['ret']
return cret
else:
return ret
finally:
channel.close()
return {} |
python | def take_screen_shot_to_array(self, screen_id, width, height, bitmap_format):
"""Takes a guest screen shot of the requested size and format
and returns it as an array of bytes.
in screen_id of type int
The guest monitor to take screenshot from.
in width of type int
Desired image width.
in height of type int
Desired image height.
in bitmap_format of type :class:`BitmapFormat`
The requested format.
return screen_data of type str
Array with resulting screen data.
"""
if not isinstance(screen_id, baseinteger):
raise TypeError("screen_id can only be an instance of type baseinteger")
if not isinstance(width, baseinteger):
raise TypeError("width can only be an instance of type baseinteger")
if not isinstance(height, baseinteger):
raise TypeError("height can only be an instance of type baseinteger")
if not isinstance(bitmap_format, BitmapFormat):
raise TypeError("bitmap_format can only be an instance of type BitmapFormat")
screen_data = self._call("takeScreenShotToArray",
in_p=[screen_id, width, height, bitmap_format])
return screen_data |
java | private static int searchLocal(
long localSecs,
ZonalTransition[] transitions
) {
int low = 0;
int high = transitions.length - 1;
while (low <= high) {
int middle = (low + high) / 2;
ZonalTransition zt = transitions[middle];
int offset = Math.max(zt.getTotalOffset(), zt.getPreviousOffset());
if (zt.getPosixTime() + offset <= localSecs) {
low = middle + 1;
} else {
high = middle - 1;
}
}
return low;
} |
python | def searchString( self, instring, maxMatches=_MAX_INT ):
"""
Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
cap_word = Word(alphas.upper(), alphas.lower())
print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))
# the sum() builtin can be used to merge results into a single ParseResults object
print(sum(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")))
prints::
[['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]
['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']
"""
try:
return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc |
python | def call_no_reply(self, fn, *args, **kwargs):
"""
See :meth:`CallChain.call_no_reply`.
"""
self.default_call_chain.call_no_reply(fn, *args, **kwargs) |
python | def lipid_box(self):
"""The box containing all of the lipids. """
if self._lipid_box:
return self._lipid_box
else:
self._lipid_box = self.lipid_components.boundingbox
# Add buffer around lipid box.
self._lipid_box.mins -= np.array([0.5*np.sqrt(self.apl),
0.5*np.sqrt(self.apl),
0.5*np.sqrt(self.apl)])
self._lipid_box.maxs += np.array([0.5*np.sqrt(self.apl),
0.5*np.sqrt(self.apl),
0.5*np.sqrt(self.apl)])
return self._lipid_box |
python | def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = super(LiveCapture, self).get_parameters(packet_count=packet_count)
# Read from STDIN
params += ['-r', '-']
return params |
java | public TreeSet<String> getParamNameSet(HtmlParameter.Type type) {
TreeSet<String> set = new TreeSet<>();
Map<String, String> paramMap = Model.getSingleton().getSession().getParams(this, type);
for (Entry<String, String> param : paramMap.entrySet()) {
set.add(param.getKey());
}
return set;
} |
python | def get_page(self, page_number):
"""
:param page_number: The page number to fetch (1-indexed)
:return: The requested page fetched from the API for the query
"""
if page_number:
kwargs = dict(self._list_kwargs)
kwargs['limit'] = self.limit
kwargs['page'] = page_number
return self._controller.list(**kwargs) |
java | @Override
public Map<String, String> getAllMessages(Locale... locales) {
Map<String, String> messages = new HashMap<>();
List<I18nExtension> extensionForLocale;
for (Locale locale : locales) {
extensionForLocale = getExtension(locale);
for (I18nExtension extension : extensionForLocale) {
merge(messages, extension.map());
}
}
// Now add the messages for the default locale
extensionForLocale = getExtension(DEFAULT_LOCALE);
for (I18nExtension extension : extensionForLocale) {
merge(messages, extension.map());
}
return messages;
} |
python | def start(self):
""" Starts the watchdog timer. """
self._timer = Timer(self.time, self.handler)
self._timer.daemon = True
self._timer.start()
return |
python | def newton_iterate(evaluate_fn, s, t):
r"""Perform a Newton iteration.
In this function, we assume that :math:`s` and :math:`t` are nonzero,
this makes convergence easier to detect since "relative error" at
``0.0`` is not a useful measure.
There are several tolerance / threshold quantities used below:
* :math:`10` (:attr:`MAX_NEWTON_ITERATIONS`) iterations will be done before
"giving up". This is based on the assumption that we are already starting
near a root, so quadratic convergence should terminate quickly.
* :math:`\tau = \frac{1}{4}` is used as the boundary between linear
and superlinear convergence. So if the current error
:math:`\|p_{n + 1} - p_n\|` is not smaller than :math:`\tau` times
the previous error :math:`\|p_n - p_{n - 1}\|`, then convergence
is considered to be linear at that point.
* :math:`\frac{2}{3}` of all iterations must be converging linearly
for convergence to be stopped (and moved to the next regime). This
will only be checked after 4 or more updates have occurred.
* :math:`\tau = 2^{-42}` (:attr:`NEWTON_ERROR_RATIO`) is used to
determine that an update is sufficiently small to stop iterating. So if
the error :math:`\|p_{n + 1} - p_n\|` smaller than :math:`\tau` times
size of the term being updated :math:`\|p_n\|`, then we
exit with the "correct" answer.
It is assumed that ``evaluate_fn`` will use a Jacobian return value of
:data:`None` to indicate that :math:`F(s, t)` is exactly ``0.0``. We
**assume** that if the function evaluates to exactly ``0.0``, then we are
at a solution. It is possible however, that badly parameterized curves
can evaluate to exactly ``0.0`` for inputs that are relatively far away
from a solution (see issue #21).
Args:
evaluate_fn (Callable[Tuple[float, float], tuple]): A callable
which takes :math:`s` and :math:`t` and produces an evaluated
function value and the Jacobian matrix.
s (float): The (first) parameter where the iteration will start.
t (float): The (second) parameter where the iteration will start.
Returns:
Tuple[bool, float, float]: The triple of
* Flag indicating if the iteration converged.
* The current :math:`s` value when the iteration stopped.
* The current :math:`t` value when the iteration stopped.
"""
# Several quantities will be tracked throughout the iteration:
# * norm_update_prev: ||p{n} - p{n-1}|| = ||dp{n-1}||
# * norm_update : ||p{n+1} - p{n} || = ||dp{n} ||
# * linear_updates : This is a count on the number of times that
# ``dp{n}`` "looks like" ``dp{n-1}`` (i.e.
# is within a constant factor of it).
norm_update_prev = None
norm_update = None
linear_updates = 0 # Track the number of "linear" updates.
current_s = s
current_t = t
for index in six.moves.xrange(MAX_NEWTON_ITERATIONS):
jacobian, func_val = evaluate_fn(current_s, current_t)
if jacobian is None:
return True, current_s, current_t
singular, delta_s, delta_t = _helpers.solve2x2(
jacobian, func_val[:, 0]
)
if singular:
break
norm_update_prev = norm_update
norm_update = np.linalg.norm([delta_s, delta_t], ord=2)
# If ||p{n} - p{n-1}|| > 0.25 ||p{n-1} - p{n-2}||, then that means
# our convergence is acting linear at the current step.
if index > 0 and norm_update > 0.25 * norm_update_prev:
linear_updates += 1
# If ``>=2/3`` of the updates have been linear, we are near a
# non-simple root. (Make sure at least 5 updates have occurred.)
if index >= 4 and 3 * linear_updates >= 2 * index:
break
# Determine the norm of the "old" solution before updating.
norm_soln = np.linalg.norm([current_s, current_t], ord=2)
current_s -= delta_s
current_t -= delta_t
if norm_update < NEWTON_ERROR_RATIO * norm_soln:
return True, current_s, current_t
return False, current_s, current_t |
python | def find(objs, selector, context=None):
''' Query a collection of Bokeh models and yield any that match the
a selector.
Args:
obj (Model) : object to test
selector (JSON-like) : query selector
context (dict) : kwargs to supply callable query attributes
Yields:
Model : objects that match the query
Queries are specified as selectors similar to MongoDB style query
selectors, as described for :func:`~bokeh.core.query.match`.
Examples:
.. code-block:: python
# find all objects with type Grid
find(p.references(), {'type': Grid})
# find all objects with type Grid or Axis
find(p.references(), {OR: [
{'type': Grid}, {'type': Axis}
]})
# same query, using IN operator
find(p.references(), {'type': {IN: [Grid, Axis]}})
# find all plot objects on the 'left' layout of the Plot
# here layout is a method that takes a plot as context
find(p.references(), {'layout': 'left'}, {'plot': p})
'''
return (obj for obj in objs if match(obj, selector, context)) |
python | def poll_error(self):
"""
Append lines from stderr to self.errors.
Returns:
list: The lines added since last call
"""
if self.block:
return self.error
new_list = self.error[self.old_error_size:]
self.old_error_size += len(new_list)
return new_list |
python | def _rows_page_start(iterator, page, response):
"""Grab total rows when :class:`~google.cloud.iterator.Page` starts.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type page: :class:`~google.api_core.page_iterator.Page`
:param page: The page that was just created.
:type response: dict
:param response: The JSON API response for a page of rows in a table.
"""
total_rows = response.get("totalRows")
if total_rows is not None:
total_rows = int(total_rows)
iterator._total_rows = total_rows |
java | public static Part<File> file(String name, String fileName, File file) {
return new Part<>(name, fileName, file, ContentTypes.probeContentType(file), null, (body, out, charset) -> {
try (InputStream in = new FileInputStream(body)) {
InputStreams.transferTo(in, out);
}
});
} |
java | public static void twoLoopHp(Vec x_grad, List<Double> rho, List<Vec> s, List<Vec> y, Vec q, double[] alphas)
{
//q ← ∇ fk;
x_grad.copyTo(q);
if(s.isEmpty())
return;//identity, we are done
//for i = k−1,k−2,...,k−m
for(int i = 0; i < s.size(); i++)
{
Vec s_i = s.get(i);
Vec y_i = y.get(i);
double alpha_i = alphas[i] = rho.get(i)*s_i.dot(q);
q.mutableSubtract(alpha_i, y_i);
}
//r ← Hk0q; and see eq (7.20), done in place in q
q.mutableMultiply(s.get(0).dot(y.get(0))/y.get(0).dot(y.get(0)));
//for i = k−m,k−m+1,...,k−1
for(int i = s.size()-1; i >= 0; i--)
{
//β ← ρ_i y_i^T r ;
double beta = rho.get(i)*y.get(i).dot(q);
//r ← r + si (αi − β)
q.mutableAdd(alphas[i]-beta, s.get(i));
}
} |
python | def make_dict_config(graph):
"""
Build a dictionary configuration from conventions and configuration.
"""
formatters = {}
handlers = {}
loggers = {}
# create the console handler
formatters["ExtraFormatter"] = make_extra_console_formatter(graph)
handlers["console"] = make_stream_handler(graph, formatter="ExtraFormatter")
# maybe create the loggly handler
if enable_loggly(graph):
formatters["JSONFormatter"] = make_json_formatter(graph)
handlers["LogglyHTTPSHandler"] = make_loggly_handler(graph, formatter="JSONFormatter")
# configure the root logger to output to all handlers
loggers[""] = {
"handlers": handlers.keys(),
"level": graph.config.logging.level,
}
# set log levels for libraries
loggers.update(make_library_levels(graph))
return dict(
version=1,
disable_existing_loggers=False,
formatters=formatters,
handlers=handlers,
loggers=loggers,
) |
java | public void setDeclType(int declType) {
if (!(declType == Token.FUNCTION
|| declType == Token.LP
|| declType == Token.VAR
|| declType == Token.LET
|| declType == Token.CONST))
throw new IllegalArgumentException("Invalid declType: " + declType);
this.declType = declType;
} |
python | def run(command):
'''
Run command in shell, accepts command construction from list
Return (return_code, stdout, stderr)
stdout and stderr - as list of strings
'''
if isinstance(command, list):
command = ' '.join(command)
out = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return (out.returncode, _prepare(out.stdout), _prepare(out.stderr)) |
python | def IsAllSpent(self):
"""
Flag indicating if all balance is spend.
Returns:
bool:
"""
for item in self.Items:
if item == CoinState.Confirmed:
return False
return True |
python | def plot_throat(self, throats, fig=None):
r"""
Plot a throat or list of throats in 2D showing key data
Parameters
----------
throats : list or array containing throat indices tp include in figure
fig : matplotlib figure object to place plot in
"""
throat_list = []
for throat in throats:
if throat in range(self.num_throats()):
throat_list.append(throat)
else:
logger.warn('Throat: ' + str(throat) + ' not part of geometry')
if len(throat_list) > 0:
verts = self['throat.vertices'][throat_list]
offsets = self['throat.offset_vertices'][throat_list]
normals = self['throat.normal'][throat_list]
coms = self['throat.centroid'][throat_list]
incentre = self['throat.incenter'][throat_list]
inradius = 0.5*self['throat.indiameter'][throat_list]
row_col = np.ceil(np.sqrt(len(throat_list)))
for i in range(len(throat_list)):
if fig is None:
fig = plt.figure()
ax = fig.add_subplot(row_col, row_col, i+1)
vert_2D = self._rotate_and_chop(verts[i], normals[i],
[0, 0, 1])
hull = ConvexHull(vert_2D, qhull_options='QJ Pp')
for simplex in hull.simplices:
plt.plot(vert_2D[simplex, 0], vert_2D[simplex, 1], 'k-',
linewidth=2)
plt.scatter(vert_2D[:, 0], vert_2D[:, 1])
offset_2D = self._rotate_and_chop(offsets[i], normals[i],
[0, 0, 1])
offset_hull = ConvexHull(offset_2D, qhull_options='QJ Pp')
for simplex in offset_hull.simplices:
plt.plot(offset_2D[simplex, 0], offset_2D[simplex, 1],
'g-', linewidth=2)
plt.scatter(offset_2D[:, 0], offset_2D[:, 1])
# Make sure the plot looks nice by finding the greatest
# range of points and setting the plot to look square
xmax = vert_2D[:, 0].max()
xmin = vert_2D[:, 0].min()
ymax = vert_2D[:, 1].max()
ymin = vert_2D[:, 1].min()
x_range = xmax - xmin
y_range = ymax - ymin
if (x_range > y_range):
my_range = x_range
else:
my_range = y_range
lower_bound_x = xmin - my_range*0.5
upper_bound_x = xmin + my_range*1.5
lower_bound_y = ymin - my_range*0.5
upper_bound_y = ymin + my_range*1.5
plt.axis((lower_bound_x, upper_bound_x, lower_bound_y,
upper_bound_y))
plt.grid(b=True, which='major', color='b', linestyle='-')
centroid = self._rotate_and_chop(coms[i], normals[i],
[0, 0, 1])
incent = self._rotate_and_chop(incentre[i], normals[i],
[0, 0, 1])
plt.scatter(centroid[0][0], centroid[0][1])
plt.scatter(incent[0][0], incent[0][1], c='r')
# Plot incircle
t = np.linspace(0, 2*np.pi, 200)
u = inradius[i]*np.cos(t)+incent[0][0]
v = inradius[i]*np.sin(t)+incent[0][1]
plt.plot(u, v, 'r-')
ax.ticklabel_format(style='sci', scilimits=(0, 0))
else:
logger.error("Please provide throat indices")
return fig |
java | private void resizeSemiUnique(int newCapacity)
{
SemiUniqueEntry[] oldTable = getNonDatedTable();
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
semiUniqueThreshold = Integer.MAX_VALUE;
return;
}
SemiUniqueEntry[] newTable = new SemiUniqueEntry[newCapacity];
transferSemiUnique(oldTable, newTable);
nonDatedTable = newTable;
/*
* If ignoring null elements and processing ref queue caused massive
* shrinkage, then restore old nonDatedTable. This should be rare, but avoids
* unbounded expansion of garbage-filled tables.
*/
if (nonDatedEntryCount >= semiUniqueThreshold / 2) {
semiUniqueThreshold = (int)(newCapacity * loadFactor);
} else {
expungeStaleEntries();
transferSemiUnique(newTable, oldTable);
nonDatedTable = oldTable;
}
} |
java | public ImmutableList<Symbol> getFileAsSymbolList(String param) throws IOException {
return FileUtils.loadSymbolList(Files.asCharSource(getExistingFile(param), Charsets.UTF_8));
} |
python | def fun_residuals(params, xnor, ynor, w, bbox, k, ext):
"""Compute fit residuals"""
spl = LSQUnivariateSpline(
x=xnor,
y=ynor,
t=[item.value for item in params.values()],
w=w,
bbox=bbox,
k=k,
ext=ext,
check_finite=False
)
return spl.get_residual() |
java | public void onPartCreate(PartCreationEvent event) {
final File part = event.getPart();
final UploadPartRequest reqUploadPart =
newUploadPartRequest(event, part);
final OnFileDelete fileDeleteObserver = event.getFileDeleteObserver();
appendUserAgent(reqUploadPart, AmazonS3EncryptionClient.USER_AGENT);
futures.add(es.submit(new Callable<UploadPartResult>() {
@Override public UploadPartResult call() {
// Upload the ciphertext directly via the non-encrypting
// s3 client
try {
return uploadPart(reqUploadPart);
} finally {
// clean up part already uploaded
if (!part.delete()) {
LogFactory.getLog(getClass()).debug(
"Ignoring failure to delete file " + part
+ " which has already been uploaded");
} else {
if (fileDeleteObserver != null)
fileDeleteObserver.onFileDelete(null);
}
}
}
}));
} |
python | def gen_version(do_write=True, txt=None):
"""
Generate a version based on git tag info. This will write the
couchbase/_version.py file. If not inside a git tree it will
raise a CantInvokeGit exception - which is normal
(and squashed by setup.py) if we are running from a tarball
"""
if txt is None:
txt = get_git_describe()
try:
info = VersionInfo(txt)
vstr = info.package_version
except MalformedGitTag:
warnings.warn("Malformed input '{0}'".format(txt))
vstr = '0.0.0'+txt
if not do_write:
print(vstr)
return
lines = (
'# This file automatically generated by',
'# {0}'.format(__file__),
'# at',
'# {0}'.format(datetime.datetime.now().isoformat(' ')),
"__version__ = '{0}'".format(vstr)
)
with open(VERSION_FILE, "w") as fp:
fp.write("\n".join(lines)) |
python | def completion_acd(edm, X0, W=None, tol=1e-6, sweeps=3):
""" Complete an denoise EDM using alternating decent.
The idea here is to simply run reconstruct_acd for a few iterations,
yieding a position estimate, which can in turn be used
to get a completed and denoised edm.
:param edm: noisy matrix (NxN)
:param X0: starting points (Nxd)
:param W: optional weight matrix.
:param tol: Stopping criterion of iterative algorithm.
:param sweeps: Maximum number of sweeps.
"""
from .algorithms import reconstruct_acd
Xhat, costs = reconstruct_acd(edm, X0, W, tol=tol, sweeps=sweeps)
return get_edm(Xhat) |
python | def _storage_init(self):
"""
Ensure that storage is initialized.
"""
if not self._storage.initialized:
self._storage.init(self._module._py3_wrapper, self._is_python_2) |
java | public static /*@pure@*/ int minIndex(int[] ints) {
int minimum = 0;
int minIndex = 0;
for (int i = 0; i < ints.length; i++) {
if ((i == 0) || (ints[i] < minimum)) {
minIndex = i;
minimum = ints[i];
}
}
return minIndex;
} |
python | def get_client_key_exchange_record(
cls,
robot_payload_enum: RobotPmsPaddingPayloadEnum,
tls_version: TlsVersionEnum,
modulus: int,
exponent: int
) -> TlsRsaClientKeyExchangeRecord:
"""A client key exchange record with a hardcoded pre_master_secret, and a valid or invalid padding.
"""
pms_padding = cls._compute_pms_padding(modulus)
tls_version_hex = binascii.b2a_hex(TlsRecordTlsVersionBytes[tls_version.name].value).decode('ascii')
pms_with_padding_payload = cls._CKE_PAYLOADS_HEX[robot_payload_enum]
final_pms = pms_with_padding_payload.format(
pms_padding=pms_padding, tls_version=tls_version_hex, pms=cls._PMS_HEX
)
cke_robot_record = TlsRsaClientKeyExchangeRecord.from_parameters(
tls_version, exponent, modulus, int(final_pms, 16)
)
return cke_robot_record |
java | public Observable<ServiceResponse<CertificatePolicy>> getCertificatePolicyWithServiceResponseAsync(String vaultBaseUrl, String certificateName) {
if (vaultBaseUrl == null) {
throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null.");
}
if (certificateName == null) {
throw new IllegalArgumentException("Parameter certificateName is required and cannot be null.");
}
if (this.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null.");
}
String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl);
return service.getCertificatePolicy(certificateName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<CertificatePolicy>>>() {
@Override
public Observable<ServiceResponse<CertificatePolicy>> call(Response<ResponseBody> response) {
try {
ServiceResponse<CertificatePolicy> clientResponse = getCertificatePolicyDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} |
python | def project_top_dir(self, *args) -> str:
""" Project top-level directory """
return os.path.join(self.project_dir, *args) |
java | public boolean hasDiscriminator() {
boolean hasDiscriminator = false;
for (Entry<String, String> entry : _inputs.entrySet()) {
String key = entry.getKey();
if (StagingData.STANDARD_LOOKUP_KEYS.contains(key))
continue;
String value = entry.getValue();
if (value != null && !value.isEmpty()) {
hasDiscriminator = true;
break;
}
}
return hasDiscriminator;
} |
java | private static String urlencode(
final String content,
final Charset charset,
final BitSet safechars,
final boolean blankAsPlus) {
if (content == null) {
return null;
}
StringBuilder buf = new StringBuilder();
ByteBuffer bb = charset.encode(content);
while (bb.hasRemaining()) {
int b = bb.get() & 0xff;
if (safechars.get(b)) {
buf.append((char) b);
} else if (blankAsPlus && b == ' ') {
buf.append('+');
} else {
buf.append("%");
char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX));
char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX));
buf.append(hex1);
buf.append(hex2);
}
}
return buf.toString();
} |
java | @JRubyMethod
public static IRubyObject yaml_initialize(IRubyObject self, IRubyObject klass, IRubyObject ivars) {
((RubyObject)self).fastSetInstanceVariable("@class", klass);
((RubyObject)self).fastSetInstanceVariable("@ivars", ivars);
return self;
} |
python | def get_distribute_verbatim_metadata(self):
"""Gets the metadata for the distribute verbatim rights flag.
return: (osid.Metadata) - metadata for the distribution rights
fields
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template
metadata = dict(self._mdata['distribute_verbatim'])
metadata.update({'existing_boolean_values': self._my_map['distributeVerbatim']})
return Metadata(**metadata) |
java | public void marshall(FulfillmentActivity fulfillmentActivity, ProtocolMarshaller protocolMarshaller) {
if (fulfillmentActivity == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(fulfillmentActivity.getType(), TYPE_BINDING);
protocolMarshaller.marshall(fulfillmentActivity.getCodeHook(), CODEHOOK_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | @SuppressWarnings("SameParameterValue")
private int getStatusCode(final byte[] response, final int request) throws UnknownResponseException {
if (response == null || response.length < 3 || response[0] != OP_CODE_RESPONSE_CODE_KEY || response[1] != request ||
(response[2] != DFU_STATUS_SUCCESS && response[2] != SecureDfuError.BUTTONLESS_ERROR_OP_CODE_NOT_SUPPORTED
&& response[2] != SecureDfuError.BUTTONLESS_ERROR_OPERATION_FAILED))
throw new UnknownResponseException("Invalid response received", response, OP_CODE_RESPONSE_CODE_KEY, request);
return response[2];
} |
java | public StartExportTaskRequest withExportDataFormat(String... exportDataFormat) {
if (this.exportDataFormat == null) {
setExportDataFormat(new java.util.ArrayList<String>(exportDataFormat.length));
}
for (String ele : exportDataFormat) {
this.exportDataFormat.add(ele);
}
return this;
} |
python | def has_started(self):
"""Tests if this assessment has begun.
return: (boolean) - ``true`` if the assessment has begun,
``false`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
assessment_offered = self.get_assessment_offered()
if assessment_offered.has_start_time():
return DateTime.utcnow() >= assessment_offered.get_start_time()
else:
return True |
java | @Override
public Object processTask(String taskName, Map<String, String[]> parameterMap) {
if ("createAdmin".equalsIgnoreCase(taskName)) {
return userService.createDefaultAdmin();
}
return null;
} |
java | public Observable<ServiceResponse<Page<DatabaseInner>>> listByElasticPoolNextWithServiceResponseAsync(final String nextPageLink) {
return listByElasticPoolNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<DatabaseInner>>, Observable<ServiceResponse<Page<DatabaseInner>>>>() {
@Override
public Observable<ServiceResponse<Page<DatabaseInner>>> call(ServiceResponse<Page<DatabaseInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByElasticPoolNextWithServiceResponseAsync(nextPageLink));
}
});
} |
java | public void aget(Local<?> target, Local<?> array, Local<Integer> index) {
addInstruction(new ThrowingInsn(Rops.opAget(target.type.ropType), sourcePosition,
RegisterSpecList.make(array.spec(), index.spec()), catches));
moveResult(target, true);
} |
java | public static void unitize1(double[] x) {
double n = norm1(x);
for (int i = 0; i < x.length; i++) {
x[i] /= n;
}
} |
python | def create_response(
self, data: dict = None, response: requests.Response = None, errors: list = None
) -> Response:
"""
Helper function to generate a :class:`~notifiers.core.Response` object
:param data: The data that was used to send the notification
:param response: :class:`requests.Response` if exist
:param errors: List of errors if relevant
"""
status = FAILURE_STATUS if errors else SUCCESS_STATUS
return Response(
status=status,
provider=self.name,
data=data,
response=response,
errors=errors,
) |
java | public void setTeamMembers(java.util.Collection<TeamMember> teamMembers) {
if (teamMembers == null) {
this.teamMembers = null;
return;
}
this.teamMembers = new java.util.ArrayList<TeamMember>(teamMembers);
} |
java | public static InputStream getStream (String path, ClassLoader loader)
{
// first try the supplied class loader
InputStream in = getResourceAsStream(path, loader);
if (in != null) {
return in;
}
// if that didn't work, try the system class loader (but only if it's different from the
// class loader we just tried)
try {
ClassLoader sysloader = ClassLoader.getSystemClassLoader();
if (sysloader != loader) {
return getResourceAsStream(path, loader);
}
} catch (AccessControlException ace) {
// can't get the system loader, no problem!
}
return null;
} |
java | private void processDependencies()
throws MojoExecutionException
{
processDependency( getProject().getArtifact() );
AndArtifactFilter filter = new AndArtifactFilter();
// filter.add( new ScopeArtifactFilter( dependencySet.getScope() ) );
if ( dependencies != null && dependencies.getIncludes() != null && !dependencies.getIncludes().isEmpty() )
{
filter.add( new IncludesArtifactFilter( dependencies.getIncludes() ) );
}
if ( dependencies != null && dependencies.getExcludes() != null && !dependencies.getExcludes().isEmpty() )
{
filter.add( new ExcludesArtifactFilter( dependencies.getExcludes() ) );
}
Collection<Artifact> artifacts =
isExcludeTransitive() ? getProject().getDependencyArtifacts() : getProject().getArtifacts();
for ( Artifact artifact : artifacts )
{
if ( filter.include( artifact ) )
{
processDependency( artifact );
}
}
} |
python | def bitmap2RRlist(bitmap):
"""
Decode the 'Type Bit Maps' field of the NSEC Resource Record into an
integer list.
"""
# RFC 4034, 4.1.2. The Type Bit Maps Field
RRlist = []
while bitmap:
if len(bitmap) < 2:
warning("bitmap too short (%i)" % len(bitmap))
return
#window_block = ord(bitmap[0]) # window number
window_block = (bitmap[0]) # window number
offset = 256*window_block # offset of the Ressource Record
#bitmap_len = ord(bitmap[0]) # length of the bitmap in bytes
bitmap_len = (bitmap[1]) # length of the bitmap in bytes
if bitmap_len <= 0 or bitmap_len > 32:
warning("bitmap length is no valid (%i)" % bitmap_len)
return
tmp_bitmap = bitmap[2:2+bitmap_len]
# Let's compare each bit of tmp_bitmap and compute the real RR value
for b in range(len(tmp_bitmap)):
v = 128
for i in range(8):
#if ord(tmp_bitmap[b]) & v:
if (tmp_bitmap[b]) & v:
# each of the RR is encoded as a bit
RRlist += [ offset + b*8 + i ]
v = v >> 1
# Next block if any
bitmap = bitmap[2+bitmap_len:]
return RRlist |
java | public T getBand(int band) {
if (band >= bands.length || band < 0)
throw new IllegalArgumentException("The specified band is out of bounds: "+band);
return bands[band];
} |
python | def _clean_fields(self):
"""
Overriding the default cleaning behaviour to exit early on errors
instead of validating each field.
"""
try:
super(OAuthForm, self)._clean_fields()
except OAuthValidationError, e:
self._errors.update(e.args[0]) |
java | private static CmsXmlContainerPage getCache(CmsObject cms, CmsResource resource, boolean keepEncoding) {
if (resource instanceof I_CmsHistoryResource) {
return null;
}
return getCache().getCacheContainerPage(
getCache().getCacheKey(resource.getStructureId(), keepEncoding),
cms.getRequestContext().getCurrentProject().isOnlineProject());
} |
java | public void marshall(DescribePlayerSessionsRequest describePlayerSessionsRequest, ProtocolMarshaller protocolMarshaller) {
if (describePlayerSessionsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describePlayerSessionsRequest.getGameSessionId(), GAMESESSIONID_BINDING);
protocolMarshaller.marshall(describePlayerSessionsRequest.getPlayerId(), PLAYERID_BINDING);
protocolMarshaller.marshall(describePlayerSessionsRequest.getPlayerSessionId(), PLAYERSESSIONID_BINDING);
protocolMarshaller.marshall(describePlayerSessionsRequest.getPlayerSessionStatusFilter(), PLAYERSESSIONSTATUSFILTER_BINDING);
protocolMarshaller.marshall(describePlayerSessionsRequest.getLimit(), LIMIT_BINDING);
protocolMarshaller.marshall(describePlayerSessionsRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def blog_following(self, blogname, **kwargs):
"""
Gets the publicly exposed list of blogs that a blog follows
:param blogname: the name of the blog you want to get information on.
eg: codingjester.tumblr.com
:param limit: an int, the number of blogs you want returned
:param offset: an int, the blog to start at, for pagination.
# Start at the 20th blog and get 20 more blogs.
client.blog_following('pytblr', offset=20, limit=20})
:returns: a dict created from the JSON response
"""
url = "/v2/blog/{}/following".format(blogname)
return self.send_api_request("get", url, kwargs, ['limit', 'offset']) |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.GSLJ__LINEJOIN:
return getLINEJOIN();
}
return super.eGet(featureID, resolve, coreType);
} |
python | def match_and(self, tokens, item):
"""Matches and."""
for match in tokens:
self.match(match, item) |
java | public Termination withCallingRegions(String... callingRegions) {
if (this.callingRegions == null) {
setCallingRegions(new java.util.ArrayList<String>(callingRegions.length));
}
for (String ele : callingRegions) {
this.callingRegions.add(ele);
}
return this;
} |
java | private synchronized void decreaseClientCount(Entry<K, V> entry) {
Preconditions.checkNotNull(entry);
Preconditions.checkState(entry.clientCount > 0);
entry.clientCount--;
} |
java | @Indexable(type = IndexableType.REINDEX)
@Override
public CommerceShippingFixedOption addCommerceShippingFixedOption(
CommerceShippingFixedOption commerceShippingFixedOption) {
commerceShippingFixedOption.setNew(true);
return commerceShippingFixedOptionPersistence.update(commerceShippingFixedOption);
} |
python | def get_valid_actions(self) -> List[Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]]:
"""
Returns a list of valid actions for each element of the group.
"""
return [state.get_valid_actions() for state in self.grammar_state] |
python | def _validate_nullable(self, nullable, field, value):
""" {'type': 'boolean'} """
if value is None:
if not nullable:
self._error(field, errors.NOT_NULLABLE)
self._drop_remaining_rules(
'allowed',
'empty',
'forbidden',
'items',
'keysrules',
'min',
'max',
'minlength',
'maxlength',
'regex',
'schema',
'type',
'valuesrules',
) |
python | def maps_re_apply_policy_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_re_apply_policy = ET.Element("maps_re_apply_policy")
config = maps_re_apply_policy
input = ET.SubElement(maps_re_apply_policy, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.text = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
python | def _fusion_to_json(self):
"""Convert this modification to a FUSION data dictionary.
Don't use this without checking ``self.type == FUSION`` first.
:rtype: dict
"""
if self.p5_reference:
range_5p = fusion_range(
reference=str(self.p5_reference),
start=int_or_str(self.p5_start),
stop=int_or_str(self.p5_stop),
)
else:
range_5p = missing_fusion_range()
if self.p3_reference:
range_3p = fusion_range(
reference=str(self.p3_reference),
start=int_or_str(self.p3_start),
stop=int_or_str(self.p3_stop),
)
else:
range_3p = missing_fusion_range()
return {
PARTNER_5P: self.p5_partner.to_json(), # just the identifier pair
PARTNER_3P: self.p3_partner.to_json(), # just the identifier pair
RANGE_5P: range_5p,
RANGE_3P: range_3p,
} |
java | public synchronized void startConsumers(Class<? extends Consumer> consumerClass) throws IOException {
List<ConsumerHolder> consumerHolderSubList = filterConsumersForClass(consumerClass);
enableConsumers(consumerHolderSubList);
} |
java | public JSONObject getLogs(int offset, int length) throws AlgoliaException {
return getLogs(offset, length, LogType.LOG_ALL);
} |
python | def tangential_component(data_x, data_y, index='index'):
r"""Obtain the tangential component of a cross-section of a vector field.
Parameters
----------
data_x : `xarray.DataArray`
The input DataArray of the x-component (in terms of data projection) of the vector
field.
data_y : `xarray.DataArray`
The input DataArray of the y-component (in terms of data projection) of the vector
field.
Returns
-------
component_tangential: `xarray.DataArray`
The component of the vector field in the tangential directions.
See Also
--------
cross_section_components, normal_component
Notes
-----
The coordinates of `data_x` and `data_y` must match.
"""
# Get the unit vectors
unit_tang, _ = unit_vectors_from_cross_section(data_x, index=index)
# Take the dot products
component_tang = data_x * unit_tang[0] + data_y * unit_tang[1]
# Reattach only reliable attributes after operation
for attr in ('units', 'grid_mapping'):
if attr in data_x.attrs:
component_tang.attrs[attr] = data_x.attrs[attr]
return component_tang |
java | public CreateLoadBalancerRequest withSubnetMappings(SubnetMapping... subnetMappings) {
if (this.subnetMappings == null) {
setSubnetMappings(new java.util.ArrayList<SubnetMapping>(subnetMappings.length));
}
for (SubnetMapping ele : subnetMappings) {
this.subnetMappings.add(ele);
}
return this;
} |
java | @Override
public void write(byte[] data, int offset, int length) throws IllegalStateException, IOException{
// validate state
if (isClosed()) {
throw new IllegalStateException("Serial connection is not open; cannot 'write()'.");
}
// write serial data to transmit buffer
com.pi4j.jni.Serial.write(fileDescriptor, data, offset, length);
} |
java | @Override
public boolean hasNext() {
boolean hasNext = bundlesIterator.hasNext();
if (null != currentBundle && null != currentBundle.getExplorerConditionalExpression())
commentCallbackHandler.closeConditionalComment();
return hasNext;
} |
java | public void setProvider(Object pObj) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "setProvider pre: pObj(class)=" + pObj.getClass() + " isProxy=" + Proxy.isProxyClass(pObj.getClass()) + " provider=" + (provider==null?"null":provider.getClass()) +
" oldProvider=" + (oldProvider==null?"null":oldProvider.getClass()));
}
this.oldProvider = this.provider;
this.provider = (T) pObj;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "setProvider post: provider=" + (provider==null?"null":provider.getClass()) +
" oldProvider=" + (oldProvider==null?"null":oldProvider.getClass()));
}
} |
java | public void output(PrintWriter out)
{
Map<String, Entry> entries = config.getSortedEntries();
if ( entries.isEmpty() )
{
return;
}
ColumnPrinter printer = build(entries);
out.println("Configuration Details");
printer.print(out);
} |
python | def from_lasio(cls, l, remap=None, funcs=None):
"""
Make a Location object from a lasio object. Assumes we're starting
with a lasio object, l.
Args:
l (lasio).
remap (dict): Optional. A dict of 'old': 'new' LAS field names.
funcs (dict): Optional. A dict of 'las field': function() for
implementing a transform before loading. Can be a lambda.
Returns:
Location. An instance of this class.
"""
params = {}
funcs = funcs or {}
funcs['location'] = str
for field, (sect, code) in las_fields['location'].items():
params[field] = utils.lasio_get(l,
sect,
code,
remap=remap,
funcs=funcs)
return cls(params) |
java | public DeploymentExportResultInner exportTemplate(String resourceGroupName, String deploymentName) {
return exportTemplateWithServiceResponseAsync(resourceGroupName, deploymentName).toBlocking().single().body();
} |
python | def _ExtractPathSpecsFromFileSystem(
self, path_spec, find_specs=None, recurse_file_system=True,
resolver_context=None):
"""Extracts path specification from a file system within a specific source.
Args:
path_spec (dfvfs.PathSpec): path specification of the root of
the file system.
find_specs (Optional[list[dfvfs.FindSpec]]): find specifications.
recurse_file_system (Optional[bool]): True if extraction should
recurse into a file system.
resolver_context (Optional[dfvfs.Context]): resolver context.
Yields:
dfvfs.PathSpec: path specification of a file entry found in
the file system.
"""
try:
file_system = path_spec_resolver.Resolver.OpenFileSystem(
path_spec, resolver_context=resolver_context)
except (
dfvfs_errors.AccessError, dfvfs_errors.BackEndError,
dfvfs_errors.PathSpecError) as exception:
logger.error(
'Unable to open file system with error: {0!s}'.format(exception))
return
try:
if find_specs:
searcher = file_system_searcher.FileSystemSearcher(
file_system, path_spec)
for extracted_path_spec in searcher.Find(find_specs=find_specs):
yield extracted_path_spec
elif recurse_file_system:
file_entry = file_system.GetFileEntryByPathSpec(path_spec)
if file_entry:
for extracted_path_spec in self._ExtractPathSpecsFromDirectory(
file_entry):
yield extracted_path_spec
else:
yield path_spec
except (
dfvfs_errors.AccessError, dfvfs_errors.BackEndError,
dfvfs_errors.PathSpecError) as exception:
logger.warning('{0!s}'.format(exception))
finally:
file_system.Close() |
java | @Override
public E remove(int index) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
E oldValue = get(elements, index);
int numMoved = len - index - 1;
if (numMoved == 0)
setArray(Arrays.copyOf(elements, len - 1));
else {
Object[] newElements = new Object[len - 1];
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index + 1, newElements, index,
numMoved);
setArray(newElements);
}
return oldValue;
} finally {
lock.unlock();
}
} |
java | static PublicKey
parseRecord(int alg, byte [] data) {
ByteArrayInputStream bytes = new ByteArrayInputStream(data);
DataInputStream in = new DataInputStream(bytes);
try {
switch (alg) {
case DNSSEC.RSAMD5:
case DNSSEC.RSASHA1:
case DNSSEC.RSA_NSEC3_SHA1:
return parseRSA(in);
case DNSSEC.DH:
return parseDH(in);
case DNSSEC.DSA:
case DNSSEC.DSA_NSEC3_SHA1:
return parseDSA(in);
default:
return null;
}
}
catch (IOException e) {
if (Options.check("verboseexceptions"))
System.err.println(e);
return null;
}
} |
python | def existingInStore(cls, store, storeID, attrs):
"""Create and return a new instance from a row from the store."""
self = cls.__new__(cls)
self.__justCreated = False
self.__subinit__(__store=store,
storeID=storeID,
__everInserted=True)
schema = self.getSchema()
assert len(schema) == len(attrs), "invalid number of attributes"
for data, (name, attr) in zip(attrs, schema):
attr.loaded(self, data)
self.activate()
return self |
java | public void addRemoveProduct(String source, String name, String value, boolean regex, Confidence confidence) {
removeProduct.add(new EvidenceMatcher(source, name, value, regex, confidence));
} |
java | private byte[] embiggen(byte[] b, int len) {
if (b == null || b.length < len) {
return new byte[len];
} else {
return b;
}
} |
java | public ArrayList<String> overTheBox_new_GET(String deviceId, String offer, String voucher) throws IOException {
String qPath = "/order/overTheBox/new";
StringBuilder sb = path(qPath);
query(sb, "deviceId", deviceId);
query(sb, "offer", offer);
query(sb, "voucher", voucher);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} |
python | def annotations(self, qname=True):
"""
wrapper that returns all triples for an onto.
By default resources URIs are transformed into qnames
"""
if qname:
return sorted([(uri2niceString(x, self.namespaces)
), (uri2niceString(y, self.namespaces)), z]
for x, y, z in self.triples)
else:
return sorted(self.triples) |
java | public List<Sentence> readString(String dataStr){
String [] lines = dataStr.split("\n");
List<Sentence> data = new ArrayList<Sentence>();
for (String line : lines){
Sentence sentence = new Sentence();
if (line.startsWith("#"))
continue;
StringTokenizer tk = new StringTokenizer(line, " ");
while (tk.hasMoreTokens()){
String word = "", tag = null;
if (!isTrainReading){
String token = tk.nextToken();
word = token;
sentence.addTWord(word, tag);
}
else {
String token = tk.nextToken();
StringTokenizer sltk = new StringTokenizer(token, "/");
word = sltk.nextToken();
tag = sltk.nextToken();
sentence.addTWord(word, tag);
}
}
data.add(sentence);
}
return data;
} |
java | @Override
public GetCommandInvocationResult getCommandInvocation(GetCommandInvocationRequest request) {
request = beforeClientExecution(request);
return executeGetCommandInvocation(request);
} |
java | public static @Nullable
String getSuffix(@NonNull View view) {
return suffixes.get(view.getId());
} |
python | def turbulent_Churchill_Zajic(Re, Pr, fd):
r'''Calculates internal convection Nusselt number for turbulent flows
in pipe according to [2]_ as developed in [1]_. Has yet to obtain
popularity.
.. math::
Nu = \left\{\left(\frac{Pr_T}{Pr}\right)\frac{1}{Nu_{di}} +
\left[1-\left(\frac{Pr_T}{Pr}\right)^{2/3}\right]\frac{1}{Nu_{D\infty}}
\right\}^{-1}
Nu_{di} = \frac{Re(f/8)}{1 + 145(8/f)^{-5/4}}
Nu_{D\infty} = 0.07343Re\left(\frac{Pr}{Pr_T}\right)^{1/3}(f/8)^{0.5}
Pr_T = 0.85 + \frac{0.015}{Pr}
Parameters
----------
Re : float
Reynolds number, [-]
Pr : float
Prandtl number, [-]
fd : float
Darcy friction factor [-]
Returns
-------
Nu : float
Nusselt number, [-]
Notes
-----
No restrictions on range. This is equation is developed with more
theoretical work than others.
Examples
--------
>>> turbulent_Churchill_Zajic(Re=1E5, Pr=1.2, fd=0.0185)
260.5564907817961
References
----------
.. [1] Churchill, Stuart W., and Stefan C. Zajic. “Prediction of Fully
Developed Turbulent Convection with Minimal Explicit Empiricism.”
AIChE Journal 48, no. 5 (May 1, 2002): 927–40. doi:10.1002/aic.690480503.
.. [2] Plawsky, Joel L. Transport Phenomena Fundamentals, Third Edition.
CRC Press, 2014.
'''
Pr_T = 0.85 + 0.015/Pr
Nu_di = Re*(fd/8.)/(1. + 145*(8./fd)**(-1.25))
Nu_dinf = 0.07343*Re*(Pr/Pr_T)**(1./3.0)*(fd/8.)**0.5
return 1./(Pr_T/Pr/Nu_di + (1. - (Pr_T/Pr)**(2/3.))/Nu_dinf) |
java | private ApiDoc getApiDoc(Class<?> controller, MethodDisplay displayMethodAs) {
log.debug("Getting JSONDoc for class: " + controller.getName());
ApiDoc apiDoc = initApiDoc(controller);
apiDoc.setSupportedversions(JSONDocApiVersionDocBuilder.build(controller));
apiDoc.setAuth(JSONDocApiAuthDocBuilder.getApiAuthDocForController(controller));
apiDoc.setMethods(getApiMethodDocs(controller, displayMethodAs));
if(controller.isAnnotationPresent(Api.class)) {
apiDoc = mergeApiDoc(controller, apiDoc);
}
return apiDoc;
} |
python | def tail(fpath, n=2, trailing=True):
""" Alias for path_ndir_split """
return path_ndir_split(fpath, n=n, trailing=trailing) |
python | def _create_aural_content_element(self, content, data_property_value):
"""
Create a element to show the content, only to aural displays.
:param content: The text content of element.
:type content: str
:param data_property_value: The value of custom attribute used to
identify the fix.
:type data_property_value: str
:return: The element to show the content.
:rtype: hatemile.util.html.htmldomelement.HTMLDOMElement
"""
content_element = self._create_content_element(
content,
data_property_value
)
content_element.set_attribute('unselectable', 'on')
content_element.set_attribute('class', 'screen-reader-only')
return content_element |
java | private List<File> loadFiles(File workingDir) {
List<File> dataFile = new ArrayList<>();
if (workingDir.exists()) {
File[] files = workingDir.listFiles();
for (File eachFile : files) {
if (eachFile.isDirectory()) {
dataFile.addAll(loadFiles(eachFile));
} else if (eachFile.getName().endsWith(".yaml") || eachFile.getName().endsWith(".yml")) {
dataFile.add(eachFile);
}
}
}
return dataFile;
} |
java | public static void iconComponent(Component component, UiIcon icon)
{
component.add(AttributeModifier.append("class", "ui-icon " + icon.getCssClass()));
} |
python | def _pfp__add_child(self, name, child, stream=None):
"""Add a child to the Union field
:name: The name of the child
:child: A :class:`.Field` instance
:returns: The resulting field
"""
res = super(Union, self)._pfp__add_child(name, child)
self._pfp__buff.seek(0, 0)
child._pfp__build(stream=self._pfp__buff)
size = len(self._pfp__buff.getvalue())
self._pfp__buff.seek(0, 0)
if stream is not None:
curr_pos = stream.tell()
stream.seek(curr_pos-size, 0)
return res |
python | def p_lconcat(self, p):
'lconcat : LBRACE lconcatlist RBRACE'
p[0] = LConcat(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
java | public static JSONArray readJSONArray(File file, Charset charset) throws IORuntimeException {
return parseArray(FileReader.create(file, charset).readString());
} |
python | def roll(cls, num, sides, add):
"""Rolls a die of sides sides, num times, sums them, and adds add"""
rolls = []
for i in range(num):
rolls.append(random.randint(1, sides))
rolls.append(add)
return rolls |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.