language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def upd_scroll(self, *args):
"""Update my own ``scroll`` property to where my deck is actually
scrolled.
"""
att = 'deck_{}_hint_offsets'.format(
'x' if self.orientation == 'horizontal' else 'y'
)
self._scroll = getattr(self.deckbuilder, att)[self.deckidx] |
python | def __call(self, uri, params=None, method="get"):
"""Only returns the response, nor the status_code
"""
try:
resp = self.__get_response(uri, params, method, False)
rjson = resp.json(**self.json_options)
assert resp.ok
except AssertionError:
... |
python | def get_symbols_with_positive_balances(self) -> List[str]:
""" Identifies all the securities with positive balances """
from gnucash_portfolio import BookAggregate
holdings = []
with BookAggregate() as book:
# query = book.securities.query.filter(Commodity.)
hol... |
java | @Path("batch")
@POST
public Response batchReplication(ReplicationList replicationList) {
try {
ReplicationListResponse batchResponse = new ReplicationListResponse();
for (ReplicationInstance instanceInfo : replicationList.getReplicationList()) {
try {
... |
java | public EventReader createReader() {
return new EventReader(eventsProcessor, sourceFilter, eventFilter, progressReporter, exceptionHandler, sqsManager, s3Manager, config);
} |
python | def randomize_graph_partial_und(A, B, maxswap, seed=None):
'''
A = RANDOMIZE_GRAPH_PARTIAL_UND(A,B,MAXSWAP) takes adjacency matrices A
and B and attempts to randomize matrix A by performing MAXSWAP
rewirings. The rewirings will avoid any spots where matrix B is
nonzero.
Parameters
---------... |
java | public static Middleware<AsyncHandler<?>, AsyncHandler<Response<ByteString>>> apolloDefaults() {
return serialize(new AutoSerializer()).and(Middlewares::httpPayloadSemantics);
} |
java | public static Result failure(String input, boolean canStopMatching) {
return new SimpleResult(false, input, null, null, canStopMatching);
} |
python | def color(self, n):
"""Color of pixel that reached limit after n iterations.
Returns a color tuple for use with PIL, tending toward
red as we tend toward self.max_iter iterations.
"""
red = int(n * self.shade_factor)
if (red > 255):
red = 255
return (... |
java | public B withConfigPath(String path) {
assertNotNull(path, "path could not be null.");
withConfigProperties(EmbedVaadinConfig.loadProperties(path));
return self();
} |
python | def description(self):
"""Retrieves the description of the incident/incidents from the output
response
Returns:
description(namedtuple): List of named tuples of descriptions of
the incident/incidents
"""
resource_list = self.traffic_incident()
des... |
java | @Override
public void initUpstream()
{
NucleicAcid nuc = tempReac.getTemplate();
if (nuc != null)
addToUpstream(nuc, getGraph());
for (Control cont : tempReac.getControlledOf())
{
addToUpstream(cont, graph);
}
} |
java | public static ProcessInstanceManager retrieveProcessInstanceManager(Object streamContext) {
ProcessInstanceManager pim = null;
if ( streamContext instanceof MarshallerWriteContext ) {
MarshallerWriteContext context = (MarshallerWriteContext) streamContext;
pim = ((ProcessRuntimeI... |
python | def middleware(self, middleware_or_request):
'''Decorate and register middleware to be called before a request.
Can either be called as @app.middleware or @app.middleware('request')
'''
def register_middleware(middleware, attach_to='request'):
if attach_to == 'request':
... |
java | public static boolean inotify(File file, FileNotify notify, int timeout) throws IllegalArgumentException
{
Params.notNull(file, "File");
Predicate predicate = INOTIFY_PREDICATES.get(notify);
if(predicate == null) {
throw new BugError("Unsupported file notification |%s|. Missing predicate.", n... |
java | public void setLayerVersions(java.util.Collection<LayerVersionsListItem> layerVersions) {
if (layerVersions == null) {
this.layerVersions = null;
return;
}
this.layerVersions = new com.amazonaws.internal.SdkInternalList<LayerVersionsListItem>(layerVersions);
} |
python | def remove_file(fpath, verbose=None, ignore_errors=True, dryrun=False,
quiet=QUIET):
""" Removes a file """
if verbose is None:
verbose = not quiet
if dryrun:
if verbose:
print('[util_path] Dryrem %r' % fpath)
return
else:
try:
os.r... |
java | private byte[] number2BytesInNetworkOrder(int number) {
byte[] orderBytes = new byte[4];
orderBytes[3] = (byte) (number & 0xFF);
orderBytes[2] = (byte) (number >> 8 & 0xFF);
orderBytes[1] = (byte) (number >> 16 & 0xFF);
orderBytes[0] = (byte) (number >> 24 & 0xFF);
return orderBytes;
} |
python | def data_to_binary(self):
"""
:return: bytes
"""
if self.channel == 0x01:
tmp = 0x03
else:
tmp = 0x0C
return bytes([
COMMAND_CODE,
tmp
]) + struct.pack('>L', self.delay_time)[-3:] |
java | private List<EventExecution> executeEvent(String event, Message msg) throws Exception {
List<EventHandler> eventHandlerList = metadataService.getEventHandlersForEvent(event, true);
Object payloadObject = getPayloadObject(msg.getPayload());
List<EventExecution> transientFailures = new ArrayList<... |
java | public UniDate updateCalendar(EUniCalendar calendar) {
final Date date = mainCal.getTime();
return new UniDate(calendar, createCalendar(calendar, date));
} |
java | private Formula constructAnd(final LinkedHashSet<? extends Formula> operands) {
And tempAnd = null;
Map<LinkedHashSet<? extends Formula>, And> opAndMap = this.andsN;
if (operands.size() > 1) {
switch (operands.size()) {
case 2:
opAndMap = this.ands2;
break;
case 3:
... |
java | private void writeInfo(Definition def, Writer out, int indent) throws IOException
{
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Gets the version of the resource adapter.\n");
writeWithIndent(out, indent, " *\n");
writeWithIndent(out, indent, " * @return String repr... |
java | @Override
public FlowConfig get(ComplexResourceKey<FlowId, EmptyRecord> key) {
String flowGroup = key.getKey().getFlowGroup();
String flowName = key.getKey().getFlowName();
FlowId flowId = new FlowId().setFlowGroup(flowGroup).setFlowName(flowName);
return this.flowConfigsResourceHandler.getFlowConfig(... |
java | private ArrayList getAttributeDescriptorsForCleanPath(String aPath, Map pathHints)
{
ArrayList result = new ArrayList();
ClassDescriptor cld = this;
ObjectReferenceDescriptor ord;
FieldDescriptor fld;
String currPath = aPath;
String segment;
StringBuff... |
python | def _from_signer_and_info(cls, signer, info, **kwargs):
"""Creates a Credentials instance from a signer and service account
info.
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
info (Mapping[str, str]): The service account info.
kwargs... |
python | def centralize(data, time=False, units=False):
"""
Function to subtract the mean across time and/or across units from data
Parameters
----------
data : numpy.ndarray
1D or 2D array containing time series, 1st index: unit, 2nd index: time
time : bool
True: subtract mea... |
java | public void setInitialLearningRate(double initialLearningRate)
{
if(Double.isInfinite(initialLearningRate) || Double.isNaN(initialLearningRate) || initialLearningRate <= 0)
throw new ArithmeticException("Learning rate must be a positive constant, not " + initialLearningRate);
this.initia... |
python | def create_table(self, name, schema):
"""
Create a new table.
If the table already exists, nothing happens.
Example:
>>> db.create_table("foo", (("id", "integer primary key"),
("value", "text")))
Arguments:
name ... |
python | def safe_int(value):
"""
Tries to convert a value to int; returns 0 if conversion failed
"""
try:
result = int(value)
if result < 0:
raise NegativeDurationError(
'Negative values in duration strings are not allowed!'
)
except NegativeDurationEr... |
java | public static Relay edit(
File file, Source upstream, ByteString metadata, long bufferMaxSize) throws IOException {
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
Relay result = new Relay(randomAccessFile, upstream, 0L, metadata, bufferMaxSize);
// Write a dirty header. That wa... |
java | public void addOperand(QueryNode operand) {
if (operands == null) {
operands = new ArrayList<QueryNode>();
}
operands.add(operand);
} |
python | def get_file(self, filename, dir='static'):
"""
get_file will search from apps directory
"""
if os.path.exists(filename):
return filename
dirs = self.apps
if dir:
fname = os.path.join(dir, filename)
else:
fname = filename
... |
java | private void yAxis(Graphics g) {
// y-axis
g.setColor(Color.BLACK);
g.drawLine(X_OFFSET_LEFT, calcY(0), X_OFFSET_LEFT, Y_OFFSET_TOP);
// center horizontal line
g.setColor(new Color(220, 220, 220));
g.drawLine(X_OFFSET_LEFT, height / 2 + Y_OFFSET_TOP, getWidth(),
... |
java | public void validateOperation(final ModelNode operation) {
if (operation == null) {
return;
}
final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));
final String name = operation.get(OP).asString();
OperationEntry entry = root.getOperationEntry(... |
java | public void readObject(@NonNull ObjectInputStream stream) throws IOException, ClassNotFoundException {
id = (String)stream.readObject();
createdTime = stream.readLong();
lastAccessedTime = stream.readLong();
maxInactiveInterval = stream.readInt();
isNew = stream.readBoolean();
... |
python | def p_text(self, text):
'''text : TEXT PARBREAK
| TEXT
| PARBREAK'''
item = text[1]
text[0] = item if item[0] != "\n" else u""
if len(text) > 2:
text[0] += "\n" |
java | protected SIBusMessage readMessage (SIMessageHandle handle)
throws ResourceException, SIMessageNotLockedException
{
final String methodName = "readMessage";
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
{
SibTr.entry(this, TRACE, methodName, ... |
python | def within(self, region):
"""
:param region: a shapely polygon
:returns: a filtered SiteCollection of sites within the region
"""
mask = numpy.array([
geometry.Point(rec['lon'], rec['lat']).within(region)
for rec in self.array])
return self.filter(... |
python | def apply_transformations(collection, transformations, select=None):
''' Apply all transformations to the variables in the collection.
Args:
transformations (list): List of transformations to apply.
select (list): Optional list of names of variables to retain after all
transformatio... |
python | def handle_error(self, msgtype, msgid, error):
"""Handle an error."""
self._proxy.error(msgid, error) |
java | protected void addSources(Video video, Media media) {
Asset asset = getDamAsset(media);
if (asset == null) {
return;
}
for (VideoProfile profile : getVideoProfiles()) {
com.day.cq.dam.api.Rendition rendition = profile.getRendition(asset);
if (rendition != null) {
video.createS... |
java | public Iterator<DependencyRelation> iterator() {
// Wrap the nodes returned by the existing path and the extended
// relation into a combined iterator.
//
// NB: The type inferencer has problems equating the return type of
// Collections.singleton().iterator() with the desired ty... |
python | def _on_call_service_msg(self, msg):
"""
Stub service handler. Start a thread to import the mitogen.service
implementation from, and deliver the message to the newly constructed
pool. This must be done as CALL_SERVICE for e.g. PushFileService may
race with a CALL_FUNCTION blockin... |
python | def _set_datapath(self, datapath):
""" Set a datapath.
"""
if datapath:
self._datapath = datapath.rstrip(os.sep)
self._fifo = int(stat.S_ISFIFO(os.stat(self.datapath).st_mode))
else:
self._datapath = None
self._fifo = False |
java | public WebSocketSession getCient(String pLoginName) {
if (!mClients.contains(pLoginName)) {
return null;
}
return mClients.get(pLoginName);
} |
java | public void openTable(TableTag.State state, AbstractRenderAppender appender) {
if(state == null)
state = TABLE_STATE;
appender.append(LINE_BREAK);
_tableRenderer.doStartTag(appender, state);
appender.append(LINE_BREAK);
} |
python | def load_stream(self, stream):
"""
Deserialize ArrowRecordBatches to an Arrow table and return as a list of pandas.Series.
"""
batches = super(ArrowStreamPandasSerializer, self).load_stream(stream)
import pyarrow as pa
for batch in batches:
yield [self.arrow_t... |
python | def plot_teq(fignum, araiblock, s, pars):
"""
plots directions of pTRM steps and zero field steps
Parameters
__________
fignum : figure number for matplotlib object
araiblock : nested list of data from pmag.sortarai()
s : specimen name
pars : default is "",
otherwise is diction... |
java | public Class<?> getType(final ELContext ctx, final Object base, final Object property)
{
return resolver.getType(ctx, base, property);
} |
java | public <L, R> SingleOutputStreamOperator<R> flatSelect(
final OutputTag<L> timedOutPartialMatchesTag,
final PatternFlatTimeoutFunction<T, L> patternFlatTimeoutFunction,
final PatternFlatSelectFunction<T, R> patternFlatSelectFunction) {
final TypeInformation<R> rightTypeInfo = TypeExtractor.getUnaryOperatorR... |
python | def run_once_per_node(func):
"""
Decorator preventing wrapped function from running more than
once per host (not just interpreter session).
Using env.patch = True will allow the wrapped function to be run
if it has been previously executed, but not otherwise
Stores the result of a function... |
java | String format(String field, long bits) {
List<Setting> settings = cases.get(field);
if (settings == null) {
return ""; //TODO error?
}
String format = null;
for (int i = settings.size() - 1; i >= 0; --i) {
Setting ing = settings... |
python | def configure_logger(level):
"""
Configure a root logger to print records in pretty format.
The format is more readable for end users, since it's not necessary at
all to know a record's dateime and a source of the record.
Examples::
[INFO] message
[WARN] message
[ERRO] mes... |
java | @SuppressWarnings("unchecked")
static <T> T stringToType(String str, Class<T> clazz) {
try {
final Function<String, ?> func = supportedElementTypes.get(clazz);
if (func != null) {
return (T) func.apply(str);
}
} catch (NumberFormatException e) {
... |
python | def _get_p(df, column, shifts):
""" get the permutation of specified range
example:
index x x_-2,-1_p
0 1 NaN
1 -1 NaN
2 3 2 (0.x > 0, and assigned to weight 2)
3 5 1 (2.x > 0, and assi... |
java | @SuppressWarnings({"rawtypes", "unchecked"})
public static Collection convertListToCollection(final List list, final Class<Collection> toClass,
final BeanFactory<Class<?>, Object> beanFactory) {
if(list.getClass().equals(toClass)) {
return list;
}
if(toClass... |
java | protected final <T extends Exception, RESP> ExceptionHandler handle(Class<T> clazz, ExceptionHandlerAction<RESP, T> action,
ResponseType<RESP> resp) {
return putHandler(clazz, action, resp);
} |
java | @ReplacedBy("com.google.common.collect.Iterables#toArray()")
public static <T> T[] toArray (Collection<? extends T> col, Class<T> type)
{
@SuppressWarnings("unchecked")
T[] array = (T[]) Array.newInstance(type, col.size());
return col.toArray(array);
} |
python | def update_ride(api_client, ride_status, ride_id):
"""Use an UberRidesClient to update ride status and print the results.
Parameters
api_client (UberRidesClient)
An authorized UberRidesClient with 'request' scope.
ride_status (str)
New ride status to update to.
r... |
java | @SuppressWarnings("unchecked")
public static <T> T[] removeValues(T[] values, Predicate<T> shouldRemove, Class<T> type) {
Collection<T> collection = new ArrayList<>(values.length);
for (T value : values) {
if (shouldRemove.negate().test(value)) {
collection.add(value);
}
}
T[] arra... |
python | def decompress(obj, return_type="bytes"):
"""
De-compress it to it's original.
:param obj: Compressed object, could be bytes or str.
:param return_type: if bytes, then return bytes; if str, then use
base64.b64decode; if obj, then use pickle.loads return an object.
"""
if isinstance(obj,... |
python | def pot_to_rpole_aligned(pot, sma, q, F, d, component=1):
"""
Transforms surface potential to polar radius
"""
q = q_for_component(q, component=component)
Phi = pot_for_component(pot, q, component=component)
logger.debug("libphobe.roche_pole(q={}, F={}, d={}, Omega={})".format(q, F, d, pot))
... |
java | public JPEGFrameGrabber getJPEGFrameGrabber(int w, int h, int input,
int std, int q, ImageFormat imf) throws V4L4JException{
if(!supportJPEG || deviceInfo==null)
throw new ImageFormatException("This video device does not support "
+"JPEG-encoding of its frames.");
if(imf!=null){
if(!deviceInfo.get... |
java | public void nextColumn() throws DocumentException {
currentColumn = (currentColumn + 1) % columnDefs.size();
top = nextY;
if (currentColumn == 0) {
newPage();
}
} |
java | private void infoOrDebug( boolean info, String msg )
{
if ( info )
{
getLogger().info( msg );
}
else
{
getLogger().debug( msg );
}
} |
python | def downlad_file(url, fname):
"""Download file from url and save as fname."""
print("Downloading {} as {}".format(url, fname))
response = urlopen(url)
download = response.read()
with open(fname, 'wb') as fh:
fh.write(download) |
python | def get_version(path, default="master"):
"""
Return the version from a VERSION file
"""
version = default
if os.path.exists(path):
version_contents = file_to_string(path)
if version_contents:
version = version_contents.strip()
return version |
python | def top_charts_genres(self):
"""Get a listing of genres from the browse top charts tab."""
response = self._call(mc_calls.BrowseTopChartGenres)
top_chart_genres = response.body.get('genres', [])
return top_chart_genres |
python | def has_own_property(self, attr):
"""
Returns if the property
"""
try:
object.__getattribute__(self, attr)
except AttributeError:
return False
else:
return True |
python | def _handle_exists(self, node, scope, ctxt, stream):
"""Handle the exists unary operator
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
res = fields.Int()
try:
self._handle_node(node.expr, scope, ctxt, stream)
... |
python | def n_exec_stmt(self, node):
"""
exec_stmt ::= expr exprlist DUP_TOP EXEC_STMT
exec_stmt ::= expr exprlist EXEC_STMT
"""
start = len(self.f.getvalue()) + len(self.indent)
try:
super(FragmentsWalker, self).n_exec_stmt(node)
except GenericASTTraversalPru... |
java | public void _writeString(String text) throws IOException
{
int len = text.length();
if (len > _outputEnd) { // Let's reserve space for entity at begin/end
_writeLongString(text);
return;
}
// Ok: we know String will fit in buffer ok
// But do we need to flush first?
if ((_outputTail + len) > _outpu... |
java | protected String createPlainTextJWT() {
com.google.gson.JsonObject header = createHeader();
com.google.gson.JsonObject payload = createPayload();
String plainTextTokenString = computeBaseString(header, payload);
StringBuffer sb = new StringBuffer(plainTextTokenString);
sb.append... |
java | @Override
public long authorizedExecutionRead(long executionId)
throws JobSecurityException, NoSuchJobExecutionException {
long instanceId = persistenceManagerService.getJobInstanceIdFromExecutionId(executionId);
authorizedInstanceRead(instanceId);
return executionId;
} |
java | public void marshall(AddAttachmentsToSetRequest addAttachmentsToSetRequest, ProtocolMarshaller protocolMarshaller) {
if (addAttachmentsToSetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(a... |
python | def set_c_prototype(self, c_decl):
"""
Set the prototype of a function in the form of a C-style function declaration.
:param str c_decl: The C-style declaration of the function.
:return: A tuple of (function name, function prototype)
:rtype: tuple
""... |
java | public List<ModelServiceInstance> getAllModelServiceInstance() {
return getData() == null ? Collections.<ModelServiceInstance>emptyList() : getData().getServiceInstances();
} |
python | def get_template(self):
"""
读取一个Excel模板,将此Excel的所有行读出来,并且识别特殊的标记进行记录
:return: 返回读取后的模板,结果类似:
[
{'cols': #各列,与subs不会同时生效
'subs':[ #子模板
{'cols':#各列,
'subs': #子模板
'field': #对应数据中字段名称
... |
java | public final hqlParser.likeEscape_return likeEscape() throws RecognitionException {
hqlParser.likeEscape_return retval = new hqlParser.likeEscape_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token ESCAPE178=null;
ParserRuleReturnScope concatenation179 =null;
CommonTree ESCAPE178_tree=n... |
java | public static authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{
authenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();
obj.set_name(name);
authenticationtacacspolicy_systemglobal_binding response[] = (a... |
java | public static OptionalEntity<WebAuthentication> getEntity(final CreateForm form, final String username, final long currentTime) {
switch (form.crudMode) {
case CrudMode.CREATE:
return OptionalEntity.of(new WebAuthentication()).map(entity -> {
entity.setCreatedBy(username);
... |
python | def initialize_service(service, operation, api_protocol):
"""create lib and test dirs if not exist
"""
lib_dir = get_lib_dir(service)
test_dir = get_test_dir(service)
print_progress('Initializing service', service, 'green')
client = boto3.client(service)
service_class = client.__class__.__... |
python | def fabric_isl(self, **kwargs):
"""Set fabric ISL state.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
enabled (bool): Is fabric ISL state enabled? (True, False)... |
python | def _get_longest_hit_at_qry_end(self, nucmer_hits):
'''Input: list of nucmer hits to the same query. Returns the longest hit to the end of the query, or None if there is no such hit'''
hits_at_end = [hit for hit in nucmer_hits if self._is_at_qry_end(hit)]
return self._get_longest_hit_by_ref_leng... |
python | def _get_all_taskpaper_files(
self):
"""*get a list of all the taskpaper filepaths in the workspace*
**Return:**
- ``taskpaperFiles`` -- a list of paths to all the taskpaper files within the workspace
"""
self.log.info('starting the ``_get_all_taskpaper_files`` m... |
java | @NotNull
public static Promise<Void> sequence(@NotNull AsyncSupplier<Void> promise1, @NotNull AsyncSupplier<Void> promise2) {
return promise1.get().then($ -> sequence(promise2));
} |
java | public SecretKey decryptKey(String encryptedKey, PrivateKey privateKey) {
// Basic null check
if (encryptedKey == null) {
return null;
}
// Convert the encryptedKey key String back to a byte array:
byte[] bytes = ByteArray.fromBase64(encryptedKey);
... |
python | def random_samples(self, n):
"""
Returns a random sampling of given size from the existing samples.
:param n:
Number of samples
:return:
:class:`pandas.DataFrame` of length ``n`` with random samples.
"""
samples = self.samples
inds = rand... |
python | def pop(self, groupName, default=None):
"""
Removes the **groupName** from the Groups and returns the list of
group members. If no group is found, **default** is returned.
**groupName** is a :ref:`type-string`. This must return either
**default** or a :ref:`type-immutable-list` o... |
python | def nodes_map(self):
"""
Build a mapping from node type to a list of nodes.
A typed mapping helps avoid polymorphism at non-persistent layers.
"""
dct = dict()
for node in self.nodes.values():
cls = next(base for base in getmro(node.__class__) if "__tablenam... |
python | def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path) |
python | def remove_constraint(self, twig=None, **kwargs):
"""
Remove a 'constraint' from the bundle
:parameter str twig: twig to filter for the constraint
:parameter **kwargs: any other tags to do the filter
(except twig or context)
"""
# let's run delayed constraint... |
python | def _trace_full (frame, event, arg):
"""Trace every executed line."""
if event == "line":
_trace_line(frame, event, arg)
else:
_trace(frame, event, arg)
return _trace_full |
java | @Override public void normalise(ProjectCalendar calendar, LinkedList<TimephasedCost> list)
{
if (!list.isEmpty())
{
//dumpList(list);
splitDays(calendar, list);
//dumpList(list);
mergeSameDay(list);
//dumpList(list);
mergeSameCost(list);
//du... |
java | public static String toBase58(byte[] b) {
if (b.length == 0) {
return "";
}
int lz = 0;
while (lz < b.length && b[lz] == 0) {
++lz;
}
StringBuilder s = new StringBuilder();
BigInteger n = new BigInteger(1, b);
while (n.compareTo(B... |
java | static ExpressionCompiler create(
ExpressionDetacher.Factory detacherFactory,
TemplateParameterLookup parameters,
TemplateVariableManager varManager,
ErrorReporter reporter,
SoyTypeRegistry registry) {
return new ExpressionCompiler(detacherFactory, parameters, varManager, reporter, reg... |
python | def replace_namespaced_service_account(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_service_account # noqa: E501
replace the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP reque... |
python | def force_to_string(unknown):
"""
converts and unknown type to string for display purposes.
"""
result = ''
if type(unknown) is str:
result = unknown
if type(unknown) is int:
result = str(unknown)
if type(unknown) is float:
result = str(unknown)
if type(unkno... |
java | private ChannelFuture checkException(ChannelPromise promise) {
Throwable t = lastException;
if (t != null) {
lastException = null;
if (promise.isVoid()) {
PlatformDependent.throwException(t);
}
return promise.setFailure(t);
}
return promise.setSucce... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.