language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | static boolean isValidPropertyName(FeatureSet mode, String name) {
if (isValidSimpleName(name)) {
return true;
} else {
return mode.has(Feature.KEYWORDS_AS_PROPERTIES) && TokenStream.isKeyword(name);
}
} |
java | private void initTable()
{
namespaces = new JTable(new FilterTableModel());
namespaces.removeColumn(namespaces.getColumn("#"));
namespaces.setFillsViewportHeight(true);
namespaces.setPreferredScrollableViewportSize(new Dimension(500, 70));
// Create the scroll pane and add the table to it.
JScrollPane s... |
python | def t_VAR(self, t):
r'[a-zA-Z_][a-zA-Z0-9_]*'
t.type = self.reserved.get(t.value.lower(), 'VAR')
return t |
java | public static <D, I, R> Mapping<D, R> compose(Mapping<D, ? extends I> first, Mapping<? super I, R> second) {
return new MappingComposition<D, I, R>(first, second);
} |
python | def match_any_learning_objective(self, match):
"""Matches an item with any objective.
arg: match (boolean): ``true`` to match items with any
learning objective, ``false`` to match items with no
learning objectives
*compliance: mandatory -- This method must be ... |
python | def as_json(self, ensure_ascii=False):
"""Property return key-value json-string from __slots__."""
return json.dumps(self.as_dict, ensure_ascii=ensure_ascii) |
python | def get_baseparser_extended_df(sample, bp_lines, ref, alt):
"""Turn baseParser results into a dataframe"""
columns = "chrom\tpos\tref\tcov\tA\tC\tG\tT\t*\t-\t+".split()
if bp_lines is None:
return None
# change baseparser output to get most common maf per indel
bpdf = pd.DataFrame([[sample]... |
python | def _compile_dimension_size(self, base_index, array,
property, sized_elements):
"""Build one set of col widths or row heights."""
sort_index = base_index + 2
sized_elements.sort(key=lambda x: x[sort_index])
for element_data in sized_elements:
s... |
java | public <T> Graph<K, VV, EV> joinWithVertices(DataSet<Tuple2<K, T>> inputDataSet,
final VertexJoinFunction<VV, T> vertexJoinFunction) {
DataSet<Vertex<K, VV>> resultedVertices = this.getVertices()
.coGroup(inputDataSet).where(0).equalTo(0)
.with(new ApplyCoGroupToVertexValues<>(vertexJoinFunction))
.n... |
java | public void map(final Group group, final Role role)
{
this.getRoleMappings().add(new RoleMapping(group, role));
} |
java | public void insert_u64(final long argIn) {
attributeValue_5.data_format = AttrDataFormat.FMT_UNKNOWN;
final long[] values = new long[1];
values[0] = argIn;
attributeValue_5.w_dim.dim_x = 1;
attributeValue_5.w_dim.dim_y = 0;
if (use_union) {
attributeValue_5.value.ulong64_att_value(values);
} else {
... |
java | public static ApplicationContext contextMergedBeans(Map<String, ?> extraBeans, Class<?> config) {
final DefaultListableBeanFactory parentBeanFactory = buildListableBeanFactory(extraBeans);
//loads the annotation classes and add definitions in the context
GenericApplicationContext parent... |
python | def warn_sf(messages, response, verbs=None, klass=SalesforceWarning):
"""Issue a warning SalesforceWarning, with message combined from message and data from SFDC response"""
warnings.warn(klass(messages, response, verbs), stacklevel=2) |
java | public boolean isLinux() {
if(!isLinuxDone) {
String agent = req.getHeader("user-agent");
isLinux=agent == null || agent.toLowerCase(Locale.ROOT).contains("linux");
isLinuxDone=true;
}
return isLinux;
} |
python | def layout(mtf_graph, mesh_shape, mtf_outputs=()):
"""Compute layout rules based on a computational graph and mesh shape.
Args:
mtf_graph: a mtf.Graph.
mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension.
mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs
of the c... |
python | def file_sizes(self):
"""Returns total filesize (in MB)"""
size = sum(map(os.path.getsize, self.file_list))
return size / 1024 / 1024 |
python | def merge_function_with_indicator(function, indicator, alternative):
'''Returns a function such that a call to it is equivalent to:
if indicator(x):
return function(x)
else:
return alternative
Note that ``function`` is not called if indicator evaluates to False.
:param function:
... |
python | def exception_message():
"""Create a message with details on the exception."""
exc_type, exc_value, exc_tb = exc_info = sys.exc_info()
return {'exception': {'type': exc_type,
'value': exc_value,
'traceback': exc_tb},
'traceback': traceback.form... |
java | protected void initBroadcastInputsSerializers(int numBroadcastInputs) throws Exception {
this.broadcastInputSerializers = new TypeSerializerFactory[numBroadcastInputs];
this.broadcastInputIterators = new MutableObjectIterator[numBroadcastInputs];
for (int i = 0; i < numBroadcastInputs; i++) {
// ------------... |
java | private static boolean updateAttributeIfExist(String key, CoreDictionary.Attribute attribute, TreeMap<String, CoreDictionary.Attribute> map, TreeMap<Integer, CoreDictionary.Attribute> rewriteTable)
{
int wordID = CoreDictionary.getWordID(key);
CoreDictionary.Attribute attributeExisted;
if (w... |
java | @SuppressWarnings("unchecked")
public static ChannelOperations.OnSetup channelOperationFactory(AbstractBootstrap<?, ?> b) {
Objects.requireNonNull(b, "bootstrap");
ChannelOperations.OnSetup ops =
(ChannelOperations.OnSetup) b.config()
.options()
... |
python | def cleanUpdatesList(self, col, cellIdx, seg):
"""
Removes any update that would be for the given col, cellIdx, segIdx.
NOTE: logically, we need to do this when we delete segments, so that if
an update refers to a segment that was just deleted, we also remove
that update from the update list. Howeve... |
java | @Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
throws Exception {
if (msg instanceof SendGrpcFrameCommand) {
sendGrpcFrame(ctx, (SendGrpcFrameCommand) msg, promise);
} else if (msg instanceof SendResponseHeadersCommand) {
sendResponseHeaders(ctx, (... |
python | def grad(func, argnum=None):
"""Return function that computes gradient of arguments.
Parameters
----------
func: a python function
The forward (loss) function.
argnum: an int or a list of int
The index of argument to calculate gradient for.
Returns
-------
grad_func: a ... |
java | public static ValueNode toValueNode(Object o){
if(o == null) return NULL_NODE;
if(o instanceof ValueNode) return (ValueNode)o;
if(o instanceof Class) return createClassNode((Class)o);
else if(isPath(o)) return new PathNode(o.toString(), false, false);
else if(isJson(o)) return cr... |
python | def _tree_line(self, no_type: bool = False) -> str:
"""Return the receiver's contribution to tree diagram."""
keys = (" [" + " ".join([k[0] for k in self.keys]) + "]"
if self.keys else "")
return super()._tree_line() + keys |
python | def set_http_body(self, coap_response):
"""
Set http body.
:param coap_response: the coap response
"""
if coap_response.payload is not None:
body = "<html><body><h1>", coap_response.payload, "</h1></body></html>"
self.wfile.write("".join(body))
el... |
python | def _register_if_needed(cls, run_object):
"""Registers Trainable or Function at runtime.
Assumes already registered if run_object is a string. Does not
register lambdas because they could be part of variant generation.
Also, does not inspect interface of given run_object.
Argum... |
java | public String[] getAllUsers()
{
String[] users = new String[allUsers.size()];
allUsers.toArray(users);
return users;
} |
python | def convert(input, type):
"""
Converts input value to request type
:param input: input value
:param type: type to cast
:return: converted value
"""
try:
if not input:
if type == Types.TYPE_STRING:
return ''
... |
java | protected final PrcPurchRetGfe lazyGetPrcPurchRetGfe(
final Map<String, Object> pAddParam) throws Exception {
PrcPurchRetGfe proc = (PrcPurchRetGfe)
this.processorsMap.get(PrcPurchRetGfe.class.getSimpleName());
if (proc == null) {
proc = new PrcPurchRetGfe();
@SuppressWarnings("unchecked")... |
java | public Subject newSubject(final String nameIdFormat, final String nameIdValue,
final String recipient, final ZonedDateTime notOnOrAfter,
final String inResponseTo, final ZonedDateTime notBefore) {
val nameID = getNameID(nameIdFormat, nameIdValue);
... |
python | def get_hmac(self, password):
"""
Returns a Base64 encoded HMAC+SHA512 of the password signed with
the salt specified by ``SECURITY_PASSWORD_SALT``.
:param password: The password to sign.
"""
salt = current_app.config.SECURITY_PASSWORD_SALT
if salt is None:
... |
python | def network_xml(identifier, xml, address=None):
"""Fills the XML file with the required fields.
* name
* uuid
* bridge
* ip
** dhcp
"""
netname = identifier[:8]
network = etree.fromstring(xml)
subelement(network, './/name', 'name', identifier)
subelement(network, './/... |
python | def add_simple_formatter(self, tag_name, format_string, **kwargs):
"""
Installs a formatter that takes the tag options dictionary, puts a value key
in it, and uses it as a format dictionary to the given format string.
"""
def _render(name, value, options, parent, context):
... |
python | def dvds_upcoming(self, **kwargs):
"""Gets the upcoming movies from the API.
Args:
page_limit (optional): number of movies to show per page, default=16
page (optional): results page number, default=1
country (optional): localized data for selected country, default="us"
... |
java | @Nonnull
public static char [] decodeBytesToChars (@Nonnull final byte [] aByteArray, @Nonnull final Charset aCharset)
{
return decodeBytesToChars (aByteArray, 0, aByteArray.length, aCharset);
} |
python | def _get_row_sparse(self, arr_list, ctx, row_id):
""" Get row_sparse data from row_sparse parameters based on row_id. """
# get row sparse params based on row ids
if not isinstance(row_id, ndarray.NDArray):
raise TypeError("row_id must have NDArray type, but %s is given"%(type(row_id... |
java | @Override
public String getOEMDomainName () throws SmbException {
try ( SmbSessionImpl session = this.treeConnection.getSession();
SmbTransportImpl transport = session.getTransport() ) {
SmbNegotiationResponse nego = transport.getNegotiateResponse();
if ( nego instanceo... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.FONT_CODED_GRAPHIC_CHARACTER_SET_GLOBAL_IDENTIFIER__GCSGID:
return getGCSGID();
case AfplibPackage.FONT_CODED_GRAPHIC_CHARACTER_SET_GLOBAL_IDENTIFIER__CPGID:
return getCPGID();
}
... |
python | def slab_from_csl(csl, surface, normal, trans_cry, max_search=20, quick_gen=False):
"""
By linear operation of csl lattice vectors to get the best corresponding
slab lattice. That is the area of a,b vectors (within the surface plane)
is the smallest, the c vector first, has shortest leng... |
java | @Override
public void setVariables(Map<String, String> variables) {
injectVariables(variables, element);
if (timeoutVariable != null) {
timeout = timeoutVariable.getConvertedValue(variables);
}
} |
python | def regular_index(*dfs):
"""
Change & restore the indices of dataframes
Dataframe with duplicate values can be hard to work with.
When split and recombined, you cannot restore the row order.
This can be the case even if the index has unique but
irregular/unordered. This contextmanager resets th... |
java | public ApiSuccessResponse assignInteractionToContact(String id, AssignInteractionToContactData assignInteractionToContactData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = assignInteractionToContactWithHttpInfo(id, assignInteractionToContactData);
return resp.getData();
} |
python | def mktns(self):
"""
Make the schema's target namespace.
@return: namespace representation of the schema's targetNamespace
value.
@rtype: (prefix, URI)
"""
tns = self.root.get("targetNamespace")
tns_prefix = None
if tns is not None:
... |
python | def Name(self):
"""
Get the peer name.
Returns:
str:
"""
name = ""
if self.Version:
name = self.Version.UserAgent
return name |
java | public TransactGetItemsRequest withTransactItems(TransactGetItem... transactItems) {
if (this.transactItems == null) {
setTransactItems(new java.util.ArrayList<TransactGetItem>(transactItems.length));
}
for (TransactGetItem ele : transactItems) {
this.transactItems.add(el... |
java | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
// Get the PlacementService.
PlacementServiceInterface placementService =
adManagerServices.get(session, PlacementServiceInterface.class);
// Get all ad units.
List<AdUnit... |
python | def choose(cls, choices, field="Id", qb=None):
"""
:param choices:
:param field:
:param qb:
:return: Filtered list
"""
return cls.where(build_choose_clause(choices, field), qb=qb) |
java | public void setup(float partialTick)
{
this.partialTick = partialTick;
currentTexture = null;
bindDefaultTexture();
GlStateManager.pushMatrix();
if (ignoreScale)
{
GlStateManager.scale(1F / scaleFactor, 1F / scaleFactor, 1);
}
setupGl();
startDrawing();
} |
java | private void visitObject(MethodVisitor mv, LocalVarInfo param) {
Type paramType = param.getType();
if (Type.getType(Character.class).equals(paramType)) {
mv.visitLdcInsn((char) FORTY_TWO);
mv.visitMethodInsn(INVOKESTATIC, paramType.getInternalName(), "valueOf",
... |
java | public static String getProperty(final Object pbean, final String pname)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return Objects.toString(PropertyUtils.getProperty(pbean, pname), null);
} |
python | def parse_track_header(self, fp):
"""Return the size of the track chunk."""
# Check the header
try:
h = fp.read(4)
self.bytes_read += 4
except:
raise IOError("Couldn't read track header from file. Byte %d."
% self.bytes_read)
... |
python | def bits_to_dict(bits):
"""Convert a Django template tag's kwargs into a dictionary of Python types.
The only necessary types are number, boolean, list, and string.
http://pygments.org/docs/formatters/#HtmlFormatter
from: ["style='monokai'", "cssclass='cssclass',", "boolean='true',", 'num=0,', "list='... |
python | def _islinklike(dir_path):
'''
Parameters
----------
dir_path : str
Directory path.
Returns
-------
bool
``True`` if :data:`dir_path` is a link *or* junction.
'''
dir_path = ph.path(dir_path)
if platform.system() == 'Windows':
if dir_path.isjunction():
... |
java | public void validateName(final String name) {
Validate.validState(
TENANT_NAME_VALIDATOR_PATTERN.matcher(name).matches(),
"Invalid tenant name '%s' -- names must match %s .",
name,
TENANT_NAME_VALIDATOR_REGEX);
} |
java | @Override
public EEnum getIfcSolarDeviceTypeEnum() {
if (ifcSolarDeviceTypeEnumEEnum == null) {
ifcSolarDeviceTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1065);
}
return ifcSolarDeviceTypeEnumEEnum;
} |
python | def wait_sending_last_messages(self):
"""
Requests all channels to close and waits for it.
"""
if self.active and self.online is not False:
self.logger.debug("client sends last %s messages ..."
% ([str(i) + ':' + str(len(x)) for i, x in six.iteri... |
java | @Override
public void stopped() {
// Stop pinger's timer
if (pingTimer != null) {
pingTimer.cancel(false);
pingTimer = null;
}
// Cleanup
responseTimes.clear();
} |
java | @Deprecated
public RemoveTracksFromPlaylistRequest.Builder removeTracksFromPlaylist(
String user_id, String playlist_id, JsonArray tracks) {
return new RemoveTracksFromPlaylistRequest.Builder(accessToken)
.setDefaults(httpManager, scheme, host, port)
.user_id(user_id)
... |
java | public final void setElementAt(int value, int index)
{
if (index >= m_mapSize)
{
int oldSize = m_mapSize;
m_mapSize += m_blocksize;
int newMap[] = new int[m_mapSize];
System.arraycopy(m_map, 0, newMap, 0, oldSize);
m_map = newMap;
}
m_map[index] = value;
} |
python | def _count_files_by_type(self, path, pattern, ignore=True):
"""Count files in the given path, with the given pattern.
If `ignore = True`, skip files in the `_IGNORE_FILES` list.
Returns
-------
num_files : int
"""
# Get all files matching the given path and pat... |
java | public static void closeQuietly(XMLStreamReader reader) {
if (reader != null) {
try {
reader.close();
} catch (XMLStreamException e) {
logger.warn("Error while closing", e);
}
}
} |
java | @SuppressWarnings({ "unchecked", "rawtypes" })
public <T> void set(PreparedStatement stmt, Path<?> path, int i, T value) throws SQLException {
if (value == null || value instanceof Null) {
Integer sqlType = null;
if (path != null) {
ColumnMetadata columnMetadata = Col... |
python | def logical_and(f1, f2): # function factory
'''Logical and from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function
Examples
--------
filter_func=logical_... |
java | public ArrayNode filter(ComparisonExpression expression) {
ArrayNode result = new ObjectMapper().createArrayNode();
if (node.isArray()) {
Iterator<JsonNode> iterator = node.iterator();
int validObjectsCount = 0;
int topCount=0;
while (iterator.hasNext()) {
JsonNode curNode = iterator.next();
... |
python | def get_delta(self, branch, turn_from, tick_from, turn_to, tick_to):
"""Get a dictionary describing changes to the world.
Most keys will be character names, and their values will be dictionaries of
the character's stats' new values, with ``None`` for deleted keys. Characters'
dictionari... |
java | public static Expectations successfullyReachedProtectedResourceWithJwtCookie(String testAction, String protectedUrl, String username) {
return successfullyReachedProtectedResourceWithJwtCookie(testAction, protectedUrl, username, JwtFatConstants.DEFAULT_ISS_REGEX);
} |
python | def add_operation(op, func_name, db):
"""
Registers the given operation within the Ibis SQL translation toolchain
Parameters
----------
op: operator class
name: used in issuing statements to SQL engine
database: database the relevant operator is registered to
"""
full_name = '{0}.{1... |
python | def update(tournament, match, attachment, **params):
"""Update the attributes of a match attachment."""
api.fetch(
"PUT",
"tournaments/%s/matches/%s/attachments/%s" % (tournament, match, attachment),
"match_attachment",
**params) |
python | def showOptionalHeaderData(peInstance):
""" Prints IMAGE_OPTIONAL_HEADER fields. """
print "[+] IMAGE_OPTIONAL_HEADER:\n"
ohFields = peInstance.ntHeaders.optionalHeader.getFields()
for field in ohFields:
if not isinstance(ohFields[field], datadirs.DataDirectory):
print "--> %s ... |
java | @Override
public void loadFromProperties(Properties props) {
String strValue = props.getProperty(container.getSimpleName() + "." + name);
if (strValue == null)
return;
try {
float value = Float.parseFloat(strValue);
set(value);
} catch (NumberForm... |
java | public GitlabServiceEmailOnPush getEmailsOnPush(Integer projectId) throws IOException {
String tailUrl = GitlabProject.URL + "/" + projectId + GitlabServiceEmailOnPush.URL;
return retrieve().to(tailUrl, GitlabServiceEmailOnPush.class);
} |
java | public final Stream<T> filter(final Predicate<? super T> predicate, final int parallelism) {
synchronized (this.state) {
checkState();
return new FilterStream<T>(this, parallelism, predicate);
}
} |
java | public static BufferedImage toImage(@javax.annotation.Nonnull final Component component) {
try {
com.simiacryptus.util.Util.layout(component);
@javax.annotation.Nonnull final BufferedImage img = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
final ... |
python | def warning(self, *args) -> "Err":
"""
Creates a warning message
"""
error = self._create_err("warning", *args)
print(self._errmsg(error))
return error |
python | def as_dict(self, section='Main', **kwargs):
"""Return template context from configs.
"""
items = super(MakesiteParser, self).items(section, **kwargs)
return dict(items) |
python | def add_permissions_menu(self, view_menu_name):
"""
Adds menu_access to menu on permission_view_menu
:param view_menu_name:
The menu name
"""
self.add_view_menu(view_menu_name)
pv = self.find_permission_view_menu("menu_access", view_menu_name)
... |
java | private void findAndInvokeCompatibleSetter(SetterTarget target, String value) throws IllegalAccessException,
InvocationTargetException, NoSuchMethodError
{
Object _objectToChange = target.getObjectToChange();
Method[] _declaredMethods = _objectToChange.getClass().getDeclaredMethods();
String _setterName = tar... |
python | def get_section_metrics(cls):
"""
Get the mapping between metrics and sections in Manuscripts report
:return: a dict with the mapping between metrics and sections in Manuscripts report
"""
return {
"overview": {
"activity_metrics": [Closed, Opened],
... |
java | @SuppressWarnings("unchecked")
public <S extends Object, R extends Object> Response<R> executeQuery(final Query<S, R> query)
throws FreesoundClientException {
final HttpRequest request = buildHTTPRequest(query);
final String credential = buildAuthorisationCredential(query);
if (credential != null) {
reque... |
java | @Override
public UpdateByteMatchSetResult updateByteMatchSet(UpdateByteMatchSetRequest request) {
request = beforeClientExecution(request);
return executeUpdateByteMatchSet(request);
} |
java | public String getDescription()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getDescription");
String desc = _foreignBus.getDescription();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getDescription", desc);
... |
python | def _get_seqs_from_cluster(seqs, seen):
"""
Returns the sequences that are already part of the cluster
:param seqs: list of sequences ids
:param clus_id: dict of sequences ids that are part of a cluster
:returns:
* :code:`already_in`list of cluster id that contained some of the sequences
... |
python | def _string_to_int(self, s):
"""Read an integer in s, in Little Indian. """
base = len(self.alphabet)
return sum((self._letter_to_int(l) * base**lsb
for lsb, l in enumerate(s)
)) |
java | public void sweep() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "Sweep : Stateful Beans = " + ivStatefulBeanList.size());
for (Enumeration<TimeoutElement> e = ivStatefulBeanList.elements(); e.hasMoreElements();) {
TimeoutElement elt = e.nextEl... |
java | public SftpFile getFile(String path) throws SftpStatusException,
SshException {
String absolute = getAbsolutePath(path);
SftpFile file = new SftpFile(absolute, getAttributes(absolute));
file.sftp = this;
return file;
} |
java | public PagedList<ResourceMetricDefinitionInner> listWebWorkerMetricDefinitionsNext(final String nextPageLink) {
ServiceResponse<Page<ResourceMetricDefinitionInner>> response = listWebWorkerMetricDefinitionsNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<ResourceMetricDefini... |
python | def path_wo_ns(obj):
"""
Return path of an instance or instance path without host or namespace.
Creates copy of the object so the original is not changed.
"""
if isinstance(obj, pywbem.CIMInstance):
path = obj.path.copy()
elif isinstance(obj, pywbem.CIMInstanceName):
path = obj.c... |
python | def _scale(self, mode):
"""
Returns value scaling coefficient for the given mode.
"""
if mode in self._mode_scale:
scale = self._mode_scale[mode]
else:
scale = 10**(-self.decimals)
self._mode_scale[mode] = scale
return scale |
python | def cli(env, columns, sortby, volume_id):
"""List ACLs."""
block_manager = SoftLayer.BlockStorageManager(env.client)
access_list = block_manager.get_block_volume_access_list(
volume_id=volume_id)
table = formatting.Table(columns.columns)
table.sortby = sortby
for key, type_name in [('al... |
python | def from_json(cls, data):
"""Create a DDY from a dictionary.
Args:
data = {
"location": ladybug Location schema,
"design_days": [] // list of ladybug DesignDay schemas}
"""
required_keys = ('location', 'design_days')
for key in required_keys:
... |
java | public static int binaryLCA(int x, int y) {
if (x == y) {
return x;
}
int xor = x ^ y;
int idx = getMaxExp(xor);
if (idx == -1) {
throw new UnsupportedOperationException();
}
return replaceBy1and0sFrom(x, idx);
} |
python | def _round_field(values, name, freq):
"""Indirectly access pandas rounding functions by wrapping data
as a Series and calling through `.dt` attribute.
Parameters
----------
values : np.ndarray or dask.array-like
Array-like container of datetime-like values
name : str (ceil, floor, round... |
java | @SuppressWarnings("unused")
protected void handleConfigureResponseOk(RaftMemberContext member, ConfigureRequest request, ConfigureResponse response) {
// Reset the member failure count and update the member's status if necessary.
succeedAttempt(member);
// Update the member's current configuration term a... |
java | public String getReport() {
StringBuffer info = new StringBuffer();
if (!isCachingEnabled()) {
info.append("cache behaviour: DISABLED\n");
} else if (isCachingPermanent()) {
info.append("cache behaviour: PERMANENT\n");
} else {
info.append("cache behaviour: NORMAL\n");
}
info.append("time to live:... |
java | public static CmsSqlBooleanClause makeAnd(I_CmsQueryFragment... fragments) {
CmsSqlBooleanClause result = new CmsSqlBooleanClause("AND");
for (I_CmsQueryFragment fragment : fragments) {
result.addCondition(fragment);
}
return result;
} |
java | private static void arcTo(float lastX, float lastY, float rx, float ry, float angle, boolean largeArcFlag, boolean sweepFlag, float x, float y, PathInterface pather)
{
if (lastX == x && lastY == y) {
// If the endpoints (x, y) and (x0, y0) are identical, then this
// is equivalent to omit... |
python | def get_usrgo2hdrgo(self):
"""Return a dict with all user GO IDs as keys and their respective header GOs as values."""
usrgo2hdrgo = {}
for hdrgo, usrgos in self.hdrgo2usrgos.items():
for usrgo in usrgos:
assert usrgo not in usrgo2hdrgo
usrgo2hdrgo[usr... |
python | def get_template_request(configuration, spec):
"""
Builds API request block.
:param configuration:
:param spec:
:return:
"""
req = RequestHolder()
req.api_method = 'GetUserObjectTemplate'
req.nonce = EBUtils.generate_nonce()
req.api_object ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.