language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | private int createNewFilesList(File sourceFiles, List compilerFailureFileNames, JspOptions options) {
String javaFileName;
int compileCount = 0;
if (compilerFailureFileNames != null && compilerFailureFileNames.size() > 0) {
int firstFailLoc = translatedJspsFileNames.indexOf((String)... |
python | def meta(*bases, **kwargs):
"""
Allows unique syntax similar to Python 3 for working with metaclasses in
both Python 2 and Python 3.
Examples
--------
>>> class BadMeta(type): # An usual metaclass definition
... def __new__(mcls, name, bases, namespace):
... if "bad" not in namespace: # A bad con... |
java | public static Digester newDigester(boolean xmlValidation,
boolean xmlNamespaceAware, RuleSet rule, boolean blockExternal) {
Digester digester = new Digester();
digester.setNamespaceAware(xmlNamespaceAware);
digester.setValidating(xmlValidation);
digester.setUseContextClassLoader(true);
EntityResol... |
python | def interact(self, banner=None):
"""Closely emulate the interactive Python console.
The optional banner argument specify the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the cur... |
java | private ArrayList/*<Filter>*/ lookupFilters(String filterExpression) {
assert filterExpression != null;
assert !filterExpression.equals("");
/* todo: perf. caching or abstraction to make this faster */
ArrayList/*<Filter>*/ filters = new ArrayList/*<Filter>*/();
for(int i = 0; ... |
python | def share(self, plotters, keys=None, draw=None, auto_update=False):
"""
Share the formatoptions of this plotter with others
This method shares the formatoptions of this :class:`Plotter` instance
with others to make sure that, if the formatoption of this changes,
those of the oth... |
java | public static GlobalApp ensureGlobalApp( HttpServletRequest request, HttpServletResponse response )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return ensureGlobalApp( request, response, servletContext );
} |
java | @XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "crsRef")
public JAXBElement<CRSRefType> createCrsRef(CRSRefType value) {
return new JAXBElement<CRSRefType>(_CrsRef_QNAME, CRSRefType.class, null, value);
} |
java | private IEntityGroup igetDistinguishedGroup(String name) throws GroupsException {
try {
String key = getDistinguishedGroupKey(name);
return compositeGroupService.findGroup(key);
} catch (Exception ex) {
throw new GroupsException(
"GroupService.getD... |
java | @GET
@Path("/download/{file}")
public Response downloadFile(final @PathParam("file") String file) {
Config config = createConfig();
String uploadDir = config.getStringValue(FILE_SYSTEM_DIRECTORY);
String filePath = uploadDir + "/" + file;
return getResponseByFile(filePath);
} |
java | public static boolean hasRoles(List<String> roleNames) throws Throwable
{
DEADBOLT_HANDLER.beforeRoleCheck();
RoleHolder roleHolder = getRoleHolder();
return roleHolder != null &&
roleHolder.getRoles() != null &&
hasAllRoles(roleHolder,
... |
java | @SafeVarargs
@SuppressWarnings("unchecked")
public static <T extends Exception> Optional<T> firstFail(ActionE0<T>... tasks) {
for (ActionE0<T> task : tasks) {
try {
task.call();
} catch (Exception t) {
return Optional.of((T) t);
}
}
return Optional.empty();
... |
java | String
rrToString() {
StringBuffer sb = new StringBuffer();
sb.append(mailbox);
sb.append(" ");
sb.append(textDomain);
return sb.toString();
} |
java | protected void removeAndProcess(Collection<R> requests) {
try {
Collection<R> removed=new ArrayList<>();
Iterator<R> it=requests.iterator();
R first_req=it.next();
removed.add(first_req);
it.remove();
while(it.hasNext()) {
... |
java | @Override
public AuthConfigProvider getConfigProvider(String layer, String appContext, RegistrationListener listener) {
CacheEntry<AuthConfigProvider, RegistrationContext, Collection<RegistrationListener>> entry = null;
lock.lock();
try {
if (layer != null && appContext != null)
... |
python | def _growlnotify(title, message):
""" Shows growl notification message via `growlnotify` command.
`title`
Notification title.
`message`
Notification message.
"""
try:
paths = common.extract_app_paths(['growlnotify'])
except ValueError:
return... |
python | def split_arg_to_name_type_value(self, args_list):
"""Split argument text to name, type, value."""
for arg in args_list:
arg_type = None
arg_value = None
has_type = False
has_value = False
pos_colon = arg.find(':')
pos_e... |
python | def to_bytes(graph: BELGraph, protocol: int = HIGHEST_PROTOCOL) -> bytes:
"""Convert a graph to bytes with pickle.
Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable
pickle, choose 0, 1, or 2.
:param graph: A BEL network
:param protoco... |
java | public static <V extends FeatureVector<?>> VectorFieldTypeInformation<V> typeRequest(Class<? super V> cls, int mindim, int maxdim) {
return new VectorFieldTypeInformation<>(cls, mindim, maxdim);
} |
python | def get(object_ids):
"""Get a remote object or a list of remote objects from the object store.
This method blocks until the object corresponding to the object ID is
available in the local object store. If this object is not in the local
object store, it will be shipped from an object store that has it ... |
python | def set_parent_commit(self, commit, check=True):
"""Set this instance to use the given commit whose tree is supposed to
contain the .gitmodules blob.
:param commit:
Commit'ish reference pointing at the root_tree, or None to always point to the
most recent commit
... |
java | private char readEscapedChar() throws IOException {
int ch = getChar();
switch (ch) {
case '"' : return '"';
case '\'' : return '\'';
case '\\' : return '\\';
case '/' : return '/';
case 'n' : return '\n';
case 'r' : return '\r';
case 't' : return '\t';
case 'f' :... |
python | def hendrixLauncher(action, options, with_tiempo=False):
"""
Decides which version of HendrixDeploy to use and then
launches it.
"""
if options['key'] and options['cert'] and options['cache']:
from hendrix.deploy import hybrid
HendrixDeploy = hybrid.HendrixDeployHybrid
elif optio... |
python | def dump_object(self, value):
"""Dumps an object into a string for redis. By default it serializes
integers as regular string and pickle dumps everything else.
"""
t = type(value)
if t is int or t is long:
return str(value)
return '!' + pickle.dumps(value) |
java | @Override
protected void onTimer(AjaxRequestTarget target)
{
getComponent().send(getComponent().getPage(), Broadcast.DEPTH,
new RefreshPayload<Void>(target));
} |
java | public MultimapWithProtoValuesFluentAssertion<M> ignoringFieldDescriptorsForValues(
FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) {
return ignoringFieldDescriptorsForValues(asList(firstFieldDescriptor, rest));
} |
python | def normalize_address(self, addr, is_write=False, convert_to_valueset=False, target_region=None, condition=None): #pylint:disable=arguments-differ
"""
Convert a ValueSet object into a list of addresses.
:param addr: A ValueSet object (which describes an address)
:param is_write: Is this... |
python | def autoconf(self):
"""Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
"""
opcinfo = OPCinfo(self._host, self._port, self._user, self._password,
self._monpath, self.... |
python | def _randomize_speed(base_speed: int, sigma: int = None) -> int:
"""
Creates a variation in wind speed
Args:
base_speed: base wind speed
sigma: sigma value for gaussian variation
Returns: random wind speed
"""
if sigma is None:
int_s... |
python | def attach(self, engine, start=Events.STARTED, pause=Events.COMPLETED, resume=None, step=None):
""" Register callbacks to control the timer.
Args:
engine (Engine):
Engine that this timer will be attached to.
start (Events):
Event which should star... |
python | def estimate_frequency(self, start: int, end: int, sample_rate: float):
"""
Estimate the frequency of the baseband signal using FFT
:param start: Start of the area that shall be investigated
:param end: End of the area that shall be investigated
:param sample_rate: Sample rate o... |
java | public void setProductViewDetails(java.util.Collection<ProductViewDetail> productViewDetails) {
if (productViewDetails == null) {
this.productViewDetails = null;
return;
}
this.productViewDetails = new java.util.ArrayList<ProductViewDetail>(productViewDetails);
} |
java | public boolean isRequestComplete() {
PooledByteBuffer[] data = getAttachment(BUFFERED_REQUEST_DATA);
if(data != null) {
return false;
}
return allAreSet(state, FLAG_REQUEST_TERMINATED);
} |
python | def get_settings(self):
"""Get settings."""
postgame = self.get_postgame()
return {
'type': (
self._header.lobby.game_type_id,
self._header.lobby.game_type
),
'difficulty': (
self._header.scenario.game_settings.d... |
java | public void setElseif(boolean newElseif)
{
boolean oldElseif = elseif;
elseif = newElseif;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, SimpleExpressionsPackage.IF_CONDITION__ELSEIF, oldElseif, elseif));
} |
python | def preprocess_section(self, section):
"""
Preprocessors a given section into it's components.
"""
lines = []
in_codeblock = False
keyword = None
components = {}
for line in section.content.split('\n'):
line = line.strip()
if line.startswith("```"):
in_codeblock = no... |
java | protected long checkSlice(long offset, long length) {
checkOffset(offset);
if (limit == -1) {
if (offset + length > capacity) {
if (capacity < maxCapacity) {
capacity(calculateCapacity(offset + length));
} else {
throw new BufferUnderflowException();
}
}
... |
java | public BigDecimal adjust(BigDecimal n) {
return NumberFormattingUtils.setup(n,
options.roundMode(), formatMode, minIntDigits, maxFracDigits, minFracDigits, maxSigDigits, minSigDigits);
} |
python | def component_for_entity(self, entity: int, component_type: Type[C]) -> C:
"""Retrieve a Component instance for a specific Entity.
Retrieve a Component instance for a specific Entity. In some cases,
it may be necessary to access a specific Component instance.
For example: directly modif... |
java | public Marshaller getMarshaller(String soapPackage) throws JAXBException
{
JAXBContextHolder jAXBContextHolder = this.get(soapPackage);
if (jAXBContextHolder == null)
return null; // Never
return jAXBContextHolder.getMarshaller();
} |
python | def row_processor_table(self, ignore_none=False):
"""Create a row processor from the schema, to convert the text values from the
CSV into real types"""
from rowgenerators.rowpipe import Table
type_map = {
None: None,
'string': 'str',
'text': 'str',
... |
java | public RequiredOrientResource[] getRequiredOrientResources(Class<?> clazz)
{
RequiredOrientResources resources = clazz.getAnnotation(RequiredOrientResources.class);
RequiredOrientResource singleResource = clazz.getAnnotation(RequiredOrientResource.class);
if(resources==null && singleResource==null) return null;
... |
java | public static CharSequence ltrim(CharSequence str)
{
int len;
int i;
if(str == null || (len = str.length()) <= 0)
return "";
for(i=0;i<len;i++)
if(!Character.isWhitespace(str.charAt(i)))
break;
if(i>=len)
return "";
return str.subSequence(i, len);
} |
python | def p_preprocessor_line_line_file(p):
""" preproc_line : _LINE INTEGER STRING
"""
p.lexer.lineno = int(p[2]) + p.lexer.lineno - p.lineno(3) - 1
gl.FILENAME = p[3] |
python | def jp_compose(s, base=None):
""" append/encode a string to json-pointer
"""
if s == None:
return base
ss = [s] if isinstance(s, six.string_types) else s
ss = [s.replace('~', '~0').replace('/', '~1') for s in ss]
if base:
ss.insert(0, base)
return '/'.join(ss) |
java | public PubsubFuture<List<String>> publish(final List<Message> messages, final String canonicalTopic) {
Topic.validateCanonicalTopic(canonicalTopic);
return publish0(messages, canonicalTopic);
} |
java | @Pure
public static byte byteValue(CharSequence value) {
try {
return Byte.decode(value.toString());
} catch (Throwable exception) {
// Silent exception.
}
return 0;
} |
python | def resolve_schema(self, data):
"""Function to resolve a schema in a parameter or response - modifies the
corresponding dict to convert Marshmallow Schema object or class into dict
:param APISpec spec: `APISpec` containing refs.
:param dict|str data: either a parameter or response dicti... |
java | public EClass getIfcServiceLife() {
if (ifcServiceLifeEClass == null) {
ifcServiceLifeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(508);
}
return ifcServiceLifeEClass;
} |
java | private static boolean needIncrement(long ldivisor, int roundingMode,
int qsign, MutableBigInteger mq, long r) {
assert r != 0L;
int cmpFracHalf;
if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
cmpFracHalf = 1; // 2 * r can't fit i... |
python | def activate_minion_cachedir(minion_id, base=None):
'''
Moves a minion from the requested/ cachedir into the active/ cachedir. This
means that Salt Cloud has verified that a requested instance properly
exists, and should be expected to exist from here on out.
'''
if base is None:
base = ... |
java | @Override
public String[] getRequestValue(final Request request) {
if (isPresent(request)) {
String[] paramValues = request.getParameterValues(getId());
return removeEmptyStrings(paramValues);
} else {
return getValue();
}
} |
python | def is_connection_dropped(conn): # Platform-specific
"""
Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycli... |
java | private Collection<Class<?>> getListenerClasses(Collection<String> names)
throws GuacamoleException {
// If no classnames are provided, just return an empty list
if (names == null)
return Collections.<Class<?>>emptyList();
// Define all auth provider classes
Col... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.FND__TYPE_FC_DESC:
return getTypeFcDesc();
case AfplibPackage.FND__FT_WT_CLASS:
return getFtWtClass();
case AfplibPackage.FND__FT_WD_CLASS:
return getFtWdClass();
case Afpl... |
python | def signature(self, block_size=None):
"Calculates signature for local file."
kwargs = {}
if block_size:
kwargs['block_size'] = block_size
return librsync.signature(open(self.path, 'rb'), **kwargs) |
java | @Override
public CommerceVirtualOrderItem findByUUID_G(String uuid, long groupId)
throws NoSuchVirtualOrderItemException {
CommerceVirtualOrderItem commerceVirtualOrderItem = fetchByUUID_G(uuid,
groupId);
if (commerceVirtualOrderItem == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO... |
python | async def async_enqueue_convert(self, converter, from_, to):
'''
Enqueue use of the given converter to convert to given
from and to resources.
'''
worker = self.pick_sticky(from_.url_string)
args = (converter, from_, to)
await worker.enqueue(enums.Task.CONVERT, ar... |
python | def make_dot_graph(filename, format='png', tool='dot', stop=True):
"""Creates a graph using a Graphviz tool that supports the dot language. It
will output into a file specified by filename with the format specified.
Setting stop to True will stop the current trace.
"""
if stop:
stop_trace()
... |
python | def compose(self, to, subject, text):
"""Login required. Sends POST to send a message to a user. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/compose/``
:param to: username or :class`things.A... |
java | public DescribeEnvironmentMembershipsRequest withPermissions(String... permissions) {
if (this.permissions == null) {
setPermissions(new java.util.ArrayList<String>(permissions.length));
}
for (String ele : permissions) {
this.permissions.add(ele);
}
retur... |
java | private static void bind(final NioDatagramChannel channel,
final ChannelFuture future, final InetSocketAddress address) {
boolean bound = false;
boolean started = false;
try {
// First bind the DatagramSocket the specified port.
channel.getDat... |
python | def get_table(name, table, table_file, **kwargs):
'''
Retrieve data from a Junos device using Tables/Views
name (required)
task definition
table (required)
Name of PyEZ Table
file
YAML file that has the table specified in table parameter
path:
Path of location... |
java | public static void notEmpty(String string, String message) {
if (string == null || string.length() == 0) {
throw new IllegalArgumentException(message);
}
} |
java | public long until(
T end,
U unit
) {
return this.getChronology().getRule(unit).between(this.getContext(), end);
} |
java | public void setFEGName(String newFEGName) {
String oldFEGName = fegName;
fegName = newFEGName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.EFG__FEG_NAME, oldFEGName, fegName));
} |
python | def find_clusters(struct, connected_matrix):
"""
Finds bonded clusters of atoms in the structure with periodic boundary
conditions.
If there are atoms that are not bonded to anything, returns [0,1,0]. (For
faster computation time)
Author: "Gowoon Cheon"
Email: "gcheon@stanford.edu"
Ar... |
python | def compare(a, b):
"""Compares two timestamps.
``a`` and ``b`` must be the same type, in addition to normal
representations of timestamps that order naturally, they can be rfc3339
formatted strings.
Args:
a (string|object): a timestamp
b (string|object): another timestamp
Returns:... |
java | @Override
public void start() {
try {
url = new URL(getStringSetting(SETTING_URL, DEFAULT_STACKDRIVER_API_URL));
} catch (MalformedURLException e) {
throw new EmbeddedJmxTransException(e);
}
apiKey = getStringSetting(SETTING_TOKEN);
if (getStringSetting(SETTING_PROXY_HOST, null) != null && !getString... |
python | def summary(self, title=None, complexity=False):
"""
Generates a summary.
:param title: optional title
:type title: str
:param complexity: whether to print the complexity information as well
:type complexity: bool
:return: the summary
:rtype: str
... |
python | def get_record_rdd_from_rdd(
self,
rdd: 'RDD',
data_processor: DataProcessor = SimpleDictionaryDataProcessor(),
) -> 'RDD':
"""
Converts a RDD of raw events into the `Record`s format for processing. `data_processor` is
used to process the per row data to c... |
java | public CompletableFuture<ExecutionResult> executeAsync(ExecutionInput executionInput) {
try {
log.debug("Executing request. operation name: '{}'. query: '{}'. variables '{}'", executionInput.getOperationName(), executionInput.getQuery(), executionInput.getVariables());
InstrumentationSt... |
python | def reverse_cyk_transforms(root):
# type: (Nonterminal) -> Nonterminal
"""
Reverse transformation made to grammar before CYK.
Performs following steps:
- transform from chomsky normal form
- restore unit rules
- restore epsilon rules
:param root: Root node... |
java | public void marshall(VmServer vmServer, ProtocolMarshaller protocolMarshaller) {
if (vmServer == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(vmServer.getVmServerAddress(), VMSERVERADDRESS_BINDING)... |
python | def process(self, **context):
"""
Render value_template of the parameter using context.
:param context: Processing context
"""
env = Environment(extensions=['jinja2_time.TimeExtension'])
value_template = env.from_string(self.value_template)
return... |
java | public void text(String expectedText, double seconds) {
double end = System.currentTimeMillis() + (seconds * 1000);
try {
double timeTook = elementPresent(seconds);
WebDriverWait wait = new WebDriverWait(element.getDriver(), (long) (seconds - timeTook), DEFAULT_POLLING_INTERVAL);... |
python | def url_escape(value: Union[str, bytes], plus: bool = True) -> str:
"""Returns a URL-encoded version of the given value.
If ``plus`` is true (the default), spaces will be represented
as "+" instead of "%20". This is appropriate for query strings
but not for the path component of a URL. Note that this... |
python | def _url_chunk_join(self, *args):
"""Join the arguments together to form a predictable URL chunk."""
# Strip slashes from either side of each path piece.
pathlets = map(lambda s: s.strip('/'), args)
# Remove empty pieces.
pathlets = filter(None, pathlets)
url = '/'.join(p... |
java | @Override
public RemoveTagsFromVaultResult removeTagsFromVault(RemoveTagsFromVaultRequest request) {
request = beforeClientExecution(request);
return executeRemoveTagsFromVault(request);
} |
python | def from_git_rev_read(path):
"""Retrieve given file path contents of certain Git revision."""
if ":" not in path:
raise ValueError("Path identifier must start with a revision hash.")
cmd = "git", "show", "-t", path
try:
return subprocess.check_output(cmd).rstrip().decode("utf-8")
ex... |
python | def delete_file(self, target, path):
"""Delete a file from a device
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances
:param path: The path on the target to the file to d... |
python | def download_channel_image(self, channel_name, plate_name,
well_name, well_pos_y, well_pos_x,
cycle_index=0, tpoint=0, zplane=0, correct=True, align =False):
'''Downloads a channel image.
Parameters
----------
channel_name: str
name of the channel
... |
java | @Override
protected void onInitializeComponents()
{
lpNoProxy = new JLayeredPane();
lpNoProxy.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
lpHostOrIpaddress = new JLayeredPane();
lpHostOrIpaddress.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
rdbtnManualProxyConfiguration ... |
python | def parse(self,xml):
"""
Parses an XML document into a form read for insertion into the database
xml = the xml document to be parsed
"""
if not self.xmlparser:
raise LIGOLwParseError, "pyRXP parser not initialized"
if not self.lwtparser:
raise LIGOLwParseError, "LIGO_LW tuple parser... |
java | private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
// TODO: it looks to me {dlf} that the serialization code was never updated
// to handle the actual/valid ulocale fields.
stream.defaultReadObject();
///CLOVER:OFF
// we don't... |
java | public ComponentModel scan(Class<?> bpmClass, SwitchYardNamespace switchyardNamespace) throws IOException {
if (switchyardNamespace == null) {
switchyardNamespace = SwitchYardNamespace.DEFAULT;
}
BPM bpm = bpmClass.getAnnotation(BPM.class);
if (bpm == null) {
thro... |
python | def update(self, document_id, update_spec, namespace, timestamp):
"""Apply updates given in update_spec to the document whose id
matches that of doc.
"""
# Commit outstanding changes so that the document to be updated is the
# same version to which the changes apply.
sel... |
python | def _range10_90(x):
'''
Returns the 10th-90th percentile range of array :py:obj:`x`.
'''
x = np.delete(x, np.where(np.isnan(x)))
i = np.argsort(x)
a = int(0.1 * len(x))
b = int(0.9 * len(x))
return x[i][b] - x[i][a] |
python | def ls(directory, long_format, recursive):
"""List contents of a directory on the board.
Can pass an optional argument which is the path to the directory. The
default is to list the contents of the root, /, path.
For example to list the contents of the root run:
ampy --port /board/serial/port ... |
python | def gather(self):
"""Return all the messages represented by this object.
This will always be a list of a single message.
:rtype: list[~uamqp.message.Message]
"""
if self.state in constants.RECEIVE_STATES:
raise TypeError("Only new messages can be gathered.")
... |
python | def describe_topic_rule(ruleName,
region=None, key=None, keyid=None, profile=None):
'''
Given a topic rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_topic_rule myrule
'... |
python | def view_meta_admonition(admonition_name, name=None):
"""List all found admonition from all the rst files found in directory.
view_meta_admonition is called by the 'meta' url: /__XXXXXXX__
where XXXXXXX represents and admonition name, like:
* todo
* warning
* danger
* ...
.. note:: th... |
python | def convertColor(self, svgAttr):
"Convert string to a RL color object."
# fix it: most likely all "web colors" are allowed
predefined = "aqua black blue fuchsia gray green lime maroon navy "
predefined = predefined + "olive orange purple red silver teal white yellow "
predefined... |
java | public void fireEndEntity(String name)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
flushMyWriter();
// we do not need to handle this.
} |
python | def _unpack_int_base128(varint, offset):
"""Implement Perl unpack's 'w' option, aka base 128 decoding."""
res = ord(varint[offset])
if ord(varint[offset]) >= 0x80:
offset += 1
res = ((res - 0x80) << 7) + ord(varint[offset])
if ord(varint[offset]) >= 0x80:
... |
java | public void drawCircle(Object parent, String name, Coordinate position, double radius, ShapeStyle style) {
if (isAttached()) {
Element circle = helper.createOrUpdateElement(parent, name, "oval", style);
// Real position is the upper left corner of the circle:
applyAbsolutePosition(circle, new Coordinate(pos... |
java | public static String getBoundAddressForId(Configuration configuration, String serverId) {
String hostPort = configuration.getString(ATLAS_SERVER_ADDRESS_PREFIX +serverId);
boolean isSecure = configuration.getBoolean(SecurityProperties.TLS_ENABLED);
String protocol = (isSecure) ? "https://" : "ht... |
python | def parallel_evaluation_mp(candidates, args):
"""Evaluate the candidates in parallel using ``multiprocessing``.
This function allows parallel evaluation of candidate solutions.
It uses the standard multiprocessing library to accomplish the
parallelization. The function assigns the evaluation of each
... |
java | private void sortGrantsByStartTime(List<ResourceGrant> grants) {
Collections.sort(grants, new Comparator<ResourceGrant>() {
@Override
public int compare(ResourceGrant g1, ResourceGrant g2) {
if (g1.grantedTime < g2.grantedTime) {
return 1;
}
if (g1.grantedTime > g2.gran... |
java | public static int getIntSelector(SlingHttpServletRequest request, int defaultValue) {
String[] selectors = request.getRequestPathInfo().getSelectors();
for (String selector : selectors) {
try {
return Integer.parseInt(selector);
} catch (NumberFormatException nfex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.