language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def add_image(self, image_path, annotations):
"""Adds an image and its bounding boxes to the current list of files
The bounding boxes are automatically estimated based on the given annotations.
**Parameters:**
``image_path`` : str
The file name of the image, including its full path
``annot... |
java | private boolean noInput(Input input) {
return input.words().isEmpty()
|| (input.words().size() == 1 && input.words().get(0).trim().isEmpty())
|| (input.words().iterator().next().matches("\\s*//.*"));
} |
java | public boolean check() {
// check formalities of IdemixIssuerPublicKey
if (AttributeNames == null || Hsk == null || HRand == null || HAttrs == null
|| BarG1 == null || BarG1.is_infinity() || BarG2 == null
|| HAttrs.length < AttributeNames.length) {
return fals... |
java | static int compilerOptionsMapFromConfig(IConfig config, Map<AccessibleObject, List<Object>> resultMap, boolean propFieldsOnly /* for unit testing */) {
final String sourceMethod = "addCompilerOptionsFromConfig"; //$NON-NLS-1$
final boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
... |
java | @SuppressWarnings("unchecked")
public static <T extends EntityModel<S>, S> PagedModel<T> wrap(Iterable<S> content, PageMetadata metadata) {
Assert.notNull(content, "Content must not be null!");
ArrayList<T> resources = new ArrayList<>();
for (S element : content) {
resources.add((T) new EntityModel<>(elemen... |
java | static Number promoteToInteger(Object wrapper )
{
if ( wrapper instanceof Character )
return Integer.valueOf(((Character) wrapper).charValue());
if ( wrapper instanceof Byte || wrapper instanceof Short )
return Integer.valueOf(((Number) wrapper).intValue());
return (... |
java | public void receiveData(String type, String data) {
for (Iterator<JavametricsListener> iterator = javametricsListeners.iterator(); iterator.hasNext();) {
JavametricsListener javametricsListener = iterator.next();
try {
javametricsListener.receive(type, data);
... |
java | void parse() {
int state;
RBBIRuleParseTable.RBBIRuleTableElement tableEl;
state = 1;
nextChar(fC);
//
// Main loop for the rule parsing state machine.
// Runs once per state transition.
// Each time through optionally performs, depending on the state... |
python | def update_parameters(parameters, grads, learning_rate=1.2):
"""
Updates parameters using the gradient descent update rule given above
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients
Returns:
parameters -- python di... |
python | def calculate_rsq(self):
"""calculate_rsq calculates coefficient of determination, or r-squared, defined here as 1.0 - SS_res / SS_tot. rsq is only calculated for those timepoints in the data for which the design matrix is non-zero.
"""
assert hasattr(self, 'betas'), 'no betas found, please run ... |
java | private int getDoubleBondedCarbonsCount(IAtomContainer ac, IAtom atom) {
List<IAtom> neighbours = ac.getConnectedAtomsList(atom);
IBond bond;
int cdbcounter = 0;
for (IAtom neighbour : neighbours) {
if (neighbour.getSymbol().equals("C")) {
bond = ac.getBond(ne... |
java | @Override
public CommerceNotificationAttachment findByUuid_Last(String uuid,
OrderByComparator<CommerceNotificationAttachment> orderByComparator)
throws NoSuchNotificationAttachmentException {
CommerceNotificationAttachment commerceNotificationAttachment = fetchByUuid_Last(uuid,
orderByComparator);
if (co... |
java | private static void printUsage() {
System.out.println();
System.out.println("USAGE");
System.out.println();
System.out.println("\t[" + ARGUMENT_PREFIX + ARGUMENT_IMAGE_FORMAT
+ " image_format] [" + ARGUMENT_PREFIX + ARGUMENT_RAW_IMAGE
+ "] input_directory tile_type geopackage_file tile_table");
System... |
python | def await_item_handle(self, original, loc, tokens):
"""Check for Python 3.5 await expression."""
internal_assert(len(tokens) == 1, "invalid await statement tokens", tokens)
if not self.target:
self.make_err(
CoconutTargetError,
"await requires a specif... |
python | def load_input(definition):
"""Load and parse input if needed.
:param definition: definition to use as an input (file, serialized JSON/YAML or dict)
:return: loaded input
:raises json2sql.ParsingInputError: when parsing fails
"""
if isinstance(definition, (str, io.TextIOWrapper)):
try:
... |
python | def display_graph(g, format='svg', include_asset_exists=False):
"""
Display a TermGraph interactively from within IPython.
"""
try:
import IPython.display as display
except ImportError:
raise NoIPython("IPython is not installed. Can't display graph.")
if format == 'svg':
... |
java | @Override
public void sessionClosed(IoSession session) throws Exception {
log.trace("Session {} closed", session.getId());
// remove connection from scope
WebSocketConnection conn = (WebSocketConnection) session.removeAttribute(Constants.CONNECTION);
if (conn != null) {
/... |
python | def pseudosample(x):
"""
draw a bootstrap sample of x
"""
#
BXs = []
for k in range(len(x)):
ind = random.randint(0, len(x) - 1)
BXs.append(x[ind])
return BXs |
python | def get_resource(self, resource_id):
"""
Returns a specific resource by resource id.
"""
# resource_id could be a path such as '/asset/123' so quote
uri = self._get_resource_uri(guid=resource_id)
return self.service._get(uri) |
java | public static long parseDuration(String str) throws IllegalArgumentException {
long seconds = 0;
if (str == null)
return 0;
// Check for ISO_8601 format
if (str.startsWith("P")) {
// A common mistake is when the minutes format is intended but the month format is ... |
java | public static void addWhiteListDomain(String domain) {
WhitelistDomainRequest request = new WhitelistDomainRequest();
request.addWhiteListedDomain(domain);
request.setDomainActionType(DomainActionType.ADD);
FbBotMillNetworkController.postThreadSetting(request);
} |
python | def realtime_comment_classifier(sender, instance, created, **kwargs):
"""
Classifies a comment after it has been created.
This behaviour is configurable by the REALTIME_CLASSIFICATION MODERATOR,
default behaviour is to classify(True).
"""
# Only classify if newly created.
if created:
... |
java | public static String getRootClassPath() {
if (rootClassPath == null) {
try {
// String path = PathKit.class.getClassLoader().getResource("").toURI().getPath();
String path = getClassLoader().getResource("").toURI().getPath();
rootClassPath = new File(path).getAbsolutePath();
}
catch (Excep... |
java | @NullSafe
public static boolean isRunning(Process process) {
try {
return (process != null && process.exitValue() == Double.NaN);
}
catch (IllegalThreadStateException ignore) {
return true;
}
} |
java | private RulesTrees buildTrees() {
long start = System.nanoTime();
// Reset the trees.
List<List<State>> rawRulesTrees = new ArrayList<List<State>>(RulesProperties.NUMBER_OF_TREES);
// Creating trees (and their initial state) and setting state vars
// for each of them.
// For this implementation, w... |
java | public String[] toStringArray()
{
String[] argout;
argout = new String[3];
argout[0] = server;
argout[1] = name;
argout[2] = _class;
//argout[3] = "Undefined";
return argout;
} |
python | def loop_write(self, max_packets=1):
"""Process read network events. Use in place of calling loop() if you
wish to handle your client reads as part of your own application.
Use socket() to obtain the client socket to call select() or equivalent
on.
Use want_write() to determine... |
python | def getSendPath(self, volume):
""" Get a path appropriate for sending the volume from this Store.
The path may be relative or absolute in this Store.
"""
try:
return self._fullPath(next(iter(self.getPaths(volume))))
except StopIteration:
return None |
python | def breakpoint_set(self, addr, thumb=False, arm=False):
"""Sets a breakpoint at the specified address.
If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if
``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a
normal breakpoint is set.
Args:
... |
python | def _get_ip(self, hostonly_interface_number, api_port):
"""
Get the IP from VirtualBox.
Due to VirtualBox limitation the only way is to send request each
second to a GNS3 endpoint in order to get the list of the interfaces and
their IP and after that match it with VirtualBox hos... |
python | def needs_refresh(self, source):
"""Has the (persisted) source expired in the store
Will return True if the source is not in the store at all, if it's
TTL is set to None, or if more seconds have passed than the TTL.
"""
now = time.time()
if source._tok in self:
... |
java | @Override
public void clearCache(CommerceOrderNote commerceOrderNote) {
entityCache.removeResult(CommerceOrderNoteModelImpl.ENTITY_CACHE_ENABLED,
CommerceOrderNoteImpl.class, commerceOrderNote.getPrimaryKey());
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLAS... |
python | def init_app(self, app, env_file=None, verbose_mode=False):
"""Imports .env file."""
if self.app is None:
self.app = app
self.verbose_mode = verbose_mode
if env_file is None:
env_file = os.path.join(os.getcwd(), ".env")
if not os.path.exists(env_file):
... |
java | public Annotation[] getAnnotations(final Method method) throws AnnotationReadException {
final Class<?> clazz = method.getDeclaringClass();
if(xmlInfo != null && xmlInfo.containsClassInfo(clazz.getName())) {
final ClassInfo classInfo = xmlInfo.getClassInfo(clazz.getNam... |
python | def get_data_by_time(path, columns, dates, start_time='00:00', end_time='23:59'):
"""Extract columns of data from a ProCoDA datalog based on date(s) and time(s)
Note: Column 0 is time. The first data column is column 1.
:param path: The path to the folder containing the ProCoDA data file(s)
:type path... |
python | def smart_search_pool(self):
""" Perform a smart pool search.
The "smart" search function tries extract a query from
a text string. This query is then passed to the search_pool
function, which performs the search.
"""
search_options = {}
if 'query_i... |
python | def _validate_snap_name(name, snap_name, strict=True, runas=None):
'''
Validate snapshot name and convert to snapshot ID
:param str name:
Name/ID of VM whose snapshot name is being validated
:param str snap_name:
Name/ID of snapshot
:param bool strict:
Raise an exception i... |
python | def _merge_objects(tref, merged, obj):
"""
Merge the snapshot size information of multiple tracked objects. The
tracked object `obj` is scanned for size information at time `tref`.
The sizes are merged into **Asized** instance `merged`.
"""
size = None
for (timestamp, tsize) in obj.snapshot... |
python | def check_fault_data(cls, fault_trace, upper_seismogenic_depth,
lower_seismogenic_depth, dip, mesh_spacing):
"""
Verify the fault data and raise ``ValueError`` if anything is wrong.
This method doesn't have to be called by hands before creating the
surface objec... |
python | def seqs2bool(seqs):
"""
convert orf and intron information to boolean
# seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]]
# seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]]
"""
for seq in s... |
python | def dropout(a, p=0.5, inplace=False):
"""Randomly set elements from `a` equal to zero, with proportion `p`.
Similar in concept to the dropout technique employed within
neural networks.
Parameters
----------
a: numpy.ndarray
Array to be modified.
p: float in [0, 1]
... |
java | protected void initLoginMessageObject() {
Object o = getDialogObject();
if ((o == null) || !(o instanceof CmsLoginMessage)) {
o = OpenCms.getLoginManager().getLoginMessage();
}
if (o != null) {
m_loginMessage = (CmsLoginMessage)((CmsLoginMessage)o).clone();
... |
java | public Entity newEntity(QualifiedName id) {
Entity res = of.createEntity();
res.setId(id);
return res;
} |
python | def resolve(self, _):
""" Resolve given variable """
if self.default_value == DUMMY_VALUE:
if self.name in os.environ:
return os.environ[self.name]
else:
raise VelException(f"Undefined environment variable: {self.name}")
else:
r... |
java | public T friends_areFriends(int userId1, int userId2)
throws FacebookException, IOException {
return this.callMethod(FacebookMethod.FRIENDS_ARE_FRIENDS,
new Pair<String, CharSequence>("uids1", Integer.toString(userId1)),
new Pair<String, CharSequence>("uids2... |
java | private FilterList onFindKeyOnly(FilterList filterList, boolean isFindKeyOnly)
{
if (isFindKeyOnly)
{
if (filterList == null)
{
filterList = new FilterList();
}
filterList.addFilter(new KeyOnlyFilter());
}
return filterL... |
python | def message_from_binary_file(fp, *args, **kws):
"""Read a binary file and parse its contents into a Message object model.
Optional _class and strict are passed to the Parser constructor.
"""
from future.backports.email.parser import BytesParser
return BytesParser(*args, **kws).parse(fp) |
python | def jdegree(CIJ):
'''
This function returns a matrix in which the value of each element (u,v)
corresponds to the number of nodes that have u outgoing connections
and v incoming connections.
Parameters
----------
CIJ : NxN np.ndarray
directed binary/weighted connnection matrix
R... |
java | public static void stdDev(Planar<GrayF64> input, GrayF64 output, @Nullable GrayF64 avg) {
stdDev(input,output,avg,0,input.getNumBands() - 1);
} |
java | @Override
public Request<DescribeFlowLogsRequest> getDryRunRequest() {
Request<DescribeFlowLogsRequest> request = new DescribeFlowLogsRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
} |
java | public void write(DataOutput out) throws IOException
{
out.writeUTF(startToken);
out.writeUTF(endToken);
out.writeInt(dataNodes.length);
for (String endpoint : dataNodes)
{
out.writeUTF(endpoint);
}
} |
java | public static void filterMarkerProperty(List<JpaProperty> properties) {
ListIterator<JpaProperty> propIt = properties.listIterator();
while (propIt.hasNext()) {
if (BEAN_MARKER_PROPERTY_NAME.equals(propIt.next().getPropertyName())) {
propIt.remove();
}
... |
java | public ReportView isReportFinishedGenerating(String reportUri) throws InterruptedException, IntegrationException {
long startTime = System.currentTimeMillis();
long elapsedTime = 0;
Date timeFinished = null;
ReportView reportInfo = null;
while (timeFinished == null) {
... |
python | def val_accuracy(show_swap):
"""http://wiki.apache.org/spamassassin/TopSharedMemoryBug"""
kv = kernel_ver()
pid = os.getpid()
swap_accuracy = -1
if kv[:2] == (2,4):
if proc.open('meminfo').read().find("Inact_") == -1:
return 1, swap_accuracy
return 0, swap_accuracy
el... |
python | def removeBlock(self, block):
'''
removeBlock - Removes a single block (text node or AdvancedTag) which is a child of this object.
@param block <str/AdvancedTag> - The block (text node or AdvancedTag) to remove.
@return Returns the removed block if one was remov... |
java | private StringBuffer determineMethodsAllowed(String path) {
StringBuffer methodsAllowed = new StringBuffer();
boolean exists = true;
I_CmsRepositoryItem item = null;
try {
item = m_session.getItem(path);
} catch (CmsException e) {
exists = false;
... |
java | public BatchArtifactRef<BatchArtifacts<T>> getOrCreateRef()
{
List<Node> nodeList = childNode.get("ref");
if (nodeList != null && nodeList.size() > 0)
{
return new BatchArtifactRefImpl<BatchArtifacts<T>>(this, "ref", childNode, nodeList.get(0));
}
return createRef();
} |
python | def balance(self):
"""Check this transaction for correctness"""
self.check()
if not sum(map(lambda x: x.amount, self.src)) == -self.amount:
raise XnBalanceError("Sum of source amounts "
"not equal to transaction amount")
if not sum(map(lambda ... |
python | def _settings_from_file(self):
"""Loads settings from file."""
settings = load_source(
'settings', text_type(self.user_dir.joinpath('settings.py')))
return {key: getattr(settings, key)
for key in const.DEFAULT_SETTINGS.keys()
if hasattr(settings, key)} |
java | public java.lang.String getHandle() {
java.lang.Object ref = handle_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
handle_ = ... |
python | def perform_async_refresh(cls, klass_str, obj_args, obj_kwargs, call_args, call_kwargs):
"""
Re-populate cache using the given job class.
The job class is instantiated with the passed constructor args and the
refresh method is called with the passed call args. That is::
da... |
python | def get_presence(self, user_name):
""" https://api.slack.com/methods/users.getPresence
"""
user_id = self.get_id_by_name(user_name)
self.params.update({
'user': user_id,
})
return FromUrl('https://slack.com/api/users.getPresence', self._requests)(data=self... |
python | def itemData(self, treeItem, column, role=Qt.DisplayRole):
""" Returns the data stored under the given role for the item.
"""
if role == Qt.DisplayRole:
if column == self.COL_NODE_NAME:
return treeItem.nodeName
elif column == self.COL_NODE_PATH:
... |
java | protected Formatter format(FormatterConfiguration conf, Locale locale, Object e, Object format, int start, int end, Object... args) {
try {
if (conf == null) conf = this.conf;
if (locale == null) locale = conf.locale();
if (locale == null) locale = Locale.ROOT;
St... |
python | def createL4L6aLocationColumn(network, L4Params, L6aParams,
inverseReadoutResolution=None,
baselineCellsPerAxis=6, suffix=""):
"""
Create a single column network containing L4 and L6a layers. L4 layer
processes sensor inputs while L6a processes motor com... |
python | def mapsplice(job, job_vars):
"""
Maps RNA-Seq reads to a reference genome.
job_vars: tuple Tuple of dictionaries: input_args and ids
"""
# Unpack variables
input_args, ids = job_vars
work_dir = job.fileStore.getLocalTempDir()
cores = input_args['cpu_count']
sudo = input_args['s... |
python | def __store_cash_balances_per_currency(self, cash_balances):
""" Store balance per currency as Stock records under Cash class """
cash = self.model.get_cash_asset_class()
for cur_symbol in cash_balances:
item = CashBalance(cur_symbol)
item.parent = cash
... |
python | def _check_available_data(archive, arc_type, day):
"""
Function to check what stations are available in the archive for a given \
day.
:type archive: str
:param archive: The archive source
:type arc_type: str
:param arc_type: The type of archive, can be:
:type day: datetime.date
:pa... |
python | def throw_random_gap_list( lengths, mask, save_interval_func, allow_overlap=False ):
"""
Generates a set of non-overlapping random intervals from a length
distribution.
`lengths`: list containing the length of each interval to be generated.
We expect this to be sorted by decreasing ... |
java | public CompletableFuture<T> exceptAsync(Consumer<Throwable> consumer) {
return whenCompleteAsync((result, error) -> {
if (error != null) {
consumer.accept(error);
}
});
} |
python | def update_selection_sm_prior(self):
"""State machine prior update of tree selection"""
if self._do_selection_update:
return
self._do_selection_update = True
tree_selection, selected_model_list, sm_selection, sm_selected_model_list = self.get_selections()
if tree_sele... |
python | def _apply_new_data_port_type(self, path, new_data_type_str):
"""Applies the new data type of the data port defined by path
:param str path: The path identifying the edited data port
:param str new_data_type_str: New data type as str
"""
try:
data_port_id = self.list... |
java | public Observable<Page<UserSubscriptionQuotaInner>> listAsync() {
return listWithServiceResponseAsync().map(new Func1<ServiceResponse<List<UserSubscriptionQuotaInner>>, Page<UserSubscriptionQuotaInner>>() {
@Override
public Page<UserSubscriptionQuotaInner> call(ServiceResponse<List<UserS... |
python | def geosgeometry_str_to_struct(value):
'''
Parses a geosgeometry string into struct.
Example:
SRID=5432;POINT(12.0 13.0)
Returns:
>> [5432, 12.0, 13.0]
'''
result = geos_ptrn.match(value)
if not result:
return None
return {
'srid': result.group(1),
... |
python | def manufacturer(self):
"""Returns the name of the manufacturer of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Manufacturer name.
"""
buf = ctypes.cast(self.sManu, ctypes.c_char_p).value
return buf.decode() if ... |
python | def validate_permissions(perms):
""" Validate :perms: contains valid permissions.
:param perms: List of permission names or ALL_PERMISSIONS.
"""
if not isinstance(perms, (list, tuple)):
perms = [perms]
valid_perms = set(PERMISSIONS.values())
if ALL_PERMISSIONS in perms:
return p... |
python | def requirements(self):
"""
Verifica che tutti i pacchetti apt necessari al "funzionamento" della
classe siano installati. Se cosi' non fosse li installa.
"""
cache = apt.cache.Cache()
for pkg in self.pkgs_required:
try:
pkg = cache[pkg]
... |
java | public int getInterDigitTimer() {
String value = Optional.fromNullable(getParameter(SignalParameters.INTER_DIGIT_TIMER.symbol())).or("30");
return Integer.parseInt(value) * 100;
} |
python | def compute_params_curve(points, centripetal=False):
""" Computes :math:`\\overline{u}_{k}` for curves.
Please refer to the Equations 9.4 and 9.5 for chord length parametrization, and Equation 9.6 for centripetal method
on The NURBS Book (2nd Edition), pp.364-365.
:param points: data points
:type ... |
java | public List<CmsAccessControlEntry> getAccessControlEntries(
CmsRequestContext context,
CmsResource resource,
boolean getInherited)
throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
List<CmsAccessControlEntry> result = null;
try {
... |
python | def clear(self, exclude=None):
"""
Remove all elements in the cache.
"""
if exclude is None:
self.cache = {}
else:
self.cache = {k: v for k, v in self.cache.items()
if k in exclude} |
python | def save_config(self, cmd="write mem", confirm=False, confirm_response=""):
"""Saves configuration."""
return super(RuckusFastironBase, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) |
java | @Nullable
public static String getFromFirstExcl (@Nullable final String sStr, final char cSearch)
{
return _getFromFirst (sStr, cSearch, false);
} |
java | public static <T, K, V> ImmutableMapCollector<T, K, V> collector(Function<T, K> keyMapper, Function<T, V> valueMapper) {
return new ImmutableMapCollector<>(keyMapper, valueMapper);
} |
java | public void setTrustStore(String trustStore, String trustPass, String trustManagerType, String trustStoreType)
{
if((trustStore == null) || (trustPass == null))
{
this.trustStore = System.getProperty("javax.net.ssl.trustStore");
this.trustPass = System.getProperty("ja... |
python | def match_end_date(self, start, end, match):
"""Matches temporals whose effective end date falls in between the given dates inclusive.
arg: start (osid.calendaring.DateTime): start of date range
arg: end (osid.calendaring.DateTime): end of date range
arg: match (boolean): ``tru... |
python | def save_tsv_header(p, vs):
'Write tsv header for Sheet `vs` to Path `p`.'
trdict = tsv_trdict(vs)
delim = options.delimiter
with p.open_text(mode='w') as fp:
colhdr = delim.join(col.name.translate(trdict) for col in vs.visibleCols) + '\n'
if colhdr.strip(): # is anything but whitespac... |
java | public static LogPosition createPosition(Event event) {
EntryPosition position = new EntryPosition();
position.setJournalName(event.getJournalName());
position.setPosition(event.getPosition());
position.setTimestamp(event.getExecuteTime());
// add serverId at 2016-06-28
p... |
java | @Override
public void mutate(Mutation mutation) throws IOException {
handleExceptions();
addCallback(helper.mutate(mutation), mutation);
} |
java | public void enableCors( boolean enableCors ) {
if( enableCors )
getProperties().put( ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, ResponseCorsFilter.class.getName());
else
getProperties().remove( ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS );
} |
python | def render_iconchoicefield(field, attrs):
"""
Render a ChoiceField with icon support; where the value is split by a pipe
(|): first element being the value, last element is the icon.
"""
choices = ""
# Loop over every choice to manipulate
for choice in field.field._choices:
value = choice[1].split("|") # Val... |
python | def launch(in_name, out_name, script_path, partitioner=False, files=(), jobconfs=(),
cmdenvs=(), libjars=(), input_format=None, output_format=None, copy_script=True,
wait=True, hstreaming=None, name=None,
use_typedbytes=True, use_seqoutput=True, use_autoinput=True,
remove_out... |
java | protected double evalG(DoubleSolution solution) {
double g = 0.0;
for (int i = 1; i < solution.getNumberOfVariables(); i++) {
g += solution.getVariableValue(i);
}
double constant = 9.0 / (solution.getNumberOfVariables() - 1);
return constant * g + 1.0;
} |
python | def HandleMessageBundles(self, request_comms, response_comms):
"""Processes a queue of messages as passed from the client.
We basically dispatch all the GrrMessages in the queue to the task scheduler
for backend processing. We then retrieve from the TS the messages destined
for this client.
Args:
... |
java | public static Deferred<Annotation> getAnnotation(final TSDB tsdb,
final long start_time) {
return getAnnotation(tsdb, (byte[])null, start_time);
} |
java | public static void main(String[] args) throws Exception {
MapReduceIntegrationChecker checker = new MapReduceIntegrationChecker();
System.exit(checker.run(args));
} |
python | def release(self):
"""
Release the connection lock
"""
if self._locked is True:
self._locked = False
self._lock.release() |
java | private void translateStructure(Point3d originalCoord, Point3d newCoord, IAtomContainer ac) {
Point3d transVector = new Point3d(originalCoord);
transVector.sub(newCoord);
for (int i = 0; i < ac.getAtomCount(); i++) {
if (!(ac.getAtom(i).getFlag(CDKConstants.ISPLACED))) {
... |
python | def split_into_segments(data):
"""Slices JPEG meta data into a list from JPEG binary data.
"""
if data[0:2] != b"\xff\xd8":
raise InvalidImageDataError("Given data isn't JPEG.")
head = 2
segments = [b"\xff\xd8"]
while 1:
if data[head: head + 2] == b"\xff\xda":
segmen... |
java | public com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdLabel getAdGroupAdLabel() {
return adGroupAdLabel;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.