language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def deregister_instances(self, load_balancer_name, instances):
"""
Remove Instances from an existing Load Balancer.
:type load_balancer_name: string
:param load_balancer_name: The name of the Load Balancer
:type instances: List of strings
:param instances: The instance ... |
java | @Override
protected boolean isValidFragment(String fragmentName) {
Boolean knownFrag = false;
for (Class<?> cls : INNER_CLASSES) {
if ( cls.getName().equals(fragmentName) ){
knownFrag = true;
break;
}
}
return knownFrag;
... |
python | def _get_value(self, entity):
"""Override _get_value() to *not* raise UnprojectedPropertyError."""
value = self._get_user_value(entity)
if value is None and entity._projection:
# Invoke super _get_value() to raise the proper exception.
return super(StructuredProperty, self)._get_value(entity)
... |
python | def generate_unique_key(master_key_path, url):
"""
Input1: Path to the BD2K Master Key (for S3 Encryption)
Input2: S3 URL (e.g. https://s3-us-west-2.amazonaws.com/cgl-driver-projects-encrypted/wcdt/exome_bams/DTB-111-N.bam)
Returns: 32-byte unique key generated for that URL
"""
with open(master... |
java | @Override
public CommerceOrderItem findByC_I_Last(long commerceOrderId,
long CPInstanceId,
OrderByComparator<CommerceOrderItem> orderByComparator)
throws NoSuchOrderItemException {
CommerceOrderItem commerceOrderItem = fetchByC_I_Last(commerceOrderId,
CPInstanceId, orderByComparator);
if (commerceOrderI... |
python | def _numpy_index_by_percentile(self, data, percentile):
""" Calculate percentile of numpy stack and return the index of the chosen pixel.
numpy percentile function is used with one of the following interpolations {'linear', 'lower', 'higher',
'midpoint', 'nearest'}
"""
d... |
python | def create_farm(farm_name):
"""
Create a farm. Creates a farm named FARM_NAME on the currently selected
cloud server. You can use the `openag cloud select_farm` command to start
mirroring data into it.
"""
utils.check_for_cloud_server()
utils.check_for_cloud_user()
server = Server(config... |
python | async def create_category(self, name, *, overwrites=None, reason=None):
"""|coro|
Same as :meth:`create_text_channel` except makes a :class:`CategoryChannel` instead.
.. note::
The ``category`` parameter is not supported in this function since categories
cannot have ca... |
java | @SuppressWarnings({"rawtypes", "unchecked"})
public static Kryo getKryo(Map conf) {
IKryoFactory kryoFactory =
(IKryoFactory) Utils.newInstance((String) conf.get(Config.TOPOLOGY_KRYO_FACTORY));
Kryo k = kryoFactory.getKryo(conf);
k.register(byte[].class);
k.register(ListDelegate.class);
k.... |
java | private static void onGlInitialization() {
if (glUninitialized) {
glGetError(); // reset any previous error
int[] size = new int[] { -1 };
glGetIntegerv(GL_MAX_TEXTURE_SIZE, size, 0);
int errorCode = glGetError();
if (errorCode != GL_NO_ERROR) {
... |
java | public static boolean consistentAccessions(List<Location> subLocations) {
Set<AccessionID> set = new HashSet<AccessionID>();
for(Location sub: subLocations) {
set.add(sub.getAccession());
}
return set.size() == 1;
} |
python | def p_expr_end(p):
"end : END_EXPR"
p[0] = node.expr(
op="end", args=node.expr_list([node.number(0), node.number(0)])) |
python | def fetch_live(self, formatter=TableFormat):
"""
View logs in real-time. If previous filters were already set on
this query, they will be preserved on the original instance (this
method forces ``fetch_type='current'``).
:param formatter: Formatter type for data represent... |
java | private static void getAllInterfaces(Class<?> cls, Collection<Class<?>> interfacesFound) {
while (cls != null) {
Class<?>[] interfaces = cls.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
interfacesFound.add(interfaces[i]);
getAllInterface... |
python | def is_preflight_request(self, request: web.Request) -> bool:
"""Is `request` is a CORS preflight request."""
route = self._request_route(request)
if _is_web_view(route, strict=False):
return request.method == 'OPTIONS'
return route in self._preflight_routes |
python | def __optimize(self):
"""
Merge overlapping or contacting subranges from ``self.__has`` attribute and update it. Called from all methods
that modify object contents.
Returns
-------
None
Method does not return. It does internal modifications on ``self.__has`... |
python | def _resolve_child(self, path):
'Return a member generator by a dot-delimited path'
obj = self
for component in path.split('.'):
ptr = obj
if not isinstance(ptr, Permuter):
raise self.MessageNotFound("Bad element path [wrong type]")
# pylint:... |
python | def view_fields(self, *attributes, **options):
""" Returns an :class:`ordered dictionary <collections.OrderedDict>` which
contains the selected field *attributes* of the `Pointer` field itself
extended with a ``['data']`` key which contains the selected field *attribute*
or the dictionar... |
java | public @Nullable <T> T findUniqueOrNull(@NotNull RowMapper<T> rowMapper, @NotNull SqlQuery query) {
return findOptional(rowMapper, query).orElse(null);
} |
python | def hardware_port_group_mode_portgroup_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
port_group = ET.SubElement(hardware, "port-group")
name_key =... |
java | @Override
public Request<DescribeNetworkInterfaceAttributeRequest> getDryRunRequest() {
Request<DescribeNetworkInterfaceAttributeRequest> request = new DescribeNetworkInterfaceAttributeRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;... |
java | public static TimestampLessThanCondition.Builder lt(String variable, Date expectedValue) {
return TimestampLessThanCondition.builder().variable(variable).expectedValue(expectedValue);
} |
python | def find_enriched(sample_entities=None,
background_entities=None,
object_category=None,
**kwargs):
"""
Given a sample set of sample_entities (e.g. overexpressed genes) and a background set (e.g. all genes assayed), and a category of descriptor (e.g. phenoty... |
python | def cftype_to_value(cftype):
"""Convert a CFType into an equivalent python type.
The convertible CFTypes are taken from the known_cftypes
dictionary, which may be added to if another library implements
its own conversion methods."""
if not cftype:
return None
typeID = cf.CFGetTypeID(cfty... |
java | public Object getObject(int parameterIndex,
Map<String, Class<?>> map) throws SQLException {
throw Util.notSupported();
} |
java | private static void validateSetValueEntryForSet(Object entry, Set<?> set) {
if (entry instanceof Set<?> || entry instanceof SetValue) {
throw new IllegalArgumentException("Unsupported Value type [nested sets]");
}
if (!set.isEmpty()) {
Object existingEntry = set.iterator().next();
if (!exi... |
java | public long getCount(Date fromWhen, Date toWhen, boolean fromInclusive, boolean toInclusive) {
return getCount(fromWhen.getTime(), toWhen.getTime(), true, false);
} |
java | public String evaluate(Map symbolTable)
throws RslEvaluationException {
String var = null;
if (symbolTable != null) {
var = (String)symbolTable.get(value);
}
if (var == null && defValue != null) {
var = defValue.evaluate(symbolTable);
}
if (var == null) {
/* NOTE: according to the rsl specs the... |
python | def get_basedir(path):
"""Returns the base directory of a path.
Examples:
get_basedir('foo/bar/baz') --> 'foo'
get_basedir('/foo/bar/baz') --> ''
get_basedir('foo') --> 'foo'
"""
return path[:path.index(os.sep)] if os.sep in path else path |
python | def parse_environ(name, parse_class=ParseResult, **defaults):
"""
same as parse() but you pass in an environment variable name that will be used
to fetch the dsn
:param name: string, the environment variable name that contains the dsn to parse
:param parse_class: ParseResult, the class that will be... |
java | public List<GitlabProject> getOwnedProjects() throws IOException {
Query query = new Query().append("owned", "true");
query.mergeWith(new Pagination().withPerPage(Pagination.MAX_ITEMS_PER_PAGE).asQuery());
String tailUrl = GitlabProject.URL + query.toString();
return retrieve().getAll(ta... |
python | def setparents(self):
"""Correct all parent relations for elements within the scop. There is sually no need to call this directly, invoked implicitly by :meth:`copy`"""
for c in self:
if isinstance(c, AbstractElement):
c.parent = self
c.setparents() |
java | Observable<ChatResult> handleConversationUpdated(ConversationUpdate request, ComapiResult<ConversationDetails> result) {
if (result.isSuccessful()) {
return persistenceController.upsertConversation(ChatConversation.builder().populate(result.getResult(), result.getETag()).build()).map(success -> ad... |
python | def _flag_handler(self, play, handler_name, host):
'''
if a task has any notify elements, flag handlers for run
at end of execution cycle for hosts that have indicated
changes have been made
'''
found = False
for x in play.handlers():
if handler_name ... |
python | def record_download_archive(track):
"""
Write the track_id in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a', encoding='utf-8') as file:
... |
java | private void reset() {
calledNextStartPosition = false;
noMorePositions = false;
noMorePositionsSpan2 = false;
lastSpans2StartPosition = -1;
lastSpans2EndPosition = -1;
previousSpans2StartPosition = -1;
previousSpans2EndPositions.clear();
} |
python | def GetName(obj):
"""A compatibility wrapper for getting object's name.
In Python 2 class names are returned as `bytes` (since class names can contain
only ASCII characters) whereas in Python 3 they are `unicode` (since class
names can contain arbitrary unicode characters).
This function makes this behaviou... |
java | @Override
public void setFromCorners(double x1, double y1, double z1, double x2, double y2, double z2) {
if (x1<x2) {
this.minx = x1;
this.maxx = x2;
}
else {
this.minx = x2;
this.maxx = x1;
}
if (y1<y2) {
this.miny = y1;
this.maxy = y2;
}
else {
this.miny = y2;
this.maxy = y1;
... |
java | public static int numNewAxis(INDArrayIndex... axes) {
int ret = 0;
for (INDArrayIndex index : axes)
if (index instanceof NewAxis)
ret++;
return ret;
} |
python | def add(self, txt, indent=0):
"""Adds some text, no newline will be appended.
The text can be indented with the optional argument 'indent'.
"""
if isinstance(txt, unicode):
try:
txt = str(txt)
except UnicodeEncodeError:
... |
python | def map_attribute_to_seq(self,
attribute: str,
key_attribute: str,
value_attribute: Optional[str] = None) -> None:
"""Converts a mapping attribute to a sequence.
This function takes an attribute of this Node whose va... |
python | def consume_socket_output(frames, demux=False):
"""
Iterate through frames read from the socket and return the result.
Args:
demux (bool):
If False, stdout and stderr are multiplexed, and the result is the
concatenation of all the frames. If True, the streams are
... |
java | public static void minimum(Planar<GrayF64> input, GrayF64 output) {
output.reshape(input.width,input.height);
if (BoofConcurrency.USE_CONCURRENT) {
ImplImageBandMath_MT.minimum(input, output, 0, input.getNumBands() - 1);
} else {
ImplImageBandMath.minimum(input, output, 0, input.getNumBands() - 1);
}
} |
java | public java.util.List<String> getEnvironmentNames() {
if (environmentNames == null) {
environmentNames = new com.amazonaws.internal.SdkInternalList<String>();
}
return environmentNames;
} |
python | def get_k8s_model(model_type, model_dict):
"""
Returns an instance of type specified model_type from an model instance or
represantative dictionary.
"""
model_dict = copy.deepcopy(model_dict)
if isinstance(model_dict, model_type):
return model_dict
elif isinstance(model_dict, dict):... |
java | public static FileChannel createTempFile(String prefix, String suffix) throws IOException {
return createTempFile(TMPDIR, prefix, suffix);
} |
java | public java.util.List<SuccessfulInstanceCreditSpecificationItem> getSuccessfulInstanceCreditSpecifications() {
if (successfulInstanceCreditSpecifications == null) {
successfulInstanceCreditSpecifications = new com.amazonaws.internal.SdkInternalList<SuccessfulInstanceCreditSpecificationItem>();
... |
python | def _read_config(filename):
"""Read configuration from the given file.
Parsing is performed through the configparser library.
Returns:
dict: a flattened dict of (option_name, value), using defaults.
"""
parser = configparser.RawConfigParser()
if filename and not parser.read(filename):
... |
java | public <R> Plan0<R> then(Func5<T1, T2, T3, T4, T5, R> selector) {
if (selector == null) {
throw new NullPointerException();
}
return new Plan5<T1, T2, T3, T4, T5, R>(this, selector);
} |
python | def _send_file(self, method, path, data, filename):
"""Make a multipart/form-encoded request.
Args:
`method`: The method of the request (POST or PUT).
`path`: The path to the resource.
`data`: The JSON-encoded data.
`filename`: The filename of the file to... |
java | protected Template getTemplate(File file) throws ServletException {
String key = file.getAbsolutePath();
Template template = findCachedTemplate(key, file);
//
// Template not cached or the source file changed - compile new template!
//
if (template == null) {
... |
java | public boolean write( RasterData rasterData ) throws RasterWritingFailureException {
try {
return writer.write(rasterData);
} catch (Exception e) {
e.printStackTrace();
throw new RasterWritingFailureException(e.getLocalizedMessage());
}
} |
python | def dl_database(db_dir, dl_dir, records='all', annotators='all',
keep_subdirs=True, overwrite=False):
"""
Download WFDB record (and optionally annotation) files from a
Physiobank database. The database must contain a 'RECORDS' file in
its base directory which lists its WFDB records.
... |
python | def new_binary_container(self, name):
"""Defines a new binary container to template.
Binary container can only contain binary fields defined with `Bin`
keyword.
Examples:
| New binary container | flags |
| bin | 2 | foo |
| bin | 6 | bar |
| End binary c... |
python | def _build_likelihood(self):
"""
This gives a variational bound on the model likelihood.
"""
# Get prior KL.
KL = self.build_prior_KL()
# Get conditionals
fmean, fvar = self._build_predict(self.X, full_cov=False, full_output_cov=False)
# Get variational... |
java | public static boolean deletePublicKeyNode(PepManager pepManager, OpenPgpV4Fingerprint fingerprint)
throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException {
PubSubManager pm = pepManager.getPepPubSubManager()... |
java | public static <T extends MethodDescription> ElementMatcher.Junction<T> isSetter(TypeDescription type) {
return isSetter(is(type));
} |
java | public void schedule(final String name, final Command command, final int delayMsec) {
BurstEvent e = m_memory.remove(name);
if (e != null) {
// disable the old event
e.getTimer().cancel();
}
// put the new event and schedule it
e = new BurstEvent(name, co... |
java | @Override
public T resolve(String name, MediaType mediaType) {
if (this.cache != null) {
if (!this.cache.containsKey(name)) {
T t = this.resolve(name);
if (t != null)
this.cache.putIfAbsent(name, t);
}
return this.cache... |
java | private static void getMethodsRecursive(Class<?> service, List<Method> methods) {
Collections.addAll(methods, service.getDeclaredMethods());
} |
python | def _update_rows(self):
""" Update the row and column numbers of child items. """
for row, item in enumerate(self._items):
item.row = row # Row is the Parent item
item.column = 0
for column, item in enumerate(self._columns):
item.row = self.row # Ro... |
python | def _load(self, path='config', filetype=None, relaxed=False, ignore=False):
""" load key value pairs from a file
Parameters:
path - path to configuration data (see Note 1)
filetype - type component of dot-delimited path
relaxed - if True, define ... |
java | private I_CmsContextMenuItem findDefaultAction(Collection<I_CmsContextMenuItem> items) {
I_CmsContextMenuItem result = null;
int resultRank = -1;
for (I_CmsContextMenuItem menuItem : items) {
if ((menuItem instanceof CmsContextMenuActionItem)
&& (((CmsContextMenuActi... |
java | protected <T> List<T> deleteListResources(String path, Class<T> objectClass) throws SmartsheetException {
Util.throwIfNull(path, objectClass);
Util.throwIfEmpty(path);
Result<List<T>> obj = null;
HttpRequest request;
request = createHttpRequest(smartsheet.getBaseURI().resolve(pa... |
java | public void registerView(@Nullable RegisterViewStatusListener callback) {
if (Branch.getInstance() != null) {
Branch.getInstance().registerView(this, callback);
} else {
if (callback != null) {
callback.onRegisterViewFinished(false, new BranchError("Register view ... |
java | @Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case BpsimPackage.GAMMA_DISTRIBUTION_TYPE__SCALE:
setScale((Double)newValue);
return;
case BpsimPackage.GAMMA_DISTRIBUTION_TYPE__SHAPE:
setShape((Double)newValue);
return;
}
super.eSet(featureID, newValue);
} |
python | def mavg(data, xseq, **params):
"""
Fit moving average
"""
window = params['method_args']['window']
# The first average comes after the full window size
# has been swept over
rolling = data['y'].rolling(**params['method_args'])
y = rolling.mean()[window:]
n = len(data)
stderr = ... |
python | def check(self, req):
"""Determine if ``req`` is in this instances cache.
Determine if there are cache hits for the request in this aggregator
instance.
Not in the cache
If req is not in the cache, it returns ``None`` to indicate that the
caller should send the request... |
java | public String getRawDataAsString() throws IOException
{
byte[] buffer = getRawData();
if ( buffer == null ) {
return null;
}
String encoding = request.getCharacterEncoding();
if ( encoding == null ) {
encoding = "utf-8";
}
... |
java | public void marshall(DescribeProductViewRequest describeProductViewRequest, ProtocolMarshaller protocolMarshaller) {
if (describeProductViewRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(d... |
java | public SubscriptionQos setExpiryDateMs(final long expiryDateMs) {
long now = System.currentTimeMillis();
if (expiryDateMs <= now && expiryDateMs != NO_EXPIRY_DATE) {
throw new IllegalArgumentException("Subscription ExpiryDate " + expiryDateMs + " in the past. Now: " + now);
}
... |
python | def _get_indicators_page_generator(self, from_time=None, to_time=None, page_number=0, page_size=None,
enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None):
"""
Creates a generator from the |get_indicators_page| method that returns each successive page.
... |
python | def obj_to_string(obj):
'''Render an object into a unicode string if possible'''
if not obj:
return None
elif isinstance(obj, bytes):
return obj.decode('utf-8')
elif isinstance(obj, basestring):
return obj
elif is_lazy_string(obj):
return obj.value
elif hasattr(ob... |
python | def get(cls):
"""Subsystems used outside of any task."""
return {
SourceRootConfig,
Reporting,
Reproducer,
RunTracker,
Changed,
BinaryUtil.Factory,
Subprocess.Factory
} |
java | @FFDCIgnore(IOException.class)
public static String getLocationFromBundleFile(BundleFile bundleFile) {
BundleEntry be = bundleFile.getEntry(BUNDLE_PROPERTY_ENTRY_NAME);
if (be != null) {
Properties p = new Properties();
try {
p.load(be.getInputStream());
... |
java | public Period plusDays(long daysToAdd) {
if (daysToAdd == 0) {
return this;
}
return create(years, months, Jdk8Methods.safeToInt(Jdk8Methods.safeAdd(days, daysToAdd)));
} |
python | def media_artist(self):
"""Artist of current playing media (Music track only)."""
try:
artists = self.session['NowPlayingItem']['Artists']
if len(artists) > 1:
return artists[0]
else:
return artists
except KeyError:
... |
python | def move(self, source_path, destination_path):
"""
Rename/move an object from one GCS location to another.
"""
self.copy(source_path, destination_path)
self.remove(source_path) |
python | def padded_accuracy_topk(logits, labels, k):
"""Percentage of times that top-k predictions matches labels on non-0s."""
with tf.variable_scope("padded_accuracy_topk", values=[logits, labels]):
logits, labels = _pad_tensors_to_same_length(logits, labels)
weights = tf.to_float(tf.not_equal(labels, 0))
eff... |
python | def chk_date_arg(s):
"""Checks if the string `s` is a valid date string.
Return True of False."""
if re_date.search(s) is None:
return False
comp = s.split('-')
try:
dt = datetime.date(int(comp[0]), int(comp[1]), int(comp[2]))
return True
except Exception as e:
r... |
python | def _check_hyperedge_id_consistency(self):
"""Consistency Check 4: check for misplaced hyperedge ids
:raises: ValueError -- detected inconsistency among dictionaries
"""
# Get list of hyperedge_ids from the hyperedge attributes dict
hyperedge_ids_from_attributes = set(self._hyp... |
java | private static Pair<Double, ClassicCounter<Integer>> readModel(File modelFile, boolean multiclass) {
int modelLineCount = 0;
try {
int numLinesToSkip = multiclass ? 13 : 10;
String stopToken = "#";
BufferedReader in = new BufferedReader(new FileReader(modelFile));
for (int ... |
python | def to_dict(self):
'''A representation of that publication data that matches the schema we use in our databases.'''
if not self.record_type == 'journal':
# todo: it may be worthwhile creating subclasses for each entry type (journal, conference, etc.) with a common
# API e.g. to_j... |
python | def get_file_uuid(fpath, hasher=None, stride=1):
""" Creates a uuid from the hash of a file
"""
if hasher is None:
hasher = hashlib.sha1() # 20 bytes of output
#hasher = hashlib.sha256() # 32 bytes of output
# sha1 produces a 20 byte hash
hashbytes_20 = get_file_hash(fpath, hasher=... |
python | def predicates_overlap(tags1: List[str], tags2: List[str]) -> bool:
"""
Tests whether the predicate in BIO tags1 overlap
with those of tags2.
"""
# Get predicate word indices from both predictions
pred_ind1 = get_predicate_indices(tags1)
pred_ind2 = get_predicate_indices(tags2)
# Return... |
python | def rename_afw_states(afw: dict, suffix: str):
""" Side effect on input! Renames all the states of the AFW
adding a **suffix**.
It is an utility function used during testing to avoid automata to have
states with names in common.
Avoid suffix that can lead to special name like "as", "and",...
... |
python | def touch_last_worklog(self, issue):
"""
Touch the last worklog for an issue (changes the updated date on the worklog). We use this date as the 'mark' for
determining the time elapsed for the next log entry.
"""
worklogs = self.get_worklog(issue)
if worklogs:
... |
python | def FinalizeTransferUrl(self, url):
"""Modify the url for a given transfer, based on auth and version."""
url_builder = _UrlBuilder.FromUrl(url)
if self.global_params.key:
url_builder.query_params['key'] = self.global_params.key
return url_builder.url |
java | private static ZonedDateTime ofLenient(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone) {
Jdk8Methods.requireNonNull(localDateTime, "localDateTime");
Jdk8Methods.requireNonNull(offset, "offset");
Jdk8Methods.requireNonNull(zone, "zone");
if (zone instanceof ZoneOffset && offs... |
java | @Override
public Pair<ByteSlice, ByteSlice> splitOnLastLineEnd() {
Pair<ByteSlice, ByteSlice> sliced = suffix.splitOnLastLineEnd();
return Pair.of(ByteSlice.join(this.prefix, sliced.first), sliced.second);
} |
python | def reactions_add(self, *, name: str, **kwargs) -> SlackResponse:
"""Adds a reaction to an item.
Args:
name (str): Reaction (emoji) name. e.g. 'thumbsup'
channel (str): Channel where the message to add reaction to was posted.
e.g. 'C1234567890'
timest... |
java | protected String setEscapedParameter(HttpMessage message, String param, String value) {
return variant.setEscapedParameter(message, originalPair, param, value);
} |
python | def batch_step(self, batch_idx=None):
"""Updates the learning rate for the batch index: ``batch_idx``.
If ``batch_idx`` is None, ``CyclicLR`` will use an internal
batch index to keep track of the index.
"""
if batch_idx is None:
batch_idx = self.last_batch_idx + 1
... |
java | public AbstractExpression getSimpleFilterExpression()
{
if (m_whereExpr != null) {
if (m_joinExpr != null) {
return ExpressionUtil.combine(m_whereExpr, m_joinExpr);
}
return m_whereExpr;
}
return m_joinExpr;
} |
python | def html_document_fromstring(s):
"""Parse html tree from string. Return None if the string can't be parsed.
"""
if isinstance(s, six.text_type):
s = s.encode('utf8')
try:
if html_too_big(s):
return None
return html5parser.document_fromstring(s, parser=_html5lib_parse... |
python | def ReadClientStartupInfoHistory(self, client_id, timerange=None):
"""Reads the full startup history for a particular client."""
from_time, to_time = self._ParseTimeRange(timerange)
history = self.startup_history.get(client_id)
if not history:
return []
res = []
for ts in sorted(history, ... |
java | public void setFontAssetDelegate(
@SuppressWarnings("NullableProblems") FontAssetDelegate assetDelegate) {
this.fontAssetDelegate = assetDelegate;
if (fontAssetManager != null) {
fontAssetManager.setDelegate(assetDelegate);
}
} |
python | def get_path():
'''
Returns a list of items in the SYSTEM path
CLI Example:
.. code-block:: bash
salt '*' win_path.get_path
'''
ret = salt.utils.stringutils.to_unicode(
__utils__['reg.read_value'](
'HKEY_LOCAL_MACHINE',
'SYSTEM\\CurrentControlSet\\Contr... |
java | @Override
protected void _fit(Dataframe trainingData) {
TrainingParameters trainingParameters = knowledgeBase.getTrainingParameters();
Configuration configuration = knowledgeBase.getConfiguration();
//reset previous entries on the bundle
resetBundle();
//initialize the part... |
python | def get_event_transfers(self, id, **data):
"""
GET /events/:id/transfers/
Returns a list of :format:`transfers` for the event.
"""
return self.get("/events/{0}/transfers/".format(id), data=data) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.