language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void error(CharSequence message, Throwable e) { log(Level.SEVERE, message, e); }
python
def get_title(mode='title'): ''' Return the terminal/console title. Arguments: str: mode, one of ('title', 'icon') or int (20-21): see links below. - `Control sequences <http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Operating-System-Commands>`_...
python
def get_selected_text(self): """ Return text selected by current text cursor, converted in unicode Replace the unicode line separator character \u2029 by the line separator characters returned by get_line_separator """ return to_text_string(self.textCursor().selec...
python
def tojson(table, source=None, prefix=None, suffix=None, *args, **kwargs): """ Write a table in JSON format, with rows output as JSON objects. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar'], ... ['a', 1], ... ['b', 2], ... ['c', ...
java
protected void addWebuserCondition(CmsSelectQuery select, CmsOrganizationalUnit orgUnit, TableAlias users) { String webuserConditionTemplate; if (orgUnit.hasFlagWebuser()) { webuserConditionTemplate = "( %1$s >= 32768 AND %1$s < 65536 )"; } else { webuserConditionTemplat...
python
def build_field(self, field_name, info, model_class, nested_depth): """ Return a two tuple of (cls, kwargs) to build a serializer field with. """ if field_name in info.fields_and_pk: model_field = info.fields_and_pk[field_name] return self.build_standard_field(fie...
python
def get_access_control_function(): """ Return a predicate for determining if a user can access the Rosetta views """ fn_path = getattr(settings, 'ROSETTA_ACCESS_CONTROL_FUNCTION', None) if fn_path is None: return is_superuser_staff_or_in_translators_group # Dynamically load a permiss...
java
@Override protected final int serializeBytes1to3 () { int line = 0; line |= taskAttributes.value() << Constants.TWO_BYTES_SHIFT; if (writeExpectedFlag) { line |= WRITE_EXPECTED_FLAG_MASK; } if (readExpectedFlag) { line |= READ_EXPECTED_FLAG_MASK; ...
java
public static String adaptReplacementToMatcher(String replacement) { // Double the backslashes, so they are left as they are after replacement. String result = replacement.replaceAll("\\\\", "\\\\\\\\"); // Add backslashes after dollar signs result = result.replaceAll("\\$", "\\\\\\$"); return result; }
python
def reparentClassLike(self): ''' Helper method for :func:`~exhale.graph.ExhaleRoot.reparentAll`. Iterates over the ``self.class_like`` list and adds each object as a child to a namespace if the class, or struct is a member of that namespace. Many classes / structs will be repare...
python
def authenticate(self, _=None): # TODO: remove unused var ''' Authenticate with the master, this method breaks the functional paradigm, it will update the master information from a fresh sign in, signing in can occur as often as needed to keep up with the revolving master AES ke...
python
def gini(data): """ Calculate the `Gini coefficient <https://en.wikipedia.org/wiki/Gini_coefficient>`_ of a 2D array. The Gini coefficient is calculated using the prescription from `Lotz et al. 2004 <http://adsabs.harvard.edu/abs/2004AJ....128..163L>`_ as: .. math:: G = \\frac{1}{\...
python
def bitterness(self, ibu_method, early_og, batch_size): "Calculate bitterness based on chosen method" if ibu_method == "tinseth": bitterness = 1.65 * math.pow(0.000125, early_og - 1.0) * ((1 - math.pow(math.e, -0.04 * self.time)) / 4.15) * ((self.alpha / 100.0 * self.amount * 1000000) / bat...
python
def result(self): """Vqe.result is deprecated. Use `result = Vqe.run()`.""" warnings.warn("Vqe.result is deprecated. Use `result = Vqe.run()`", DeprecationWarning) return self._result if self._result is not None else VqeResult()
python
def generate_type_docs(types): """Parse an object of types and generate RAML documentation for them. Expects each type to be either a regular type or a list/array. If a type is a list, it must specify what type to use for each item. """ output = StringIO() indent = " " # 2 # loop through...
python
def _transform_col(self, x, col): """Normalize one numerical column. Args: x (numpy.array): a numerical column to normalize col (int): column index Returns: A normalized feature vector. """ return norm.ppf(self.ecdfs[col](x) * .998 + .001)
python
def updateCurrentValue(self, value): """ Disables snapping during the current value update to ensure a smooth transition for node animations. Since this can only be called via code, we don't need to worry about snapping to the grid for a user. """ xsnap = None ys...
python
def disconnect(self): "Disconnects all connections in the pool" self._checkpid() all_conns = chain(self._available_connections, self._in_use_connections) for connection in all_conns: connection.disconnect()
java
@Override public com.liferay.commerce.account.service.persistence.CommerceAccountOrganizationRelPK getPrimaryKey() { return _commerceAccountOrganizationRel.getPrimaryKey(); }
python
def calc_nu_b(b): """Calculate the cyclotron frequency in Hz given a magnetic field strength in Gauss. This is in cycles per second not radians per second; i.e. there is a 2π in the denominator: ν_B = e B / (2π m_e c) """ return cgs.e * b / (2 * cgs.pi * cgs.me * cgs.c)
java
public static DMatrixRMaj extractRow(DMatrixRMaj a , int row , DMatrixRMaj out ) { if( out == null) out = new DMatrixRMaj(1,a.numCols); else if( !MatrixFeatures_DDRM.isVector(out) || out.getNumElements() != a.numCols ) throw new MatrixDimensionException("Output must be a vector o...
python
def unbuild(self): """ Iterates through the views pointed to by self.detail_views, runs unbuild_object with `self`, and calls _build_extra() and _build_related(). """ for detail_view in self.detail_views: view = self._get_view(detail_view) view().u...
python
def convert_dt_time(duration, return_iter=False): """ Summary: convert timedelta objects to human readable output Args: :duration (datetime.timedelta): time duration to convert :return_iter (tuple): tuple containing time sequence Returns: days, hours, minutes, seconds | ...
python
def disk2ram(self): """Move internal data from disk to RAM.""" values = self.series self.deactivate_disk() self.ramflag = True self.__set_array(values) self.update_fastaccess()
java
public EClass getIfcVertexBasedTextureMap() { if (ifcVertexBasedTextureMapEClass == null) { ifcVertexBasedTextureMapEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(634); } return ifcVertexBasedTextureMapEClass; }
java
protected void onShowPopup(final MouseEvent e) { if (e.isPopupTrigger()) { System.out.println(e.getSource()); popupMenu.show(e.getComponent(), e.getX(), e.getY()); } }
java
public static Map<String, List<Interaction>> getPoolData(List<TraceEvent> data, boolean ignoreDelist, boolean ignoreTracking, boolean ignoreIncomplete) { // Pool -> Interactions Map<Str...
python
def _add_nic_to_mapping(self, net, dom, nic): """ Populates the given net spec mapping entry with the nics of the given domain, by the following rules: * If ``net`` is management, 'domain_name': nic_ip * For each interface: 'domain_name-eth#': nic_ip, where # is the ...
python
def handle_request(self): """simply collect requests and put them on the queue for the workers.""" try: request, client_address = self.get_request() except socket.error: return if self.verify_request(request, client_address): self.workerpool.run(self....
python
def get_logs(self, container_id): """ Return the full stdout/stderr of a container""" stdout = self._docker.containers.get(container_id).logs(stdout=True, stderr=False).decode('utf8') stderr = self._docker.containers.get(container_id).logs(stdout=False, stderr=True).decode('utf8') return...
python
def satisfiesShapeExprRef(cntxt: Context, n: Node, se: ShExJ.shapeExprLabel, c: DebugContext) -> bool: """ Se is a shapeExprRef and there exists in the schema a shape expression se2 with that id and satisfies(n, se2, G, m). """ if c.debug: print(f"id: {se}") for shape in cntxt.schema.shape...
python
def _compute_magnitude_scaling_term(self, C, mag): """ Compute and return magnitude scaling term in equation 2, page 970. """ c1 = self.CONSTS['c1'] if mag <= c1: return C['b1'] + C['b2'] * (mag - c1) + C['b3'] * (8.5 - mag) ** 2 else: ...
java
public Content getPackageSummaryHeader(PackageDoc pkg) { Content pkgName = getTargetProfilePackageLink(pkg, "classFrame", new StringContent(pkg.name()), profile.name); Content heading = HtmlTree.HEADING(HtmlTag.H3, pkgName); HtmlTree li = HtmlTree.LI(HtmlStyle.blockList, head...
java
public BatchGetBuildsResult withBuildsNotFound(String... buildsNotFound) { if (this.buildsNotFound == null) { setBuildsNotFound(new java.util.ArrayList<String>(buildsNotFound.length)); } for (String ele : buildsNotFound) { this.buildsNotFound.add(ele); } r...
java
public static boolean hasGroupBy(JPQLExpression jpqlExpression) { if (isSelectStatement(jpqlExpression)) { return ((SelectStatement) jpqlExpression.getQueryStatement()).hasGroupByClause(); } return false; }
java
public static List<String> extractParameterNames(Serializable lambda, int lambdaParametersCount) { SerializedLambda serializedLambda = serialized(lambda); Method lambdaMethod = lambdaMethod(serializedLambda); String[] paramNames = paramNameReader.getParamNames(lambdaMethod); return asLi...
python
def _add_token_to_document(self, token_string, token_attrs=None): """add a token node to this document graph""" token_feat = {self.ns+':token': token_string} if token_attrs: token_attrs.update(token_feat) else: token_attrs = token_feat token_id = 'token_{}...
java
public synchronized Boolean start() { if (started) { return true; } createSerialPort(); serialPort.addEventListener(this); if (!serialPort.connect()) { log.error("Failed to start Firmata Library. Cannot connect to Serial Port."); log.error("...
java
public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { // Read a valid record int iErrorCode = super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record (Move the header record data down) if (iErrorCode != DBConstants.NORMAL_RETURN) ...
python
def set_intersection(self, division, intersection): """Set intersection percentage of intersecting divisions.""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).update(intersection=intersection)
python
def save_config(self, config_file_name): """ Save configuration file to xpc file. :param config_file_name: full path to the configuration file. """ with open(config_file_name, 'w+') as f: f.write('P_RESET\n') for line in self.send_command_return_multilines('p_fu...
java
protected void initTabs(Element root, CmsXmlContentDefinition contentDefinition) { if (Boolean.valueOf(root.attributeValue(APPINFO_ATTR_USEALL, CmsStringUtil.FALSE)).booleanValue()) { // all first level elements should be treated as tabs Iterator<I_CmsXmlSchemaType> i = contentDefinitio...
java
public SortedMap<String, String> getDisplayNames(ULocale locale, Comparator<Object> com) { return getDisplayNames(locale, com, null); }
python
def SetEncoding(sval): """Sets the encoding variable according to the text passed :param sval: text specification for the desired model """ global encoding s=sval.lower() if s == "additive": encoding = Encoding.Additive elif s == "dominant": encoding = Encoding.Dominant ...
python
def _getLocation(self, coordinate, reference_id, strand, position_types): """ Make an object for the location, which has: {coordinate : integer, reference : reference_id, types = []} where the strand is indicated in the type array :param coordinate: :param reference_id: ...
python
def incident(self, name, owner=None, **kwargs): """ Create the Incident TI object. Args: owner: name: **kwargs: Return: """ return Incident(self.tcex, name, owner=owner, **kwargs)
java
public boolean removeAll(Collection<?> c) { if (!(c instanceof JumboEnumSet)) return super.removeAll(c); JumboEnumSet<?> es = (JumboEnumSet<?>)c; if (es.elementType != elementType) return false; for (int i = 0; i < elements.length; i++) elements[i] &...
java
static final int match(String text, int pos, int ch) { if (pos < 0 || pos >= text.length()) { return -1; } pos = skipBidiMarks(text, pos); if (PatternProps.isWhiteSpace(ch)) { // Advance over run of white space in input text // Must see at least one wh...
python
def read_embedded(self, data, parent_var_type): """Read method for "mixed" variable type. .. Note:: The ``read()`` method will automatically determine if the input is a variable or needs to be searched for embedded variables. There usually is no reason to call this m...
java
private void verifyDocument(Document document, String docLocation) throws Exception { // Gets the signature element within the document NodeList nodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); ...
python
def values(self, axis=None): """ Returns the values for this dataset. :return [{<str> axis: <variant> value, ..}, ..] """ if axis is None: return self._plot else: return [value.get(axis) for value in self._plot]
java
@Override public Locale getLocale() { if (super.getSession(false) == null) { return super.getLocale(); } final IUserInstance userInstance = this.userInstanceManager.getUserInstance(this.getWrappedRequest()); final LocaleManager localeManager = userInstanc...
python
def fit_texture(layer): """Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture. """ x, y = layer x = (x - np.nanmin(x)) / (np.nanmax(x) -...
java
private static void encodeBasicProperties(ByteArrayOutputStream baos, boolean isTopic, Map<String,Object> destProps) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "encodeBasicProperties", new Object[]{baos, isTopic, destProps}); // Examine the basic property information. No...
java
public String createPersistentSequential(String path, Object data) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { return create(pa...
java
public static Config fromYAML(URL url) throws IOException { ConfigSupport support = new ConfigSupport(); return support.fromYAML(url, Config.class); }
python
def rendered(self): """Return (generating first if needed) rendered template.""" if not self._rendered: template_path = get_template_path(self.raw_template_path) if template_path: with open(template_path, 'r') as template: if len(os.path.splite...
python
def _finalize(self, all_msg_errors=None): """Access all the instance descriptors This wil trigger an exception if a required parameter is not set """ if all_msg_errors is None: all_msg_errors = [] for key in self.stored(): try: ge...
python
def get_width(self): """ Returns the Widget target width. :return: Widget target width. :rtype: int """ return self.__margin + \ self.__editor.fontMetrics().width(foundations.strings.to_string(max(1, self.__editor.blockCount())))
python
def _UpdateForemanProcessStatus(self): """Update the foreman process status.""" used_memory = self._process_information.GetUsedMemory() or 0 display_name = getattr(self._merge_task, 'identifier', '') self._processing_status.UpdateForemanStatus( self._name, self._status, self._pid, used_memory,...
java
public void flush() { if (!enabled) { return; } if (!queue.isEmpty()) { // start a new thread to upload without blocking the current thread Runnable runUpload = new TelemetryUploader(this, exportQueueToString()); uploader.execute(runUpload); } }
python
def serialize(data, measurement=None, tag_columns=None, **extra_tags): """Converts input data into line protocol format""" if isinstance(data, bytes): return data elif isinstance(data, str): return data.encode('utf-8') elif hasattr(data, 'to_lineprotocol'): return data.to_linepro...
python
def get_tool(self, name, parameters, version=None): """ Gets the tool object from the tool channel(s), and instantiates it using the tool parameters :param name: The name or stream id for the tool in the tool channel :param parameters: The parameters for the tool :param version:...
java
public Nfs3ReaddirplusResponse getReaddirplus(NfsReaddirplusRequest request) throws IOException { Nfs3ReaddirplusResponse response = new Nfs3ReaddirplusResponse(); _rpcWrapper.callRpcNaked(request, response); return response; }
python
def add_semantic_hub_layout(cx, hub): """Attach a layout aspect to a CX network given a hub node.""" graph = cx_to_networkx(cx) hub_node = get_node_by_name(graph, hub) node_classes = classify_nodes(graph, hub_node) layout_aspect = get_layout_aspect(hub_node, node_classes) cx['cartesianLayout'] =...
java
@Override protected boolean compare(final AtomicValue[] mOperand1, final AtomicValue[] mOperand2) throws TTXPathException { assert mOperand1.length >= 1 && mOperand2.length >= 1; for (AtomicValue op1 : mOperand1) { for (AtomicValue op2 : mOperand2) { String valu...
python
def overlay_gateway_site_extend_vlan_add(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, "name") na...
java
public void addScreenLabels(Container parent) { GridBagConstraints c = this.getGBConstraints(); c.weightx = 0.0; // Minimum width to hold labels c.anchor = GridBagConstraints.NORTHEAST; // Labels right justified c.gridx = 0; // Col...
java
public static ParserRuleContext getFirstChildNode(final ParserRuleContext node, final RuleName ruleName) { Optional<ParserRuleContext> result = findFirstChildNode(node, ruleName); Preconditions.checkState(result.isPresent()); return result.get(); }
python
def service_references(self): """ returns a list of service names """ services_blue_print = self._scheme_references.get('services') if services_blue_print is None: raise LookupError('unable to find any services in the config.') # TODO: this needs to be cleaned up and...
python
def deserialize(self, data): """ :type cls: type :param data: :type data: bytes :return: :rtype: yowsup.config.base.config.Config """ for transform in self._transforms[::-1]: data = transform.reverse(data) return data
python
def _display(self, sent, now, chunk, mbps): """ Display intermediate progress. """ if self.parent is not None: self.parent._display(self.parent.offset + sent, now, chunk, mbps) return elapsed = now - self.startTime if sent > 0 and self.total is not None and sent...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.IOCA_FUNCTION_SET_IDENTIFICATION__CATEGORY: setCATEGORY(CATEGORY_EDEFAULT); return; case AfplibPackage.IOCA_FUNCTION_SET_IDENTIFICATION__FCNSET: setFCNSET(FCNSET_EDEFAULT); return; } super.eUnset(featureID...
java
private Node createTemplateNode() { // The Node type choice is arbitrary. Node templateNode = new Node(Token.SCRIPT); templateNode.setStaticSourceFile(sourceFile); return templateNode; }
java
public void fillRoundRect(float x, float y, float width, float height, int cornerRadius, int segs) { if (cornerRadius < 0) throw new IllegalArgumentException("corner radius must be > 0"); if (cornerRadius == 0) { fillRect(x, y, width, height); return; } int mr = (int) Math.min(width, heigh...
python
def patch_discriminator(x, filters=64, filter_size=5, n=4, name="patch_discrim"): """Patch descriminator.""" with tf.variable_scope(name): x_shape = shape_list(x) spatial_dims = [x_shape[1] // 4, x_shape[2] // 4] x = tf.random_crop(x, [x_shape[0]] + spatial_dims + [x_shape[3]]) ...
python
def cancel(self): """Cancel a connector from completing.""" if self.started and not self.connected and not self.timedout: self.connect_watcher.stop() self.timeout_watcher.stop()
python
def get_auth_error_message(self): ''' create an informative error message if there is an issue authenticating''' errors = ["Authentication error retrieving ec2 inventory."] if None in [os.environ.get('AWS_ACCESS_KEY_ID'), os.environ.get('AWS_SECRET_ACCESS_KEY')]: errors.append(' - No...
python
def to_perseus(df, path_or_file, main_columns=None, separator=separator, convert_bool_to_category=True, numerical_annotation_rows = set([])): """ Save pd.DataFrame to Perseus text format. :param df: pd.DataFrame. :param path_or_file: File name or file-like object. :param mai...
python
def get_queryset(self): """ Returns a queryset of all executive offices holding an election on a date. """ try: date = ElectionDay.objects.get(date=self.kwargs['date']) except Exception: raise APIException( 'No elections on {}.'.for...
python
def conditional_expected_average_profit(self, frequency=None, monetary_value=None): """ Conditional expectation of the average profit. This method computes the conditional expectation of the average profit per transaction for a group of one or more customers. Parameters ...
python
def attitude_quaternion_cov_send(self, time_boot_ms, q, rollspeed, pitchspeed, yawspeed, covariance, force_mavlink1=False): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w,...
python
def _handle_command(self, connection, sender, target, command, payload): """ Handles a command, if any """ try: # Find the handler handler = getattr(self, "cmd_{0}".format(command)) except AttributeError: self.safe_send(connection, target, "Unk...
python
def parse_macro_params(token): """ Common parsing logic for both use_macro and macro_block """ try: bits = token.split_contents() tag_name, macro_name, values = bits[0], bits[1], bits[2:] except IndexError: raise template.TemplateSyntaxError( "{0} tag requires at ...
java
private boolean iterateGroup(ValueIterator.Element result, int limit) { if (m_groupIndex_ < 0) { m_groupIndex_ = m_name_.getGroup(m_current_); } while (m_groupIndex_ < m_name_.m_groupcount_ && m_current_ < limit) { // iterate till the last group or the...
java
public static void setPreferredRoadType(RoadType type) { final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkConstants.class); if (prefs != null) { if (type == null) { prefs.remove("ROAD_TYPE"); //$NON-NLS-1$ } else { prefs.put("ROAD_TYPE", type.name()); //$NON-NLS-1$ } } }
python
def remove_from_role(server_context, role, user_id=None, email=None, container_path=None): """ Remove user/group from security role :param server_context: A LabKey server context. See utils.create_server_context. :param role: (from get_roles) to remove user from :param user_id: to remove permissions...
python
def notifications_mark_read(input_params={}, always_retry=True, **kwargs): """ Invokes the /notifications/markRead API method. """ return DXHTTPRequest('/notifications/markRead', input_params, always_retry=always_retry, **kwargs)
python
def count_args(node, results): # type: (Node, Dict[str, Base]) -> Tuple[int, bool, bool, bool] """Count arguments and check for self and *args, **kwds. Return (selfish, count, star, starstar) where: - count is total number of args (including *args, **kwds) - selfish is True if the initial arg is na...
python
def exit(exit_code=0): r"""A function to support exiting from exit hooks. Could also be used to exit from the calling scripts in a thread safe manner. """ core.processExitHooks() if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook sys.stderr.flush() sy...
java
@Override public String compareDatastreamChecksum(String pid, String dsID, String versionDate) { assertInitialized(); try { MessageContext ctx = context.getMessageContext(); return m_manag...
java
@FFDCIgnore(Throwable.class) @Override public <R> MethodResult<R> run(Callable<R> callable) { try { return MethodResult.success(callable.call()); } catch (Throwable t) { return MethodResult.failure(t); } }
java
@NonNull public static Spanned style(@NonNull Context ctx, @NonNull Spanned textSpanned) { return style(ctx, null, textSpanned, null, null); }
java
public static File getMavenHome() throws Exception { final String command; switch (OS.current()) { case LINUX: case MAC: command = "mvn"; break; case WINDOWS: command = "mvn.bat"; break; default: throw new Illega...
python
def bsp_traverse_post_order( node: tcod.bsp.BSP, callback: Callable[[tcod.bsp.BSP, Any], None], userData: Any = 0, ) -> None: """Traverse this nodes hierarchy with a callback. .. deprecated:: 2.0 Use :any:`BSP.post_order` instead. """ _bsp_traverse(node.post_order(), callback, userDa...
java
public Observable<Void> purgeDeletedAsync(String vaultName, String location) { return purgeDeletedWithServiceResponseAsync(vaultName, location).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body...
python
def get_userloved(self): """Whether the user loved this track""" if not self.username: return params = self._get_params() params["username"] = self.username doc = self._request(self.ws_prefix + ".getInfo", True, params) loved = _number(_extract(doc, "userlo...
java
@Override public LoopPreventionMessage createLPP() { LoopPreventionMessage msg = new LoopPreventionMessageImpl(_LPP_HOLDER.mandatoryCodes, _LPP_HOLDER.mandatoryVariableCodes, _LPP_HOLDER.optionalCodes, _LPP_HOLDER.mandatoryCodeToIndex, _LPP_HOLDER.mandatoryVariableCodeToIndex, ...
java
Rule AbcEol() { return Sequence( OptionalS(Comment()), SequenceS(OptionalS(FirstOfS(LineContinuation(), HardLineBreak())), ZeroOrMore(WSP()).suppressNode(), FirstOf(Eol(), EOI).suppressNode() ) //FirstOfS(Comment(), suppr(Eol()), suppr(EOI)) ).label(AbcEol); }
python
def get_max_ballcount(cls, ball_diam, rolling_radius, min_gap=0.): """ The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float`...